openapi: 3.1.0
info:
  title: Widgets API
  version: "2026-12-01"
  summary: HTML-виджеты Telegram одной строкой — упаковка, отправка, живые данные, события, оплаты.
  description: |
    Ранний доступ. Ключ — https://t.me/widgetsai?start=apikey
    API бесплатно с лимитами (GET /limits). Больше лимитов или своё решение — https://t.me/volodya. Баланс и платные способности — позже (x-later).
    Версия выбирается заголовком Widgets-Version. Ключ wk_test_… работает на тестовом сервере Telegram (песочница),
    wk_live_… — на боевом. Все POST принимают Idempotency-Key (24 ч).
servers:
  - url: https://api.widgets.tg/v1
security:
  - key: []

tags:
  - { name: pack, description: Упаковка и проверка своего HTML }
  - { name: templates, description: Шаблоны и их схемы }
  - { name: widgets, description: Рендер шаблона в готовый HTML }
  - { name: messages, description: Отправка и правка данных }
  - { name: feeds, description: Одно значение на много сообщений }
  - { name: assets, description: Картинки, эмодзи, коннекторы }
  - { name: builds, description: ИИ-генерация }
  - { name: renders, description: Постер и видео виджета }
  - { name: payments, description: Stars и TON в пузыре }
  - { name: flows, description: Сценарии бота }
  - { name: events, description: Вебхуки и прокси widget_query }
  - { name: stats, description: Аналитика }
  - { name: billing, description: "Лимиты бесплатного API; баланс ⭐ и платные способности — позже" }
  - { name: runtime, description: Воркер, поиск, браузер-агент, TON — бесплатно в лимитах }

