| 1 | // The dev app's mock bot (docs/sdk-v1.md §2.13–§2.15): what a client and the server do around a widget's data and |
| 2 | // requests, in this trusted page. It keeps the message's `chatData` / `publicData` per file (as the server keeps |
| 3 | // them per message), answers the widget's requests with a built-in bot (the widget names it with |
| 4 | // `<meta name="tw-bot" content="poll">`, the panel can switch it), applies the bot's edits as the server's update |
| 5 | // (`setData` to every live host, before the answer), and sets the context a client passes: the server's flags for a |
| 6 | // kind of message (`WIDGET_MESSAGE_KINDS`), the chat type, the viewer. Dev tooling, not a product path. |
| 7 | // The wallet (docs/sdk-v1.md §2.18): the client has a mock Gram Wallet (the panel's **wallet**, `?wallet=0` off); a |
| 8 | // request with `{ wallet: true }` gives the bot the viewer's mock wallet card; a wallet call asks the page's mock wallet |
| 9 | // window (the `confirmWallet` hook) and, confirmed, gives the bot the outcome (a made-up `msg_hash` or signature). |
| 10 | |
| 11 | import type { ChatType, WalletCall, WidgetContext, WidgetData, WidgetRequest, WidgetRequestAnswer } from '@telegram/widget-sandbox/host/widget-host'; |
| 12 | import { CHAT_TYPES, MAX_WIDGET_DATA_BYTES, WIDGET_MESSAGE_KINDS, utf8Length, viewerFromList, type WidgetMessageKind } from '@telegram/widget-sandbox/shared/sdk-policy'; |
| 13 | |
| 14 | type Data = { chatData: string | null; publicData: string | null }; |
| 15 | /** A bot's work on a request: `result` for the widget; a data field that is present is its edit (`editMessageWidgetData`, null clears it). */ |
| 16 | interface Reply { result?: string | null; chatData?: string | null; publicData?: string | null } |
| 17 | /** The viewer's wallet card as the server attaches it to a request (`wallet.card`: address and balance in nanotons). */ |
| 18 | interface WalletCard { address: string; balance: number } |
| 19 | interface BotContext { |
| 20 | viewer: number; |
| 21 | name: string; |
| 22 | data: Data; |
| 23 | /** The viewer's wallet card: a request with `{ wallet: true }`, and every wallet call's outcome. */ |
| 24 | wallet?: WalletCard; |
| 25 | } |
| 26 | interface Bot { |
| 27 | title: string; |
| 28 | /** The data the bot sent the widget with. */ |
| 29 | initial: Data; |
| 30 | /** `name`: the viewer's first name, as the bot gets it in `from`. */ |
| 31 | answer(data: string, ctx: BotContext): Reply; |
| 32 | /** The outcome of a wallet call the user confirmed: the transaction's `msgHash`, or the signature (`signed`). Without it the bot answers `{ result: null }`. */ |
| 33 | wallet?(call: WalletCall, ctx: BotContext & { msgHash?: string; signed?: { signature: string; domain: |
| 34 | } |
| 35 | |
| 36 | /** The dev app's viewer besides the id (1001): first name, last name, username, premium (`viewerFromList`). */ |
| 37 | export const DEFAULT_PROFILE = 'Ann,Lee,ann_lee'; |
| 38 | const json = (s: string | null, fallback: any) => { try { return s === null ? |
| 39 | |
| 40 | const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1 |
| 41 | const winner = (b: string) => LINES.find(([a, c, d]) => b[a] !== '-' && b[a] |
| 42 | /** The bot's move: win, block, centre, a corner, anything. */ |
| 43 | function botMove(b: string): number { |
| 44 | for (const mark of ['o', 'x']) { |
| 45 | for (const line of LINES) { |
| 46 | const marks = line.map((i) => b[i]); |
| 47 | if (marks.filter((m) => m === mark).length === 2 && marks.includes('-')) return line[marks.indexOf('-')]; |
| 48 | } |
| 49 | } |
| 50 | return [4, 0, 2, 6, 8, 1, 3, 5, 7].find((i) => b[i] === '-') |
| 51 | } |
| 52 | |
| 53 | /** The viewer's mock Gram Wallet: what the server would attach (`wallet.card`); 12.5 TON. */ |
| 54 | export const MOCK_WALLET: WalletCard = { address: '0:' + 'f00d'.repeat(16), balance: 12_500_000_000 }; |
| 55 | /** MOCK_WALLET's address in the user-friendly form (non-bounceable, mainnet): what a transaction's message takes. */ |
| 56 | const MOCK_WALLET_FRIENDLY = 'UQDwDfAN8A3wDfAN8A3wDfAN8A3wDfAN8A3wDfAN8A3wDZTR'; |
| 57 | /** The mock shop's address: where its transactions pay. */ |
| 58 | const SHOP_ADDRESS = 'EQ' + 'shop'.repeat(11) + 'Sh'; |
| 59 | const SHOP_ITEMS = [['Coffee', '1500000000'], ['Croissant', '2000000000'], ['Day pass', '5000000000']]; |
| 60 | |
| 61 | export const BOTS: Record<string, Bot> = { |
| 62 | echo: { |
| 63 | title: 'echo: result = the request data', |
| 64 | initial: { chatData: null, publicData: null }, |
| 65 | answer: (data) => ({ result: data }), |
| 66 | }, |
| 67 | poll: { |
| 68 | title: 'poll: vote:N toggles the viewer\'s vote; chatData {v: counts, u: {viewer: option}}, publicData {v}', |
| 69 | initial: { chatData: '{"v":[3,5,1],"u":{"7":0,"8":1,"9":1}}', publicData: '{"v":[3,5,1]}' }, |
| 70 | answer(data, { viewer, data: d }) { |
| 71 | const m = /^vote:([0-9])$/.exec(data); |
| 72 | if (!m) return { result: 'unknown' }; |
| 73 | const state = json(d.chatData, { v: [0, 0, 0], u: {} }); |
| 74 | const option = Number(m[1]); |
| 75 | if (!(option < state.v.length)) return { result: 'unknown' }; |
| 76 | const before = state.u[viewer]; |
| 77 | if (before !== undefined) state.v[before]--; |
| 78 | if (before === option) delete state.u[viewer]; |
| 79 | else { state.u[viewer] = option; state.v[option]++; } |
| 80 | return { result: JSON.stringify({ voted: state.u[viewer] ?? null }), chatData: JSON.stringify(state), publicData: JSON.stringify({ v: state.v }) }; |
| 81 | }, |
| 82 | }, |
| 83 | tictactoe: { |
| 84 | title: 'tic-tac-toe: move:N plays X and the bot answers O; reset; chatData {b, s}, publicData = the last game', |
| 85 | initial: { chatData: '{"b":"---------","s":"play"}', publicData: null }, |
| 86 | answer(data, { data: d }) { |
| 87 | if (data === 'reset') return { result: 'new game', chatData: '{"b":"---------","s":"play"}' }; |
| 88 | const m = /^move:([0-8])$/.exec(data); |
| 89 | const game = json(d.chatData, { b: '---------', s: 'play' }); |
| 90 | if (!m || game.s !== 'play' || game.b[Number(m[1])] !== '-') return { result: 'invalid move' }; |
| 91 | let b = game.b.slice(0, Number(m[1])) + 'x' + game.b.slice(Number(m[1]) + 1); |
| 92 | let w = winner(b); |
| 93 | if (!w) { const o = botMove(b); b = b.slice(0, o) + 'o' + b.slice(o + 1); w |
| 94 | const next = JSON.stringify({ b, s: w ?? 'play' }); |
| 95 | return { result: w ? (w === 'draw' ? 'draw' : w + ' wins') : 'your move', chatData: next, ...(w ? { publicData: next } : {}) }; |
| 96 | }, |
| 97 | }, |
| 98 | ticker: { |
| 99 | title: 'ticker: tick (background) → {t, p}; like → chatData {likes}', |
| 100 | initial: { chatData: '{"likes":0}', publicData: null }, |
| 101 | answer(data, { data: d }) { |
| 102 | if (data === 'like') return { result: 'liked', chatData: JSON.stringify({ likes: (json(d.chatData, {}).likes ?? 0) + 1 }) }; |
| 103 | const p = 100 + 10 * Math.sin(Date.now() / 20000) + Math.random(); |
| 104 | return { result: JSON.stringify({ t: new Date().toISOString().slice(11, 19), p: Math.round(p * 100) / 100 }) }; |
| 105 | }, |
| 106 | }, |
| 107 | promo: { |
| 108 | title: 'promo: redeem once; publicData {code, off}, chatData {redeemed}', |
| 109 | initial: { chatData: null, publicData: '{"code":"TG-WIDGET-2026","off":20}' }, |
| 110 | answer(data, { data: d }) { |
| 111 | if (data !== 'redeem') return { result: 'unknown' }; |
| 112 | if (json(d.chatData, {}).redeemed) return { result: 'already' }; |
| 113 | return { result: 'ok', chatData: JSON.stringify({ redeemed: new Date().toISOString().slice(0, 16) }) }; |
| 114 | }, |
| 115 | }, |
| 116 | shop: { |
| 117 | title: 'shop (the wallet): pay:N with { wallet: true } → a transaction to the shop (valid 5 min); paid → chatData {paid}; signData → {signed}', |
| 118 | initial: { chatData: null, publicData: JSON.stringify({ items: SHOP_ITEMS.map(([n, a]) => [n, Number(a) / 1e9]) }) }, |
| 119 | answer(data, { wallet }) { |
| 120 | const m = /^pay:([0-9])$/.exec(data); |
| 121 | if (!m || !SHOP_ITEMS[Number(m[1])]) return { result: JSON.stringify({ err: 'unknown' }) }; |
| 122 | if (!wallet) return { result: JSON.stringify({ err: 'no wallet: ask with { wallet: true }' }) }; |
| 123 | const [, amount] = SHOP_ITEMS[Number(m[1])]; |
| 124 | if (wallet.balance < Number(amount)) return { result: JSON.stringify({ err: 'not enough TON', balance: wallet.balance / 1e9 }) }; |
| 125 | // A fresh order, priced now, valid 5 minutes: TON Connect's transaction as the widget passes it on. |
| 126 | const tx = { valid_until: Math.floor(Date.now() / 1000) + 300, messages: [{ address: SHOP_ADDRESS, amount }] }; |
| 127 | return { result: JSON.stringify({ tx, from: wallet.address }) }; |
| 128 | }, |
| 129 | wallet(call, { msgHash, signed, wallet, data: d }) { |
| 130 | // A real bot finds the transaction by msg_hash, waits for it to be final and checks the sender, the amount and the order. |
| 131 | if (call.method === 'sendTransaction') { |
| 132 | const item = SHOP_ITEMS.find(([, a]) => a === call.transaction.messages[0]?.amount)?.[0] ?? '?'; |
| 133 | const paid = [...(json(d.chatData, {}).paid ?? []), item].slice(-5); |
| 134 | return { result: JSON.stringify({ paid: item, hash: msgHash?.slice(0, 8), from: wallet?.address.slice(0, 8) }), chatData: JSON.stringify({ paid }) }; |
| 135 | } |
| 136 | return { result: JSON.stringify({ signed: signed?.domain, text: call.payload.text ?? null }) }; |
| 137 | }, |
| 138 | }, |
| 139 | // corpus/bot-demos (notes on the protocol in each file's header; the real bot is scripts/bot-demos.ts). |
| 140 | gram: { |
| 141 | title: 'bot-demos wallet test: w:me / w:pay with { wallet: true }, w:text, signData → s, sendTransaction → t wait, w:st → ok; chatData {m, s, t}', |
| 142 | initial: { chatData: null, publicData: null }, |
| 143 | answer(data, { wallet, data: d }) { |
| 144 | const state = json(d.chatData, {}); |
| 145 | const out = (part: Record<string, unknown>) => ({ result: JSON.stringify(part), chatData: JSON.stringify({ ...state, ...part }) }); |
| 146 | if (data === 'w:me') return wallet ? out({ m: { a: MOCK_WALLET_FRIENDLY, b: String(wallet.balance) } }) : { result: JSON.stringify({ err: 'No wallet card came: ask with { wallet: true }' }) }; |
| 147 | if (data === 'w:text') return { result: JSON.stringify({ text: `Gram Wallet test for @mockbot\nSigned at ${new Date().toISOString().slice(0, 19)}Z\n |
| 148 | if (data === 'w:pay') { |
| 149 | if (!wallet) return { result: JSON.stringify({ err: 'No wallet card came: ask with { wallet: true }' }) }; |
| 150 | return { result: JSON.stringify({ tx: { valid_until: Math.floor(Date.now() / 1000) + 300, network: '-239', messages: [{ address: MOCK_WALLET_FRIENDLY, amount: '10000000' }] } }) }; |
| 151 | } |
| 152 | // The real bot looks the transfer up on toncenter by its message hash; here the chain has it on the first look. |
| 153 | if (data === 'w:st') return state.t?.st === 'wait' ? out({ t: { h: state.t.h, st: 'ok', w: 'To the same wallet · fee 0.0031 TON' } }) : { result: JSON.stringify({ t: state.t ?? null |
| 154 | return { result: JSON.stringify({ err: 'Unknown request' }) }; |
| 155 | }, |
| 156 | wallet(call, { msgHash, data: d }) { |
| 157 | const state = json(d.chatData, {}); |
| 158 | const part = call.method === 'sendTransaction' |
| 159 | ? { t: { h: msgHash, st: 'wait', w: 'Waiting for the chain…' } } |
| 160 | : { s: { ok: true, w: 'Valid · v4r2, the key on chain' } }; |
| 161 | return { result: JSON.stringify(part), chatData: JSON.stringify({ ...state, ...part }) }; |
| 162 | }, |
| 163 | }, |
| 164 | order: { |
| 165 | title: 'bot-demos order: order:poll / order:refresh (refresh moves the order one step on), order:cancel while st ≤ 1', |
| 166 | initial: { |
| 167 | chatData: '{"items":[["Margherita",2,1250],["Burrata",1,900],["Lemonade",2,350]],"cur":"€","addr":"221B Baker St, flat 3","pay":"•• 4242"}', |
| 168 | publicData: '{"shop":"Pizzeria Uno","e":"🍕","id":"A-1042","st":1,"eta":"19:40","u":"19:12","bot":"examplebot"}', |
| 169 | }, |
| 170 | answer(data, { data: d }) { |
| 171 | const p = json(d.publicData, { st: 0 }); |
| 172 | if (data === 'order:cancel') { |
| 173 | if (p.st > 1 || p.st < 0) return { result: JSON.stringify({ err: p.st < 0 ? 'Already cancelled' : 'Too late to cancel' |
| 174 | p.st = -1; |
| 175 | } else if (data === 'order:refresh') { |
| 176 | // Each refresh moves the order one step on, and the courier gets closer. |
| 177 | if (p.st >= 0 && p.st < 3) { p.st++; p.eta = new Date(Date.now() + (3 - p.st) * |
| 178 | } |
| 179 | else if (data !== 'order:poll') return { result: JSON.stringify({ err: 'unknown' }) }; |
| 180 | if (data !== 'order:poll') p.u = new Date().toTimeString().slice(0, 5); |
| 181 | return { result: JSON.stringify({ st: p.st, eta: p.eta }), publicData: JSON.stringify(p) }; |
| 182 | }, |
| 183 | }, |
| 184 | vote: { |
| 185 | title: 'bot-demos poll: vote:N toggles the viewer\'s vote; publicData {q, o, v, r} (r: the revision)', |
| 186 | initial: { chatData: null, publicData: '{"q":"Where do we go on Friday?","o":["Pizza","Sushi","Tacos","Burgers"],"v":[3,5,1,2]}' }, |
| 187 | answer(data, { viewer, data: d }) { |
| 188 | const m = /^vote:(\d)$/.exec(data), p = json(d.publicData, { o: [], v: [] }); |
| 189 | if (!m || Number(m[1]) >= p.o.length) return { result: JSON.stringify({ err: 'unknown' }) }; |
| 190 | const n = Number(m[1]), before = demoVotes.get(viewer); |
| 191 | if (before !== undefined) p.v[before]--; |
| 192 | if (before === n) demoVotes.delete(viewer); else { demoVotes.set(viewer, n); p.v[n]++; } |
| 193 | p.r = (p.r ?? 0) + 1; |
| 194 | return { result: JSON.stringify({ my: demoVotes.get(viewer) ?? -1, v: p.v, r: p.r }), publicData: JSON.stringify(p) }; |
| 195 | }, |
| 196 | }, |
| 197 | rsvp: { |
| 198 | title: 'bot-demos rsvp: rsvp:in / rsvp:may / rsvp:out (the same again clears); chatData {in, may, out}, publicData {t, w, p, max, n}', |
| 199 | initial: { |
| 200 | chatData: '{"in":[[101,"Bob"],[102,"Eve"],[103,"Max"],[104,"Kim"],[105,"Leo"]],"may":[[106,"Zoe"]],"out":[[107,"Ian"]]}', |
| 201 | publicData: '{"t":"Friday football","w":"Fri, Nov 6 · 19:00","p":"Central Park, field 3","max":10,"n":5}', |
| 202 | }, |
| 203 | answer(data, { viewer, name, data: d }) { |
| 204 | const m = /^rsvp:(in|may|out)$/.exec(data); |
| 205 | if (!m) return { result: JSON.stringify({ err: 'unknown' }) }; |
| 206 | const c = json(d.chatData, { in: [], may: [], out: [] }), p = json(d.publicData, {}); |
| 207 | const was = (['in', 'may', 'out'] as const).find((k) => c[k].some((e: [number, string |
| 208 | for (const k of ['in', 'may', 'out']) c[k] = c[k].filter((e: [number, string]) => e[0] !== |
| 209 | const me = was === m[1] ? null : m[1]; |
| 210 | if (me === 'in' && c.in.length >= p.max) return { result: JSON.stringify({ err: 'Full', me: was ?? null }) }; |
| 211 | if (me) c[me].push([viewer, name]); |
| 212 | p.n = c.in.length; |
| 213 | return { result: JSON.stringify({ me }), chatData: JSON.stringify(c), publicData: JSON.stringify(p) }; |
| 214 | }, |
| 215 | }, |
| 216 | duel: { |
| 217 | title: 'bot-demos duel: ttt:N, ttt:new; the mock plays O as Bob after your X so one person can try it', |
| 218 | initial: { chatData: '{"b":"---------","x":null,"o":null,"t":"x","w":null,"l":null,"s":[0,0]}', publicData: null }, |
| 219 | answer(data, { viewer, name, data: d }) { |
| 220 | const g = json(d.chatData, { b: '---------', x: null, o: null, t: 'x', w: null, l: null, s: [0, 0] }); |
| 221 | const err = (e: string) => ({ result: JSON.stringify({ err: e }) }); |
| 222 | const snap = () => JSON.stringify({ b: g.b, x: g.x?.[1] ?? null, o: g.o?.[1] ?? null, w: g.w, s: g.s, bot: 'examplebot' }); |
| 223 | const play = (mark: 'x' | 'o', i: number) => { |
| 224 | g.b = g.b.slice(0, i) + mark + g.b.slice(i + 1); |
| 225 | const line = LINES.find(([a, c, e]) => g.b[a] !== '-' && g.b[a] === g.b[c] && g.b[a] === g.b[e]); |
| 226 | if (line) { g.w = mark; g.l = line; g.s[mark === 'x' ? 0 : 1]++; } else if (!g.b.includes('-')) g.w |
| 227 | g.t = mark === 'x' ? 'o' : 'x'; |
| 228 | }; |
| 229 | if (data === 'ttt:new') { |
| 230 | if (!g.w) return err('Game on'); |
| 231 | const loserStarts = g.w === 'x' ? 'o' : 'x'; |
| 232 | Object.assign(g, { b: '---------', t: loserStarts, w: null, l: null }); |
| 233 | // Bob lost or drew as O and starts the rematch: he moves at once. |
| 234 | if (g.t === 'o' && g.o?.[0] === 2002) play('o', botMove(g.b)); |
| 235 | return { result: '{"ok":1}', chatData: JSON.stringify(g), publicData: snap() }; |
| 236 | } |
| 237 | const m = /^ttt:([0-8])$/.exec(data); |
| 238 | if (!m) return err('unknown'); |
| 239 | if (g.w) return err('Game over'); |
| 240 | if (!g.x) g.x = [viewer, name]; |
| 241 | const mark = g.x[0] === viewer ? 'x' : g.o?.[0] === viewer ? 'o' : g.o ? null |
| 242 | if (!mark) return err('Full'); |
| 243 | if (mark === 'o' && !g.o) g.o = [viewer, name]; |
| 244 | if (g.t !== mark) return err('Not your turn'); |
| 245 | if (g.b[Number(m[1])] !== '-') return err('Taken'); |
| 246 | play(mark, Number(m[1])); |
| 247 | // One person in the dev app: Bob answers as O. |
| 248 | if (!g.w && mark === 'x' && (!g.o || g.o[0] === 2002)) { g.o = [2002, 'Bob']; play( |
| 249 | return { result: '{"ok":1}', chatData: JSON.stringify(g), publicData: snap() }; |
| 250 | }, |
| 251 | }, |
| 252 | quote: { |
| 253 | title: 'bot-demos ticker: no requests; push a new publicData with __tw.bot.edit or the panel to animate it', |
| 254 | initial: { chatData: null, publicData: '{"s":"TON","n":"Toncoin","c":"$","p":5.4321,"o":5.31,"h":[5.31,5.29,5.33,5.36,5.34,5.38,5.41,5.39,5.37,5.4,5.44,5.42,5.45,5.43,5.41,5.39,5.42,5.46,5.44,5.47,5.45,5.43,5.44,5.4321],"t":"21:59:30"}' }, |
| 255 | answer: () => ({ result: JSON.stringify({ err: 'no requests' }) }), |
| 256 | }, |
| 257 | reaction: { |
| 258 | title: 'bot-demos reaction: score:N (100–2000 ms) → the shared top (8 rows, also in the answer) and the chat\'s best', |
| 259 | initial: { chatData: '{"best":243}', publicData: '{"top":[["Max",171],["Eve",188],["Bob",203],["Kim",219],["Leo",240],["Zoe",262]],"plays":42}' }, |
| 260 | answer(data, { viewer, name, data: d }) { |
| 261 | const m = /^score:(\d{3,4})$/.exec(data), ms = m ? Number(m[1]) : 0; |
| 262 | if (!(ms >= 100 && ms <= 2000)) return { result: JSON.stringify({ err: 'Not a human time' }) }; |
| 263 | const p = json(d.publicData, { top: [], plays: 0 }), c = json(d.chatData, {}); |
| 264 | const mine = p.top.find((r: [string, number]) => r[0] === name); |
| 265 | if (mine) mine[1] = Math.min(mine[1], ms); else p.top.push([name, ms]); |
| 266 | p.top.sort((a: [string, number], b: [string, number]) => a[1] - b[1]); |
| 267 | p.top = p.top.slice(0, 8); |
| 268 | p.plays++; |
| 269 | p.r = (p.r ?? 0) + 1; |
| 270 | const best = Math.min(c.best ?? ms, ms), rank = p.top.findIndex((r: [string, number]) => r[0] === name) + |
| 271 | return { result: JSON.stringify({ rank, best: mine ? mine[1] : ms, top: p.top, plays: p.plays, r: p.r }), chatData: JSON.stringify({ best }), publicData: JSON.stringify(p) }; |
| 272 | }, |
| 273 | }, |
| 274 | }; |
| 275 | |
| 276 | /** The bot-demos poll's votes by viewer (the mock keeps no per-viewer state in the message). */ |
| 277 | const demoVotes = new Map<number, number>(); |
| 278 | |
| 279 | /** How the mock bot answers: with the selected bot, or as a client's failures; `manual` keeps the request until a button answers it. */ |
| 280 | export const MODES = ['bot', 'manual', 'TIMEOUT', 'RATE_LIMITED', 'FAILED'] as const; |
| 281 | export type Mode = (typeof MODES)[number]; |
| 282 | |
| 283 | export interface RequestRecord { |
| 284 | at: string; |
| 285 | file: string | null; |
| 286 | data: string; |
| 287 | /** `wallet`: a request that asked for the wallet; `sendTransaction` / `signData`: a wallet call. */ |
| 288 | kind?: 'wallet' | 'sendTransaction' | 'signData'; |
| 289 | /** What went back to the host: the answer, or a failure code; undefined while pending. */ |
| 290 | answer?: WidgetRequestAnswer; |
| 291 | error?: string; |
| 292 | } |
| 293 | |
| 294 | /** The bot named by `<meta name="tw-bot" content="…">` in the widget, `echo` otherwise. */ |
| 295 | export function botOf(html: string): string { |
| 296 | const m = /<meta\s+name=["']tw-bot["']\s+content=["']([\w-]+)["']/i.exec(html); |
| 297 | return m && BOTS[m[1]] ? m[1] : 'echo'; |
| 298 | } |
| 299 | |
| 300 | export interface MockBotHooks { |
| 301 | /** The context changed: the widget is re-created (a host's context is fixed for its life). */ |
| 302 | restart(): void; |
| 303 | /** The bot edited the data: every live host of the file gets it (the server's update, or the polled shared object). */ |
| 304 | setData(data: Data): void; |
| 305 | /** Something the panel shows changed. */ |
| 306 | changed(): void; |
| 307 | /** The client's wallet window for a wallet call: true when the user confirmed it. */ |
| 308 | confirmWallet(call: WalletCall): Promise<boolean>; |
| 309 | } |
| 310 | |
| 311 | export class MockBot { |
| 312 | bot = 'echo'; |
| 313 | mode: Mode = 'bot'; |
| 314 | delayMs = 300; |
| 315 | /** |
| 316 | * The kind of message (the server's flags), its chat type (null: the kind's own), the viewer's id and the rest of |
| 317 | * the viewer as `first,last,username,premium` (`viewerFromList`; the host checks it). |
| 318 | */ |
| 319 | context: { message: WidgetMessageKind; chatType: ChatType | null; viewer: number | null; profile: string |
| 320 | { message: 'private', chatType: null, viewer: 1001, profile: DEFAULT_PROFILE }; |
| 321 | /** |
| 322 | * The widget is a shared object (its message has a `widget_id`): the client polls its `public_data` while it is on |
| 323 | * screen and watches (`TelegramWidget.watchPublicData`), every `pollMs` (the server's period: 5–3600 s, |
| 324 | * default 30 s, here shorter for the dev app). Without it nothing is polled. |
| 325 | */ |
| 326 | shared = true; |
| 327 | pollMs = 5000; |
| 328 | /** The live widget watches its public_data (the host's `onWatchPublicData`); the panel shows it. */ |
| 329 | watching = false; |
| 330 | /** Polls made, and the ones that brought a new value. */ |
| 331 | polls = { made: 0, changed: 0 }; |
| 332 | /** The client has Gram Wallet for this user (`WidgetContext.wallet`; `?wallet=0` off). */ |
| 333 | wallet = true; |
| 334 | readonly requests: RequestRecord[] = []; |
| 335 | private data = new Map<string, Data>(); |
| 336 | /** The data the live widget has: what it got with the message, a pushed edit or a poll. */ |
| 337 | private delivered = new Map<string, Data>(); |
| 338 | private pending = new Map<RequestRecord, (outcome: { answer?: WidgetRequestAnswer; error?: string }) => void>(); |
| 339 | |
| 340 | constructor(readonly hooks: MockBotHooks) {} |
| 341 | |
| 342 | /** The message's data as the "server" has it now (the bot's initial data the first time). */ |
| 343 | dataFor(file: string | null): Data { |
| 344 | const key = file ?? ''; |
| 345 | if (!this.data.has(key)) this.data.set(key, { ...BOTS[this.bot].initial }); |
| 346 | return this.data.get(key)!; |
| 347 | } |
| 348 | |
| 349 | /** A fresh message: the bot's initial data again. */ |
| 350 | resetData(file: string | null) { |
| 351 | this.data.delete(file ?? ''); |
| 352 | } |
| 353 | |
| 354 | /** The client created a host with the message's data (`dataFor`): that is what the widget has now. */ |
| 355 | loaded(file: string | null) { |
| 356 | this.delivered.set(file ?? '', this.dataFor(file)); |
| 357 | this.watching = false; |
| 358 | } |
| 359 | |
| 360 | /** |
| 361 | * The bot's `editWidgetData` (a shared object by its id): the server's value changes, nothing is pushed; the widget |
| 362 | * gets it at the client's next poll if it watches, or with the message the next time it is shown. |
| 363 | */ |
| 364 | editShared(file: string | null, publicData: string | null) { |
| 365 | this.data.set(file ?? '', { ...this.dataFor(file), publicData }); |
| 366 | this.hooks.changed(); |
| 367 | } |
| 368 | |
| 369 | /** The client's poll (`getWidgetPublicData`): the full state if the shared value changed since the widget got it, else null. */ |
| 370 | poll(file: string | null): Data | null { |
| 371 | if (!this.shared) return null; |
| 372 | this.polls.made++; |
| 373 | const key = file ?? ''; |
| 374 | const now = this.dataFor(file), had = this.delivered.get(key); |
| 375 | if (had && had.publicData === now.publicData) return null; |
| 376 | this.polls.changed++; |
| 377 | const next = { chatData: had?.chatData ?? now.chatData, publicData: now.publicData }; |
| 378 | this.delivered.set(key, next); |
| 379 | this.hooks.changed(); |
| 380 | return next; |
| 381 | } |
| 382 | |
| 383 | hostContext(): WidgetContext { |
| 384 | const c = this.context; |
| 385 | const kind = WIDGET_MESSAGE_KINDS[c.message]; |
| 386 | const viewer = c.viewer !== null ? viewerFromList(`${c.viewer},${c.profile}`) : null; |
| 387 | return { ...kind, chatType: c.chatType ?? kind.chatType, ...(viewer ? { viewer } : {}), ...(this.wallet ? { wallet: true } : {}) }; |
| 388 | } |
| 389 | |
| 390 | /** The bot's edit (`editMessageWidgetData`): the full state of both strings to every live host. */ |
| 391 | edit(file: string | null, data: Data) { |
| 392 | this.data.set(file ?? '', data); |
| 393 | this.delivered.set(file ?? '', data); |
| 394 | this.hooks.setData(data); |
| 395 | this.hooks.changed(); |
| 396 | } |
| 397 | |
| 398 | /** `WidgetHostOptions.onRequest`: what the client would send over MTProto and get back. */ |
| 399 | request(file: string | null, req: WidgetRequest): Promise<WidgetRequestAnswer> { |
| 400 | const rec: RequestRecord = { at: new Date().toISOString().slice(11, 23), file, data: req.data, ...(req.wallet ? { kind: 'wallet' as |
| 401 | this.requests.push(rec); |
| 402 | if (this.requests.length > 200) this.requests.shift(); |
| 403 | this.hooks.changed(); |
| 404 | return new Promise<WidgetRequestAnswer>((resolve, reject) => { |
| 405 | const settle = (o: { answer?: WidgetRequestAnswer; error?: string }) => { |
| 406 | this.pending.delete(rec); |
| 407 | rec.answer = o.answer; |
| 408 | rec.error = o.error; |
| 409 | this.hooks.changed(); |
| 410 | if (o.error) reject(o.error); |
| 411 | else resolve(o.answer!); |
| 412 | }; |
| 413 | this.pending.set(rec, settle); |
| 414 | if (this.mode === 'manual') return; |
| 415 | const mode = this.mode; |
| 416 | setTimeout(() => (mode === 'bot' ? this.answer(rec) : this.fail(rec, mode)), this.delayMs); |
| 417 | }); |
| 418 | } |
| 419 | |
| 420 | /** |
| 421 | * Answers a pending request with the selected bot, as a bot does: it edits its data with a separate call (which |
| 422 | * reaches every live host as the server's update, here before the answer), then answers with `result` only. |
| 423 | */ |
| 424 | answer(rec: RequestRecord) { |
| 425 | const settle = this.pending.get(rec); |
| 426 | if (!settle) return; |
| 427 | const ctx = this.botContext(rec.file, rec.kind === 'wallet'); |
| 428 | this.apply(rec.file, settle, BOTS[this.bot].answer(rec.data, ctx)); |
| 429 | } |
| 430 | |
| 431 | private botContext(file: string | null, wallet: boolean): BotContext { |
| 432 | return { viewer: this.context.viewer ?? 0, name: this.context.profile.split(',')[0] || `User ${this.context.viewer}`, data: this.dataFor |
| 433 | } |
| 434 | |
| 435 | /** The bot's edits (as the server's update, before the answer), then the answer. */ |
| 436 | private apply(file: string | null, settle: (o: { answer?: WidgetRequestAnswer; error?: string }) => |
| 437 | const data = this.dataFor(file); |
| 438 | if ('chatData' in reply || 'publicData' in reply) { |
| 439 | this.edit(file, { chatData: 'chatData' in reply ? reply.chatData || null : data.chatData, publicData: 'publicData' in reply ? reply.publicData || null : data.publicData }); |
| 440 | } |
| 441 | settle({ answer: { result: reply.result ?? null } }); |
| 442 | } |
| 443 | |
| 444 | /** |
| 445 | * `WidgetHostOptions.onWallet`: the client's wallet window (`confirmWallet`), then, confirmed, the transaction sent or |
| 446 | * the data signed for `bot<bot_id>`, and the outcome to the bot as a query (with the wallet card); its answer back. A |
| 447 | * decline is REJECTED; the panel's failure modes fail the query after the window. |
| 448 | */ |
| 449 | async walletCall(file: string | null, call: WalletCall): Promise<WidgetRequestAnswer> { |
| 450 | const rec: RequestRecord = { at: new Date().toISOString().slice(11, 23), file, data: call.data, kind: call.method }; |
| 451 | this.requests.push(rec); |
| 452 | if (this.requests.length > 200) this.requests.shift(); |
| 453 | this.hooks.changed(); |
| 454 | const done = (o: { answer?: WidgetRequestAnswer; error?: string }) => { rec.answer = o.answer; rec.error = o.error; this.hooks.changed(); }; |
| 455 | if (!(await this.hooks.confirmWallet(call))) { |
| 456 | done({ error: 'REJECTED' }); |
| 457 | throw { code: 'REJECTED' }; |
| 458 | } |
| 459 | await new Promise((r) => setTimeout(r, this.delayMs)); |
| 460 | if (this.mode !== 'bot' && this.mode !== 'manual') { |
| 461 | done({ error: this.mode }); |
| 462 | throw { code: this.mode }; |
| 463 | } |
| 464 | const hex = (n: number) => Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join |
| 465 | const outcome = call.method === 'sendTransaction' |
| 466 | ? { msgHash: hex(64) } |
| 467 | : { signed: { signature: btoa(hex(64)), domain: 'bot1234567', timestamp: Math.floor(Date.now() / 1000) } }; |
| 468 | const bot = BOTS[this.bot]; |
| 469 | const reply = bot.wallet ? bot.wallet(call, { ...this.botContext(file, true), ...outcome }) : { result: null }; |
| 470 | return new Promise<WidgetRequestAnswer>((resolve) => this.apply(file, (o) => { done(o); resolve(o.answer!); }, reply)); |
| 471 | } |
| 472 | |
| 473 | fail(rec: RequestRecord, code: string) { |
| 474 | this.pending.get(rec)?.({ error: code }); |
| 475 | } |
| 476 | |
| 477 | get pendingRequests(): RequestRecord[] { |
| 478 | return [...this.pending.keys()]; |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | // ───────────── the panel ───────────── |
| 483 | |
| 484 | function make<T extends HTMLElement = HTMLElement>(tag: string, props: Record<string, unknown> = {}, ... |
| 485 | const e = Object.assign(document.createElement(tag), props) as T; |
| 486 | e.append(...children); |
| 487 | return e; |
| 488 | } |
| 489 | const bytes = (s: string) => `${utf8Length(s)} / ${MAX_WIDGET_DATA_BYTES} B`; |
| 490 | |
| 491 | /** The right column's "Bot (mock)" section: context, the data and its edit, the answer mode, the requests. */ |
| 492 | export function mountPanel(root: HTMLElement, bot: MockBot, file: () => string | null) { |
| 493 | const message = make<HTMLSelectElement>('select', { title: 'the kind of message, and so the server\'s flags: private = the original in the bot\'s private chat (taps and background requests); group, via-bot = taps only; no-queries = an original sent without allow_queries (no requests, no network marker); live-copy = a forward of a widget sent with fwd_allow_queries (taps only); copy = a forward without it (no requests); preview = an inline result not sent yet. Re-creates the widget' }, |
| 494 | ...Object.entries(WIDGET_MESSAGE_KINDS).map(([k, f]) => make('option', { value: k, textContent: k, title: `isCopy ${f.isCopy}, canQuery ${f.canQuery}, backgroundQuery ${f. |
| 495 | const chatType = make<HTMLSelectElement>('select', { title: 'the chat kind the client reports; default: the message kind\'s (re-creates the widget)' }, ...['', ...CHAT_TYPES].map((t) => |
| 496 | const viewer = make<HTMLInputElement>('input', { type: 'number', min: '1', title: 'the viewer\'s user id; empty: none (re-creates the widget)' }); |
| 497 | const profile = make<HTMLInputElement>('input', { type: 'text', size: 18, placeholder: 'first,last,username,premium', title: 'the rest of the viewer (WebAppUser): first name, last name, username, premium; empty parts are absent; the host leaves out a field that breaks its rule (data-rejected). Re-creates the widget' }); |
| 498 | const botSelect = make<HTMLSelectElement>('select', { title: 'which built-in bot answers; a widget names its own with <meta name="tw-bot">' }, ...Object.entries(BOTS).map(([k, b]) => make |
| 499 | const mode = make<HTMLSelectElement>('select', { title: 'bot: the bot answers after the delay; manual: answer each request below; the rest fail as a client reports it' }, ...MODES.map((m) => make('option', { value: m, textContent: m }))); |
| 500 | const delay = make<HTMLInputElement>('input', { type: 'number', min: '0', step: '100', title: 'how long the bot takes to answer (ms)' }); |
| 501 | const chatData = make<HTMLTextAreaElement>('textarea', { rows: 2, spellcheck: false, placeholder: 'chatData (null)' }); |
| 502 | const publicData = make<HTMLTextAreaElement>('textarea', { rows: 2, spellcheck: false, placeholder: 'publicData (null)' }); |
| 503 | const size = make('span', { className: 'muted' }); |
| 504 | const apply = make('button', { type: 'button', textContent: 'edit data', title: 'the bot\'s editMessageWidgetData: both strings to the widget (an empty field is none)' }); |
| 505 | const reset = make('button', { type: 'button', textContent: 'reset', title: 'the bot\'s initial data again (a fresh message; re-creates the widget)' }); |
| 506 | const byId = make('button', { type: 'button', textContent: 'edit by id', title: 'the bot\'s editWidgetData: only publicData, in the shared object; nothing is pushed: the widget gets it at the next poll if it watches (watchPublicData), else with the message next time' }); |
| 507 | const shared = make<HTMLInputElement>('input', { type: 'checkbox', title: 'the widget is a shared object (its message has a widget_id): the client polls its publicData while it watches' }); |
| 508 | const wallet = make<HTMLInputElement>('input', { type: 'checkbox', title: 'the client has Gram Wallet for this user (WidgetContext.wallet): TelegramWidget.wallet where the widget may ask the bot. Re-creates the widget' }); |
| 509 | const period = make<HTMLInputElement>('input', { type: 'number', min: '100', step: '500', title: 'the poll period in ms (the server\'s period: 5–3600 s, 30 s by default; shorter here)' }); |
| 510 | const polling = make('span', { className: 'muted' }); |
| 511 | const list = make('ul', { id: 'bot-requests' }); |
| 512 | const title = make('div', { className: 'muted bot-title' }); |
| 513 | root.replaceChildren( |
| 514 | make('div', { className: 'bot-row' }, make('label', {}, 'message ', message), make('label', {}, 'chat ', chatType), make('label', {}, 'viewer ', viewer), make('label', {}, 'as ' |
| 515 | make('div', { className: 'bot-row' }, make('label', {}, 'bot ', botSelect), make('label', {}, 'answers ', mode), make('label', {}, delay, ' ms')), |
| 516 | title, chatData, publicData, |
| 517 | make('div', { className: 'bot-row' }, apply, byId, reset, size), |
| 518 | make('div', { className: 'bot-row' }, make('label', {}, shared, ' shared (widget_id)'), make('label', {}, 'poll ', period, ' ms'), polling), |
| 519 | list, |
| 520 | ); |
| 521 | |
| 522 | const fill = () => { |
| 523 | const c = bot.context; |
| 524 | message.value = c.message; |
| 525 | chatType.value = c.chatType ?? ''; |
| 526 | viewer.value = c.viewer === null ? '' : String(c.viewer); |
| 527 | profile.value = c.profile; |
| 528 | botSelect.value = bot.bot; |
| 529 | mode.value = bot.mode; |
| 530 | delay.value = String(bot.delayMs); |
| 531 | title.textContent = BOTS[bot.bot].title; |
| 532 | const d = bot.dataFor(file()); |
| 533 | if (document.activeElement !== chatData) chatData.value = d.chatData ?? ''; |
| 534 | if (document.activeElement !== publicData) publicData.value = d.publicData ?? ''; |
| 535 | size.textContent = `chatData ${bytes(chatData.value)}, publicData ${bytes(publicData.value)}`; |
| 536 | shared.checked = bot.shared; |
| 537 | wallet.checked = bot.wallet; |
| 538 | if (document.activeElement !== period) period.value = String(bot.pollMs); |
| 539 | polling.textContent = !bot.shared ? 'not shared: never polled' : bot.watching ? `watching: polled ${bot.polls.made}×, ${bot.polls.changed} new` : 'not watching: not polled' |
| 540 | }; |
| 541 | const renderRequests = () => { |
| 542 | list.replaceChildren(...bot.requests.slice(-12).reverse().map((r) => { |
| 543 | const outcome = r.error ? `✖ ${r.error}` : r.answer ? `→ ${JSON.stringify(r.answer.result)}` |
| 544 | const kind = r.kind === 'wallet' ? ' + wallet' : r.kind ? ` (wallet.${r.kind})` : ''; |
| 545 | const li = make('li', { title: r.answer ? JSON.stringify(r.answer) : '' }, `${r.at} ${JSON.stringify(r |
| 546 | if (!r.kind?.startsWith('s') && !r.answer && !r.error && bot.pendingRequests.includes(r)) { |
| 547 | li.append(' ', make('button', { type: 'button', textContent: 'answer', onclick: () => bot.answer(r) }), ' ', make('button', { type: 'button', textContent: 'timeout', onclick |
| 548 | } |
| 549 | return li; |
| 550 | })); |
| 551 | }; |
| 552 | const restartWith = (patch: Partial<MockBot['context']>) => { Object.assign(bot.context, patch); bot.hooks.restart(); bot.hooks.changed(); }; |
| 553 | message.addEventListener('change', () => restartWith({ message: message.value as WidgetMessageKind })); |
| 554 | chatType.addEventListener('change', () => restartWith({ chatType: (chatType.value || null) as ChatType | null })); |
| 555 | viewer.addEventListener('change', () => restartWith({ viewer: viewer.value ? Number(viewer.value) : null })); |
| 556 | profile.addEventListener('change', () => restartWith({ profile: profile.value })); |
| 557 | botSelect.addEventListener('change', () => { bot.bot = botSelect.value; fill(); }); |
| 558 | mode.addEventListener('change', () => { bot.mode = mode.value as Mode; bot.hooks.changed(); }); |
| 559 | delay.addEventListener('change', () => { bot.delayMs = Math.max(0, Number(delay.value) || 0); }); |
| 560 | for (const t of [chatData, publicData]) t.addEventListener('input', () => { size.textContent = `chatData ${bytes(chatData.value)}, publicData ${bytes(publicData.value |
| 561 | apply.addEventListener('click', () => bot.edit(file(), { chatData: chatData.value || null, publicData: publicData.value || null })); |
| 562 | reset.addEventListener('click', () => { bot.resetData(file()); chatData.value = ''; publicData.value = ''; bot.hooks.restart(); }); |
| 563 | byId.addEventListener('click', () => bot.editShared(file(), publicData.value || null)); |
| 564 | shared.addEventListener('change', () => { bot.shared = shared.checked; bot.hooks.changed(); }); |
| 565 | wallet.addEventListener('change', () => { bot.wallet = wallet.checked; bot.hooks.restart(); bot.hooks.changed(); }); |
| 566 | period.addEventListener('change', () => { bot.pollMs = Math.max(100, Number(period.value) || 5000); bot.hooks.changed(); }); |
| 567 | return { render: () => { fill(); renderRequests(); } }; |
| 568 | } |
| 569 | |
| 570 | /** What a client shows after `copyText`: the copied text itself (anti-swap), over the bubble for a moment. */ |
| 571 | export function showCopied(bubble: HTMLElement, text: string) { |
| 572 | const tag = make('div', { className: 'bubble-gesture bubble-copied', textContent: `Copied: ${text}` }); |
| 573 | bubble.querySelector('.bubble-copied')?.remove(); |
| 574 | bubble.appendChild(tag); |
| 575 | setTimeout(() => tag.remove(), 2000); |
| 576 | } |
| 577 | |
| 578 | const TON = (nano: string | number) => `${(Number(nano) / 1e9).toLocaleString('en-US', { |
| 579 | |
| 580 | /** |
| 581 | * The client's own wallet window over the chat (docs/sdk-v1.md §2.18, §5): who asks (the bot of the message, never the |
| 582 | * widget), what for (each message's amount and destination, or the text to sign; a warning for bytes and cells), and |
| 583 | * Confirm / Decline. Taps on it are ignored for its first 600 ms (a double tap's second tap must not land on Confirm). |
| 584 | * Resolves true on Confirm. Dev tooling: a client draws its existing TON Connect window. |
| 585 | */ |
| 586 | export function showWalletWindow(botName: string, call: WalletCall): Promise<boolean> { |
| 587 | return new Promise((resolve) => { |
| 588 | const what = call.method === 'sendTransaction' |
| 589 | ? call.transaction.messages.map((m) => make('div', { className: 'wallet-line' }, make('b', {}, TON(m.amount)), ` → ${m.address.slice(0, |
| 590 | : [call.payload.type === 'text' ? make('pre', { className: 'wallet-text' }, call.payload.text ?? '') : make('div', { className: 'wallet-warn' }, `Signs ${call. |
| 591 | const confirm = make<HTMLButtonElement>('button', { type: 'button', id: 'wallet-confirm', textContent: call.method === 'sendTransaction' ? 'Confirm and send' : 'Sign', disabled: true |
| 592 | const decline = make<HTMLButtonElement>('button', { type: 'button', id: 'wallet-decline', textContent: 'Decline', disabled: true }); |
| 593 | const sheet = make('div', { className: 'wallet-sheet', role: 'dialog' }, |
| 594 | make('div', { className: 'wallet-card' }, |
| 595 | make('div', { className: 'wallet-head' }, `@${botName}`, make('span', { className: 'muted' }, call.method === 'sendTransaction' ? ' asks you to send' : ' asks you to sign')), |
| 596 | ...what, |
| 597 | make('div', { className: 'muted wallet-from' }, `from your wallet ${MOCK_WALLET.address.slice(0, 6)}…, ${TON(MOCK_WALLET.balance)}`), |
| 598 | make('div', { className: 'wallet-buttons' }, decline, confirm))); |
| 599 | const close = (ok: boolean) => { sheet.remove(); resolve(ok); }; |
| 600 | confirm.onclick = () => close(true); |
| 601 | decline.onclick = () => close(false); |
| 602 | document.body.appendChild(sheet); |
| 603 | setTimeout(() => { confirm.disabled = decline.disabled = false; }, 600); |
| 604 | }); |
| 605 | } |
| 606 | |
| 607 | export type { Data as MockBotData, WidgetData }; |
| 608 | |