/** * The verifier page (DESIGN §4-2, M3): type the seed shown after a game (32 hex characters) and see the fingerprint and the first N rolls, * computed by the very same `core/dice.ts` the game runs (imported directly, no copy), so the page cannot disagree with the app. Also checks the * "Huella de los dados" the game showed before roll #1, and works out the daily seed of any date. `verify` is pure (verificar.test.ts checks it * against the core for 20 sampled seeds); the DOM part below only runs in the browser. The page prefills from `#seed=<32 hex>[&n=]` so the * app's end screen can open it with the seed of the finished game. Model: apps/scopa/src/verifica.ts. */ import { dailySeed, fingerprint, fingerprintCommand, legacyFingerprint, rollList, seedText } from '../src/core/dice.ts'; export const DEFAULT_ROLLS = 60; export const MAX_ROLLS = 2000; export interface Verification { /** The seed as 32 lowercase hex characters. */ seed: string; fingerprint: string; /** The one-line shell command that prints the same fingerprint (first 8 characters of its output). */ command: string; rolls: number[]; /** How many times each face 1-6 appears among `rolls`. */ counts: number[]; } /** Reads the page's hash: `#seed=<32 hex>[&n=]`. Null when there is no seed in it. */ export function parseHash(hash: string): { seed: string; n: number } | null { const m = /^#seed=([0-9a-fA-F]{32})(?:&n=(\d{1,6}))?$/.exec(hash); return m ? { seed: m[1]!.toLowerCase(), n: clampRolls(m[2] ? Number(m[2]) : DEFAULT_ROLLS) } : null; } export const hashFor = (seed: string, n = DEFAULT_ROLLS): string => `#seed=${seed}${n === DEFAULT_ROLLS ? '' : `&n=${n}`}`; export const clampRolls = (n: number): number => (Number.isFinite(n) ? Math.min(MAX_ROLLS, Math.max(1, Math.floor(n))) : DEFAULT_ROLLS); /** Seed text (any case, spaces ignored) → everything the page prints. Throws on a seed that is not 32 hex characters. */ export function verify(text: string, n = DEFAULT_ROLLS): Verification { const seed = seedText(text); const rolls = rollList(seed, clampRolls(n)); const counts = [0, 0, 0, 0, 0, 0]; for (const f of rolls) counts[f - 1]++; return { seed, fingerprint: fingerprint(seed), command: fingerprintCommand(seed), rolls, counts }; } /** * Does the fingerprint the game showed before roll #1 match this seed? Case and spaces ignored; false for anything that is not 8 hex characters. * A game started before fix round 1 showed the older value (SHA-256 of the raw bytes): it is accepted too, so no old game reads as a mismatch. */ export const fingerprintMatches = (text: string, shown: string): boolean => { const f = shown.replace(/\s+/g, '').toLowerCase(); return /^[0-9a-f]{8}$/.test(f) && (f === fingerprint(text) || f === legacyFingerprint(text)); }; const ymdOf = (d: Date): string => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; /** The device's local date as YYYY-MM-DD (the date the daily game of this device uses). */ export const localToday = (now: Date = new Date()): string => ymdOf(now); /** * The seed of the daily game of a date (the same for everyone): SHA-256 of "parchis-daily-v1|YYYY-MM-DD". Any valid date works, today's * included (DECISIONS D25: the derivation is public by design, so a "come back after midnight" block only broke the honest link from the end * card; the daily has no leaderboard or prize). Throws for something that is not a date. */ export function dailyFor(ymd: string): string { if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) throw new Error('daily bad'); return dailySeed(ymd); } // ---------- the page ---------- const T = { es: { lead: 'Escribe la semilla (32 caracteres hexadecimales) que muestra el juego al terminar la partida. La página calcula la huella y las primeras tiradas con el mismo código que usa el juego.', seed: 'Semilla', go: 'Verificar', bad: 'La semilla debe tener 32 caracteres hexadecimales (0-9, a-f); los espacios no importan.', fp: 'Huella de los dados', fpNote: 'Los 8 primeros caracteres de SHA-256 del texto de la semilla (32 caracteres hexadecimales en minúscula, sin espacios). El juego la muestra antes de la primera tirada: si coincide con esta, los dados son los de esta semilla.', cmd: 'Compruébalo tú mismo en una terminal (los 8 primeros caracteres del resultado):', shown: 'La huella que vio el juego (opcional)', match: 'Coincide: la partida usó esta semilla.', nomatch: 'No coincide: esta semilla no es la de esa partida.', rolls: 'Primeras tiradas', rollsNote: 'En orden, la tirada nº 1 primero. El juego las usa en este mismo orden, repartidas entre los jugadores según el turno; ninguna depende de cómo vas jugando.', count: 'Cuántas tiradas', faces: 'Caras en estas tiradas', daily: 'Partida del día', dailyNote: 'La semilla del día es SHA-256 de «parchis-daily-v1|AAAA-MM-DD» (primeros 16 bytes): la misma para todos ese día.', date: 'Fecha', source: 'Código fuente', sourceNote: 'Cada tirada depende solo de la semilla y de su número: ningún movimiento, nivel, marcador ni reloj entra en el cálculo.', honest: 'El juego se compromete con la semilla antes de que juegues (la huella) y te la enseña después, para que puedas comprobar las tiradas. No afirmamos más que eso.', }, en: { lead: 'Enter the seed (32 hexadecimal characters) the game shows when a game ends. The page works out the fingerprint and the first rolls with the same code the game runs.', seed: 'Seed', go: 'Verify', bad: 'The seed must be 32 hexadecimal characters (0-9, a-f); spaces do not matter.', fp: 'Dice fingerprint', fpNote: 'The first 8 characters of SHA-256 of the seed text (32 lowercase hexadecimal characters, no spaces). The game shows it before roll #1: if it matches, the dice are the ones of this seed.', cmd: 'Check it yourself in a terminal (the first 8 characters of the output):', shown: 'The fingerprint the game showed (optional)', match: 'It matches: the game used this seed.', nomatch: 'No match: this is not the seed of that game.', rolls: 'First rolls', rollsNote: 'In order, roll #1 first. The game uses them in this same order, handed to the players by turn; none depends on how you play.', count: 'How many rolls', faces: 'Faces in these rolls', daily: 'Daily game', dailyNote: 'The daily seed is SHA-256 of "parchis-daily-v1|YYYY-MM-DD" (first 16 bytes): the same for everyone that day.', date: 'Date', source: 'Source code', sourceNote: 'Each roll depends only on the seed and its number: no move, level, score or clock goes into it.', honest: 'The game commits to the seed before you play (the fingerprint) and shows it afterwards so you can check the rolls. We claim no more than that.', }, "pt-BR": { lead: "Digite a semente (32 caracteres hexadecimais) que o jogo mostra ao fim da partida. A página calcula a digital e os primeiros lances com o mesmo código que o jogo usa.", seed: "Semente", go: "Verificar", bad: "A semente deve ter 32 caracteres hexadecimais (0-9, a-f); os espaços não importam.", fp: "Digital dos dados", fpNote: "Os 8 primeiros caracteres do SHA-256 do texto da semente (32 caracteres hexadecimais minúsculos, sem espaços). O jogo a mostra antes do primeiro lance: se coincidir com esta, os dados são os desta semente.", cmd: "Confira você mesmo num terminal (os 8 primeiros caracteres do resultado):", shown: "A digital que o jogo mostrou (opcional)", match: "Coincide: a partida usou esta semente.", nomatch: "Não coincide: esta não é a semente daquela partida.", rolls: "Primeiros lances", rollsNote: "Em ordem, o lance nº 1 primeiro. O jogo os usa nesta mesma ordem, distribuídos entre os jogadores conforme o turno; nenhum depende de como você joga.", count: "Quantos lances", faces: "Faces nestes lances", daily: "Partida do dia", dailyNote: "A semente do dia é o SHA-256 de “parchis-daily-v1|YYYY-MM-DD” (primeiros 16 bytes): a mesma para todos naquele dia.", date: "Data", source: "Código-fonte", sourceNote: "Cada lance depende só da semente e do seu número: nenhum movimento, nível, placar ou relógio entra no cálculo.", honest: "O jogo se compromete com a semente antes de você jogar (a digital) e a mostra depois, para você conferir os lances. Não afirmamos nada além disso.", }, de: { lead: "Gib den Startwert (32 Hexadezimalzeichen) ein, den das Spiel am Ende zeigt. Die Seite berechnet den Fingerabdruck und die ersten Würfe mit demselben Code wie das Spiel.", seed: "Startwert", go: "Prüfen", bad: "Der Startwert muss aus 32 Hexadezimalzeichen bestehen (0-9, a-f); Leerzeichen sind egal.", fp: "Würfel-Fingerabdruck", fpNote: "Die ersten 8 Zeichen des SHA-256 des Startwert-Textes (32 kleine Hexadezimalzeichen, ohne Leerzeichen). Das Spiel zeigt ihn vor Wurf 1: stimmt er mit diesem überein, stammen die Würfel aus diesem Startwert.", cmd: "Prüf es selbst im Terminal (die ersten 8 Zeichen der Ausgabe):", shown: "Der Fingerabdruck aus dem Spiel (optional)", match: "Stimmt überein: das Spiel nutzte diesen Startwert.", nomatch: "Stimmt nicht: das ist nicht der Startwert dieses Spiels.", rolls: "Erste Würfe", rollsNote: "Der Reihe nach, Wurf 1 zuerst. Das Spiel nutzt sie in genau dieser Reihenfolge und verteilt sie nach Zug auf die Spieler; keiner hängt davon ab, wie du spielst.", count: "Wie viele Würfe", faces: "Augen in diesen Würfen", daily: "Tagesspiel", dailyNote: "Der Tages-Startwert ist SHA-256 von „parchis-daily-v1|YYYY-MM-DD“ (erste 16 Bytes): für alle an diesem Tag gleich.", date: "Datum", source: "Quellcode", sourceNote: "Jeder Wurf hängt nur vom Startwert und seiner Nummer ab: kein Zug, kein Level, kein Spielstand und keine Uhr fließt ein.", honest: "Das Spiel legt sich vor dem Spielen auf den Startwert fest (der Fingerabdruck) und zeigt ihn danach, damit du die Würfe prüfen kannst. Mehr behaupten wir nicht.", }, fr: { lead: "Saisis la graine (32 caractères hexadécimaux) que le jeu affiche à la fin d'une partie. La page calcule l'empreinte et les premiers lancers avec le même code que le jeu.", seed: "Graine", go: "Vérifier", bad: "La graine doit compter 32 caractères hexadécimaux (0-9, a-f) ; les espaces ne comptent pas.", fp: "Empreinte des dés", fpNote: "Les 8 premiers caractères du SHA-256 du texte de la graine (32 caractères hexadécimaux en minuscules, sans espaces). Le jeu l'affiche avant le lancer n° 1 : si elle correspond à celle-ci, les dés sont ceux de cette graine.", cmd: "Vérifie-le toi-même dans un terminal (les 8 premiers caractères du résultat) :", shown: "L'empreinte affichée par le jeu (facultatif)", match: "Ça correspond : la partie a utilisé cette graine.", nomatch: "Ça ne correspond pas : ce n'est pas la graine de cette partie.", rolls: "Premiers lancers", rollsNote: "Dans l'ordre, le lancer n° 1 d'abord. Le jeu les utilise dans ce même ordre, répartis entre les joueurs selon le tour ; aucun ne dépend de ta façon de jouer.", count: "Nombre de lancers", faces: "Faces dans ces lancers", daily: "Partie du jour", dailyNote: "La graine du jour est le SHA-256 de « parchis-daily-v1|YYYY-MM-DD » (16 premiers octets) : la même pour tous ce jour-là.", date: "Date", source: "Code source", sourceNote: "Chaque lancer ne dépend que de la graine et de son numéro : aucun coup, niveau, score ni horloge n'entre dans le calcul.", honest: "Le jeu s'engage sur la graine avant que tu joues (l'empreinte) et te la montre après, pour que tu puisses vérifier les lancers. Nous n'affirmons rien de plus.", }, id: { lead: "Masukkan seed (32 karakter heksadesimal) yang ditampilkan game saat game berakhir. Halaman ini menghitung sidik jari dan lemparan pertama dengan kode yang sama dengan game.", seed: "Seed", go: "Verifikasi", bad: "Seed harus 32 karakter heksadesimal (0-9, a-f); spasi tidak masalah.", fp: "Sidik jari dadu", fpNote: "8 karakter pertama SHA-256 dari teks seed (32 karakter heksadesimal huruf kecil, tanpa spasi). Game menampilkannya sebelum lemparan #1: kalau cocok dengan ini, dadunya berasal dari seed ini.", cmd: "Cek sendiri di terminal (8 karakter pertama hasilnya):", shown: "Sidik jari yang ditampilkan game (opsional)", match: "Cocok: game itu memakai seed ini.", nomatch: "Tidak cocok: ini bukan seed game itu.", rolls: "Lemparan pertama", rollsNote: "Berurutan, lemparan #1 lebih dulu. Game memakainya dalam urutan yang sama, dibagikan ke pemain sesuai giliran; tidak ada yang bergantung pada caramu bermain.", count: "Jumlah lemparan", faces: "Mata dadu dalam lemparan ini", daily: "Game harian", dailyNote: "Seed harian adalah SHA-256 dari “parchis-daily-v1|YYYY-MM-DD” (16 byte pertama): sama untuk semua orang hari itu.", date: "Tanggal", source: "Kode sumber", sourceNote: "Setiap lemparan hanya bergantung pada seed dan nomornya: tidak ada langkah, level, skor, atau jam yang ikut dihitung.", honest: "Game mengunci seed sebelum kamu bermain (sidik jari) dan menunjukkannya setelahnya, supaya kamu bisa mengecek lemparannya. Kami tidak mengklaim lebih dari itu.", }, ko: { lead: "게임이 끝날 때 보여 주는 시드(16진수 32자)를 입력하세요. 이 페이지는 게임과 같은 코드로 지문과 처음 굴림들을 계산해요.", seed: "시드", go: "검증", bad: "시드는 16진수 32자(0-9, a-f)여야 해요. 공백은 상관없어요.", fp: "주사위 지문", fpNote: "시드 텍스트(소문자 16진수 32자, 공백 없음)의 SHA-256 앞 8자리예요. 게임은 첫 굴림 전에 이 값을 보여 줘요. 여기 값과 같으면 그 주사위는 이 시드에서 나온 거예요.", cmd: "터미널에서 직접 확인해 보세요 (결과의 앞 8자리):", shown: "게임에서 본 지문 (선택)", match: "일치해요: 이 게임은 이 시드를 썼어요.", nomatch: "일치하지 않아요: 이 시드는 그 게임의 시드가 아니에요.", rolls: "처음 굴림", rollsNote: "1번 굴림부터 순서대로예요. 게임은 이 순서 그대로 차례에 따라 플레이어들에게 나눠 써요. 어떤 굴림도 플레이 방식에 따라 달라지지 않아요.", count: "굴림 개수", faces: "이 굴림들의 눈", daily: "오늘의 게임", dailyNote: "오늘의 게임 시드는 “parchis-daily-v1|YYYY-MM-DD”의 SHA-256(앞 16바이트)이에요. 그날은 모두에게 같아요.", date: "날짜", source: "소스 코드", sourceNote: "각 굴림은 시드와 굴림 번호에만 달려 있어요. 이동, 레벨, 점수, 시계는 계산에 들어가지 않아요.", honest: "게임은 플레이 전에 시드를 약속하고(지문), 끝난 뒤 보여 줘서 굴림을 확인할 수 있게 해요. 우리가 주장하는 건 거기까지예요.", }, ja: { lead: "対局終了時に表示されるシード(16進数32文字)を入力してください。このページはゲームと同じコードで指紋と最初の出目を計算します。", seed: "シード", go: "検証", bad: "シードは16進数32文字(0-9、a-f)です。スペースは関係ありません。", fp: "サイコロの指紋", fpNote: "シードの文字列(小文字の16進数32文字、スペースなし)のSHA-256の最初の8文字です。ゲームは1回目の出目の前にこれを表示します。ここと一致すれば、そのサイコロはこのシードのものです。", cmd: "ターミナルで自分で確認できます(結果の最初の8文字):", shown: "ゲームで表示された指紋(任意)", match: "一致:この対局はこのシードを使いました。", nomatch: "不一致:このシードはその対局のものではありません。", rolls: "最初の出目", rollsNote: "1回目から順番に並んでいます。ゲームはこの順番のまま、手番に従って各プレイヤーに配ります。どの出目もあなたの打ち方には左右されません。", count: "出目の数", faces: "これらの出目の内訳", daily: "今日の一局", dailyNote: "今日の一局のシードは「parchis-daily-v1|YYYY-MM-DD」のSHA-256(最初の16バイト)です。その日は全員同じです。", date: "日付", source: "ソースコード", sourceNote: "各出目はシードと何回目かだけで決まります。手、レベル、スコア、時計は計算に入りません。", honest: "ゲームはプレイ前にシードを約束し(指紋)、終了後に見せるので、出目を確認できます。私たちが主張するのはそこまでです。", }, "zh-Hans": { lead: "输入对局结束时游戏显示的种子(32 个十六进制字符)。本页用与游戏相同的代码算出指纹和前几次掷骰。", seed: "种子", go: "验证", bad: "种子必须是 32 个十六进制字符(0-9、a-f);空格不影响。", fp: "骰子指纹", fpNote: "种子文本(32 个小写十六进制字符,无空格)的 SHA-256 的前 8 个字符。游戏在第 1 次掷骰前显示它:如果与这里一致,骰子就来自这个种子。", cmd: "在终端里自己验证(输出的前 8 个字符):", shown: "游戏显示的指纹(可选)", match: "一致:这局使用的就是这个种子。", nomatch: "不一致:这不是那局的种子。", rolls: "前几次掷骰", rollsNote: "按顺序排列,第 1 次在最前。游戏按同样的顺序使用它们,按回合分给各位玩家;没有一次取决于你怎么下。", count: "掷骰次数", faces: "这些掷骰的点数分布", daily: "每日一局", dailyNote: "每日种子是“parchis-daily-v1|YYYY-MM-DD”的 SHA-256(前 16 个字节):当天所有人都一样。", date: "日期", source: "源代码", sourceNote: "每次掷骰只取决于种子和它的序号:任何走法、等级、比分或时钟都不参与计算。", honest: "游戏在你开始前就承诺了种子(指纹),结束后再公开,让你能验证掷骰。我们的主张仅限于此。", }, "zh-Hant": { lead: "輸入對局結束時遊戲顯示的種子(32 個十六進位字元)。本頁用與遊戲相同的程式碼算出指紋和前幾次擲骰。", seed: "種子", go: "驗證", bad: "種子必須是 32 個十六進位字元(0-9、a-f);空格不影響。", fp: "骰子指紋", fpNote: "種子文字(32 個小寫十六進位字元,無空格)的 SHA-256 的前 8 個字元。遊戲在第 1 次擲骰前顯示它:如果與這裡一致,骰子就來自這個種子。", cmd: "在終端機中自己驗證(輸出的前 8 個字元):", shown: "遊戲顯示的指紋(選填)", match: "一致:這局使用的就是這個種子。", nomatch: "不一致:這不是那局的種子。", rolls: "前幾次擲骰", rollsNote: "依順序排列,第 1 次在最前。遊戲按同樣的順序使用它們,依回合分給各位玩家;沒有一次取決於你怎麼下。", count: "擲骰次數", faces: "這些擲骰的點數分布", daily: "每日一局", dailyNote: "每日種子是「parchis-daily-v1|YYYY-MM-DD」的 SHA-256(前 16 個位元組):當天所有人都一樣。", date: "日期", source: "原始碼", sourceNote: "每次擲骰只取決於種子和它的序號:任何走法、等級、比分或時鐘都不參與計算。", honest: "遊戲在你開始前就承諾了種子(指紋),結束後再公開,讓你能驗證擲骰。我們的主張僅止於此。", }, th: { lead: "ใส่ซีด (เลขฐานสิบหก 32 ตัว) ที่เกมแสดงเมื่อจบเกม หน้านี้จะคำนวณลายนิ้วมือและผลทอยแรกๆ ด้วยโค้ดเดียวกับที่เกมใช้", seed: "ซีด", go: "ตรวจสอบ", bad: "ซีดต้องเป็นเลขฐานสิบหก 32 ตัว (0-9, a-f) จะมีเว้นวรรคก็ไม่เป็นไร", fp: "ลายนิ้วมือลูกเต๋า", fpNote: "8 ตัวอักษรแรกของ SHA-256 ของข้อความซีด (เลขฐานสิบหกตัวพิมพ์เล็ก 32 ตัว ไม่มีเว้นวรรค) เกมแสดงค่านี้ก่อนการทอยครั้งที่ 1 ถ้าตรงกับค่านี้ ลูกเต๋าก็มาจากซีดนี้", cmd: "ตรวจสอบเองในเทอร์มินัล (8 ตัวอักษรแรกของผลลัพธ์):", shown: "ลายนิ้วมือที่เกมแสดง (ไม่บังคับ)", match: "ตรงกัน: เกมนั้นใช้ซีดนี้", nomatch: "ไม่ตรงกัน: นี่ไม่ใช่ซีดของเกมนั้น", rolls: "ผลทอยแรกๆ", rollsNote: "เรียงตามลำดับ การทอยครั้งที่ 1 มาก่อน เกมใช้ตามลำดับเดียวกันนี้ แจกให้ผู้เล่นตามตา ไม่มีผลทอยไหนขึ้นกับวิธีเล่นของคุณ", count: "จำนวนการทอย", faces: "หน้าลูกเต๋าในการทอยเหล่านี้", daily: "เกมประจำวัน", dailyNote: "ซีดประจำวันคือ SHA-256 ของ “parchis-daily-v1|YYYY-MM-DD” (16 ไบต์แรก) ทุกคนได้ซีดเดียวกันในวันนั้น", date: "วันที่", source: "ซอร์สโค้ด", sourceNote: "ผลทอยแต่ละครั้งขึ้นกับซีดและลำดับของมันเท่านั้น การเดิน เลเวล คะแนน หรือนาฬิกาไม่มีส่วนในการคำนวณ", honest: "เกมผูกมัดกับซีดก่อนคุณเล่น (ลายนิ้วมือ) และแสดงให้ดูหลังจบ เพื่อให้คุณตรวจผลทอยได้ เราไม่อ้างอะไรมากกว่านั้น", }, vi: { lead: "Nhập mã khởi tạo (32 ký tự thập lục phân) mà trò chơi hiện khi ván kết thúc. Trang này tính vân tay và các lượt gieo đầu tiên bằng đúng đoạn mã mà trò chơi dùng.", seed: "Mã khởi tạo", go: "Xác minh", bad: "Mã khởi tạo phải gồm 32 ký tự thập lục phân (0-9, a-f); dấu cách không quan trọng.", fp: "Vân tay xúc xắc", fpNote: "8 ký tự đầu của SHA-256 của chuỗi mã khởi tạo (32 ký tự thập lục phân viết thường, không dấu cách). Trò chơi hiện nó trước lượt gieo số 1: nếu khớp với giá trị này, xúc xắc là của mã khởi tạo này.", cmd: "Tự kiểm tra trong terminal (8 ký tự đầu của kết quả):", shown: "Vân tay mà trò chơi đã hiện (không bắt buộc)", match: "Khớp: ván đó dùng mã khởi tạo này.", nomatch: "Không khớp: đây không phải mã khởi tạo của ván đó.", rolls: "Các lượt gieo đầu", rollsNote: "Theo thứ tự, lượt số 1 trước. Trò chơi dùng chúng đúng thứ tự này, chia cho người chơi theo lượt; không lượt nào phụ thuộc vào cách bạn chơi.", count: "Số lượt gieo", faces: "Các mặt trong những lượt gieo này", daily: "Ván mỗi ngày", dailyNote: "Mã khởi tạo mỗi ngày là SHA-256 của “parchis-daily-v1|YYYY-MM-DD” (16 byte đầu): giống nhau cho mọi người trong ngày đó.", date: "Ngày", source: "Mã nguồn", sourceNote: "Mỗi lượt gieo chỉ phụ thuộc vào mã khởi tạo và số thứ tự của nó: không nước đi, cấp độ, tỉ số hay đồng hồ nào tham gia tính toán.", honest: "Trò chơi cam kết mã khởi tạo trước khi bạn chơi (vân tay) và cho bạn xem sau đó, để bạn kiểm tra các lượt gieo. Chúng tôi không khẳng định gì hơn thế.", }, } as const; export type Lang = keyof typeof T; /** The page's language from the browser's list (12 languages, same set as the game; Spanish otherwise). */ export function pickVerifierLang(prefs: readonly string[]): Lang { for (const raw of prefs) { const p = raw.toLowerCase(); if (p.startsWith('zh')) return /hant|tw|hk|mo/.test(p) ? 'zh-Hant' : 'zh-Hans'; if (p.startsWith('pt')) return 'pt-BR'; const two = p.slice(0, 2); if (two in T) return two as Lang; } return 'es'; } const esc = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!); /** The result as HTML in one language (also what the test renders to check nothing throws). */ export function render(v: Verification, lang: Lang, shown = ''): string { const t = T[lang]; const cells = v.rolls.map((f, i) => `${f}`).join(''); const check = shown.trim() ? `

${esc(fingerprintMatches(v.seed, shown) ? t.match : t.nomatch)}

` : ''; return `

${esc(t.fp)}

${v.fingerprint.toUpperCase()}

${esc(t.fpNote)}

${esc(t.cmd)}

${esc(v.command)}

${check}

${esc(t.rolls)} (${v.rolls.length})

${esc(t.rollsNote)}

${cells}

${esc(t.faces)}

${v.counts.map((c, i) => `${i + 1}: ${c}`).join(' ')}

`; } // ---------- DOM (browser only) ---------- const $ = (id: string): E => document.getElementById(id) as E; function main(): void { let lang: Lang = pickVerifierLang(navigator.languages ?? [navigator.language || 'es']); const run = (): void => { const t = T[lang]; const out = $('out'); try { const v = verify($('seed').value, Number($('count').value)); out.innerHTML = render(v, lang, $('shown').value); history.replaceState(null, '', hashFor(v.seed, v.rolls.length)); } catch { out.innerHTML = `

${esc(t.bad)}

`; } }; const label = (): void => { const t = T[lang]; document.documentElement.lang = lang; for (const k of ['lead', 'seed', 'go', 'shown', 'count', 'daily', 'dailyNote', 'date', 'source', 'sourceNote', 'honest'] as const) { const el = document.getElementById(`t-${k}`); if (el) el.textContent = t[k]; } showDaily(); run(); }; for (const b of document.querySelectorAll('[data-lang]')) b.addEventListener('click', () => ((lang = b.dataset.lang as Lang), label())); $('form').addEventListener('submit', (e) => (e.preventDefault(), run())); const hash = parseHash(location.hash); if (hash) { $('seed').value = hash.seed; $('count').value = String(hash.n); } const date = $('date'); const showDaily = (): void => { try { const seed = dailyFor(date.value); $('daily-out').innerHTML = `

${seed}

`; $('use').addEventListener('click', () => ((($('seed') as HTMLInputElement).value = seed), run())); } catch { $('daily-out').innerHTML = ''; } }; date.value = localToday(); date.addEventListener('input', showDaily); showDaily(); label(); } if (typeof document !== 'undefined' && document.getElementById('form')) main();