paths:
  /pack:
    post:
      tags: [pack]
      summary: Ужать HTML до ≤ 3950 Б и проверить под JSC, Nova и Android
      operationId: pack
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [html]
              properties:
                html: { type: string, description: Исходный HTML, хоть 9 КБ }
                target: { type: integer, default: 3950 }
                oracle: { type: boolean, default: true, description: Прогнать в QuickJS-песочнице }
      responses:
        "200":
          description: Упаковано
          content: { application/json: { schema: { $ref: "#/components/schemas/PackResult" } } }
        "422": { $ref: "#/components/responses/Error" }
  /lint:
    post:
      tags: [pack]
      summary: Только проверки движков, без упаковки
      operationId: lint
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [html], properties: { html: { type: string } } } } }
      responses:
        "200":
          description: Отчёт
          content: { application/json: { schema: { $ref: "#/components/schemas/Checks" } } }

  /templates:
    get:
      tags: [templates]
      summary: Каталог шаблонов
      operationId: listTemplates
      parameters:
        - { name: task, in: query, schema: { type: string }, description: "Задача каталога: booking, greeting, game, shop…" }
        - { $ref: "#/components/parameters/Cursor" }
      responses:
        "200":
          description: Список
          content:
            application/json:
              schema:
                type: object
                properties:
                  items: { type: array, items: { $ref: "#/components/schemas/Template" } }
                  next: { type: [string, "null"] }
    post:
      tags: [templates]
      summary: Опубликовать свой шаблон (автор)
      operationId: createTemplate
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id, html, params]
              properties:
                id: { type: string, pattern: "^[a-z0-9-]{3,40}$" }
                html: { type: string }
                params: { type: object, description: JSON Schema данных шаблона }
                price_stars: { type: integer, minimum: 0, description: Позже — цена шаблона для других; сейчас всегда 0 }
                public: { type: boolean, default: false, description: В каталог после модерации }
      responses:
        "201": { description: Создан, content: { application/json: { schema: { $ref: "#/components/schemas/Template" } } } }
        "422": { $ref: "#/components/responses/Error" }
  /templates/{id}:
    get:
      tags: [templates]
      summary: Шаблон и схема его данных
      operationId: getTemplate
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Шаблон, content: { application/json: { schema: { $ref: "#/components/schemas/Template" } } } }
        "404": { $ref: "#/components/responses/Error" }

  /widgets:
    post:
      tags: [widgets]
      summary: Отрисовать шаблон с данными в готовый HTML (отправляете сами)
      operationId: renderWidget
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/WidgetInput" } } }
      responses:
        "200":
          description: Готово
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, example: wgt_8Kq2 }
                  html: { type: string }
                  chat_data: { type: string, description: Начальные данные, ≤ 1000 знаков }
                  public_data: { type: string }
                  pending_chunks: { type: integer, description: Сколько кусков картинок дошлём после отправки }
                  preview_url: { type: string, format: uri }
                  bytes: { type: integer }
                  mark: { type: boolean }
                  checks: { $ref: "#/components/schemas/Checks" }
        "422": { $ref: "#/components/responses/Error" }

  /messages:
    post:
      tags: [messages]
      summary: Отправить виджет в чат
      operationId: sendMessage
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: "#/components/schemas/WidgetInput"
                - type: object
                  required: [chat_id]
                  properties:
                    chat_id: { oneOf: [{ type: integer }, { type: string }] }
                    widget_id: { type: string, description: Вместо template/html — уже отрисованный }
                    feed: { type: string, description: Подписать сообщение на фид }
                    source: { $ref: "#/components/schemas/Source" }
                    shared: { type: boolean, default: false, description: sendSharedWidget — данные общие для группы }
                    fallback: { type: string, enum: [auto, none], default: auto, description: "auto — постер с кнопкой, где виджеты не пускают" }
                    bot: { type: string, description: "Бот проекта; по умолчанию — основной" }
      responses:
        "200": { description: Отправлено, content: { application/json: { schema: { $ref: "#/components/schemas/Message" } } } }
        "202": { description: В очереди (лимит Telegram), итог — событием message.sent, content: { application/json: { schema: { $ref: "#/components/schemas/Message" } } } }
        "429": { $ref: "#/components/responses/Error" }
        "422": { $ref: "#/components/responses/Error" }
  /messages/{id}:
    get:
      tags: [messages]
      summary: Сообщение, его данные и счётчики
      operationId: getMessage
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Сообщение, content: { application/json: { schema: { $ref: "#/components/schemas/Message" } } } }
  /messages/{id}/data:
    patch:
      tags: [messages]
      summary: Живые данные без переотправки (editMessageWidgetData)
      operationId: patchMessageData
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { $ref: "#/components/parameters/Idem" }
      requestBody:
        required: true
        content:
          application/merge-patch+json:
            schema: { type: object, description: "Слияние по RFC 7396; итог ≤ 1000 знаков, иначе too_big" }
      responses:
        "200": { description: Применено, content: { application/json: { schema: { $ref: "#/components/schemas/Message" } } } }

  /feeds/{key}:
    put:
      tags: [feeds]
      summary: Записать значение — правка уходит всем подписанным сообщениям
      operationId: putFeed
      parameters:
        - { name: key, in: path, required: true, schema: { type: string, example: "slots:anya" } }
        - { $ref: "#/components/parameters/Idem" }
      requestBody:
        required: true
        content: { application/json: { schema: { type: object } } }
      responses:
        "202":
          description: Принято; рассылка очередью ≤ 30 правок/с на бота
          content:
            application/json:
              schema:
                type: object
                properties:
                  key: { type: string }
                  version: { type: integer }
                  subscribers: { type: integer }
                  eta_s: { type: number }
    get:
      tags: [feeds]
      summary: Текущее значение и число подписанных
      operationId: getFeed
      parameters: [{ name: key, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Фид, content: { application/json: { schema: { type: object } } } }

  /assets:
    post:
      tags: [assets]
      summary: Картинка или эмодзи в data:-виде под бюджет виджета
      description: 'То же доступно без вызова — `{"$asset": "<kind>:<src>"}` прямо в data шаблона.'
      operationId: createAsset
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [kind, src]
              properties:
                kind: { type: string, enum: [image, userpic, emoji, custom-emoji, glass-bg, palette, blocks, face-fit] }
                src: { type: string, description: "Ссылка, @имя, эмодзи или custom_emoji_id" }
                size: { type: integer, description: Сторона в px }
                fx: { type: array, items: { type: string, example: duotone } }
      responses:
        "200":
          description: Готово
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  data_url: { type: string }
                  bytes: { type: integer }
                  colors: { type: array, items: { type: string } }
        "422": { $ref: "#/components/responses/Error" }
  /connectors/{kind}:
    get:
      tags: [assets]
      summary: Данные из внешних сервисов готовыми полями (music, steam, steam-price, dota, price)
      operationId: connector
      parameters:
        - { name: kind, in: path, required: true, schema: { type: string, enum: [music, steam, steam-price, dota, price] } }
        - { name: q, in: query, required: true, schema: { type: string } }
      responses:
        "200": { description: Поля, content: { application/json: { schema: { type: object } } } }

  /builds:
    post:
      tags: [builds]
      summary: Сгенерировать виджет по описанию (кредиты; правки бесплатны)
      operationId: createBuild
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [prompt]
              properties:
                prompt: { type: string }
                from: { type: string, description: "widget_id для правки" }
                lang: { type: string, default: ru }
      responses:
        "202": { description: Запущено; итог — событием build.done, content: { application/json: { schema: { $ref: "#/components/schemas/Job" } } } }
        "429": { $ref: "#/components/responses/Error" }
  /builds/{id}:
    get:
      tags: [builds]
      operationId: getBuild
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Задача, content: { application/json: { schema: { $ref: "#/components/schemas/Job" } } } }

  /renders:
    post:
      tags: [renders]
      summary: Постер PNG или видео MP4 виджета для соцсетей
      operationId: createRender
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [widget_id, format]
              properties:
                widget_id: { type: string }
                format: { type: string, enum: [png, mp4] }
                frame: { type: string, enum: [bubble, chat, phone], default: chat }
                aspect: { type: string, enum: ["1:1", "9:16", "16:9"], default: "9:16" }
                seconds: { type: integer, maximum: 15, default: 6 }
                taps: { type: array, items: { type: object, properties: { at_ms: { type: integer }, x: { type: number }, y: { type: number } } }, description: Нажатия в ролике }
                theme: { type: string, enum: [light, dark], default: dark }
      responses:
        "202": { description: Запущено; итог — render.done, content: { application/json: { schema: { $ref: "#/components/schemas/Job" } } } }
  /renders/{id}:
    get:
      tags: [renders]
      operationId: getRender
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Задача, content: { application/json: { schema: { $ref: "#/components/schemas/Job" } } } }

  /invoices:
    post:
      tags: [payments]
      summary: Счёт в пузыре — Stars на бот продавца или TON на его кошелёк
      description: Деньги идут продавцу напрямую; мы считаем число оплат. Итог — payment.succeeded.
      operationId: createInvoice
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [message_id, currency, amount, title]
              properties:
                message_id: { type: string }
                currency: { type: string, enum: [XTR, TON] }
                amount: { type: string, description: "⭐ целым или TON строкой: \"1.5\"" }
                title: { type: string }
                payload: { type: string, maxLength: 128, description: Ваш номер заказа — вернётся в событии }
      responses:
        "201":
          description: Счёт
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  status: { type: string, enum: [open, paid, expired, refunded] }
                  ton: { type: object, properties: { address: { type: string }, amount_nano: { type: string }, comment: { type: string }, links: { type: array, items: { type: string } } } }
  /invoices/{id}:
    get:
      tags: [payments]
      operationId: getInvoice
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Счёт, content: { application/json: { schema: { type: object } } } }

  /widgets/{id}/stats:
    get:
      tags: [stats]
      summary: Воронка одного виджета (объекта) — по дням или по источникам
      operationId: widgetStats
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: from, in: query, schema: { type: string, format: date } }
        - { name: to, in: query, schema: { type: string, format: date } }
        - { name: group_by, in: query, schema: { type: string, enum: [day, source, chat_type], default: day } }
      responses:
        "200": { description: Ряды, content: { application/json: { schema: { type: object, properties: { rows: { type: array, items: { $ref: "#/components/schemas/Funnel" } } } } } } }
  /attribution:
    get:
      tags: [stats]
      summary: Откуда показы, тапы, пересылки, переходы и оплаты (бесплатно)
      operationId: attribution
      parameters:
        - { name: template, in: query, schema: { type: string } }
        - { name: campaign, in: query, schema: { type: string } }
        - { name: from, in: query, schema: { type: string, format: date } }
        - { name: to, in: query, schema: { type: string, format: date } }
        - { name: group_by, in: query, schema: { type: string, enum: [source, channel, campaign, forward], default: source } }
      responses:
        "200": { description: Ряды, content: { application/json: { schema: { type: object, properties: { rows: { type: array, items: { $ref: "#/components/schemas/Funnel" } } } } } } }
        "429": { $ref: "#/components/responses/Error" }
  /promos:
    post:
      x-later: true
      tags: [stats]
      summary: Позже — кампания медиации — виджет в каналах каталога, оплата за тап или конверсию (⭐ с баланса)
      operationId: createPromo
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [widget_id, budget_stars, pay_for, price_stars]
              properties:
                widget_id: { type: string }
                budget_stars: { type: integer, minimum: 100 }
                pay_for: { type: string, enum: [tap, conversion], description: "tap — уникальный (widget_id, viewer) за 24 ч; conversion — подтверждённая оплата" }
                price_stars: { type: number }
                channels: { type: array, items: { type: string }, description: Пусто — подбор по теме каталога }
      responses:
        "201": { description: Кампания, content: { application/json: { schema: { type: object } } } }
        "429": { $ref: "#/components/responses/Error" }
  /promos/{id}:
    get:
      x-later: true
      tags: [stats]
      summary: Позже — Расход, засчитанные и снятые антифродом события по каналам
      operationId: getPromo
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Кампания, content: { application/json: { schema: { type: object } } } }

  /limits:
    get:
      tags: [billing]
      summary: Лимиты бесплатного API на проект — сколько можно в сутки и сколько осталось
      operationId: getLimits
      responses:
        "200":
          description: Лимиты
          content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/Limit" } } } }
  /balance:
    get:
      x-later: true
      tags: [billing]
      summary: Позже — Баланс ⭐ проекта и лимиты в день
      operationId: getBalance
      responses:
        "200": { description: Баланс, content: { application/json: { schema: { $ref: "#/components/schemas/Balance" } } } }
  /balance/topup:
    post:
      x-later: true
      tags: [billing]
      summary: Позже — Счёт Stars на пополнение (ссылка на оплату в @widgetsai)
      operationId: topup
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [stars], properties: { stars: { type: integer, enum: [50, 250, 1000] }, auto: { type: boolean, default: false, description: Подписка Stars раз в 30 дней } } } } }
      responses:
        "201": { description: Счёт, content: { application/json: { schema: { type: object, properties: { invoice_link: { type: string, format: uri } } } } } }
  /balance/limits:
    put:
      x-later: true
      tags: [billing]
      summary: Позже — Лимит расхода в сутки — на проект и на каждую способность
      operationId: putLimits
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                daily_stars: { type: number, default: 100 }
                per_capability: { type: object, additionalProperties: { type: number }, example: { search: 20, browser: 30 } }
                warn_at: { type: number, default: 0.8 }
      responses:
        "200": { description: Лимиты, content: { application/json: { schema: { $ref: "#/components/schemas/Balance" } } } }
  /usage:
    get:
      x-later: true
      tags: [billing]
      summary: Позже — Расход по способностям, ключам, виджетам и дням
      operationId: usage
      parameters:
        - { name: from, in: query, schema: { type: string, format: date } }
        - { name: to, in: query, schema: { type: string, format: date } }
        - { name: group_by, in: query, schema: { type: string, enum: [capability, day, key, widget], default: capability } }
      responses:
        "200":
          description: Ряды
          content:
            application/json:
              schema:
                type: object
                properties:
                  rows:
                    type: array
                    items: { type: object, properties: { key: { type: string }, units: { type: number }, example: { type: string, description: "«Поиск 312 × 1 ⭐ — виджет “Где дешевле”»" } } }
  /workers:
    post:
      tags: [runtime]
      summary: Выложить свой JS — отвечает на request виджета, по cron и на вебхук
      operationId: createWorker
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code: { type: string, description: "export default { request(e, env), cron(env), webhook(req, env) }" }
                routes: { type: array, items: { type: string }, description: "Префиксы request, напр. wheel:" }
                cron: { type: string, example: "0 * * * *" }
                runtime: { type: string, enum: [call, persistent], default: call, description: "persistent — постоянный процесс, оплата посуточно" }
                fallback: { type: string, description: Ответ виджету при нуле на балансе }
      responses:
        "201": { description: Воркер, content: { application/json: { schema: { type: object, properties: { id: { type: string }, url: { type: string, format: uri } } } } } }
  /workers/{id}/invoke:
    post:
      tags: [runtime]
      summary: Вызвать воркер вручную (отладка)
      operationId: invokeWorker
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      requestBody: { content: { application/json: { schema: { type: object } } } }
      responses:
        "200": { description: Ответ, content: { application/json: { schema: { type: object, properties: { result: {}, ms: { type: integer } } } } } }
        "429": { $ref: "#/components/responses/Error" }
  /search:
    post:
      tags: [runtime]
      summary: Поиск в интернете — 10 ссылок со сниппетами
      operationId: search
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [q], properties: { q: { type: string }, lang: { type: string } } } } }
      responses:
        "200": { description: Результаты, content: { application/json: { schema: { type: object, properties: { items: { type: array, items: { type: object, properties: { title: { type: string }, url: { type: string }, snippet: { type: string } } } } } } } } }
        "429": { $ref: "#/components/responses/Error" }
  /browse:
    post:
      tags: [runtime]
      summary: Браузер-агент — открыть страницу и вытащить поля, или задача до 10 шагов
      operationId: browse
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                url: { type: string, format: uri }
                extract: { type: object, description: "Поля и их смысл: {price: \"цена товара\"}" }
                task: { type: string, description: Задача агенту вместо url+extract; до 10 шагов }
      responses:
        "200": { description: Поля, content: { application/json: { schema: { type: object, properties: { fields: { type: object }, steps: { type: integer } } } } } }
        "202": { description: Задача агента запущена, content: { application/json: { schema: { $ref: "#/components/schemas/Job" } } } }
        "429": { $ref: "#/components/responses/Error" }
  /ton/accounts/{address}:
    get:
      tags: [runtime]
      summary: Баланс адреса TON; /nfts, /jettons, /events — коллекция, токены, история
      operationId: tonAccount
      parameters:
        - { name: address, in: path, required: true, schema: { type: string } }
        - { name: include, in: query, schema: { type: array, items: { type: string, enum: [nfts, jettons, events] } }, style: form, explode: false }
      responses:
        "200": { description: Счёт, content: { application/json: { schema: { type: object } } } }
  /ton/emulate:
    post:
      tags: [runtime]
      summary: Эмуляция транзакции до подписи — что спишется и что придёт
      operationId: tonEmulate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from, messages]
              properties:
                from: { type: string }
                messages: { type: array, items: { type: object, properties: { address: { type: string }, amount: { type: string }, payload: { type: string } } }, description: Формат TON Connect, как wallet.sendTransaction }
      responses:
        "200":
          description: Итог
          content: { application/json: { schema: { type: object, properties: { fee_nano: { type: string }, balance_change_nano: { type: string }, receives: { type: array, items: { type: object } }, risk: { type: array, items: { type: string } } } } } }
        "429": { $ref: "#/components/responses/Error" }

  /flow-templates:
    get:
      tags: [flows]
      summary: Готовые сценарии с настройками (запись, игра с рекордами, лаба, магазин, секретарь)
      operationId: listFlowTemplates
      responses:
        "200": { description: Список, content: { application/json: { schema: { type: array, items: { type: object } } } } }
  /flows:
    post:
      tags: [flows]
      summary: Включить сценарий на боте проекта
      operationId: createFlow
      parameters: [{ $ref: "#/components/parameters/Idem" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [template]
              properties:
                template: { type: string, example: booking }
                settings: { type: object }
      responses:
        "201": { description: Сценарий, content: { application/json: { schema: { type: object } } } }
  /flows/{id}/test:
    post:
      tags: [flows]
      summary: Прогнать сценарий в личке владельца
      operationId: testFlow
      parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
      responses:
        "200": { description: Журнал прогона, content: { application/json: { schema: { type: object } } } }

  /webhooks:
    post:
      tags: [events]
      summary: Подписать адрес на события проекта
      operationId: createWebhook
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string, format: uri }
                events: { type: array, items: { $ref: "#/components/schemas/EventType" } }
      responses:
        "201":
          description: Создан; secret показывается один раз
          content: { application/json: { schema: { type: object, properties: { id: { type: string }, secret: { type: string } } } } }
  /widget-query:
    post:
      tags: [events]
      summary: Прокси — ваш бот получил widget_query, мы возвращаем тело для answerWidgetQuery
      operationId: widgetQuery
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [update], properties: { update: { type: object } } } } }
      responses:
        "200":
          description: Ответ для Telegram
          content:
            application/json:
              schema:
                type: object
                properties:
                  answer: { type: object, description: Тело answerWidgetQuery }
                  chat_data: { type: [string, "null"], description: Правка данных, если нужна }

  /stats:
    get:
      tags: [stats]
      summary: Открытия, тапы, пересылки, оплаты
      operationId: stats
      parameters:
        - { name: template, in: query, schema: { type: string } }
        - { name: message_id, in: query, schema: { type: string } }
        - { name: from, in: query, schema: { type: string, format: date } }
        - { name: to, in: query, schema: { type: string, format: date } }
        - { name: group_by, in: query, schema: { type: string, enum: [day, template, chat_type], default: day } }
      responses:
        "200":
          description: Ряды
          content:
            application/json:
              schema:
                type: object
                properties:
                  rows:
                    type: array
                    items: { type: object, properties: { key: { type: string }, opened: { type: integer }, tapped: { type: integer }, forwarded: { type: integer }, paid: { type: integer } } }

