Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,164 @@
# OpenSpec Change: enterprise-telegram-client
- **Change ID**: enterprise-telegram-client
- **Package**: `@suaveplan/telegram-client`
- **Category**: universal
- **Target path**: `universal/social/telegram-client`
- **Status**: IN PROGRESS
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/telegram-client.md`
---
## Summary
Deliver `@suaveplan/telegram-client` on the genesis branch from scratch at enterprise quality. The package provides a generic Telegram Bot API client: `sendMessage`, `sendPhoto`, `sendDocument`, `sendAudio`, `sendVideo`, `editMessageText`, `deleteMessage`, `answerCallbackQuery`, `answerInlineQuery`, `setWebhook`/`deleteWebhook`, `getUpdates` long-poll loop, inline keyboard builder, reply keyboard builder, and a `TelegramBot` facade. Injectable fetch; no `node-telegram-bot-api` dependency. Genesis adds structured errors, Zod schemas, OTel instrumentation, retry with circuit breaker, and `AbortSignal` cancellation.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | `TelegramError`; `TELEGRAM.*` error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock` |
| `@suaveplan/retry` (`workspace:^`) | Retry + circuit breaker for API calls |
| `zod` (`catalog:forms`) | Schema validation |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### `TelegramBot`
```ts
class TelegramBot {
constructor(options: TelegramBotOptions)
// Messaging
sendMessage(chatId: ChatId, text: string, options?: SendMessageOptions): Promise<TelegramMessage>
sendPhoto(chatId: ChatId, photo: string | Uint8Array, options?: SendMediaOptions): Promise<TelegramMessage>
sendDocument(chatId: ChatId, document: string | Uint8Array, options?: SendMediaOptions): Promise<TelegramMessage>
editMessageText(chatId: ChatId, messageId: number, text: string, options?: EditOptions): Promise<TelegramMessage>
deleteMessage(chatId: ChatId, messageId: number): Promise<void>
forwardMessage(toChatId: ChatId, fromChatId: ChatId, messageId: number): Promise<TelegramMessage>
// Callbacks and inline
answerCallbackQuery(callbackQueryId: string, options?: AnswerCallbackOptions): Promise<void>
answerInlineQuery(inlineQueryId: string, results: InlineQueryResult[]): Promise<void>
// Webhooks and polling
setWebhook(url: string, options?: WebhookOptions): Promise<void>
deleteWebhook(): Promise<void>
getUpdates(options?: GetUpdatesOptions): AsyncGenerator<TelegramUpdate>
// Bot info
getMe(): Promise<TelegramUser>
}
type ChatId = number | string
interface TelegramBotOptions {
token: string
retryOptions?: RetryOptions
fetch?: typeof globalThis.fetch
clock?: Clock
logger?: LoggerLike
}
```
### Keyboard builders
```ts
function inlineKeyboard(rows: InlineKeyboardButton[][]): InlineKeyboardMarkup
function replyKeyboard(rows: KeyboardButton[][], options?: ReplyKeyboardOptions): ReplyKeyboardMarkup
function removeKeyboard(): ReplyKeyboardRemove
```
### Error codes
```ts
type TelegramErrorCode =
| 'TELEGRAM_AUTH_FAILED'
| 'TELEGRAM_API_ERROR'
| 'TELEGRAM_RATE_LIMITED'
| 'TELEGRAM_CHAT_NOT_FOUND'
| 'TELEGRAM_MESSAGE_NOT_FOUND'
| 'TELEGRAM_WEBHOOK_FAILED'
| 'TELEGRAM_ABORTED'
```
---
## Genesis additions
1. **`TelegramError`** extends `SuaveplanError` with seven stable codes.
2. **Zod schemas** for `TelegramMessage`, `TelegramUpdate`, `TelegramUser`, `SendMessageOptions`, `InlineKeyboardMarkup`, `ReplyKeyboardMarkup`, `InlineQueryResult`.
3. **Long-poll loop** — `getUpdates` returns an `AsyncGenerator<TelegramUpdate>` that manages offset tracking and exits cleanly on `AbortSignal`.
4. **Rate-limit handling** — Telegram returns 429 with `retry_after`; the client waits the prescribed delay before retrying.
5. **OTel instrumentation** — span `telegram.api_call` with attribute `telegram.method`; counter `telegram.api_total`; histogram `telegram.api_duration_ms`.
6. **Property-based tests** — keyboard builder produces valid nested JSON for arbitrary row/button configurations.
---
## File layout
```text
universal/social/telegram-client/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
core/
telegram-bot/
telegram-bot.ts
telegram-bot.md
telegram-bot.types.ts
telegram-bot.test.ts
index.ts
api-caller/
api-caller.ts
api-caller.md
api-caller.test.ts
index.ts
update-poller/
update-poller.ts
update-poller.md
update-poller.test.ts
index.ts
keyboards/
keyboard-builder/
keyboard-builder.ts
keyboard-builder.md
keyboard-builder.test.ts
index.ts
__benchmarks__/
telegram-client.bench.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Downstream consumers**: `@suaveplan/message-bridge`, `@suaveplan/notification-channel`.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/retry`.

