teledzik 1.0.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.
Files changed (198) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1126 -0
  3. package/filters.d.ts +1 -0
  4. package/filters.js +1 -0
  5. package/format.d.ts +1 -0
  6. package/format.js +1 -0
  7. package/future.d.ts +1 -0
  8. package/future.js +1 -0
  9. package/lib/button.js +101 -0
  10. package/lib/cli.mjs +105 -0
  11. package/lib/composer.js +581 -0
  12. package/lib/context.js +1300 -0
  13. package/lib/core/helpers/ai-stream.js +69 -0
  14. package/lib/core/helpers/args.js +58 -0
  15. package/lib/core/helpers/check.js +56 -0
  16. package/lib/core/helpers/compact.js +17 -0
  17. package/lib/core/helpers/deunionize.js +13 -0
  18. package/lib/core/helpers/formatting.js +89 -0
  19. package/lib/core/helpers/input-box.js +87 -0
  20. package/lib/core/helpers/rich-sanitizer.js +31 -0
  21. package/lib/core/helpers/smart-queue.js +70 -0
  22. package/lib/core/helpers/util.js +50 -0
  23. package/lib/core/network/client.js +318 -0
  24. package/lib/core/network/error.js +21 -0
  25. package/lib/core/network/multipart-stream.js +61 -0
  26. package/lib/core/network/polling.js +86 -0
  27. package/lib/core/network/webhook.js +54 -0
  28. package/lib/core/types/rich-message.js +287 -0
  29. package/lib/core/types/typegram.js +18 -0
  30. package/lib/filters.js +69 -0
  31. package/lib/format.js +38 -0
  32. package/lib/future.js +166 -0
  33. package/lib/index.js +61 -0
  34. package/lib/input.js +61 -0
  35. package/lib/markup.js +111 -0
  36. package/lib/middleware.js +2 -0
  37. package/lib/paginated.js +76 -0
  38. package/lib/reactions.js +81 -0
  39. package/lib/router.js +45 -0
  40. package/lib/scenes/base.js +39 -0
  41. package/lib/scenes/context.js +99 -0
  42. package/lib/scenes/form-scene.js +23 -0
  43. package/lib/scenes/index.js +21 -0
  44. package/lib/scenes/stage.js +49 -0
  45. package/lib/scenes/wizard/context.js +30 -0
  46. package/lib/scenes/wizard/index.js +45 -0
  47. package/lib/scenes.js +17 -0
  48. package/lib/session.js +163 -0
  49. package/lib/telegraf.js +274 -0
  50. package/lib/telegram-types.js +6 -0
  51. package/lib/telegram.js +1286 -0
  52. package/lib/types.js +2 -0
  53. package/lib/utils.js +5 -0
  54. package/markup.d.ts +1 -0
  55. package/markup.js +1 -0
  56. package/package.json +141 -0
  57. package/scenes.d.ts +1 -0
  58. package/scenes.js +1 -0
  59. package/session.d.ts +1 -0
  60. package/session.js +1 -0
  61. package/src/button.ts +182 -0
  62. package/src/composer.ts +1008 -0
  63. package/src/context.ts +1778 -0
  64. package/src/core/helpers/ai-stream.ts +96 -0
  65. package/src/core/helpers/args.ts +63 -0
  66. package/src/core/helpers/check.ts +71 -0
  67. package/src/core/helpers/compact.ts +18 -0
  68. package/src/core/helpers/deunionize.ts +26 -0
  69. package/src/core/helpers/formatting.ts +119 -0
  70. package/src/core/helpers/input-box.ts +86 -0
  71. package/src/core/helpers/rich-sanitizer.ts +36 -0
  72. package/src/core/helpers/smart-queue.ts +89 -0
  73. package/src/core/helpers/util.ts +96 -0
  74. package/src/core/network/client.ts +396 -0
  75. package/src/core/network/error.ts +29 -0
  76. package/src/core/network/multipart-stream.ts +45 -0
  77. package/src/core/network/polling.ts +94 -0
  78. package/src/core/network/webhook.ts +58 -0
  79. package/src/core/types/rich-message.ts +375 -0
  80. package/src/core/types/typegram.ts +44 -0
  81. package/src/filters.js +69 -0
  82. package/src/filters.ts +109 -0
  83. package/src/format.js +38 -0
  84. package/src/format.ts +110 -0
  85. package/src/future.js +147 -0
  86. package/src/future.ts +231 -0
  87. package/src/index.ts +27 -0
  88. package/src/input.ts +59 -0
  89. package/src/markup.js +93 -0
  90. package/src/markup.ts +142 -0
  91. package/src/middleware.ts +24 -0
  92. package/src/paginated.ts +75 -0
  93. package/src/reactions.ts +118 -0
  94. package/src/router.ts +55 -0
  95. package/src/scenes/base.ts +52 -0
  96. package/src/scenes/context.ts +136 -0
  97. package/src/scenes/form-scene.ts +34 -0
  98. package/src/scenes/index.ts +21 -0
  99. package/src/scenes/stage.ts +71 -0
  100. package/src/scenes/wizard/context.ts +58 -0
  101. package/src/scenes/wizard/index.ts +63 -0
  102. package/src/scenes.js +17 -0
  103. package/src/scenes.ts +1 -0
  104. package/src/session.js +175 -0
  105. package/src/session.ts +204 -0
  106. package/src/telegraf.ts +385 -0
  107. package/src/telegram-types.ts +256 -0
  108. package/src/telegram.ts +1700 -0
  109. package/src/types.js +2 -0
  110. package/src/types.ts +2 -0
  111. package/src/utils.js +5 -0
  112. package/src/utils.ts +1 -0
  113. package/types.d.ts +1 -0
  114. package/types.js +1 -0
  115. package/typings/button.d.ts +35 -0
  116. package/typings/button.d.ts.map +1 -0
  117. package/typings/composer.d.ts +226 -0
  118. package/typings/composer.d.ts.map +1 -0
  119. package/typings/context.d.ts +711 -0
  120. package/typings/context.d.ts.map +1 -0
  121. package/typings/core/helpers/ai-stream.d.ts +33 -0
  122. package/typings/core/helpers/args.d.ts +10 -0
  123. package/typings/core/helpers/args.d.ts.map +1 -0
  124. package/typings/core/helpers/check.d.ts +55 -0
  125. package/typings/core/helpers/check.d.ts.map +1 -0
  126. package/typings/core/helpers/compact.d.ts +3 -0
  127. package/typings/core/helpers/compact.d.ts.map +1 -0
  128. package/typings/core/helpers/deunionize.d.ts +17 -0
  129. package/typings/core/helpers/deunionize.d.ts.map +1 -0
  130. package/typings/core/helpers/formatting.d.ts +29 -0
  131. package/typings/core/helpers/formatting.d.ts.map +1 -0
  132. package/typings/core/helpers/input-box.d.ts +32 -0
  133. package/typings/core/helpers/rich-sanitizer.d.ts +5 -0
  134. package/typings/core/helpers/smart-queue.d.ts +18 -0
  135. package/typings/core/helpers/util.d.ts +26 -0
  136. package/typings/core/helpers/util.d.ts.map +1 -0
  137. package/typings/core/network/client.d.ts +54 -0
  138. package/typings/core/network/client.d.ts.map +1 -0
  139. package/typings/core/network/error.d.ts +15 -0
  140. package/typings/core/network/error.d.ts.map +1 -0
  141. package/typings/core/network/multipart-stream.d.ts +19 -0
  142. package/typings/core/network/multipart-stream.d.ts.map +1 -0
  143. package/typings/core/network/polling.d.ts +15 -0
  144. package/typings/core/network/polling.d.ts.map +1 -0
  145. package/typings/core/network/webhook.d.ts +6 -0
  146. package/typings/core/network/webhook.d.ts.map +1 -0
  147. package/typings/core/types/rich-message.d.ts +143 -0
  148. package/typings/core/types/rich-message.d.ts.map +1 -0
  149. package/typings/core/types/typegram.d.ts +36 -0
  150. package/typings/core/types/typegram.d.ts.map +1 -0
  151. package/typings/filters.d.ts +17 -0
  152. package/typings/filters.d.ts.map +1 -0
  153. package/typings/format.d.ts +21 -0
  154. package/typings/format.d.ts.map +1 -0
  155. package/typings/future.d.ts +11 -0
  156. package/typings/future.d.ts.map +1 -0
  157. package/typings/index.d.ts +21 -0
  158. package/typings/index.d.ts.map +1 -0
  159. package/typings/input.d.ts +58 -0
  160. package/typings/input.d.ts.map +1 -0
  161. package/typings/markup.d.ts +26 -0
  162. package/typings/markup.d.ts.map +1 -0
  163. package/typings/middleware.d.ts +7 -0
  164. package/typings/middleware.d.ts.map +1 -0
  165. package/typings/paginated.d.ts +20 -0
  166. package/typings/reactions.d.ts +31 -0
  167. package/typings/reactions.d.ts.map +1 -0
  168. package/typings/router.d.ts +20 -0
  169. package/typings/router.d.ts.map +1 -0
  170. package/typings/scenes/base.d.ts +21 -0
  171. package/typings/scenes/base.d.ts.map +1 -0
  172. package/typings/scenes/context.d.ts +35 -0
  173. package/typings/scenes/context.d.ts.map +1 -0
  174. package/typings/scenes/form-scene.d.ts +17 -0
  175. package/typings/scenes/index.d.ts +10 -0
  176. package/typings/scenes/index.d.ts.map +1 -0
  177. package/typings/scenes/stage.d.ts +23 -0
  178. package/typings/scenes/stage.d.ts.map +1 -0
  179. package/typings/scenes/wizard/context.d.ts +28 -0
  180. package/typings/scenes/wizard/context.d.ts.map +1 -0
  181. package/typings/scenes/wizard/index.d.ts +15 -0
  182. package/typings/scenes/wizard/index.d.ts.map +1 -0
  183. package/typings/scenes.d.ts +1 -0
  184. package/typings/scenes.d.ts.map +1 -0
  185. package/typings/session.d.ts +54 -0
  186. package/typings/session.d.ts.map +1 -0
  187. package/typings/telegraf.d.ts +118 -0
  188. package/typings/telegraf.d.ts.map +1 -0
  189. package/typings/telegram-types.d.ts +140 -0
  190. package/typings/telegram-types.d.ts.map +1 -0
  191. package/typings/telegram.d.ts +697 -0
  192. package/typings/telegram.d.ts.map +1 -0
  193. package/typings/types.d.ts +2 -0
  194. package/typings/types.d.ts.map +1 -0
  195. package/typings/utils.d.ts +1 -0
  196. package/typings/utils.d.ts.map +1 -0
  197. package/utils.d.ts +1 -0
  198. package/utils.js +1 -0
