@adriangalilea/utils 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -443,6 +443,7 @@ Then `pnpm install`. Every `ctx.send` / `ctx.sendDocument` / `ctx.reply` / etc.
443
443
  | `@adriangalilea/utils/bot/profile` | `syncBotProfile(bot, { name?, description?, about?, photo?, commands?, expects?, adminIds? })` — the bot's Telegram-facing identity as CODE, never BotFather: localized name / description / About / public command list, reconciled idempotently on every boot (get → compare → set per field per language; unchanged values cost one read, so cold-start firing is rate-limit-free). `expects: { inline: true }` declares the BotFather-only capabilities the code assumes — a mismatch (inline mode off on an inline-dependent bot) DMs the admins, since the API can only detect it, not fix it. Never throws; failures log and the bot keeps running. |
444
444
  | `@adriangalilea/utils/bot/access-control` | Personal-bot ACL — gates non-admin/non-default users; admin gets DM with `[✅ Aprobar][❌ Denegar]` on first attempt; `/access` opens a persistent menu (revoke / reapprove / list pending). Backed by `@gramio/session` per-user + a small index. **Native alternative**: BotFather → Bot Settings → Access → "Restrict bot usage" — flat allow-list at Telegram. Use this plugin when you want in-bot approval flow instead of a BotFather round-trip; both can coexist. |
445
445
  | `@adriangalilea/utils/bot/allow-list` | Static allow-list by **id and/or @username** — stateless, no session/storage. `allowList({ ids?, usernames? })` is a plugin that decorates `ctx.allowed` (boolean); gate in your handlers (`if (!ctx.allowed) return`). `makeAllowList(...)` is the pure framework-free predicate. The light counterpart to `access-control` (which adds an approve/deny flow + revocable store, needing session+storage). Username caveat: a `@username` is optional and mutable, and the Bot API can't resolve username→id ahead of time — prefer `ids` when known, `usernames` is the pragmatic fallback. |
446
+ | `@adriangalilea/utils/bot/groups` | Group-chat identity as plain functions: `isGroupChat(ctx)` / `isPrivateChat(ctx)` + `isGroupAdmin(ctx, { chatId?, userId? }?)` — the `getChatMember` creator/administrator check behind every admin-gated group setting (auto-summary toggles, "dismiss" buttons on group welcomes), chat/user defaulted from the ctx. Takes real gramio ctxs and `MenuCtx` with no cast; a miswired ctx panics, an API rejection fails closed (`false`). Composition over policy: bot-owner override stays at your call site (`ctx.isAdmin \|\| await isGroupAdmin(ctx)`). |
446
447
  | `@adriangalilea/utils/bot/coalesce` | Joins client-split inbound messages back into one. When a user pastes >4096 chars, Telegram clients fragment it into separate `message` updates with no marker. Middleware detects the burst and emits one combined event. |