View File

@@ -0,0 +1,68 @@
# Tasks: enterprise-telegram-client
**Change ID**: enterprise-telegram-client
**Package**: `@suaveplan/telegram-client`
**Target path**: `universal/social/telegram-client`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/retry`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold
- [ ] Create `universal/social/telegram-client/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
---
## 2. Types + errors
- [ ] `src/types/common.ts` — `TelegramBotOptions`, `SendMessageOptions`, `SendMediaOptions`, `EditOptions`, `AnswerCallbackOptions`, `GetUpdatesOptions`, `WebhookOptions`, `TelegramMessage`, `TelegramUpdate`, `TelegramUser`, `InlineQueryResult`, `InlineKeyboardMarkup`, `ReplyKeyboardMarkup`, `ReplyKeyboardRemove`.
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
- [ ] `src/error-codes.ts` — `TelegramErrorCode` (7 codes), metadata, register, eager call.
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas.
---
## 3. Core modules
- [ ] **`src/core/api-caller/`** — `ApiCaller`: calls `https://api.telegram.org/bot{token}/method`; parses JSON; throws `TELEGRAM_API_ERROR` on `ok:false` (with Telegram `error_code` and `description`); handles 429 with `retry_after`; wraps with `@suaveplan/retry`. Tests: success, ok:false, 429.
- [ ] **`src/core/telegram-bot/`** — `TelegramBot`: implements all public methods. `sendPhoto`/`sendDocument` with URL string uses `photo=url` form data; with `Uint8Array` uses `multipart/form-data`. Tests: `sendMessage` text+HTML parse_mode, `sendPhoto` URL, `editMessageText`, `deleteMessage`, `answerCallbackQuery`, `setWebhook`, `deleteWebhook`, `getMe`.
- [ ] **`src/core/update-poller/`** — `getUpdates(options)`: `AsyncGenerator<TelegramUpdate>` that manages `offset` (last_update_id + 1); each iteration calls `getUpdates` API with `timeout=25` (long-poll); on `AbortSignal`, finishes current batch and yields. Tests: yields updates in order, offset advances, abort exits generator cleanly.
- [ ] **`src/keyboards/keyboard-builder/`** — `inlineKeyboard`, `replyKeyboard`, `removeKeyboard`: pure constructors. Tests: 2×2 inline, 3-button reply, remove, ForceReply.
---
## 4. OTel instrumentation
- [ ] Span `telegram.api_call` with attribute `telegram.method`; counter `telegram.api_total`; histogram `telegram.api_duration_ms`.
---
## 5. Property-based tests (`tests/property.test.ts`)
- [ ] Keyboard builder: for arbitrary row/button arrays, `inlineKeyboard(rows)` produces JSON with `inline_keyboard` array of same dimensions.
---
## 6. Benchmarks (`src/__benchmarks__/telegram-client.bench.ts`)
- [ ] `inlineKeyboard` construction for 10-row × 5-button keyboard 100 000 times.
---
## 7. Docs + verify
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/telegram-client` — green.
- [ ] `bunx turbo test:coverage --filter=@suaveplan/telegram-client` — 100%.
- [ ] `bun scripts/publish.ts --package @suaveplan/telegram-client`.
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-telegram-client/`.