@@ -0,0 +1,71 @@
1
+ import { isSessionContext, SessionContext } from '../session'
2
+ import SceneContextScene, {
3
+ SceneContextSceneOptions,
4
+ SceneSession,
5
+ SceneSessionData,
6
+ } from './context'
7
+ import { BaseScene } from './base'
8
+ import { Composer } from '../composer'
9
+ import { Context } from '../context'
10
+
11
+ export class Stage<
12
+ C extends SessionContext<SceneSession<D>> & {
13
+ scene: SceneContextScene<C, D>
14
+ },
15
+ D extends SceneSessionData = SceneSessionData,
16
+ > extends Composer<C> {
17
+ options: Partial<SceneContextSceneOptions<D>>
18
+ scenes: Map<string, BaseScene<C>>
19
+
20
+ constructor(
21
+ scenes: ReadonlyArray<BaseScene<C>> = [],
22
+ options?: Partial<SceneContextSceneOptions<D>>
23
+ ) {
24
+ super()
25
+ this.options = { ...options }
26
+ this.scenes = new Map<string, BaseScene<C>>()
27
+ scenes.forEach((scene) => this.register(scene))
28
+ }
29
+
30
+ register(...scenes: ReadonlyArray<BaseScene<C>>) {
31
+ scenes.forEach((scene) => {
32
+ if (scene?.id == null || typeof scene.middleware !== 'function') {
33
+ throw new Error('telegraf: Unsupported scene')
34
+ }
35
+ this.scenes.set(scene.id, scene)
36
+ })
37
+ return this
38
+ }
39
+
40
+ middleware() {
41
+ const handler = Composer.compose<C>([
42
+ (ctx, next) => {
43
+ const scenes: Map<string, BaseScene<C>> = this.scenes
44
+ const scene = new SceneContextScene<C, D>(ctx, scenes, this.options)
45
+ ctx.scene = scene
46
+ return next()
47
+ },
48
+ super.middleware(),
49
+ Composer.lazy<C>((ctx) => ctx.scene.current ?? Composer.passThru()),
50
+ ])
51
+ return Composer.optional(isSessionContext, handler)
52
+ }
53
+
54
+ static enter<C extends Context & { scene: SceneContextScene<C> }>(
55
+ ...args: Parameters<SceneContextScene<C>['enter']>
56
+ ) {
57
+ return (ctx: C) => ctx.scene.enter(...args)
58
+ }
59
+
60
+ static reenter<C extends Context & { scene: SceneContextScene<C> }>(
61
+ ...args: Parameters<SceneContextScene<C>['reenter']>
62
+ ) {
63
+ return (ctx: C) => ctx.scene.reenter(...args)
64
+ }
65
+
66
+ static leave<C extends Context & { scene: SceneContextScene<C> }>(
67
+ ...args: Parameters<SceneContextScene<C>['leave']>
68
+ ) {
69
+ return (ctx: C) => ctx.scene.leave(...args)
70
+ }
71
+ }
@@ -0,0 +1,58 @@
1
+ import SceneContextScene, { SceneSession, SceneSessionData } from '../context'
2
+ import Context from '../../context'
3
+ import { Middleware } from '../../middleware'
4
+ import { SessionContext } from '../../session'
5
+
6
+ export interface WizardContext<D extends WizardSessionData = WizardSessionData>
7
+ extends Context {
8
+ session: WizardSession<D>
9
+ scene: SceneContextScene<WizardContext<D>, D>
10
+ wizard: WizardContextWizard<WizardContext<D>>
11
+ }
12
+
13
+ export interface WizardSessionData extends SceneSessionData {
14
+ cursor: number
15
+ }
16
+
17
+ export interface WizardSession<S extends WizardSessionData = WizardSessionData>
18
+ extends SceneSession<S> {}
19
+
20
+ export default class WizardContextWizard<
21
+ C extends SessionContext<WizardSession> & {
22
+ scene: SceneContextScene<C, WizardSessionData>
23
+ },
24
+ > {
25
+ readonly state: object
26
+ constructor(
27
+ private readonly ctx: C,
28
+ private readonly steps: ReadonlyArray<Middleware<C>>
29
+ ) {
30
+ this.state = ctx.scene.state
31
+ this.cursor = ctx.scene.session.cursor ?? 0
32
+ }
33
+
34
+ get step() {
35
+ return this.steps[this.cursor]
36
+ }
37
+
38
+ get cursor() {
39
+ return this.ctx.scene.session.cursor
40
+ }
41
+
42
+ set cursor(cursor: number) {
43
+ this.ctx.scene.session.cursor = cursor
44
+ }
45
+
46
+ selectStep(index: number) {
47
+ this.cursor = index
48
+ return this
49
+ }
50
+
51
+ next() {
52
+ return this.selectStep(this.cursor + 1)
53
+ }
54
+
55
+ back() {
56
+ return this.selectStep(this.cursor - 1)
57
+ }
58
+ }
@@ -0,0 +1,63 @@
1
+ import BaseScene, { SceneOptions } from '../base'
2
+ import { Middleware, MiddlewareObj } from '../../middleware'
3
+ import WizardContextWizard, { WizardSessionData } from './context'
4
+ import Composer from '../../composer'
5
+ import Context from '../../context'
6
+ import SceneContextScene from '../context'
7
+
8
+ export class WizardScene<
9
+ C extends Context & {
10
+ scene: SceneContextScene<C, WizardSessionData>
11
+ wizard: WizardContextWizard<C>
12
+ },
13
+ >
14
+ extends BaseScene<C>
15
+ implements MiddlewareObj<C>
16
+ {
17
+ steps: Array<Middleware<C>>
18
+
19
+ constructor(id: string, ...steps: Array<Middleware<C>>)
20
+ constructor(
21
+ id: string,
22
+ options: SceneOptions<C>,
23
+ ...steps: Array<Middleware<C>>
24
+ )
25
+ constructor(
26
+ id: string,
27
+ options: SceneOptions<C> | Middleware<C>,
28
+ ...steps: Array<Middleware<C>>
29
+ ) {
30
+ let opts: SceneOptions<C> | undefined
31
+ let s: Array<Middleware<C>>
32
+ if (typeof options === 'function' || 'middleware' in options) {
33
+ opts = undefined
34
+ s = [options, ...steps]
35
+ } else {
36
+ opts = options
37
+ s = steps
38
+ }
39
+ super(id, opts)
40
+ this.steps = s
41
+ }
42
+
43
+ middleware() {
44
+ return Composer.compose<C>([
45
+ (ctx, next) => {
46
+ ctx.wizard = new WizardContextWizard<C>(ctx, this.steps)
47
+ return next()
48
+ },
49
+ super.middleware(),
50
+ (ctx, next) => {
51
+ if (ctx.wizard.step === undefined) {
52
+ ctx.wizard.selectStep(0)
53
+ return ctx.scene.leave()
54
+ }
55
+ return Composer.unwrap(ctx.wizard.step)(ctx, next)
56
+ },
57
+ ])
58
+ }
59
+
60
+ enterMiddleware() {
61
+ return Composer.compose([this.enterHandler, this.middleware()])
62
+ }
63
+ }
package/src/scenes.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./scenes/index.js"), exports);
package/src/scenes.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './scenes/index.js'
package/src/session.js ADDED
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.isSessionContext = exports.MemorySessionStore = exports.session = void 0;
16
+ const debug_1 = __importDefault(require("debug"));
17
+ const debug = (0, debug_1.default)('telegraf:session');
18
+ /**
19
+ * Returns middleware that adds `ctx.session` for storing arbitrary state per session key.
20
+ *
21
+ * The default `getSessionKey` is `${ctx.from.id}:${ctx.chat.id}`.
22
+ * If either `ctx.from` or `ctx.chat` is `undefined`, default session key and thus `ctx.session` are also `undefined`.
23
+ *
24
+ * > ⚠️ Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
25
+ * >
26
+ * > If you want to persist data across process restarts, or share it among multiple instances, you should use
27
+ * [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.
28
+ *
29
+ * @see {@link https://github.com/feathers-studio/telegraf-docs/blob/b694bcc36b4f71fb1cd650a345c2009ab4d2a2a5/guide/session.md Telegraf Docs | Session}
30
+ * @see {@link https://github.com/feathers-studio/telegraf-docs/blob/master/examples/session-bot.ts Example}
31
+ */
32
+ function session(options) {
33
+ var _a, _b, _c;
34
+ const prop = (_a = options === null || options === void 0 ? void 0 : options.property) !== null && _a !== void 0 ? _a : 'session';
35
+ const getSessionKey = (_b = options === null || options === void 0 ? void 0 : options.getSessionKey) !== null && _b !== void 0 ? _b : defaultGetSessionKey;
36
+ const store = (_c = options === null || options === void 0 ? void 0 : options.store) !== null && _c !== void 0 ? _c : new MemorySessionStore();
37
+ // caches value from store in-memory while simultaneous updates share it
38
+ // when counter reaches 0, the cached ref will be freed from memory
39
+ const cache = new Map();
40
+ // temporarily stores concurrent requests
41
+ const concurrents = new Map();
42
+ // this function must be handled with care
43
+ // read full description on the original PR: https://github.com/telegraf/telegraf/pull/1713
44
+ // make sure to update the tests in test/session.js if you make any changes or fix bugs here
45
+ return (ctx, next) => __awaiter(this, void 0, void 0, function* () {
46
+ var _d;
47
+ const updId = ctx.update.update_id;
48
+ let released = false;
49
+ function releaseChecks() {
50
+ if (released && process.env.EXPERIMENTAL_SESSION_CHECKS)
51
+ throw new Error("Session was accessed or assigned to after the middleware chain exhausted. This is a bug in your code. You're probably accessing session asynchronously and missing awaits.");
52
+ }
53
+ // because this is async, requests may still race here, but it will get autocorrected at (1)
54
+ // v5 getSessionKey should probably be synchronous to avoid that
55
+ const key = yield getSessionKey(ctx);
56
+ if (!key) {
57
+ // Leaving this here could be useful to check for `prop in ctx` in future middleware
58
+ ctx[prop] = undefined;
59
+ return yield next();
60
+ }
61
+ let cached = cache.get(key);
62
+ if (cached) {
63
+ debug(`(${updId}) found cached session, reusing from cache`);
64
+ ++cached.counter;
65
+ }
66
+ else {
67
+ debug(`(${updId}) did not find cached session`);
68
+ // if another concurrent request has already sent a store request, fetch that instead
69
+ let promise = concurrents.get(key);
70
+ if (promise)
71
+ debug(`(${updId}) found a concurrent request, reusing promise`);
72
+ else {
73
+ debug(`(${updId}) fetching from upstream store`);
74
+ promise = store.get(key);
75
+ }
76
+ // synchronously store promise so concurrent requests can share response
77
+ concurrents.set(key, promise);
78
+ const upstream = yield promise;
79
+ // all concurrent awaits will have promise in their closure, safe to remove now
80
+ concurrents.delete(key);
81
+ debug(`(${updId}) updating cache`);
82
+ // another request may have beaten us to the punch
83
+ const c = cache.get(key);
84
+ if (c) {
85
+ // another request did beat us to the punch
86
+ c.counter++;
87
+ // (1) preserve cached reference; in-memory reference is always newer than from store
88
+ cached = c;
89
+ }
90
+ else {
91
+ // we're the first, so we must cache the reference
92
+ cached = { ref: upstream !== null && upstream !== void 0 ? upstream : (_d = options === null || options === void 0 ? void 0 : options.defaultSession) === null || _d === void 0 ? void 0 : _d.call(options, ctx), counter: 1 };
93
+ cache.set(key, cached);
94
+ }
95
+ }
96
+ // TS already knows cached is always defined by this point, but does not guard cached.
97
+ // It will, however, guard `c` here.
98
+ const c = cached;
99
+ let touched = false;
100
+ Object.defineProperty(ctx, prop, {
101
+ get() {
102
+ releaseChecks();
103
+ touched = true;
104
+ return c.ref;
105
+ },
106
+ set(value) {
107
+ releaseChecks();
108
+ touched = true;
109
+ c.ref = value;
110
+ },
111
+ });
112
+ try {
113
+ yield next();
114
+ released = true;
115
+ }
116
+ finally {
117
+ if (--c.counter === 0) {
118
+ // decrement to avoid memory leak
119
+ debug(`(${updId}) refcounter reached 0, removing cached`);
120
+ cache.delete(key);
121
+ }
122
+ debug(`(${updId}) middlewares completed, checking session`);
123
+ // only update store if ctx.session was touched
124
+ if (touched)
125
+ if (c.ref == null) {
126
+ debug(`(${updId}) ctx.${prop} missing, removing from store`);
127
+ yield store.delete(key);
128
+ }
129
+ else {
130
+ debug(`(${updId}) ctx.${prop} found, updating store`);
131
+ yield store.set(key, c.ref);
132
+ }
133
+ }
134
+ });
135
+ }
136
+ exports.session = session;
137
+ function defaultGetSessionKey(ctx) {
138
+ var _a, _b;
139
+ const fromId = (_a = ctx.from) === null || _a === void 0 ? void 0 : _a.id;
140
+ const chatId = (_b = ctx.chat) === null || _b === void 0 ? void 0 : _b.id;
141
+ if (fromId == null || chatId == null)
142
+ return undefined;
143
+ return `${fromId}:${chatId}`;
144
+ }
145
+ /** @deprecated Use `Map` */
146
+ class MemorySessionStore {
147
+ constructor(ttl = Infinity) {
148
+ this.ttl = ttl;
149
+ this.store = new Map();
150
+ }
151
+ get(name) {
152
+ const entry = this.store.get(name);
153
+ if (entry == null) {
154
+ return undefined;
155
+ }
156
+ else if (entry.expires < Date.now()) {
157
+ this.delete(name);
158
+ return undefined;
159
+ }
160
+ return entry.session;
161
+ }
162
+ set(name, value) {
163
+ const now = Date.now();
164
+ this.store.set(name, { session: value, expires: now + this.ttl });
165
+ }
166
+ delete(name) {
167
+ this.store.delete(name);
168
+ }
169
+ }
170
+ exports.MemorySessionStore = MemorySessionStore;
171
+ /** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
172
+ function isSessionContext(ctx) {
173
+ return 'session' in ctx;
174
+ }
175
+ exports.isSessionContext = isSessionContext;
package/src/session.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { Context } from './context'
2
+ import { ExclusiveKeys, MaybePromise } from './core/helpers/util'
3
+ import { MiddlewareFn } from './middleware'
4
+ import d from 'debug'
5
+ const debug = d('telegraf:session')
6
+
7
+ export interface SyncSessionStore<T> {
8
+ get: (name: string) => T | undefined
9
+ set: (name: string, value: T) => void
10
+ delete: (name: string) => void
11
+ }
12
+
13
+ export interface AsyncSessionStore<T> {
14
+ get: (name: string) => Promise<T | undefined>
15
+ set: (name: string, value: T) => Promise<unknown>
16
+ delete: (name: string) => Promise<unknown>
17
+ }
18
+
19
+ export type SessionStore<T> = SyncSessionStore<T> | AsyncSessionStore<T>
20
+
21
+ interface SessionOptions<S, C extends Context, P extends string> {
22
+ /** Customise the session prop. Defaults to "session" and is available as ctx.session. */
23
+ property?: P
24
+ getSessionKey?: (ctx: C) => MaybePromise<string | undefined>
25
+ store?: SessionStore<S>
26
+ defaultSession?: (ctx: C) => S
27
+ }
28
+
29
+ /** @deprecated session can use custom properties now. Construct this type directly. */
30
+ export interface SessionContext<S extends object> extends Context {
31
+ session?: S
32
+ }
33
+
34
+ /**
35
+ * Returns middleware that adds `ctx.session` for storing arbitrary state per session key.
36
+ *
37
+ * The default `getSessionKey` is `${ctx.from.id}:${ctx.chat.id}`.
38
+ * If either `ctx.from` or `ctx.chat` is `undefined`, default session key and thus `ctx.session` are also `undefined`.
39
+ *
40
+ * > ⚠️ Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
41
+ * >
42
+ * > If you want to persist data across process restarts, or share it among multiple instances, you should use
43
+ * [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.
44
+ *
45
+ * @see {@link https://github.com/feathers-studio/telegraf-docs/blob/b694bcc36b4f71fb1cd650a345c2009ab4d2a2a5/guide/session.md Telegraf Docs | Session}
46
+ * @see {@link https://github.com/feathers-studio/telegraf-docs/blob/master/examples/session-bot.ts Example}
47
+ */
48
+ export function session<
49
+ S extends NonNullable<C[P]>,
50
+ C extends Context & { [key in P]?: C[P] },
51
+ P extends (ExclusiveKeys<C, Context> & string) | 'session' = 'session',
52
+ // ^ Only allow prop names that aren't keys in base Context.
53
+ // At type level, this is cosmetic. To not get cluttered with all Context keys.
54
+ >(options?: SessionOptions<S, C, P>): MiddlewareFn<C> {
55
+ const prop = options?.property ?? ('session' as P)
56
+ const getSessionKey = options?.getSessionKey ?? defaultGetSessionKey
57
+ const store = options?.store ?? new MemorySessionStore()
58
+ // caches value from store in-memory while simultaneous updates share it
59
+ // when counter reaches 0, the cached ref will be freed from memory
60
+ const cache = new Map<string, { ref?: S; counter: number }>()
61
+ // temporarily stores concurrent requests
62
+ const concurrents = new Map<string, MaybePromise<S | undefined>>()
63
+
64
+ // this function must be handled with care
65
+ // read full description on the original PR: https://github.com/telegraf/telegraf/pull/1713
66
+ // make sure to update the tests in test/session.js if you make any changes or fix bugs here
67
+ return async (ctx, next) => {
68
+ const updId = ctx.update.update_id
69
+
70
+ let released = false
71
+
72
+ function releaseChecks() {
73
+ if (released && process.env.EXPERIMENTAL_SESSION_CHECKS)
74
+ throw new Error(
75
+ "Session was accessed or assigned to after the middleware chain exhausted. This is a bug in your code. You're probably accessing session asynchronously and missing awaits."
76
+ )
77
+ }
78
+
79
+ // because this is async, requests may still race here, but it will get autocorrected at (1)
80
+ // v5 getSessionKey should probably be synchronous to avoid that
81
+ const key = await getSessionKey(ctx)
82
+ if (!key) {
83
+ // Leaving this here could be useful to check for `prop in ctx` in future middleware
84
+ ctx[prop] = undefined as unknown as S
85
+ return await next()
86
+ }
87
+
88
+ let cached = cache.get(key)
89
+ if (cached) {
90
+ debug(`(${updId}) found cached session, reusing from cache`)
91
+ ++cached.counter
92
+ } else {
93
+ debug(`(${updId}) did not find cached session`)
94
+ // if another concurrent request has already sent a store request, fetch that instead
95
+ let promise = concurrents.get(key)
96
+ if (promise)
97
+ debug(`(${updId}) found a concurrent request, reusing promise`)
98
+ else {
99
+ debug(`(${updId}) fetching from upstream store`)
100
+ promise = store.get(key)
101
+ }
102
+ // synchronously store promise so concurrent requests can share response
103
+ concurrents.set(key, promise)
104
+ const upstream = await promise
105
+ // all concurrent awaits will have promise in their closure, safe to remove now
106
+ concurrents.delete(key)
107
+ debug(`(${updId}) updating cache`)
108
+ // another request may have beaten us to the punch
109
+ const c = cache.get(key)
110
+ if (c) {
111
+ // another request did beat us to the punch
112
+ c.counter++
113
+ // (1) preserve cached reference; in-memory reference is always newer than from store
114
+ cached = c
115
+ } else {
116
+ // we're the first, so we must cache the reference
117
+ cached = { ref: upstream ?? options?.defaultSession?.(ctx), counter: 1 }
118
+ cache.set(key, cached)
119
+ }
120
+ }
121
+
122
+ // TS already knows cached is always defined by this point, but does not guard cached.
123
+ // It will, however, guard `c` here.
124
+ const c = cached
125
+
126
+ let touched = false
127
+
128
+ Object.defineProperty(ctx, prop, {
129
+ get() {
130
+ releaseChecks()
131
+ touched = true
132
+ return c.ref
133
+ },
134
+ set(value: S) {
135
+ releaseChecks()
136
+ touched = true
137
+ c.ref = value
138
+ },
139
+ })
140
+
141
+ try {
142
+ await next()
143
+ released = true
144
+ } finally {
145
+ if (--c.counter === 0) {
146
+ // decrement to avoid memory leak
147
+ debug(`(${updId}) refcounter reached 0, removing cached`)
148
+ cache.delete(key)
149
+ }
150
+ debug(`(${updId}) middlewares completed, checking session`)
151
+
152
+ // only update store if ctx.session was touched
153
+ if (touched)
154
+ if (c.ref == null) {
155
+ debug(`(${updId}) ctx.${prop} missing, removing from store`)
156
+ await store.delete(key)
157
+ } else {
158
+ debug(`(${updId}) ctx.${prop} found, updating store`)
159
+ await store.set(key, c.ref)
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ function defaultGetSessionKey(ctx: Context): string | undefined {
166
+ const fromId = ctx.from?.id
167
+ const chatId = ctx.chat?.id
168
+ if (fromId == null || chatId == null) return undefined
169
+ return `${fromId}:${chatId}`
170
+ }
171
+
172
+ /** @deprecated Use `Map` */
173
+ export class MemorySessionStore<T> implements SyncSessionStore<T> {
174
+ private readonly store = new Map<string, { session: T; expires: number }>()
175
+
176
+ constructor(private readonly ttl = Infinity) {}
177
+
178
+ get(name: string): T | undefined {
179
+ const entry = this.store.get(name)
180
+ if (entry == null) {
181
+ return undefined
182
+ } else if (entry.expires < Date.now()) {
183
+ this.delete(name)
184
+ return undefined
185
+ }
186
+ return entry.session
187
+ }
188
+
189
+ set(name: string, value: T): void {
190
+ const now = Date.now()
191
+ this.store.set(name, { session: value, expires: now + this.ttl })
192
+ }
193
+
194
+ delete(name: string): void {
195
+ this.store.delete(name)
196
+ }
197
+ }
198
+
199
+ /** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
200
+ export function isSessionContext<S extends object>(
201
+ ctx: Context
202
+ ): ctx is SessionContext<S> {
203
+ return 'session' in ctx
204
+ }