447
448
  | `@adriangalilea/utils/bot/llm` | The full LLM-chatbot pipeline in one module. **Input:** `streamChat(response)` parses OpenAI-compatible SSE (OpenAI, vllm, mlx-lm, llama.cpp, Together, Groq, …) into a typed `AsyncGenerator<{type: 'content' \| 'reasoning', text}>`. **Output:** `ctx.startStream()` (low-level: debounced markdown to Telegram, 4000-char split, exposes `wasPartial` after `.end()`). `ctx.startChatStream(response)` (high-level: consumes the stream, renders reasoning as a Telegram `expandable_blockquote` entity + content as streamed markdown — both go through `markdownToFormattable` with graceful degradation — returns `{ content, reasoning }`). **History:** `llmHistory({...})` returns `.plugin` (decorates `ctx.llm` with `.add() / .get() / .clear() / .all() / .clearAll()`, per-(user, thread) OpenAI `ChatMessage` shape, persisted in the shared session record so the menu's 🗑 Forget wipes it automatically) AND `.menuItem` (drop-in "🗑 Delete this thread" for `botMenu` — wipes the LLM history AND calls `deleteForumTopic` so the Telegram thread + all its messages disappear from the chat; falls back to Redis-only clear when no `threadId` is present). |
448
449
  | `@adriangalilea/utils/bot/menu` | `botMenu({ command, description, items, privacy?, personalData?, adminContact })` — `/settings` command + InlineKeyboard router. Root view always renders a `🛡️ Privacy & data` submenu button that wraps the privacy policy link plus (if `personalData: { storage }`) 🗑 Forget + 📥 Export buttons. Items take `keepRow` (render on the same row as the next item — e.g. a two-per-row language picker) and `rootExtra` (render at the bottom of the root menu, below Privacy & data). `label` / `header` / `style` / `visible` resolvers may be **async** (read your db at render time — never cache render strings in the session); `parseMode: 'HTML'` renders the header formatted (you own escaping); `personalData.onForget(ctx, userId)` wipes YOUR tables inside the same try as the session delete, so Forget either forgets everything or reports failure. `toggleMenuItem({ id, read, write, label: { off, on }, toast? })` — convenience factory for boolean-toggle items with dynamic label + optional toast, storage-agnostic via `read`/`write` closures. |
@@ -0,0 +1,33 @@
1
+ /** Minimum ctx shape the chat-type predicates read. */
2
+ export type ChatTypeCtx = {
3
+ chat?: {
4
+ type?: string;
5
+ };
6
+ };
7
+ /** Minimum ctx shape `isGroupAdmin` reads. `bot` is the running gramio Bot — typed
8
+ * `unknown` so MenuCtx and every real ctx assign without a cast; its
9
+ * `api.getChatMember` is asserted at call time. */
10
+ export type GroupAdminCtx = {
11
+ bot: unknown;
12
+ chat?: {
13
+ id?: number;
14
+ };
15
+ from?: {
16
+ id?: number;
17
+ };
18
+ };
19
+ /** True for a group or supergroup chat. */
20
+ export declare const isGroupChat: (ctx: ChatTypeCtx) => boolean;
21
+ /** True for a 1:1 private chat. */
22
+ export declare const isPrivateChat: (ctx: ChatTypeCtx) => boolean;
23
+ /**
24
+ * Whether a user is a creator/administrator of a group, per `getChatMember`. Chat and
25
+ * user default to the ctx's own (`ctx.chat.id`, `ctx.from.id` — gramio's own
26
+ * parameter-defaulting idiom); pass `chatId` / `userId` for cross-chat checks. Missing
27
+ * ids (an actor-less service event) or an API rejection answer `false`.
28
+ */
29
+ export declare function isGroupAdmin(ctx: GroupAdminCtx, opts?: {
30
+ chatId?: number;
31
+ userId?: number;
32
+ }): Promise<boolean>;
33
+ //# sourceMappingURL=groups.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"groups.d.ts","sourceRoot":"","sources":["../../src/bot/groups.ts"],"names":[],"mappings":"AAqCA,uDAAuD;AACvD,MAAM,MAAM,WAAW,GAAG;IACzB,IAAI,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACzB,CAAC;AAEF;;oDAEoD;AACpD,MAAM,MAAM,aAAa,GAAG;IAC3B,GAAG,EAAE,OAAO,CAAC;IACb,IAAI,CAAC,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACvB,IAAI,CAAC,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACvB,CAAC;AAcF,2CAA2C;AAC3C,eAAO,MAAM,WAAW,GAAI,KAAK,WAAW,KAAG,OACe,CAAC;AAE/D,mCAAmC;AACnC,eAAO,MAAM,aAAa,GAAI,KAAK,WAAW,KAAG,OACpB,CAAC;AAE9B;;;;;GAKG;AACH,wBAAsB,YAAY,CACjC,GAAG,EAAE,aAAa,EAClB,IAAI,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAC7C,OAAO,CAAC,OAAO,CAAC,CAkBlB"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Group-chat identity — chat-type predicates and the group-admin check. Worker-safe
3
+ * (no env, no OS).
4
+ *
5
+ * Telegram's Bot API has no "is this user a group admin?" primitive and neither does
6
+ * gramio: the raw material is `getChatMember` returning a member whose `status` may be
7
+ * `"creator"` or `"administrator"`. Every bot with an admin-gated group setting re-rolls
8
+ * that check; this module rolls it ONCE.
9
+ *
10
+ * These take minimum structural ctx shapes (the `bot/ctx.ts` philosophy) that real
11
+ * gramio contexts AND `bot/menu`'s `MenuCtx` satisfy by duck typing — a menu action
12
+ * gates with `isGroupAdmin(ctx)`, no cast. `ctx.bot` stays `unknown` for exactly that
13
+ * assignability (MenuCtx's own choice); a ctx whose bot has no `api.getChatMember`
14
+ * PANICS — a miswire screams, it doesn't read as "not admin".
15
+ *
16
+ * `isGroupAdmin` FAILS CLOSED on the API call itself: a `getChatMember` rejection (user
17
+ * never seen in the chat, network, the bot removed mid-tap) answers `false`, never
18
+ * throws — it is a permission gate, and a gate that throws breaks the surface it guards
19
+ * (a menu tap's single answerCallbackQuery, a command reply). That rejection is the
20
+ * messy real world; denial is the only honest answer to "I couldn't verify".
21
+ *
22
+ * Anonymous-admin caveat: an admin posting anonymously wears the group's own identity
23
+ * in `message.from` (the GroupAnonymousBot), so a MESSAGE from them fails this check.
24
+ * Callback taps always carry the real user, so inline-button gates (the settings case)
25
+ * are unaffected.
26
+ *
27
+ * @example
28
+ * // Gate a group-wide toggle: the bot's own admins always may, otherwise the
29
+ * // tapper must hold power over THIS group. (Policy composes at the call site.)
30
+ * if (!ctx.isAdmin && !(await isGroupAdmin(ctx))) return tr("groupAdminsOnly")
31
+ *
32
+ * @example
33
+ * // Cross-chat: is user 42 an admin of chat -100123?
34
+ * await isGroupAdmin(ctx, { chatId: -100123, userId: 42 })
35
+ */
36
+ import { assert } from "../offensive.js";
37
+ // The two chat-member statuses that hold power over a group. Not exported: the
38
+ // contract is the question `isGroupAdmin` answers, never status comparison.
39
+ const GROUP_ADMIN_STATUSES = new Set(["creator", "administrator"]);
40
+ /** True for a group or supergroup chat. */
41
+ export const isGroupChat = (ctx) => ctx.chat?.type === "group" || ctx.chat?.type === "supergroup";
42
+ /** True for a 1:1 private chat. */
43
+ export const isPrivateChat = (ctx) => ctx.chat?.type === "private";
44
+ /**
45
+ * Whether a user is a creator/administrator of a group, per `getChatMember`. Chat and
46
+ * user default to the ctx's own (`ctx.chat.id`, `ctx.from.id` — gramio's own
47
+ * parameter-defaulting idiom); pass `chatId` / `userId` for cross-chat checks. Missing
48
+ * ids (an actor-less service event) or an API rejection answer `false`.
49
+ */
50
+ export async function isGroupAdmin(ctx, opts = {}) {
51
+ const chatId = opts.chatId ?? ctx.chat?.id;
52
+ const userId = opts.userId ?? ctx.from?.id;
53
+ if (chatId === undefined || userId === undefined)
54
+ return false;
55
+ const bot = ctx.bot;
56
+ assert(typeof bot?.api?.getChatMember === "function", "isGroupAdmin: ctx.bot.api.getChatMember missing — not a gramio ctx?");
57
+ try {
58
+ const member = await bot.api.getChatMember({
59
+ chat_id: chatId,
60
+ user_id: userId,
61
+ });
62
+ return GROUP_ADMIN_STATUSES.has(member.status ?? "");
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ //# sour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AO,EAAE,MAAM;SACf,CAAC,CAAC;QACH,OAAO,oBAAoB,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IACtD,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC"}
@@ -16,6 +16,7 @@ export * from "./admin.js";
16
16
  export * from "./callbacks.js";
17
17
  export * from "./coalesce.js";
18
18
  export * from "./ctx.js";
19
+ export * from "./groups.js";
19
20
  export * from "./keys.js";
20
21
  export * from "./kit.js";
21
22
  export * from "./language.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bot/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bot/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC"}
package/dist/bot/index.js CHANGED
@@ -16,6 +16,7 @@ export * from "./admin.js";
16
16
  export * from "./callbacks.js";
17
17
  export * from "./coalesce.js";
18
18
  export * from "./ctx.js";
19
+ export * from "./groups.js";
19
20
  export * from "./keys.js";
20
21
  export * from "./kit.js";
21
22
  export * from "./language.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/bot/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/bot/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adriangalilea/utils",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "TypeScript utilities - logger, currency, formatter, GramIO bot plugins, and more",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -127,6 +127,10 @@
127
127
  "./bot/flags": {
128
128
  "types": "./dist/bot/flags.d.ts",
129
129
  "default": "./dist/bot/flags.js"
130
+ },
131
+ "./bot/groups": {
132
+ "types": "./dist/bot/groups.d.ts",
133
+ "default": "./dist/bot/groups.js"
130
134
  }
131
135
  },
132
136
  "files": [
@@ -151,7 +155,8 @@
151
155
  "test:worker-safe": "pnpm run build && tsx tests/worker-safe-test.ts",
152
156
  "demo:bot": "tsx tests/create-demo.ts",
153
157
  "test:tg-html": "tsx tests/tg-html-test.ts",
154
- "test:flags": "tsx tests/flags-test.ts"
158
+ "test:flags": "tsx tests/flags-test.ts",
159
+ "test:groups": "tsx tests/groups-test.ts"
155
160
  },
156
161
  "keywords": [
157
162
  "typescript",