| 1 | // Builds packages/conformance (the conformance set shipped with the framework) from its widget files: |
| 2 | // 1. catalogue.json / catalogue.md from scripts/conformance/catalogue.ts; |
| 3 | // 2. the harness region of every widget: the harness CSS of its set, the |
| 4 | // harness JS bundled with only the exports the widget uses and minified |
| 5 |
| 6 | // with a margin (SIZE_LIMIT), or the build fails; |
| 7 | // 3. reference images: every stage rendered natively by headless Chromium |
| 8 | // (and WebKit when Playwright has it installed) at DPR 2, in reference mode |
| 9 | // (a stage with <template data-ref> gets the template's markup), with the |
| 10 | // renderer's UA stylesheet from profile.json (the unstyled <button>) → |
| 11 | // packages/conformance/refs/<set>/<widget>/<stage>.<engine>[.dark].png; |
| 12 | // 4. the reference pictures posted next to the visual set and the client-SDK |
| 13 | // group in the test channel: the whole widget rendered natively at the |
| 14 | // reference width (refs/visual/<widget>[.dark].png); the height gate |
| 15 | // (MAX_HEIGHT): a visual or client-SDK widget taller than the bubble's |
| 16 | // cap allows fails the build; so does an automatic widget, measured |
| 17 | // through the sandbox (heights.ts: the dev app on a dev server the build |
| 18 | // starts, or --origin; --no-heights skips it); and so does a picture of |
| 19 | // the visual set that differs from the widget drawn through the sandbox |
| 20 | // (picture-check.ts, on the same dev server): a picture shows what widget |
| 21 | // profile 1 draws, not what Chromium does with an out-of-profile feature; |
| 22 | // 5. the native run of every widget (no template swap): what a plain |
| 23 | // browser engine says to each check, recorded in the manifest as a sanity |
| 24 | // reference for the tests themselves; |
| 25 | // 6. manifest.json: test → catalogue IDs, kind, stages and references, |
| 26 | // actions, host checks, themes and widths, coverage per set; |
| 27 | // 7. channel.json: the posting order for the test channel. |
| 28 | // |
| 29 | // corepack pnpm tsx scripts/conformance/build.ts [--only 04-layout] [--no-refs] [--engines chromium,webkit] [--origin http://127.0.0.1:5175 | --no-heights] |
| 30 | // corepack pnpm tsx scripts/conformance/build.ts --sizes [--only …] # sizes and the size gate only: no browser, nothing written |
| 31 |
| 32 | import fs from 'node:fs'; |
| 33 | import zlib from 'node:zlib'; |
| 34 | import path from 'node:path'; |
| 35 | import { createRequire } from 'node:module'; |
| 36 | import { chromium, webkit, type Browser, type BrowserContext, type Page } from '@playwright/test'; |
| 37 | import { PNG } from 'pngjs'; |
| 38 | import { CATALOGUE } from './catalogue'; |
| 39 | import { emitCatalogue } from './emit-catalogue'; |
| 40 | import { AUTO_GRID, CONF, MAX_HEIGHT, ROOT, STAGE, autoStagePos, listWidgets, parseWidget, perform, picturePath, posixRelative, readJson, refPath, type BotAction, type MessageSpec, type Published, type Widget } from './lib'; |
| 41 | import { diffStats } from '../../packages/conformance/tools/diff.mjs'; |
| 42 | import { measureHeights } from './heights'; |
| 43 | import { checkPictures } from './picture-check'; |
| 44 | import { spawn } from 'node:child_process'; |
| 45 | import net from 'node:net'; |
| 46 | import { fileURLToPath } from 'node:url'; |
| 47 | import { REFERENCE_STYLESHEET, REFERENCE_TIME_LABEL, referenceSafeAreaCss, timeCornerStyle } from '../../packages/core/src/shared/reference.ts'; |
| 48 | import { DEFAULT_THEME_PARAMS, checkContentSafeArea, type ContentSafeArea } from '../../packages/core/src/shared/sdk-policy.ts'; |
| 49 |
| 50 | const args = process.argv.slice(2); |
| 51 | const opt = (name: string) => (args.includes('--' + name) ? args[args.indexOf('--' + name) + 1] : undefined); |
| 52 | const ONLY = opt('only'); |
| 53 | const SIZES = args.includes('--sizes'); |
| 54 | const NO_REFS = args.includes('--no-refs') || SIZES; |
| 55 | const ENGINES = (opt('engines') ?? 'chromium,webkit').split(','); |
| 56 | const WIDTH = 390; |
| 57 | const DPR = 2; |
| 58 |
| 59 | const harnessDir = path.join(CONF, 'harness'); |
| 60 | // esbuild comes with the core package (its dev dependency); the conformance set needs nothing of its own. |
| 61 | const esbuild = createRequire(path.join(ROOT, 'packages', 'core', 'package.json'))('esbuild'); |
| 62 | const minCss = (file: string) => esbuild.transformSync(fs.readFileSync(path.join(harnessDir, file), 'utf8'), { loader: 'css', minify: true }).code.trim(); |
| 63 | const HARNESS_CSS: Record<string, string> = { auto: minCss('harness.css') + minCss('auto.css'), visual: minCss('harness.css') + minCss('visual.css') }; |
| 64 | const BEGIN = '<!-- conformance:harness -->'; |
| 65 | const END = '<!-- /conformance:harness -->'; |
| 66 | // The client-SDK group (visual/sdk) uses the mini harness, so a widget fits a v1 mini-widget. |
| 67 | const MINI_JS = fs.readFileSync(path.join(harnessDir, 'mini.js'), 'utf8').replace(/^\/\/.*\n/gm, '').trim(); |
| 68 | const MINI_CSS = fs.readFileSync(path.join(harnessDir, 'mini.css'), 'utf8').trim(); |
| 69 | const MINI_BEGIN = '<!-- conformance:mini -->'; |
| 70 | const MINI_END = '<!-- /conformance:mini -->'; |
| 71 | const SDK_MOCK = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'sdk-mock.js'), 'utf8'); |
| 72 | /** |
| 73 | * v1 mini-widgets (docs/tgw-format.md): the server refuses more than 4 KB after zlib at level 9 |
| 74 | * (PHP gzcompress) or 32 KB of HTML (INPUT_MEDIA_WIDGET_TOO_LARGE). Every widget stays within |
| 75 | * 3800 bytes compressed, the margin the harness and the dev app warn at (src/shared/widget-size.ts). |
| 76 | */ |
| 77 | const SIZE_LIMIT = { zlib: 3800, raw: 32768 }; |
| 78 | const sizeOf = (html: string) => { const b = Buffer.from(html); return { raw: b.length, zlib: zlib.deflateSync(b, { level: 9 }).length }; }; |
| 79 | const isSdk = (w: Widget) => w.id.startsWith('visual/sdk/'); |
| 80 | /** |
| 81 | * The renderer's UA layer (profile.json tables.uaStylesheet: the root and text defaults, the unstyled <button>) with |
| 82 | * the reference theme (default palettes, reference text tokens): every renderer adds it to a widget, so the native |
| 83 | * runs do too (packages/core/src/shared/reference.ts). |
| 84 | */ |
| 85 | const UA_CSS = REFERENCE_STYLESHEET; |
| 86 |
| 87 | // ───────────── 2. harness region ───────────── |
| 88 |
| 89 | /** Auto set: stages sit on a fixed grid (auto.css places the first one; these rules the others, by position). */ |
| 90 | function stageCss(w: Widget): string { |
| 91 | const rules: string[] = []; |
| 92 | const n = w.stages.length; |
| 93 | if (w.set === 'auto' && n) { |
| 94 | for (let c = 1; c < Math.min(n, AUTO_GRID.perRow); c++) rules.push(`.conf-stages>:nth-child(${AUTO_GRID.perRow}n+${c + 1}){left:${AUTO_GRID.left + c * AUTO_GRID.dx}px}`); |
| 95 | for (let r = 1; r * AUTO_GRID.perRow < n; r++) rules.push(`.conf-stages>:nth-child(n+${r * AUTO_GRID.perRow + 1}){top:${AUTO_GRID.top + r * AUTO_GRID.dy}px}`); |
| 96 | rules.push(`.conf-stages{height:${AUTO_GRID.top + Math.ceil(n / AUTO_GRID.perRow) * AUTO_GRID.dy}px}`); |
| 97 | } |
| 98 | // A stage of another size than its set's default. |
| 99 | for (const s of w.stages) if (s.w !== STAGE[w.set].w || s.h !== STAGE[w.set].h) rules.push(`[data-stage="${s.name}"]{width:${s.w}px;height:${s.h}px}`); |
| 100 | return rules.join(''); |
| 101 | } |
| 102 |
| 103 | /** The harness JS for one widget: only the exports it uses (T.ok, T.run, …), bundled and minified, as `var T`. */ |
| 104 | function harnessJs(body: string): string { |
| 105 | const names = [...new Set([...body.matchAll(/\bT\.([a-zA-Z]+)/g)].map((m) => m[1]).concat('run'))].sort(); |
| 106 | const list = /id="conf-list"/.test(body) ? "import { list } from './harness.js'; list();\n" : ''; |
| 107 | const out = esbuild.buildSync({ |
| 108 | stdin: { contents: `${list}export { ${names.join(', ')} } from './harness.js';`, resolveDir: harnessDir, loader: 'js' }, |
| 109 | bundle: true, format: 'esm', minify: true, write: false, target: 'es2017', charset: 'utf8', legalComments: 'none', |
| 110 | }).outputFiles[0].text.trim(); |
| 111 | const m = /export\s*\{([^}]*)\};?$/.exec(out); |
| 112 | if (!m) throw new Error('harness bundle has no export list'); |
| 113 | const members = m[1].split(',').map((p: string) => { const [local, as] = p.trim().split(/\s+as\s+/); return `${as ?? local}:${local}`; }); |
| 114 | return `var T=function(){${out.slice(0, m.index)}return{${members.join(',')}}}();`; |
| 115 | } |
| 116 |
| 117 | function withHarness(w: Widget): string { |
| 118 | if (w.html.includes(MINI_BEGIN)) { |
| 119 | const i = w.html.indexOf(MINI_BEGIN), j = w.html.indexOf(MINI_END); |
| 120 | if (j < 0) throw new Error(`${w.id}: no ${MINI_END}`); |
| 121 | const css = w.meta.bare ? '' : `<style>${MINI_CSS.replace(/\n/g, '')}</style>`; |
| 122 | return w.html.slice(0, i) + `${MINI_BEGIN}${css}<script>${MINI_JS}</script>${MINI_END}` + w.html.slice(j + MINI_END.length); |
| 123 | } |
| 124 | const i = w.html.indexOf(BEGIN), j = w.html.indexOf(END); |
| 125 | if (i < 0 || j < 0) throw new Error(`${w.id}: no ${BEGIN} … ${END} region`); |
| 126 | const body = w.html.slice(0, i) + w.html.slice(j + END.length); |
| 127 | // A bare widget tests the renderer's own defaults: no harness CSS over them. |
| 128 | const css = (w.meta.bare ? '' : HARNESS_CSS[w.set]) + stageCss(w); |
| 129 | const region = `${BEGIN}${css ? `<style>${css}</style>` : ''}<script>${harnessJs(body)}</script>${END}`; |
| 130 | return w.html.slice(0, i) + region + w.html.slice(j + END.length); |
| 131 | } |
| 132 |
| 133 | // ───────────── native runs ───────────── |
| 134 |
| 135 | async function newContext(browser: Browser, theme: 'light' | 'dark', width = WIDTH): Promise<BrowserContext> { |
| 136 | const ctx = await browser.newContext({ viewport: { width, height: 2000 }, deviceScaleFactor: DPR, colorScheme: theme }); |
| 137 | // A native page has the network: nothing may leave it (the widgets never need it; links must not navigate). |
| 138 | await ctx.route('**/*', (r) => (r.request().url().startsWith('data:') ? r.continue() : r.abort())); |
| 139 | return ctx; |
| 140 | } |
| 141 |
| 142 | async function published(page: Page): Promise<Published | null> { |
| 143 | return page.evaluate(() => { const v = document.documentElement.getAttribute('data-conformance'); return v ? JSON.parse(v) : null; }); |
| 144 | } |
| 145 |
| 146 | async function waitStatus(page: Page, want: string[], timeout: number): Promise<Published | null> { |
| 147 | const t0 = Date.now(); |
| 148 | let last: Published | null = null; |
| 149 | while (Date.now() - t0 < timeout) { |
| 150 | last = await published(page).catch(() => null); |
| 151 | if (last && want.includes(last.status)) return last; |
| 152 | await page.waitForTimeout(100); |
| 153 | } |
| 154 | return last; |
| 155 | } |
| 156 |
| 157 | /** |
| 158 | * Reference pictures: a page whose root says `color-scheme: dark` gets Chromium's own dark canvas, not the default background |
| 159 | * set through CDP, where a client shows its bubble through the transparent renderer. When neither the root nor the body paints |
| 160 | * a background (so nothing propagates), the root takes the bubble's colour. |
| 161 | */ |
| 162 | const BUBBLE = `addEventListener('load',function(){var d=document.documentElement,b=document.body,t=function(e){var s=getComputedStyle(e);return s.backgroundImage==='none'&&/^(transparent|rgba\\(0, 0, 0, 0\\))$/.test(s.backgroundColor)};if(b&&t(d)&&t(b))d.style.backgroundColor=matchMedia('(prefers-color-scheme: dark)').matches?${JSON.stringify(DEFAULT_THEME_PARAMS.dark.bg_color)}:${JSON.stringify(DEFAULT_THEME_PARAMS.light.bg_color)}});`; |
| 163 |
| 164 | /** In reference mode every stage with a <template data-ref="name"> gets the template's markup (after the widget's own scripts ran). */ |
| 165 | const SWAP = "document.addEventListener('DOMContentLoaded',function(){[].forEach.call(document.querySelectorAll('template[data-ref]'),function(t){var s=document.querySelector('[data-stage=\"'+t.getAttribute('data-ref')+'\"]');if(s)s.innerHTML=t.innerHTML})})"; |
| 166 |
| 167 | /** |
| 168 | * sdk: 'mock' = the SDK stand-in (client-SDK group pictures); 'palette' = only the reference palette (visual set pictures). |
| 169 | * The page's canvas is the reference palette's bubble colour, set outside the document (Chromium), as the client's bubble is |
| 170 | * behind a transparent renderer: a widget's root background or body background still paints over it (propagation). |
| 171 | */ |
| 172 | async function openNative(ctx: BrowserContext, html: string, mode: 'ref' | 'native', sdk: 'mock' | 'palette' | false = false, theme: 'light' | 'dark' = 'light', message?: MessageSpec, safeArea?: Partial<ContentSafeArea>): Promise<Page> { |
| 173 | const page = await ctx.newPage(); |
| 174 | // A widget drawn with the client's time over its corner (the header's `safeArea`, reference mode only): the engine's |
| 175 | // own env(safe-area-inset-*) and the root variables a renderer sets both hold the band (Chromium only). |
| 176 | const area = mode === 'ref' && safeArea && ctx.browser()?.browserType().name() === 'chromium' ? checkContentSafeArea(safeArea) : null; |
| 177 | if (ctx.browser()?.browserType().name() === 'chromium') { |
| 178 | const hex = DEFAULT_THEME_PARAMS[theme].bg_color; |
| 179 | const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)); |
| 180 | const cdp = await ctx.newCDPSession(page); |
| 181 | await cdp.send('Emulation.setDefaultBackgroundColorOverride', { color: { r, g, b, a: 1 } }); |
| 182 | if (area) await cdp.send('Emulation.setSafeAreaInsetsOverride' as any, { insets: { top: area.top, right: area.right, bottom: area.bottom, left: area.left } }); |
| 183 | } |
| 184 | // The mode goes into the HTML, before the harness. Links never navigate in a native reference run. |
| 185 | const boot = (UA_CSS ? `<style>${UA_CSS}${area ? referenceSafeAreaCss(area) : ''}</style>` : '') + `<script>window.__conformanceMode=${JSON.stringify(mode)};document.addEventListener('click',function(e){var a=e.target&&e.target.closest&&e.target.closest('a');if(a)e.preventDefault()},true);${mode === 'ref' ? SWAP + ';' + BUBBLE : ''}</script>` + (sdk ? `<script>${sdk === 'palette' ? 'window.__conformanceNoSdk=1;' : ''}${message ? `window.__conformanceMessage=${JSON.stringify(message)};` : ''}${SDK_MOCK}</script>` : ''); |
| 186 | // Served from a real (fake) origin, not about:blank, so storage works as in a WebView. |
| 187 | const url = 'https://conformance.test/widget.html'; |
| 188 | await page.route(url, (r) => r.fulfill({ contentType: 'text/html; charset=utf-8', body: html.replace(/<head>/i, '<head>' + boot) })); |
| 189 | // The SDK group's pictures show clock times (11-crash-restart): a fixed clock keeps them the same on every build. |
| 190 | if (sdk) await page.clock.setFixedTime(new Date('2026-10-17T12:00:00')); |
| 191 | await page.goto(url, { waitUntil: 'load' }); |
| 192 | return page; |
| 193 | } |
| 194 |
| 195 | interface NativeResult { status: string; checks: [string, string, string, string][]; skipped: string[] } |
| 196 |
| 197 | async function runNative(ctx: BrowserContext, w: Widget, html: string): Promise<NativeResult> { |
| 198 | const page = await openNative(ctx, html, 'native', isSdk(w) && 'mock', 'light', w.meta.message?.[0]); |
| 199 | let pub = await waitStatus(page, ['done', 'awaiting'], 15_000); |
| 200 | let skipped: string[] = []; |
| 201 | let skippedIds: string[] = []; |
| 202 | if (w.meta.actions?.length) { |
| 203 | ({ skipped, ids: skippedIds } = await perform(page, w.meta.actions, { |
| 204 | origin: async () => ({ x: 0, y: 0 }), |
| 205 | setTheme: async (t) => { await page.emulateMedia({ colorScheme: t }); }, |
| 206 | }, () => published(page))); |
| 207 | pub = await waitStatus(page, ['done'], 8_000); |
| 208 | } |
| 209 | await page.close(); |
| 210 | const checks = (pub?.checks ?? []).map((c) => (skippedIds.includes(c[0]) ? [c[0], c[1], 'skip', 'input not available natively'] : c) as [string, string, string, string]); |
| 211 | return { status: pub?.status ?? 'none', checks, skipped }; |
| 212 | } |
| 213 |
| 214 | async function renderRefs(browsers: Record<string, Browser>, w: Widget, html: string): Promise<Record<string, Record<string, string>>> { |
| 215 | const out: Record<string, Record<string, string>> = {}; |
| 216 | if (!w.stages.length) return out; |
| 217 | for (const [engine, browser] of Object.entries(browsers)) { |
| 218 | for (const theme of ['light', 'dark'] as const) { |
| 219 | const stages = w.stages.filter((s) => s.themes.includes(theme)); |
| 220 | if (!stages.length) continue; |
| 221 | const ctx = await newContext(browser, theme); |
| 222 | const page = await openNative(ctx, html, 'ref', false, theme); |
| 223 | await waitStatus(page, ['done', 'awaiting'], 15_000); |
| 224 | await page.waitForTimeout(150); |
| 225 | for (const s of stages) { |
| 226 | const file = refPath(w, s.name, engine, theme); |
| 227 | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| 228 | const loc = page.locator(`[data-stage="${s.name}"]`); |
| 229 | const buf = await loc.screenshot({ animations: 'allow', caret: 'hide' }); |
| 230 | writeIfChanged(file, buf); |
| 231 | ((out[s.name] ??= {})[`${engine}${theme === 'dark' ? '.dark' : ''}`] = posixRelative(CONF, file)); |
| 232 | } |
| 233 | await ctx.close(); |
| 234 | } |
| 235 | } |
| 236 | return out; |
| 237 | } |
| 238 |
| 239 | /** The visual set's and the client-SDK group's themes: a picture per theme. */ |
| 240 | const pictureThemes = (w: Widget) => (w.meta.themes ?? (w.stages.some((s) => s.themes.includes('dark')) ? ['light', 'dark'] : ['light'])) as ('light' | 'dark')[]; |
| 241 |
| 242 | /** |
| 243 | * The reference picture posted next to a visual or client-SDK widget in the test channel: the whole widget |
| 244 | * rendered natively in reference mode at the reference width, DPR 2, on the reference palette's background |
| 245 | * (the SDK group with the SDK stand-in), at most 2000 CSS px tall (1200 for the SDK group) → refs/visual/<widget>[.dark].png. |
| 246 | * Animations as they are: Playwright's `animations: 'disabled'` finishes a finite animation, a paused one too (it drew |
| 247 | * 06-css-animations' frozen box back at its start); a row that moves has a template. |
| 248 | */ |
| 249 | async function renderPictures(browser: Browser, w: Widget, html: string): Promise<Record<string, string>> { |
| 250 | const out: Record<string, string> = {}; |
| 251 | for (const theme of pictureThemes(w)) { |
| 252 | const ctx = await newContext(browser, theme); |
| 253 | const page = await openNative(ctx, html, 'ref', isSdk(w) ? 'mock' : 'palette', theme, w.meta.message?.[0], w.meta.safeArea); |
| 254 | await waitStatus(page, ['done', 'awaiting'], 15_000); |
| 255 | await page.waitForTimeout(300); |
| 256 | const h = Math.min(isSdk(w) ? 1200 : 2000, await page.evaluate(() => Math.ceil(document.documentElement.getBoundingClientRect().height))); |
| 257 | if (w.meta.safeArea) await drawTime(page, w.meta.safeArea, h); |
| 258 | const file = picturePath(w, theme); |
| 259 | fs.mkdirSync(path.dirname(file), { recursive: true }); |
| 260 | writeIfChanged(file, await page.screenshot({ clip: { x: 0, y: 0, width: WIDTH, height: Math.max(h, 40) }, animations: 'allow', caret: 'hide' })); |
| 261 | out[theme] = posixRelative(CONF, file); |
| 262 | await ctx.close(); |
| 263 | } |
| 264 | return out; |
| 265 | } |
| 266 |
| 267 | /** |
| 268 | * The client's time over the bottom corner of a picture `height` CSS px tall, as the dev app draws it over a bubble |
| 269 | * (reference.ts `timeCornerStyle`): outside the widget's document flow, on top of everything. |
| 270 | */ |
| 271 | async function drawTime(page: Page, area: Partial<ContentSafeArea>, height: number) { |
| 272 | const style = timeCornerStyle(area); |
| 273 | if (!style) return; |
| 274 | await page.evaluate(({ style, height, label }) => { |
| 275 | const box = document.createElement('div'); |
| 276 | box.style.cssText = `position:absolute;left:0;top:0;width:100%;height:${height}px;pointer-events:none;z-index:2147483647`; |
| 277 | const time = document.createElement('div'); |
| 278 | time.setAttribute('style', style); |
| 279 | time.textContent = label; |
| 280 | box.appendChild(time); |
| 281 | document.documentElement.appendChild(box); |
| 282 | }, { style, height, label: REFERENCE_TIME_LABEL }); |
| 283 | } |
| 284 |
| 285 | /** The height gate: the widget's height at MAX_HEIGHT.width, drawn natively in reference mode. */ |
| 286 | async function measureHeight(browser: Browser, w: Widget, html: string): Promise<number> { |
| 287 | const ctx = await newContext(browser, 'light', MAX_HEIGHT.width); |
| 288 | const page = await openNative(ctx, html, 'ref', isSdk(w) ? 'mock' : 'palette', 'light', w.meta.message?.[0], w.meta.safeArea); |
| 289 | await waitStatus(page, ['done', 'awaiting'], 15_000); |
| 290 | await page.waitForTimeout(300); |
| 291 | const h = await page.evaluate(() => Math.ceil(document.documentElement.getBoundingClientRect().height)); |
| 292 | await ctx.close(); |
| 293 | return h; |
| 294 | } |
| 295 |
| 296 | /** Sanity check of a reftest: the stage drawn natively by the feature vs its template. */ |
| 297 | async function selfVsRef(browser: Browser, w: Widget, html: string): Promise<Record<string, number>> { |
| 298 | const res: Record<string, number> = {}; |
| 299 | const reftests = w.stages.filter((s) => s.reftest); |
| 300 | if (!reftests.length) return res; |
| 301 | const ctx = await newContext(browser, 'light'); |
| 302 | const page = await openNative(ctx, html, 'native'); |
| 303 | await waitStatus(page, ['done', 'awaiting'], 15_000); |
| 304 | await page.waitForTimeout(150); |
| 305 | for (const s of reftests) { |
| 306 | if (!s.themes.includes('light')) continue; |
| 307 | const buf = await page.locator(`[data-stage="${s.name}"]`).screenshot({ animations: 'allow', caret: 'hide' }); |
| 308 | const ref = refPath(w, s.name, 'chromium', 'light'); |
| 309 | if (fs.existsSync(ref)) res[s.name] = Math.round(diffStats(PNG.sync.read(buf), PNG.sync.read(fs.readFileSync(ref))).ink * 10000) / 10000; |
| 310 | } |
| 311 | await ctx.close(); |
| 312 | return res; |
| 313 | } |
| 314 |
| 315 | function writeIfChanged(file: string, data: string | Buffer) { |
| 316 | if (fs.existsSync(file) && Buffer.compare(fs.readFileSync(file), Buffer.from(data)) === 0) return; |
| 317 | fs.writeFileSync(file, data); |
| 318 | } |
| 319 |
| 320 | // ───────────── main ───────────── |
| 321 |
| 322 | /** The size gate: every widget is a v1 mini-widget, with a margin. */ |
| 323 | function checkSize(w: Widget, html: string): string | null { |
| 324 | const z = sizeOf(html); |
| 325 | return z.raw > SIZE_LIMIT.raw || z.zlib > SIZE_LIMIT.zlib |
| 326 | ? `${w.id}: ${z.zlib} B compressed, ${z.raw} B of HTML; the limit is ${SIZE_LIMIT.zlib} / ${SIZE_LIMIT.raw}` |
| 327 | : null; |
| 328 | } |
| 329 |
| 330 | /** --sizes: the built size of every widget and the gate, without a browser and without writing anything. */ |
| 331 | function sizesOnly(widgets: Widget[]) { |
| 332 | let over = 0; |
| 333 | for (const w of widgets) { |
| 334 | const html = withHarness(w), z = sizeOf(html), bad = checkSize(w, html); |
| 335 | if (bad) over++; |
| 336 | console.log(`${w.id.padEnd(40)} ${String(z.raw).padStart(6)} B zlib ${String(z.zlib).padStart(5)}${bad ? ` OVER by ${z.zlib - SIZE_LIMIT.zlib}` : ''}`); |
| 337 | } |
| 338 | if (over) { console.log(`\n${over} widget(s) over the limit (${SIZE_LIMIT.zlib} B compressed, ${SIZE_LIMIT.raw} B of HTML)`); process.exitCode = 1; } |
| 339 | } |
| 340 |
| 341 | async function main() { |
| 342 | const widgets = listWidgets(ONLY); |
| 343 | if (SIZES) return sizesOnly(widgets); |
| 344 | emitCatalogue(); |
| 345 | const ids = new Set(CATALOGUE.map((f) => f.id)); |
| 346 | const browsers: Record<string, Browser> = {}; |
| 347 | for (const e of ENGINES) { |
| 348 | try { browsers[e] = await (e === 'webkit' ? webkit : chromium).launch(); } |
| 349 | catch (err) { console.warn(`${e}: not available (${String((err as Error).message).split('\n')[0]}); skipping its references`); } |
| 350 | } |
| 351 | if (!browsers.chromium) throw new Error('chromium is required'); |
| 352 |
| 353 | const manifestFile = path.join(CONF, 'manifest.json'); |
| 354 | const prev = readJson<{ tests: any[] }>(manifestFile, { tests: [] }); |
| 355 | const entries = new Map<string, any>(prev.tests.map((t) => [t.id, t])); |
| 356 | const problems: string[] = []; |
| 357 | const tooLarge: string[] = []; |
| 358 | const tooTall: string[] = []; |
| 359 |
| 360 | for (const w0 of widgets) { |
| 361 | let html = withHarness(w0); |
| 362 | const w = parseWidget(w0.set, w0.stem, html); |
| 363 | process.stdout.write(`${w.id}: `); |
| 364 | const refs = NO_REFS ? (entries.get(w.id)?.stages ?? []).reduce((m: any, s: any) => ({ ...m, [s.name]: s.refs }), {}) : await renderRefs(browsers, w, html); |
| 365 | const refImages = w.set === 'visual' ? (NO_REFS ? entries.get(w.id)?.refImages ?? {} : await renderPictures(browsers.chromium, w, html)) : undefined; |
| 366 | const height = w.set === 'visual' ? await measureHeight(browsers.chromium, w, html) : undefined; |
| 367 | if (height !== undefined && height > MAX_HEIGHT.height && !w.meta.tall) tooTall.push(`${w.id}: ${height} px at ${MAX_HEIGHT.width} px wide`); |
| 368 | const size = sizeOf(html); |
| 369 | const bad = checkSize(w, html); |
| 370 | if (bad) tooLarge.push(bad); |
| 371 | writeIfChanged(w.file, html); |
| 372 |
| 373 | const native: Record<string, NativeResult> = {}; |
| 374 | for (const [engine, browser] of Object.entries(browsers)) { |
| 375 | const ctx = await newContext(browser, 'light'); |
| 376 | native[engine] = await runNative(ctx, w, html); |
| 377 | await ctx.close(); |
| 378 | } |
| 379 | const sanity = NO_REFS ? {} : await selfVsRef(browsers.chromium, w, html); |
| 380 |
| 381 | const checkKeys = new Map<string, { id: string; name: string; native: Record<string, string> }>(); |
| 382 | for (const [engine, r] of Object.entries(native)) { |
| 383 | for (const [id, name, st] of r.checks) { |
| 384 | const k = `${id}|${name}`; |
| 385 | const e = checkKeys.get(k) ?? { id, name, native: {} }; |
| 386 | e.native[engine] = st; |
| 387 | checkKeys.set(k, e); |
| 388 | } |
| 389 | } |
| 390 | const checks = [...checkKeys.values()]; |
| 391 | const covers = new Set<string>([...checks.map((c) => c.id), ...w.stages.flatMap((s) => s.covers), ...(w.meta.covers ?? []), ...(w.meta.host ?? []).map((h) => h.id)]); |
| 392 | covers.delete('harness'); |
| 393 | for (const c of covers) if (!ids.has(c)) problems.push(`${w.id}: unknown catalogue id ${c}`); |
| 394 | for (const c of checks) if (c.id === 'harness') problems.push(`${w.id}: harness error ${c.name}`); |
| 395 | for (const c of checks) { |
| 396 | const f = CATALOGUE.find((x) => x.id === c.id); |
| 397 | if (!isSdk(w) && f?.status === 'in' && c.native.chromium === 'fail') problems.push(`${w.id}: in-profile check fails in native Chromium: ${c.id} — ${c.name}`); |
| 398 | } |
| 399 | // Visual-set templates are illustrations (end states, motion diagrams), not reftests: only the auto set is checked. |
| 400 | // The template of an out feature's stage draws it neutralised, so a native engine differs from it by design. |
| 401 | const outOnly = (st?: { covers: string[] }) => !!st?.covers.length && st.covers.every((id) => CATALOGUE.find((x) => x.id === id)?.status === 'out'); |
| 402 | if (w.set === 'auto') for (const [s, d] of Object.entries(sanity)) { const st = w.stages.find((x) => x.name === s); if (d > 0.02 && !st?.xfail && !outOnly(st)) problems.push(`${w.id}: stage ${s} drawn natively differs from its template by ${(d * 100).toFixed(1)} %`); } |
| 403 | const stagePos = (i: number) => (w.set === 'auto' ? [...autoStagePos(i), w.stages[i].w, w.stages[i].h] : null); |
| 404 | entries.set(w.id, { |
| 405 | id: w.id, |
| 406 | set: w.set, |
| 407 | file: posixRelative(CONF, w.file), |
| 408 | title: w.meta.title, |
| 409 | hint: w.meta.hint, |
| 410 | kind: [checks.length ? 'self' : null, w.stages.length ? 'pixel' : null, w.meta.actions?.length ? 'interactive' : null].filter(Boolean), |
| 411 | covers: [...covers].sort(), |
| 412 | themes: w.meta.themes ?? (w.stages.some((s) => s.themes.includes('dark')) ? ['light', 'dark'] : ['light']), |
| 413 | widths: [360, 390, 430], |
| 414 | actions: w.meta.actions ?? [], |
| 415 | host: w.meta.host ?? [], |
| 416 | checks: checks.map((c) => ({ id: c.id, name: c.name, native: c.native })), |
| 417 | stages: w.stages.map((s, i) => ({ name: s.name, rect: stagePos(i), size: [s.w, s.h], covers: s.covers, themes: s.themes, reftest: s.reftest, maxDiff: s.maxDiff, colors: s.colors, xfail: s.xfail, refs: refs[s.name] ?? {}, nativeVsTemplate: sanity[s.name] })), |
| 418 | bytes: size.raw, |
| 419 | zlib: size.zlib, |
| 420 | ...(refImages ? { refImages } : {}), |
| 421 | ...(height !== undefined ? { height } : {}), |
| 422 | ...(isSdk(w) ? { group: 'sdk', expect: w.meta.expect, contract: w.meta.contract, pending: w.meta.pending } : {}), |
| 423 | ...(w.meta.stops ? { stops: w.meta.stops } : {}), |
| 424 | ...(w.meta.safeArea ? { safeArea: w.meta.safeArea } : {}), |
| 425 | ...(w.meta.message ? { message: w.meta.message } : {}), |
| 426 | ...(w.meta.bot ? { bot: w.meta.bot } : {}), |
| 427 | }); |
| 428 | const n = native.chromium.checks.reduce((m: Record<string, number>, c) => ({ ...m, [c[2]]: (m[c[2]] ?? 0) + 1 }), {}); |
| 429 | console.log(`${checks.length} checks (chromium: ${Object.entries(n).map(([k, v]) => `${k} ${v}`).join(', ')}), ${w.stages.length} stages, ${(size.raw / 1024).toFixed(1)} KB (${size.zlib} B compressed)${bad ? ' TOO LARGE' : ''}${height !== undefined ? `, ${height} px tall${tooTall.at(-1)?.startsWith(w.id + ':') ? ' TOO TALL' : ''}` : ''}`); |
| 430 | } |
| 431 | for (const b of Object.values(browsers)) await b.close(); |
| 432 |
| 433 | // Drop entries of widgets that no longer exist. |
| 434 | const all = new Set(listWidgets().map((w) => w.id)); |
| 435 | for (const k of [...entries.keys()]) if (!all.has(k)) entries.delete(k); |
| 436 | const tests = [...entries.values()].sort((a, b) => a.id.localeCompare(b.id)); |
| 437 | const coverage = (set: string) => new Set(tests.filter((t) => t.set === set).flatMap((t) => t.covers)); |
| 438 | const auto = coverage('auto'), visual = coverage('visual'); |
| 439 | // Covered by other suites of this repository (they kill or flood the widget, which a conformance widget cannot report on itself). |
| 440 | const external: Record<string, string> = { |
| 441 | 'limit.nodes': 'corpus/attacks (pnpm test:attacks): node flood', |
| 442 | 'limit.cpu': 'corpus/attacks and tests/lifecycle.spec.ts: CPU quota, deferral, kill', |
| 443 | 'limit.memory': 'corpus/attacks (pnpm test:attacks): memory cap', |
| 444 | 'limit.html-size': 'server-side (D20): not a client check', |
| 445 | // Client behaviour around the widget: judged by people with the client-SDK group (visual/sdk). |
| 446 | 'behaviour.restart': 'visual/sdk/11-crash-restart (client behaviour)', |
| 447 | 'behaviour.gesture-claim': 'visual/sdk/12-drag-gestures (client behaviour)', |
| 448 | 'behaviour.storage-persist': 'visual/sdk/07, 08, 09 (client behaviour)', |
| 449 | 'behaviour.storage-forward': 'visual/sdk/15-storage-forward (client behaviour)', |
| 450 | 'behaviour.message-edit': 'visual/sdk/16-state-edit (client behaviour)', |
| 451 | 'behaviour.data-edit': 'visual/sdk/16-state-edit, 24-watch-public-data, 25-group-chat-state (client behaviour)', |
| 452 | 'behaviour.forward-copy': 'visual/sdk/20-forward-requests and auto/26-context-copy, -live-copy viewed as forwards (client behaviour)', |
| 453 | 'behaviour.preview': 'visual/sdk/23-preview and auto/26-context-preview in the inline results (client behaviour)', |
| 454 | 'behaviour.network-marker': 'visual/sdk/21-network-marker (client behaviour)', |
| 455 | 'behaviour.resize-anchor': 'visual/sdk/18-resize-anchor (client behaviour)', |
| 456 | 'behaviour.size-hint': 'visual/sdk/17-size-hint (client behaviour)', |
| 457 | 'behaviour.time-corner': 'visual/17-time-corner, sent without a caption (client behaviour)', |
| 458 | }; |
| 459 | const needAuto = CATALOGUE.filter((f) => f.status !== 'out' && !auto.has(f.id) && !external[f.id]).map((f) => f.id); |
| 460 | const outUncovered = CATALOGUE.filter((f) => f.status === 'out' && !auto.has(f.id)).map((f) => f.id); |
| 461 | const manifest = { |
| 462 | $comment: 'Generated by scripts/conformance/build.ts. One entry per widget of packages/conformance/{auto,visual}; checks[].native = what plain browser engines answer (a sanity reference for the test, not the expectation: out-of-profile and sandbox-only checks differ by design).', |
| 463 | version: 1, |
| 464 | catalogue: 'catalogue.json', |
| 465 | render: { widths: [360, 390, 430], themes: ['light', 'dark'], dpr: DPR, referenceWidth: WIDTH, stageGrid: AUTO_GRID }, |
| 466 | coverage: { auto: auto.size, visual: visual.size, catalogue: CATALOGUE.length, external, notInAuto: needAuto, outNotInAuto: outUncovered }, |
| 467 | tests, |
| 468 | }; |
| 469 | fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 1) + '\n'); |
| 470 | // The client-SDK group's post list for the test channel, from the manifest. |
| 471 | const sdk = tests.filter((t) => t.group === 'sdk'); |
| 472 | if (sdk.length) { |
| 473 | const lines = [ |
| 474 | '# Client SDK group: what each client implements on its side of SDK v1', |
| 475 | '', |
| 476 | 'Generated by `scripts/conformance/build.ts` from the widget headers. Contract: `docs/sdk-v1.md`. Each widget is a v1 mini-widget (at most 4 KB compressed, 32 KB of HTML); post it as a widget message with its picture as a separate image next to it (two pictures: light and dark). A tester does what the instruction says and checks the client against the expected behaviour. Rows marked *waits* need server support first; they are here so the client side can be built against them. *Sent as* says how the test bot sends the widget (the `inputMediaWidget` fields, the chat, a forward, the inline results) and *The bot* what it does on the widget\'s requests (`scripts/conformance/test-bot.ts`, `CLIENTS.md`).', |
| 477 | '', |
| 478 | '| # | Widget | Picture | The tester | The client must | Sent as · the bot | Contract | zlib |', |
| 479 | '|---|---|---|---|---|---|---|---|', |
| 480 | ...sdk.map((t) => `| ${t.id.split('/').pop().slice(0, 2)} | [${t.title}](${path.basename(t.file)})${t.pending ? `<br>*waits: ${t.pending}*` : ''} | ${Object.entries(t.refImages ?? {}).map(([k, v]) => `[${k}](../../${v})`).join(' · ')} | ${t.hint ?? ''} | ${t.expect ?? ''} | ${sentAs(t.message, t.bot) || '—'} | ${t.contract ?? ''} | ${(t.zlib / 1024).toFixed(1)} KB |`.replace(/\n/g, ' ')), |
| 481 | '', |
| 482 | ]; |
| 483 | fs.writeFileSync(path.join(CONF, 'visual', 'sdk', 'README.md'), lines.join('\n')); |
| 484 | } |
| 485 | writeChannel(tests); |
| 486 | emitCatalogue(); |
| 487 | console.log(`\nmanifest: ${tests.length} widgets; auto covers ${auto.size}, visual ${visual.size} of ${CATALOGUE.length}; in/candidate not in auto: ${needAuto.length}; out not in auto: ${outUncovered.length}`); |
| 488 | if (needAuto.length) console.log(' not covered by auto: ' + needAuto.join(', ')); |
| 489 | if (problems.length) { console.log('\nproblems:'); for (const p of problems) console.log(' ' + p); } |
| 490 | if (tooLarge.length) { |
| 491 | console.log(`\ntoo large for a mini-widget (${SIZE_LIMIT.zlib} B compressed, ${SIZE_LIMIT.raw} B of HTML):`); |
| 492 | for (const p of tooLarge) console.log(' ' + p); |
| 493 | process.exitCode = 1; |
| 494 | } |
| 495 | // Through the sandbox, on the dev app: the automatic set's height gate (drawn natively an automatic widget also |
| 496 | // lists the out-of-profile checks Chromium fails, so the native height is not the client's), and the pictures just |
| 497 | // drawn against the pipeline (the widget files as written above). |
| 498 | const measured = args.includes('--no-heights') ? [] : widgets.filter((w) => w.set === 'auto'); |
| 499 | const pictured = NO_REFS ? [] : listWidgets(ONLY).filter((w) => w.set === 'visual'); |
| 500 | let differ: string[] = []; |
| 501 | if (measured.length || pictured.length) await withDevServer(async (origin) => { |
| 502 | if (measured.length) { |
| 503 | console.log(`\nheights of the automatic set through the sandbox (${origin}):`); |
| 504 | tooTall.push(...(await measureHeights(measured, origin, 'shadow', [MAX_HEIGHT.width], (line) => console.log(' ' + line)))); |
| 505 | } |
| 506 | if (pictured.length) { |
| 507 | console.log(`\nthe visual set's pictures against the widget drawn through the sandbox (${origin}):`); |
| 508 | differ = await checkPictures(pictured, origin, 'shadow', (line) => console.log(' ' + line)); |
| 509 | } |
| 510 | }); |
| 511 | if (tooTall.length) { |
| 512 | console.log(`\ntaller than ${MAX_HEIGHT.height} px at a ${MAX_HEIGHT.width} px bubble (the cap is 600; split the widget, or "tall": true for a test of the cap):`); |
| 513 | for (const p of tooTall) console.log(' ' + p); |
| 514 | process.exitCode = 1; |
| 515 | } |
| 516 | if (differ.length) { |
| 517 | console.log('\npictures that differ from the widget drawn through the sandbox (an out-of-profile feature drawn by Chromium: neutralise it in reference mode; or a pipeline bug; diffs in reports/conformance/pictures):'); |
| 518 | for (const p of differ) console.log(' ' + p); |
| 519 | process.exitCode = 1; |
| 520 | } |
| 521 | } |
| 522 |
| 523 | /** |
| 524 | * Size anchors (inputMediaWidget width / height, CSS px, 0 = auto) for widgets the test bot sends more than |
| 525 | * once or with a size: a header's "anchors" ([[width, height], …]) wins. 17-size-hint is sent four times, one per anchor case of its hint (0×0, 0×300, 300×0, 300×300). |
| 526 | */ |
| 527 | const ANCHORS: Record<string, [number, number][]> = { 'visual/sdk/17-size-hint': [[0, 0], [0, 300], [300, 0], [300, 300]] }; |
| 528 |
| 529 | /** Runs `fn` on the dev app: --origin's, or a dev server the build starts for it on a free port. */ |
| 530 | async function withDevServer(fn: (origin: string) => Promise<void>): Promise<void> { |
| 531 | let origin = opt('origin'); |
| 532 | let server: ReturnType<typeof spawn> | undefined; |
| 533 | if (!origin) { |
| 534 | const port = await new Promise<number>((resolve) => { const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = (s.address() as net.AddressInfo).port; s.close(() => resolve(p)); }); }); |
| 535 | origin = `http://127.0.0.1:${port}`; |
| 536 | server = spawn('corepack', ['pnpm', 'dev', '--port', String(port)], { cwd: ROOT, stdio: 'ignore', detached: true }); |
| 537 | const t0 = Date.now(); |
| 538 | for (;;) { |
| 539 | try { if ((await fetch(origin)).ok) break; } catch {} |
| 540 | if (Date.now() - t0 > 90_000) { process.kill(-server.pid!); throw new Error(`the dev server for the checks through the sandbox did not start on ${origin}`); } |
| 541 | await new Promise((r) => setTimeout(r, 500)); |
| 542 | } |
| 543 | } |
| 544 | try { await fn(origin); } |
| 545 | finally { if (server) process.kill(-server.pid!); } |
| 546 | } |
| 547 |
| 548 | /** One message spec in words (the README's Sent as column, a post's caption). */ |
| 549 | export function describeMessage(m: MessageSpec): string { |
| 550 | const where = m.inline ? 'an inline result for the query conf-preview' : m.chat === 'group' ? 'the test group' : 'the private chat'; |
| 551 | const flags = (['allow_queries', 'fwd_allow_queries', 'shared_widget'] as const).filter((f) => m[f]); |
| 552 | const data = (['chat_data', 'public_data'] as const).filter((f) => m[f] !== undefined).map((f) => `${f} ${JSON.stringify(m[f])}`); |
| 553 | return [`${m.kind}: ${where}`, flags.length ? flags.join(', ') : 'no flags', ...data, m.forward ? 'then forwarded' : ''].filter(Boolean).join(', '); |
| 554 | } |
| 555 | /** What the test bot does for one request data. */ |
| 556 | export function describeBot(data: string, a: BotAction): string { |
| 557 | const parts = [ |
| 558 | a.edit ? `editMessageWidgetData ${Object.entries(a.edit).map(([k, v]) => `${k} ${JSON.stringify(v)}`).join(', ')}` : '', |
| 559 | a.editShared ? `editWidgetData public_data ${JSON.stringify(a.editShared.public_data)}${a.editShared.cache_time !== undefined ? `, cache_time ${a.editShared.cache_time}` : ''}` : '', |
| 560 | a.repeat ? `every ${a.repeat.every} s, ${a.repeat.times} times` : '', |
| 561 | a.result !== undefined ? `result ${JSON.stringify(a.result)}` : 'an empty answer', |
| 562 | ].filter(Boolean); |
| 563 | return `\`${data}\` → ${parts.join('; ')}`; |
| 564 | } |
| 565 | function sentAs(message?: MessageSpec[], bot?: Record<string, BotAction>): string { |
| 566 | return [...(message ?? []).map(describeMessage), ...Object.entries(bot ?? {}).map(([d, a]) => describeBot(d, a))].join('<br>'); |
| 567 | } |
| 568 |
| 569 | /** channel.json: the test channel's posting order (the visual set, the client-SDK group, then the automatic set), one entry per message. */ |
| 570 | function writeChannel(tests: any[]) { |
| 571 | const order = (t: any) => (t.set === 'visual' ? (t.group === 'sdk' ? 1 : 0) : 2); |
| 572 | const posts: any[] = []; |
| 573 | const bot: Record<string, { case: string; action: BotAction }> = {}; |
| 574 | for (const t of [...tests].sort((a, b) => order(a) - order(b) || a.id.localeCompare(b.id))) { |
| 575 | const header = parseWidget(t.set, t.id.slice(t.set.length + 1), fs.readFileSync(path.join(CONF, t.file), 'utf8')).meta as any; |
| 576 | const check = t.set === 'auto' |
| 577 | ? 'the widget checks itself: its result line at the bottom must say "done" and show no "fail" (each failure is listed under it)' |
| 578 | : t.group === 'sdk' ? `${t.hint ?? ''} The client must: ${t.expect ?? ''}` : t.hint ?? 'compare with the picture'; |
| 579 | const messages: (MessageSpec | undefined)[] = header.message ?? [undefined]; |
| 580 | // The client draws its time over a widget with no caption below it (docs/sdk-v1.md §2.17): a case of it goes out |
| 581 | // without a caption, then with its caption above the widget (invert_media), which must look the same. |
| 582 | const captions: ('none' | 'above' | undefined)[] = header.safeArea ? ['none', 'above'] : [undefined]; |
| 583 | for (const message of messages) for (const captionAt of captions) for (const [width, height] of header.anchors ?? ANCHORS[t.id] ?? [[0, 0]]) { |
| 584 | const view = message ? ` Sent as ${describeMessage(message)}${message.view ? `; look at ${message.view}` : ''}.` : ''; |
| 585 | const placed = captionAt === 'none' ? ' Sent without a caption: your time over the widget\'s bottom corner.' |
| 586 | : captionAt === 'above' ? ' Sent with its caption above the widget (invert_media): your time over the widget\'s bottom corner, as without a caption.' : ''; |
| 587 | posts.push({ |
| 588 | widget: t.file, |
| 589 | width, height, |
| 590 | ...(message ? { message, ...(messages.length > 1 ? { variant: message.kind } : {}) } : {}), |
| 591 | ...(captionAt === 'none' ? { withoutCaption: true } : captionAt === 'above' ? { captionAbove: true, variant: 'caption-above' } : {}), |
| 592 | caption: `${t.id} · ${t.title}. ${check}${view}${placed && !/\.\s*$/.test(check + view) ? '.' : ''}${placed}`.replace(/\s+/g, ' ').trim(), |
| 593 | photos: Object.values(t.refImages ?? {}), |
| 594 | zlib: t.zlib, |
| 595 | ...(t.pending ? { pending: t.pending } : {}), |
| 596 | }); |
| 597 | } |
| 598 | for (const [data, action] of Object.entries((header.bot ?? {}) as Record<string, BotAction>)) { |
| 599 | if (bot[data] && JSON.stringify(bot[data].action) !== JSON.stringify(action)) throw new Error(`${t.id}: bot data ${data} is also used by ${bot[data].case} with another action`); |
| 600 | bot[data] = { case: t.id, action }; |
| 601 | } |
| 602 | } |
| 603 | const channel = { |
| 604 | $comment: 'Generated by scripts/conformance/build.ts: the test channel, in posting order. A test bot sends each widget as a layer-233 message (inputMediaWidget: html = the file, width / height = the anchors, 0 = auto) with its caption (none with `withoutCaption`, shown above the widget with `captionAbove`, Bot API show_caption_above_media / layer-233 invert_media: the client then draws the message time over the bottom corner of the widget, docs/sdk-v1.md §2.17), then the photos (the reference pictures, light then dark) as a separate message next to it. A post with `message` is sent with those fields (allow_queries, fwd_allow_queries, shared_widget, chat_data, public_data), into the test group when chat is group, forwarded by the tester when forward, or as the inline result for the query conf-preview when inline; its kind is the message context the client must report where the tester looks. `bot`: what the test bot does on a widget_query with that data (scripts/conformance/test-bot.ts; templates {n}, {from}, {time}).', |
| 605 | version: 1, |
| 606 | posts, |
| 607 | bot, |
| 608 | }; |
| 609 | fs.writeFileSync(path.join(CONF, 'channel.json'), JSON.stringify(channel, null, 1) + '\n'); |
| 610 | } |
| 611 |
| 612 | main().catch((e) => { console.error(e); process.exit(1); }); |
| 613 |