webhooks:
  event:
    post:
      summary: Событие проекта; подпись в Widgets-Signature (t=…,v1=HMAC-SHA256 от "t.тело")
      description: Повтор 8 раз с ростом паузы до 6 ч. Для widget.request ответ ≤ 2 с уходит в answerWidgetQuery.
      requestBody:
        content: { application/json: { schema: { $ref: "#/components/schemas/Event" } } }
      responses:
        "200":
          description: Принято; для widget.request тело — ответ виджету
          content: { application/json: { schema: { type: object, properties: { text: { type: string }, alert: { type: boolean }, data: { type: object } } } } }

components:
  securitySchemes:
    key: { type: http, scheme: bearer, description: "wk_test_… или wk_live_…, права send, data, build, pay, read" }
  parameters:
    Idem: { name: Idempotency-Key, in: header, schema: { type: string, maxLength: 64 } }
    Cursor: { name: cursor, in: query, schema: { type: string } }
  responses:
    Error:
      description: Ошибка
      content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
  schemas:
    Error:
      type: object
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              enum: [invalid_params, too_big, engine_unsupported, widgets_not_allowed, bot_blocked, chat_not_found, bot_token_invalid, rate_limited, limit_reached, idempotency_conflict, asset_unreachable, not_found]
            message: { type: string }
            hint: { type: string }
            docs: { type: string, format: uri }
            details: { type: object }
    WidgetInput:
      type: object
      properties:
        template: { type: string, example: booking }
        html: { type: string, description: Свой HTML вместо шаблона — упакуем }
        data: { type: object, description: "Параметры шаблона; {\"$asset\": \"userpic:@name\"} — картинка" }
        lang: { type: string, default: ru }
        mark: { type: boolean, default: true, description: false — по плану или за кредиты }
        height: { type: integer }
    Checks:
      type: object
      properties:
        ok: { type: boolean }
        clients:
          type: object
          properties:
            ios: { type: string, enum: [ok, warn, fail] }
            android: { type: string, enum: [ok, warn, fail] }
            desktop: { type: string, enum: [ok, warn, fail] }
        issues:
          type: array
          items: { type: object, properties: { rule: { type: string }, client: { type: string }, line: { type: integer }, message: { type: string } } }
    PackResult:
      type: object
      properties:
        html: { type: string }
        bytes: { type: integer, description: zlib, как мерит бот }
        bytes_telegram: { type: integer, description: zlib, как мерит сервер Telegram }
        from_bytes: { type: integer }
        fits: { type: boolean }
        steps: { type: array, items: { type: object, properties: { id: { type: string }, bytes: { type: integer }, kept: { type: boolean } } } }
        checks: { $ref: "#/components/schemas/Checks" }
    Template:
      type: object
      properties:
        id: { type: string }
        title: { type: string }
        task: { type: string }
        params: { type: object, description: JSON Schema }
        example: { type: object }
        preview_url: { type: string, format: uri }
        author: { type: string }
        price_stars: { type: integer }
        features: { type: array, items: { type: string, enum: [tap, data, pay, images] } }
    Message:
      type: object
      properties:
        id: { type: string, example: msg_3Xr9 }
        status: { type: string, enum: [queued, sent, fallback, failed] }
        chat_id: { oneOf: [{ type: integer }, { type: string }] }
        telegram_message_id: { type: integer }
        feed: { type: [string, "null"] }
        bytes: { type: integer }
        mark: { type: boolean }
        clients: { $ref: "#/components/schemas/Checks/properties/clients" }
        counters: { type: object, properties: { opened: { type: integer }, tapped: { type: integer }, paid: { type: integer } } }
    Job:
      type: object
      properties:
        id: { type: string }
        status: { type: string, enum: [queued, running, done, failed] }
        result: { type: object, description: "build: widget_id и html; render: url файла" }
    EventType:
      type: string
      enum: [widget.shown, widget.tapped, widget.forward_tapped, widget.request, link.opened, message.sent, message.failed, payment.succeeded, payment.refunded, promo.charged, build.done, render.done, flow.fired]
    Limit:
      type: object
      properties:
        id: { type: string, enum: [requests, sends, data_edits, feeds, pack, assets, asset_storage, connectors, build, render_png, render_mp4, worker, search, browser, browser_task, ton_api, ton_emulate] }
        unit: { type: string, example: "отправок в сутки" }
        per_day: { type: number, example: 10000 }
        used: { type: number }
        reset_at: { type: string, format: date-time }
    Balance:
      x-later: true
      type: object
      properties:
        stars: { type: number, description: Дробно, до тысячных }
        today_spent: { type: number }
        limits: { type: object, properties: { daily_stars: { type: number }, per_capability: { type: object, additionalProperties: { type: number } }, warn_at: { type: number } } }
        auto_topup: { type: boolean }
    Source:
      type: object
      description: Метка источника; едет в chat_data (и в public_data объекта для пересылок) и в startapp ссылок виджета
      properties:
        channel: { type: string, example: "@coffee_news" }
        post: { type: integer }
        campaign: { type: string, maxLength: 24, pattern: "^[A-Za-z0-9_-]+$" }
        promo: { type: string, description: id кампании медиации }
    Funnel:
      type: object
      description: Только агрегаты; число меньше 5 отдаётся как null и флагом lt5
      properties:
        key: { type: string }
        shown: { type: [integer, "null"], description: Только личка; в группах, каналах и пересылках показ = первый тап }
        tapped: { type: [integer, "null"] }
        unique_tappers: { type: [integer, "null"] }
        forward_taps: { type: [integer, "null"] }
        links_opened: { type: [integer, "null"] }
        paid: { type: [integer, "null"] }
        revenue: { type: object, properties: { XTR: { type: integer }, TON: { type: string } } }
        quarantined: { type: integer, description: Тапы, снятые антифродом }
        lt5: { type: boolean }
    Event:
      type: object
      properties:
        id: { type: string }
        type: { $ref: "#/components/schemas/EventType" }
        created: { type: integer }
        project: { type: string }
        live: { type: boolean }
        data: { type: object }
