@mtcute/dispatcher 0.1.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 (190) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +26 -0
  3. package/cjs/callback-data-builder.d.ts +43 -0
  4. package/cjs/callback-data-builder.js +99 -0
  5. package/cjs/callback-data-builder.js.map +1 -0
  6. package/cjs/context/base.d.ts +8 -0
  7. package/cjs/context/base.js +3 -0
  8. package/cjs/context/base.js.map +1 -0
  9. package/cjs/context/callback-query.d.ts +27 -0
  10. package/cjs/context/callback-query.js +56 -0
  11. package/cjs/context/callback-query.js.map +1 -0
  12. package/cjs/context/chat-join-request.d.ts +16 -0
  13. package/cjs/context/chat-join-request.js +34 -0
  14. package/cjs/context/chat-join-request.js.map +1 -0
  15. package/cjs/context/chosen-inline-result.d.ts +21 -0
  16. package/cjs/context/chosen-inline-result.js +35 -0
  17. package/cjs/context/chosen-inline-result.js.map +1 -0
  18. package/cjs/context/index.d.ts +8 -0
  19. package/cjs/context/index.js +24 -0
  20. package/cjs/context/index.js.map +1 -0
  21. package/cjs/context/inline-query.d.ts +14 -0
  22. package/cjs/context/inline-query.js +22 -0
  23. package/cjs/context/inline-query.js.map +1 -0
  24. package/cjs/context/message.d.ts +72 -0
  25. package/cjs/context/message.js +142 -0
  26. package/cjs/context/message.js.map +1 -0
  27. package/cjs/context/parse.d.ts +1 -0
  28. package/cjs/context/parse.js +34 -0
  29. package/cjs/context/parse.js.map +1 -0
  30. package/cjs/context/pre-checkout-query.d.ts +16 -0
  31. package/cjs/context/pre-checkout-query.js +26 -0
  32. package/cjs/context/pre-checkout-query.js.map +1 -0
  33. package/cjs/dispatcher.d.ts +641 -0
  34. package/cjs/dispatcher.js +765 -0
  35. package/cjs/dispatcher.js.map +1 -0
  36. package/cjs/filters/bots.d.ts +70 -0
  37. package/cjs/filters/bots.js +129 -0
  38. package/cjs/filters/bots.js.map +1 -0
  39. package/cjs/filters/bundle.d.ts +10 -0
  40. package/cjs/filters/bundle.js +27 -0
  41. package/cjs/filters/bundle.js.map +1 -0
  42. package/cjs/filters/chat.d.ts +27 -0
  43. package/cjs/filters/chat.js +55 -0
  44. package/cjs/filters/chat.js.map +1 -0
  45. package/cjs/filters/group.d.ts +25 -0
  46. package/cjs/filters/group.js +72 -0
  47. package/cjs/filters/group.js.map +1 -0
  48. package/cjs/filters/index.d.ts +3 -0
  49. package/cjs/filters/index.js +29 -0
  50. package/cjs/filters/index.js.map +1 -0
  51. package/cjs/filters/logic.d.ts +29 -0
  52. package/cjs/filters/logic.js +114 -0
  53. package/cjs/filters/logic.js.map +1 -0
  54. package/cjs/filters/message.d.ts +295 -0
  55. package/cjs/filters/message.js +150 -0
  56. package/cjs/filters/message.js.map +1 -0
  57. package/cjs/filters/state.d.ts +15 -0
  58. package/cjs/filters/state.js +32 -0
  59. package/cjs/filters/state.js.map +1 -0
  60. package/cjs/filters/text.d.ts +64 -0
  61. package/cjs/filters/text.js +132 -0
  62. package/cjs/filters/text.js.map +1 -0
  63. package/cjs/filters/types.d.ts +91 -0
  64. package/cjs/filters/types.js +6 -0
  65. package/cjs/filters/types.js.map +1 -0
  66. package/cjs/filters/updates.d.ts +46 -0
  67. package/cjs/filters/updates.js +46 -0
  68. package/cjs/filters/updates.js.map +1 -0
  69. package/cjs/filters/user.d.ts +24 -0
  70. package/cjs/filters/user.js +76 -0
  71. package/cjs/filters/user.js.map +1 -0
  72. package/cjs/handler.d.ts +31 -0
  73. package/cjs/handler.js +4 -0
  74. package/cjs/handler.js.map +1 -0
  75. package/cjs/index.d.ts +8 -0
  76. package/cjs/index.js +25 -0
  77. package/cjs/index.js.map +1 -0
  78. package/cjs/package.json +3 -0
  79. package/cjs/propagation.d.ts +21 -0
  80. package/cjs/propagation.js +26 -0
  81. package/cjs/propagation.js.map +1 -0
  82. package/cjs/state/index.d.ts +3 -0
  83. package/cjs/state/index.js +20 -0
  84. package/cjs/state/index.js.map +1 -0
  85. package/cjs/state/key.d.ts +23 -0
  86. package/cjs/state/key.js +45 -0
  87. package/cjs/state/key.js.map +1 -0
  88. package/cjs/state/storage.d.ts +75 -0
  89. package/cjs/state/storage.js +17 -0
  90. package/cjs/state/storage.js.map +1 -0
  91. package/cjs/state/update-state.d.ts +151 -0
  92. package/cjs/state/update-state.js +211 -0
  93. package/cjs/state/update-state.js.map +1 -0
  94. package/cjs/wizard.d.ts +60 -0
  95. package/cjs/wizard.js +103 -0
  96. package/cjs/wizard.js.map +1 -0
  97. package/esm/callback-data-builder.d.ts +43 -0
  98. package/esm/callback-data-builder.js +95 -0
  99. package/esm/callback-data-builder.js.map +1 -0
  100. package/esm/context/base.d.ts +8 -0
  101. package/esm/context/base.js +2 -0
  102. package/esm/context/base.js.map +1 -0
  103. package/esm/context/callback-query.d.ts +27 -0
  104. package/esm/context/callback-query.js +52 -0
  105. package/esm/context/callback-query.js.map +1 -0
  106. package/esm/context/chat-join-request.d.ts +16 -0
  107. package/esm/context/chat-join-request.js +30 -0
  108. package/esm/context/chat-join-request.js.map +1 -0
  109. package/esm/context/chosen-inline-result.d.ts +21 -0
  110. package/esm/context/chosen-inline-result.js +31 -0
  111. package/esm/context/chosen-inline-result.js.map +1 -0
  112. package/esm/context/index.d.ts +8 -0
  113. package/esm/context/index.js +8 -0
  114. package/esm/context/index.js.map +1 -0
  115. package/esm/context/inline-query.d.ts +14 -0
  116. package/esm/context/inline-query.js +18 -0
  117. package/esm/context/inline-query.js.map +1 -0
  118. package/esm/context/message.d.ts +72 -0
  119. package/esm/context/message.js +138 -0
  120. package/esm/context/message.js.map +1 -0
  121. package/esm/context/parse.d.ts +1 -0
  122. package/esm/context/parse.js +30 -0
  123. package/esm/context/parse.js.map +1 -0
  124. package/esm/context/pre-checkout-query.d.ts +16 -0
  125. package/esm/context/pre-checkout-query.js +22 -0
  126. package/esm/context/pre-checkout-query.js.map +1 -0
  127. package/esm/dispatcher.d.ts +641 -0
  128. package/esm/dispatcher.js +761 -0
  129. package/esm/dispatcher.js.map +1 -0
  130. package/esm/filters/bots.d.ts +70 -0
  131. package/esm/filters/bots.js +125 -0
  132. package/esm/filters/bots.js.map +1 -0
  133. package/esm/filters/bundle.d.ts +10 -0
  134. package/esm/filters/bundle.js +11 -0
  135. package/esm/filters/bundle.js.map +1 -0
  136. package/esm/filters/chat.d.ts +27 -0
  137. package/esm/filters/chat.js +50 -0
  138. package/esm/filters/chat.js.map +1 -0
  139. package/esm/filters/group.d.ts +25 -0
  140. package/esm/filters/group.js +67 -0
  141. package/esm/filters/group.js.map +1 -0
  142. package/esm/filters/index.d.ts +3 -0
  143. package/esm/filters/index.js +3 -0
  144. package/esm/filters/index.js.map +1 -0
  145. package/esm/filters/logic.d.ts +29 -0
  146. package/esm/filters/logic.js +107 -0
  147. package/esm/filters/logic.js.map +1 -0
  148. package/esm/filters/message.d.ts +295 -0
  149. package/esm/filters/message.js +130 -0
  150. package/esm/filters/message.js.map +1 -0
  151. package/esm/filters/state.d.ts +15 -0
  152. package/esm/filters/state.js +27 -0
  153. package/esm/filters/state.js.map +1 -0
  154. package/esm/filters/text.d.ts +64 -0
  155. package/esm/filters/text.js +124 -0
  156. package/esm/filters/text.js.map +1 -0
  157. package/esm/filters/types.d.ts +91 -0
  158. package/esm/filters/types.js +5 -0
  159. package/esm/filters/types.js.map +1 -0
  160. package/esm/filters/updates.d.ts +46 -0
  161. package/esm/filters/updates.js +39 -0
  162. package/esm/filters/updates.js.map +1 -0
  163. package/esm/filters/user.d.ts +24 -0
  164. package/esm/filters/user.js +70 -0
  165. package/esm/filters/user.js.map +1 -0
  166. package/esm/handler.d.ts +31 -0
  167. package/esm/handler.js +3 -0
  168. package/esm/handler.js.map +1 -0
  169. package/esm/index.d.ts +8 -0
  170. package/esm/index.js +9 -0
  171. package/esm/index.js.map +1 -0
  172. package/esm/propagation.d.ts +21 -0
  173. package/esm/propagation.js +23 -0
  174. package/esm/propagation.js.map +1 -0
  175. package/esm/state/index.d.ts +3 -0
  176. package/esm/state/index.js +4 -0
  177. package/esm/state/index.js.map +1 -0
  178. package/esm/state/key.d.ts +23 -0
  179. package/esm/state/key.js +41 -0
  180. package/esm/state/key.js.map +1 -0
  181. package/esm/state/storage.d.ts +75 -0
  182. package/esm/state/storage.js +13 -0
  183. package/esm/state/storage.js.map +1 -0
  184. package/esm/state/update-state.d.ts +151 -0
  185. package/esm/state/update-state.js +206 -0
  186. package/esm/state/update-state.js.map +1 -0
  187. package/esm/wizard.d.ts +60 -0
  188. package/esm/wizard.js +99 -0
  189. package/esm/wizard.js.map +1 -0
  190. package/package.json +21 -0
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UpdateState = exports.RateLimitError = void 0;
4
+ /* eslint-disable dot-notation */
5
+ /* eslint-disable @typescript-eslint/no-explicit-any */
6
+ const client_1 = require("@mtcute/client");
7
+ const utils_js_1 = require("@mtcute/client/utils.js");
8
+ /**
9
+ * Error thrown by `.rateLimit()`
10
+ */
11
+ class RateLimitError extends client_1.MtcuteError {
12
+ constructor(reset) {
13
+ super('You are being rate limited.');
14
+ this.reset = reset;
15
+ }
16
+ }
17
+ exports.RateLimitError = RateLimitError;
18
+ /**
19
+ * State of the current update.
20
+ *
21
+ * @template State Type that represents the state
22
+ * @template SceneName Possible scene names
23
+ */
24
+ class UpdateState {
25
+ constructor(storage, key, scene, scoped, customStorage, customKey) {
26
+ this._storage = storage;
27
+ this._key = key;
28
+ this._scene = scene;
29
+ this._scoped = scoped;
30
+ this._localStorage = customStorage ?? storage;
31
+ this._localKeyBase = customKey ?? key;
32
+ this._updateLocalKey();
33
+ }
34
+ /** Name of the current scene */
35
+ get scene() {
36
+ return this._scene;
37
+ }
38
+ _updateLocalKey() {
39
+ if (!this._scoped)
40
+ this._localKey = this._localKeyBase;
41
+ else {
42
+ this._localKey = this._scene ? this._scene + '_' + this._localKeyBase : this._localKeyBase;
43
+ }
44
+ }
45
+ async get(fallback, force) {
46
+ if (typeof fallback === 'boolean') {
47
+ force = fallback;
48
+ fallback = undefined;
49
+ }
50
+ if (!force && this._cached !== undefined) {
51
+ if (!this._cached && fallback) {
52
+ return typeof fallback === 'function' ? fallback() : fallback;
53
+ }
54
+ return this._cached;
55
+ }
56
+ let res = (await this._localStorage.getState(this._localKey));
57
+ if (!res && fallback) {
58
+ res = typeof fallback === 'function' ? fallback() : fallback;
59
+ }
60
+ this._cached = res;
61
+ return res;
62
+ }
63
+ /**
64
+ * Set new state to the storage
65
+ *
66
+ * @param state New state
67
+ * @param ttl TTL for the new state (in seconds)
68
+ */
69
+ async set(state, ttl) {
70
+ this._cached = state;
71
+ await this._localStorage.setState(this._localKey, state, ttl);
72
+ }
73
+ /**
74
+ * Merge the given object to the current state.
75
+ *
76
+ * > **Note**: If the storage currently has no state,
77
+ * > then `fallback` must be provided.
78
+ *
79
+ * Basically a shorthand to calling `.get()`,
80
+ * modifying and then calling `.set()`
81
+ *
82
+ * @param state State to be merged
83
+ * @param fallback Default state
84
+ * @param ttl TTL for the new state (in seconds)
85
+ * @param forceLoad Whether to force load the old state from storage
86
+ */
87
+ async merge(state, params = {}) {
88
+ const { fallback, ttl, forceLoad } = params;
89
+ const old = await this.get(forceLoad);
90
+ if (!old) {
91
+ if (!fallback) {
92
+ throw new client_1.MtArgumentError('Cannot use merge on empty state without fallback.');
93
+ }
94
+ const fallback_ = typeof fallback === 'function' ? fallback() : fallback;
95
+ await this.set({ ...fallback_, ...state }, ttl);
96
+ }
97
+ else {
98
+ await this.set({ ...old, ...state }, ttl);
99
+ }
100
+ // _cached is set by .set()
101
+ return this._cached;
102
+ }
103
+ /**
104
+ * Delete the state from the storage
105
+ */
106
+ async delete() {
107
+ this._cached = null;
108
+ await this._localStorage.deleteState(this._localKey);
109
+ }
110
+ /**
111
+ * Enter some scene
112
+ */
113
+ async enter(scene, params) {
114
+ const { with: with_, ttl, reset = true } = params ?? {};
115
+ if (reset && this._scoped)
116
+ await this.delete();
117
+ if (!scene['_scene']) {
118
+ throw new client_1.MtArgumentError('Cannot enter a non-scene Dispatcher');
119
+ }
120
+ if (!scene['_parent']) {
121
+ throw new client_1.MtArgumentError('This scene has not been registered');
122
+ }
123
+ this._scene = scene['_scene'];
124
+ this._scoped = scene['_sceneScoped'];
125
+ this._updateLocalKey();
126
+ await this._storage.setCurrentScene(this._key, this._scene, ttl);
127
+ if (with_) {
128
+ if (scene['_customStateKeyDelegate']) {
129
+ throw new client_1.MtArgumentError('Cannot use `with` parameter when the scene uses a custom state key delegate');
130
+ }
131
+ await scene.getState(this._key).set(with_, ttl);
132
+ }
133
+ }
134
+ /**
135
+ * Exit from current scene to the root
136
+ *
137
+ * @param reset
138
+ * Whether to reset scene state (only applicable in case this is a scoped scene)
139
+ */
140
+ async exit(reset = true) {
141
+ if (reset && this._scoped)
142
+ await this.delete();
143
+ this._scene = null;
144
+ this._updateLocalKey();
145
+ await this._storage.deleteCurrentScene(this._key);
146
+ }
147
+ /**
148
+ * Rate limit some handler.
149
+ *
150
+ * When the rate limit exceeds, {@link RateLimitError} is thrown.
151
+ *
152
+ * This is a simple rate-limiting solution that uses
153
+ * the same key as the state. If you need something more
154
+ * sophisticated and/or customizable, you'll have to implement
155
+ * your own rate-limiter.
156
+ *
157
+ * > **Note**: `key` is used to prefix the local key
158
+ * > derived using the given key delegate.
159
+ *
160
+ * @param key Key of the rate limit
161
+ * @param limit Maximum number of requests in `window`
162
+ * @param window Window size in seconds
163
+ * @returns Tuple containing the number of remaining and
164
+ * unix time in ms when the user can try again
165
+ */
166
+ async rateLimit(key, limit, window) {
167
+ const [remaining, reset] = await this._localStorage.getRateLimit(`${key}:${this._localKey}`, limit, window);
168
+ if (!remaining) {
169
+ throw new RateLimitError(reset);
170
+ }
171
+ return [remaining - 1, reset];
172
+ }
173
+ /**
174
+ * Throttle some handler.
175
+ *
176
+ * When the rate limit exceeds, this function waits for it to reset.
177
+ *
178
+ * This is a simple wrapper over {@link rateLimit}, and follows the same logic.
179
+ *
180
+ * > **Note**: `key` is used to prefix the local key
181
+ * > derived using the given key delegate.
182
+ *
183
+ * @param key Key of the rate limit
184
+ * @param limit Maximum number of requests in `window`
185
+ * @param window Window size in seconds
186
+ * @returns Tuple containing the number of remaining and
187
+ * unix time in ms when the user can try again
188
+ */
189
+ async throttle(key, limit, window) {
190
+ try {
191
+ return await this.rateLimit(key, limit, window);
192
+ }
193
+ catch (e) {
194
+ if (e instanceof RateLimitError) {
195
+ await (0, utils_js_1.sleep)(e.reset - Date.now());
196
+ return this.throttle(key, limit, window);
197
+ }
198
+ throw e;
199
+ }
200
+ }
201
+ /**
202
+ * Reset the rate limit
203
+ *
204
+ * @param key Key of the rate limit
205
+ */
206
+ async resetRateLimit(key) {
207
+ await this._localStorage.resetRateLimit(`${key}:${this._localKey}`);
208
+ }
209
+ }
210
+ exports.UpdateState = UpdateState;
211
+ //# sourceMappingURL=update-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-state.js","sourceRoot":"","sources":["../../../src/state/update-state.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,uDAAuD;AACvD,2CAA6D;AAC7D,sDAA+C;AAK/C;;GAEG;AACH,MAAa,cAAe,SAAQ,oBAAW;IAC3C,YAAqB,KAAa;QAC9B,KAAK,CAAC,6BAA6B,CAAC,CAAA;QADnB,UAAK,GAAL,KAAK,CAAQ;IAElC,CAAC;CACJ;AAJD,wCAIC;AAED;;;;;GAKG;AACH,MAAa,WAAW;IAapB,YACI,OAAsB,EACtB,GAAW,EACX,KAAoB,EACpB,MAAgB,EAChB,aAA6B,EAC7B,SAAkB;QAElB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAA;QACvB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAA;QACf,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;QACnB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;QAErB,IAAI,CAAC,aAAa,GAAG,aAAa,IAAI,OAAO,CAAA;QAC7C,IAAI,CAAC,aAAa,GAAG,SA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AC,SAAS,CAAC,GAAW,EAAE,KAAa,EAAE,MAAc;QACtD,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,GAAG,GAAG,IAAI,IAAI,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;QAE3G,IAAI,CAAC,SAAS,EAAE;YACZ,MAAM,IAAI,cAAc,CAAC,KAAK,CAAC,CAAA;SAClC;QAED,OAAO,CAAC,SAAS,GAAG,CAAC,EAAE,KAAK,CAAC,CAAA;IACjC,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACH,KAAK,CAAC,QAAQ,CAAC,GAAW,EAAE,KAAa,EAAE,MAAc;QACrD,IAAI;YACA,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;SAClD;QAAC,OAAO,CAAU,EAAE;YACjB,IAAI,CAAC,YAAY,cAAc,EAAE;gBAC7B,MAAM,IAAA,gBAAK,EAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;gBAEjC,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;aAC3C;YAED,MAAM,CAAC,CAAA;SACV;IACL,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,cAAc,CAAC,GAAW;QAC5B,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,GAAG,GAAG,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;IACvE,CAAC;CACJ;AA5RD,kCA4RC","sourcesContent":["/* eslint-disable dot-notation */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { MtArgumentError, MtcuteError } from '@mtcute/client'\nimport { sleep } from '@mtcute/client/utils.js'\n\nimport type { Dispatcher } from '../dispatcher.js'\nimport { IStateStorage } from './storage.js'\n\n/**\n * Error thrown by `.rateLimit()`\n */\nexport class RateLimitError extends MtcuteError {\n constructor(readonly reset: number) {\n super('You are being rate limited.')\n }\n}\n\n/**\n * State of the current update.\n *\n * @template State Type that represents the state\n * @template SceneName Possible scene names\n */\nexport class UpdateState<State extends object> {\n private _key: string\n private _localKey!: string\n\n private _storage: IStateStorage\n\n private _scene: string | null\n private _scoped?: boolean\n private _cached?: State | null\n\n private _localStorage: IStateStorage\n private _localKeyBase: string\n\n constructor(\n storage: IStateStorage,\n key: string,\n scene: string | null,\n scoped?: boolean,\n customStorage?: IStateStorage,\n customKey?: string,\n ) {\n this._storage = storage\n this._key = key\n this._scene = scene\n this._scoped = scoped\n\n this._localStorage = customStorage ?? storage\n this._localKeyBase = customKey ?? key\n\n this._updateLocalKey()\n }\n\n /** Name of the current scene */\n get scene(): string | null {\n return this._scene\n }\n\n private _updateLocalKey(): void {\n if (!this._scoped) this._localKey = this._localKeyBase\n else {\n this._localKey = this._scene ? this._scene + '_' + this._localKeyBase : this._localKeyBase\n }\n }\n\n /**\n * Retrieve the state from the storage, falling back to default\n * if not found\n *\n * @param fallback Default state value\n * @param force Whether to ignore cached state (def. `false`)\n */\n async get(fallback: State | (() => State), force?: boolean): Promise<State>\n\n /**\n * Retrieve the state from the storage, falling back to default\n * if not found\n *\n * @param fallback Default state value\n * @param force Whether to ignore cached state (def. `false`)\n */\n async get(fallback?: State | (() => State), force?: boolean): Promise<State | null>\n /**\n * Retrieve the state from the storage\n *\n * @param force Whether to ignore cached state (def. `false`)\n */\n async get(force?: boolean): Promise<State | null>\n async get(fallback?: State | (() => State) | boolean, force?: boolean): Promise<State | null> {\n if (typeof fallback === 'boolean') {\n force = fallback\n fallback = undefined\n }\n\n if (!force && this._cached !== undefined) {\n if (!this._cached && fallback) {\n return typeof fallback === 'function' ? fallback() : fallback\n }\n\n return this._cached\n }\n\n let res = (await this._localStorage.getState(this._localKey)) as State | null\n\n if (!res && fallback) {\n res = typeof fallback === 'function' ? fallback() : fallback\n }\n this._cached = res\n\n return res\n }\n\n /**\n * Set new state to the storage\n *\n * @param state New state\n * @param ttl TTL for the new state (in seconds)\n */\n async set(state: State, ttl?: number): Promise<void> {\n this._cached = state\n await this._localStorage.setState(this._localKey, state, ttl)\n }\n\n /**\n * Merge the given object to the current state.\n *\n * > **Note**: If the storage currently has no state,\n * > then `fallback` must be provided.\n *\n * Basically a shorthand to calling `.get()`,\n * modifying and then calling `.set()`\n *\n * @param state State to be merged\n * @param fallback Default state\n * @param ttl TTL for the new state (in seconds)\n * @param forceLoad Whether to force load the old state from storage\n */\n async merge(\n state: Partial<State>,\n params: {\n fallback?: State | (() => State)\n ttl?: number\n forceLoad?: boolean\n } = {},\n ): Promise<State> {\n const { fallback, ttl, forceLoad } = params\n\n const old = await this.get(forceLoad)\n\n if (!old) {\n if (!fallback) {\n throw new MtArgumentError('Cannot use merge on empty state without fallback.')\n }\n\n const fallback_ = typeof fallback === 'function' ? fallback() : fallback\n\n await this.set({ ...fallback_, ...state }, ttl)\n } else {\n await this.set({ ...old, ...state }, ttl)\n }\n\n // _cached is set by .set()\n\n return this._cached!\n }\n\n /**\n * Delete the state from the storage\n */\n async delete(): Promise<void> {\n this._cached = null\n await this._localStorage.deleteState(this._localKey)\n }\n\n /**\n * Enter some scene\n */\n async enter<SceneState extends object, Scene extends Dispatcher<SceneState>>(\n scene: Scene,\n params?: {\n /**\n * Initial state for the scene\n *\n * Note that this will only work if the scene uses the same key delegate as this state.\n */\n with?: SceneState\n\n /** TTL for the scene (in seconds) */\n ttl?: number\n\n /**\n * If currently in a scoped scene, whether to reset the state\n *\n * @default true\n */\n reset?: boolean\n },\n ): Promise<void> {\n const { with: with_, ttl, reset = true } = params ?? {}\n\n if (reset && this._scoped) await this.delete()\n\n if (!scene['_scene']) {\n throw new MtArgumentError('Cannot enter a non-scene Dispatcher')\n }\n\n if (!scene['_parent']) {\n throw new MtArgumentError('This scene has not been registered')\n }\n\n this._scene = scene['_scene']\n this._scoped = scene['_sceneScoped']\n this._updateLocalKey()\n\n await this._storage.setCurrentScene(this._key, this._scene, ttl)\n\n if (with_) {\n if (scene['_customStateKeyDelegate']) {\n throw new MtArgumentError('Cannot use `with` parameter when the scene uses a custom state key delegate')\n }\n\n await scene.getState(this._key).set(with_, ttl)\n }\n }\n\n /**\n * Exit from current scene to the root\n *\n * @param reset\n * Whether to reset scene state (only applicable in case this is a scoped scene)\n */\n async exit(reset = true): Promise<void> {\n if (reset && this._scoped) await this.delete()\n this._scene = null\n this._updateLocalKey()\n await this._storage.deleteCurrentScene(this._key)\n }\n\n /**\n * Rate limit some handler.\n *\n * When the rate limit exceeds, {@link RateLimitError} is thrown.\n *\n * This is a simple rate-limiting solution that uses\n * the same key as the state. If you need something more\n * sophisticated and/or customizable, you'll have to implement\n * your own rate-limiter.\n *\n * > **Note**: `key` is used to prefix the local key\n * > derived using the given key delegate.\n *\n * @param key Key of the rate limit\n * @param limit Maximum number of requests in `window`\n * @param window Window size in seconds\n * @returns Tuple containing the number of remaining and\n * unix time in ms when the user can try again\n */\n async rateLimit(key: string, limit: number, window: number): Promise<[number, number]> {\n const [remaining, reset] = await this._localStorage.getRateLimit(`${key}:${this._localKey}`, limit, window)\n\n if (!remaining) {\n throw new RateLimitError(reset)\n }\n\n return [remaining - 1, reset]\n }\n\n /**\n * Throttle some handler.\n *\n * When the rate limit exceeds, this function waits for it to reset.\n *\n * This is a simple wrapper over {@link rateLimit}, and follows the same logic.\n *\n * > **Note**: `key` is used to prefix the local key\n * > derived using the given key delegate.\n *\n * @param key Key of the rate limit\n * @param limit Maximum number of requests in `window`\n * @param window Window size in seconds\n * @returns Tuple containing the number of remaining and\n * unix time in ms when the user can try again\n */\n async throttle(key: string, limit: number, window: number): Promise<[number, number]> {\n try {\n return await this.rateLimit(key, limit, window)\n } catch (e: unknown) {\n if (e instanceof RateLimitError) {\n await sleep(e.reset - Date.now())\n\n return this.throttle(key, limit, window)\n }\n\n throw e\n }\n }\n\n /**\n * Reset the rate limit\n *\n * @param key Key of the rate limit\n */\n async resetRateLimit(key: string): Promise<void> {\n await this._localStorage.resetRateLimit(`${key}:${this._localKey}`)\n }\n}\n"]}
@@ -0,0 +1,60 @@
1
+ import { MaybeAsync } from '@mtcute/client';
2
+ import { MessageContext } from './context/message.js';
3
+ import { Dispatcher } from './dispatcher.js';
4
+ import { filters } from './filters/index.js';
5
+ import { UpdateState } from './state/update-state.js';
6
+ /**
7
+ * Action for the wizard scene.
8
+ *
9
+ * `Next`: Continue to the next registered step
10
+ * (or exit, if this is the last step)
11
+ *
12
+ * `Stay`: Stay on the same step
13
+ *
14
+ * `Exit`: Exit from the wizard scene
15
+ *
16
+ * You can also return a `number` to jump to that step
17
+ */
18
+ export declare enum WizardSceneAction {
19
+ Next = "next",
20
+ Stay = "stay",
21
+ Exit = "exit"
22
+ }
23
+ interface WizardInternalState {
24
+ $step?: number;
25
+ }
26
+ /**
27
+ * Wizard is a special type of Dispatcher
28
+ * that can be used to simplify implementing
29
+ * step-by-step scenes.
30
+ */
31
+ export declare class WizardScene<State extends object> extends Dispatcher<State & WizardInternalState> {
32
+ private _steps;
33
+ private _defaultState;
34
+ setDefaultState(defaultState: State): void;
35
+ /**
36
+ * Get the total number of registered steps
37
+ */
38
+ get totalSteps(): number;
39
+ /**
40
+ * Go to the Nth step
41
+ */
42
+ goToStep(state: UpdateState<WizardInternalState>, step: number): Promise<void>;
43
+ /**
44
+ * Skip N steps
45
+ */
46
+ skip(state: UpdateState<WizardInternalState>, count?: number): Promise<void>;
47
+ /**
48
+ * Filter that will only pass if the current step is `step`
49
+ */
50
+ static onNthStep(step: number): filters.UpdateFilter<any, {}, WizardInternalState>;
51
+ /**
52
+ * Filter that will only pass if the current step is the one after last one added
53
+ */
54
+ onCurrentStep(): filters.UpdateFilter<any, {}, WizardInternalState>;
55
+ /**
56
+ * Add a step to the wizard
57
+ */
58
+ addStep(handler: (msg: MessageContext, state: UpdateState<State & WizardInternalState>) => MaybeAsync<WizardSceneAction | number>): void;
59
+ }
60
+ export {};
package/cjs/wizard.js ADDED
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WizardScene = exports.WizardSceneAction = void 0;
4
+ const dispatcher_js_1 = require("./dispatcher.js");
5
+ const index_js_1 = require("./filters/index.js");
6
+ /**
7
+ * Action for the wizard scene.
8
+ *
9
+ * `Next`: Continue to the next registered step
10
+ * (or exit, if this is the last step)
11
+ *
12
+ * `Stay`: Stay on the same step
13
+ *
14
+ * `Exit`: Exit from the wizard scene
15
+ *
16
+ * You can also return a `number` to jump to that step
17
+ */
18
+ var WizardSceneAction;
19
+ (function (WizardSceneAction) {
20
+ WizardSceneAction["Next"] = "next";
21
+ WizardSceneAction["Stay"] = "stay";
22
+ WizardSceneAction["Exit"] = "exit";
23
+ })(WizardSceneAction = exports.WizardSceneAction || (exports.WizardSceneAction = {}));
24
+ /**
25
+ * Wizard is a special type of Dispatcher
26
+ * that can be used to simplify implementing
27
+ * step-by-step scenes.
28
+ */
29
+ class WizardScene extends dispatcher_js_1.Dispatcher {
30
+ constructor() {
31
+ super(...arguments);
32
+ this._steps = 0;
33
+ this._defaultState = {};
34
+ }
35
+ setDefaultState(defaultState) {
36
+ this._defaultState = defaultState;
37
+ }
38
+ /**
39
+ * Get the total number of registered steps
40
+ */
41
+ get totalSteps() {
42
+ return this._steps;
43
+ }
44
+ /**
45
+ * Go to the Nth step
46
+ */
47
+ async goToStep(state, step) {
48
+ if (step >= this._steps) {
49
+ await state.exit();
50
+ }
51
+ else {
52
+ await state.merge({ $step: step }, this._defaultState);
53
+ }
54
+ }
55
+ /**
56
+ * Skip N steps
57
+ */
58
+ async skip(state, count = 1) {
59
+ const { $step } = (await state.get()) || {};
60
+ if ($step === undefined)
61
+ throw new Error('Wizard state is not initialized');
62
+ return this.goToStep(state, $step + count);
63
+ }
64
+ /**
65
+ * Filter that will only pass if the current step is `step`
66
+ */
67
+ static onNthStep(step) {
68
+ const filter = index_js_1.filters.state((it) => it.$step === step);
69
+ if (step === 0)
70
+ return index_js_1.filters.or(index_js_1.filters.stateEmpty, filter);
71
+ return filter;
72
+ }
73
+ /**
74
+ * Filter that will only pass if the current step is the one after last one added
75
+ */
76
+ onCurrentStep() {
77
+ return WizardScene.onNthStep(this._steps);
78
+ }
79
+ /**
80
+ * Add a step to the wizard
81
+ */
82
+ addStep(handler) {
83
+ const step = this._steps++;
84
+ this.onNewMessage(WizardScene.onNthStep(step), async (msg, state) => {
85
+ const result = await handler(msg, state);
86
+ if (typeof result === 'number') {
87
+ await this.goToStep(state, result);
88
+ return;
89
+ }
90
+ switch (result) {
91
+ case 'next': {
92
+ await this.goToStep(state, step + 1);
93
+ break;
94
+ }
95
+ case 'exit':
96
+ await state.exit();
97
+ break;
98
+ }
99
+ });
100
+ }
101
+ }
102
+ exports.WizardScene = WizardScene;
103
+ //# sourceMappingURL=wizard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wizard.js","sourceRoot":"","sources":["../../src/wizard.ts"],"names":[],"mappings":";;;AAGA,mDAA4C;AAC5C,iDAA4C;AAG5C;;;;;;;;;;;GAWG;AACH,IAAY,iBAIX;AAJD,WAAY,iBAAiB;IACzB,kCAAa,CAAA;IACb,kCAAa,CAAA;IACb,kCAAa,CAAA;AACjB,CAAC,EAJW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAI5B;AAMD;;;;GAIG;AACH,MAAa,WAAkC,SAAQ,0BAAuC;IAA9F;;QACY,WAAM,GAAG,CAAC,CAAA;QAEV,kBAAa,GAAgC,EAAiC,CAAA;IAmF1F,CAAC;IAjFG,eAAe,CAAC,YAAmB;QAC/B,IAAI,CAAC,aAAa,GAAG,YAA2C,CAAA;IACpE,CAAC;IAED;;OAEG;IACH,IAAI,UAAU;QACV,OAAO,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,QAAQ,CAAC,KAAuC,EAAE,IAAY;QAChE,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,E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AAO,MAAM,KAAK,QAAQ,EAAE;gBAC5B,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;gBAElC,OAAM;aACT;YAED,QAAQ,MAAM,EAAE;gBACZ,KAAK,MAAM,CAAC,CAAC;oBACT,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,GAAG,CAAC,CAAC,CAAA;oBACpC,MAAK;iBACR;gBACD,KAAK,MAAM;oBACP,MAAM,KAAK,CAAC,IAAI,EAAE,CAAA;oBAClB,MAAK;aACZ;QACL,CAAC,CAAC,CAAA;IACN,CAAC;CACJ;AAtFD,kCAsFC","sourcesContent":["import { MaybeAsync } from '@mtcute/client'\n\nimport { MessageContext } from './context/message.js'\nimport { Dispatcher } from './dispatcher.js'\nimport { filters } from './filters/index.js'\nimport { UpdateState } from './state/update-state.js'\n\n/**\n * Action for the wizard scene.\n *\n * `Next`: Continue to the next registered step\n * (or exit, if this is the last step)\n *\n * `Stay`: Stay on the same step\n *\n * `Exit`: Exit from the wizard scene\n *\n * You can also return a `number` to jump to that step\n */\nexport enum WizardSceneAction {\n Next = 'next',\n Stay = 'stay',\n Exit = 'exit',\n}\n\ninterface WizardInternalState {\n $step?: number\n}\n\n/**\n * Wizard is a special type of Dispatcher\n * that can be used to simplify implementing\n * step-by-step scenes.\n */\nexport class WizardScene<State extends object> extends Dispatcher<State & WizardInternalState> {\n private _steps = 0\n\n private _defaultState: State & WizardInternalState = {} as State & WizardInternalState\n\n setDefaultState(defaultState: State): void {\n this._defaultState = defaultState as State & WizardInternalState\n }\n\n /**\n * Get the total number of registered steps\n */\n get totalSteps(): number {\n return this._steps\n }\n\n /**\n * Go to the Nth step\n */\n async goToStep(state: UpdateState<WizardInternalState>, step: number) {\n if (step >= this._steps) {\n await state.exit()\n } else {\n await state.merge({ $step: step }, this._defaultState)\n }\n }\n\n /**\n * Skip N steps\n */\n async skip(state: UpdateState<WizardInternalState>, count = 1) {\n const { $step } = (await state.get()) || {}\n if ($step === undefined) throw new Error('Wizard state is not initialized')\n\n return this.goToStep(state, $step + count)\n }\n\n /**\n * Filter that will only pass if the current step is `step`\n */\n static onNthStep(step: number) {\n const filter = filters.state<WizardInternalState>((it) => it.$step === step)\n\n if (step === 0) return filters.or(filters.stateEmpty, filter)\n\n return filter\n }\n\n /**\n * Filter that will only pass if the current step is the one after last one added\n */\n onCurrentStep() {\n return WizardScene.onNthStep(this._steps)\n }\n\n /**\n * Add a step to the wizard\n */\n addStep(\n handler: (\n msg: MessageContext,\n state: UpdateState<State & WizardInternalState>,\n ) => MaybeAsync<WizardSceneAction | number>,\n ): void {\n const step = this._steps++\n\n this.onNewMessage(WizardScene.onNthStep(step), async (msg, state) => {\n const result = await handler(msg, state)\n\n if (typeof result === 'number') {\n await this.goToStep(state, result)\n\n return\n }\n\n switch (result) {\n case 'next': {\n await this.goToStep(state, step + 1)\n break\n }\n case 'exit':\n await state.exit()\n break\n }\n })\n }\n}\n"]}
@@ -0,0 +1,43 @@
1
+ import { CallbackQuery, MaybeArray } from '@mtcute/client';
2
+ import { UpdateFilter } from './filters/types.js';
3
+ /**
4
+ * Callback data builder, inspired by [aiogram](https://github.com/aiogram/aiogram).
5
+ *
6
+ * This can be used to simplify management of different callbacks.
7
+ *
8
+ * [Learn more in the docs](/guide/topics/keyboards.html#callback-data-builders)
9
+ */
10
+ export declare class CallbackDataBuilder<T extends string> {
11
+ prefix: string;
12
+ private readonly _fields;
13
+ sep: string;
14
+ /**
15
+ * @param prefix Prefix for the data. Use something unique across your bot.
16
+ * @param fields Field names in the order they will be serialized.
17
+ */
18
+ constructor(prefix: string, ...fields: T[]);
19
+ /**
20
+ * Build a callback data string
21
+ *
22
+ * @param obj Object containing the data
23
+ */
24
+ build(obj: Record<T, string>): string;
25
+ /**
26
+ * Parse callback data to object
27
+ *
28
+ * @param data Callback data as string
29
+ */
30
+ parse(data: string): Record<T, string>;
31
+ /**
32
+ * Create a filter for this callback data.
33
+ *
34
+ * > **Note**: `params` object will be compiled to a RegExp,
35
+ * > so avoid using characters that have special meaning in regex,
36
+ * > or use RegExp directly to let the IDE guide you.
37
+ *
38
+ * @param params
39
+ */
40
+ filter(params: Partial<Record<T, MaybeArray<string | RegExp>>>): UpdateFilter<CallbackQuery, {
41
+ match: Record<T, string>;
42
+ }>;
43
+ }
@@ -0,0 +1,95 @@
1
+ import { MtArgumentError } from '@mtcute/client';
2
+ /**
3
+ * Callback data builder, inspired by [aiogram](https://github.com/aiogram/aiogram).
4
+ *
5
+ * This can be used to simplify management of different callbacks.
6
+ *
7
+ * [Learn more in the docs](/guide/topics/keyboards.html#callback-data-builders)
8
+ */
9
+ export class CallbackDataBuilder {
10
+ /**
11
+ * @param prefix Prefix for the data. Use something unique across your bot.
12
+ * @param fields Field names in the order they will be serialized.
13
+ */
14
+ constructor(prefix, ...fields) {
15
+ this.prefix = prefix;
16
+ this.sep = ':';
17
+ this._fields = fields;
18
+ }
19
+ /**
20
+ * Build a callback data string
21
+ *
22
+ * @param obj Object containing the data
23
+ */
24
+ build(obj) {
25
+ const ret = this.prefix +
26
+ this.sep +
27
+ this._fields
28
+ .map((f) => {
29
+ const val = obj[f];
30
+ if (val.includes(this.sep)) {
31
+ throw new MtArgumentError(`Value for ${f} ${val} contains separator ${this.sep} and cannot be used.`);
32
+ }
33
+ return val;
34
+ })
35
+ .join(this.sep);
36
+ if (ret.length > 64) {
37
+ throw new MtArgumentError('Resulting callback data is too long.');
38
+ }
39
+ return ret;
40
+ }
41
+ /**
42
+ * Parse callback data to object
43
+ *
44
+ * @param data Callback data as string
45
+ */
46
+ parse(data) {
47
+ const parts = data.split(this.sep);
48
+ if (parts[0] !== this.prefix) {
49
+ throw new MtArgumentError('Invalid data passed');
50
+ }
51
+ if (parts.length !== this._fields.length + 1) {
52
+ throw new MtArgumentError('Invalid data passed');
53
+ }
54
+ const ret = {};
55
+ parts.forEach((it, idx) => {
56
+ ret[this._fields[idx - 1]] = it;
57
+ });
58
+ return ret;
59
+ }
60
+ /**
61
+ * Create a filter for this callback data.
62
+ *
63
+ * > **Note**: `params` object will be compiled to a RegExp,
64
+ * > so avoid using characters that have special meaning in regex,
65
+ * > or use RegExp directly to let the IDE guide you.
66
+ *
67
+ * @param params
68
+ */
69
+ filter(params) {
70
+ const parts = [];
71
+ this._fields.forEach((field) => {
72
+ if (!(field in params)) {
73
+ parts.push(`[^${this.sep}]*?`);
74
+ return;
75
+ }
76
+ const value = params[field];
77
+ if (Array.isArray(value)) {
78
+ parts.push(`(${value.map((i) => (typeof i === 'string' ? i : i.source)).join('|')})`);
79
+ }
80
+ else {
81
+ // noinspection SuspiciousTypeOfGuard
82
+ parts.push(typeof value === 'string' ? value : value.source);
83
+ }
84
+ });
85
+ const regex = new RegExp(`^${this.prefix}${this.sep}${parts.join(this.sep)}$`);
86
+ return (query) => {
87
+ const m = query.dataStr?.match(regex);
88
+ if (!m)
89
+ return false;
90
+ query.match = this.parse(m[0]);
91
+ return true;
92
+ };
93
+ }
94
+ }
95
+ //# sourceMappingURL=callback-data-builder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callback-data-builder.js","sourceRoot":"","sources":["../../src/callback-data-builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAI3E;;;;;;GAMG;AACH,MAAM,OAAO,mBAAmB;IAK5B;;;OAGG;IACH,YACW,MAAc,EACrB,GAAG,MAAW;QADP,WAAM,GAAN,MAAM,CAAQ;QAPzB,QAAG,GAAG,GAAG,CAAA;QAUL,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACzB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,GAAsB;QACxB,MAAM,GAAG,GACL,IAAI,CAAC,MAAM;YACX,IAAI,CAAC,GAAG;YACR,IAAI,CAAC,OAAO;iBACP,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;gBACP,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAA;gBAElB,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E;gBACpB,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,CAAA;gBAE9B,OAAM;aACT;YAED,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;YAE3B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBACtB,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;aACxF;iBAAM;gBACH,qCAAqC;gBACrC,KAAK,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAE,KAAgB,CAAC,MAAM,CAAC,CAAA;aAC3E;QACL,CAAC,CAAC,CAAA;QAEF,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAE9E,OAAO,CAAC,KAAK,EAAE,EAAE;YACb,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAA;YACrC,IAAI,CAAC,CAAC;gBAAE,OAAO,KAAK,CACnB;YACG,KAGH,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YAE1B,OAAO,IAAI,CAAA;QACf,CAAC,CAAA;IACL,CAAC;CACJ","sourcesContent":["import { CallbackQuery, MaybeArray, MtArgumentError } from '@mtcute/client'\n\nimport { UpdateFilter } from './filters/types.js'\n\n/**\n * Callback data builder, inspired by [aiogram](https://github.com/aiogram/aiogram).\n *\n * This can be used to simplify management of different callbacks.\n *\n * [Learn more in the docs](/guide/topics/keyboards.html#callback-data-builders)\n */\nexport class CallbackDataBuilder<T extends string> {\n private readonly _fields: T[]\n\n sep = ':'\n\n /**\n * @param prefix Prefix for the data. Use something unique across your bot.\n * @param fields Field names in the order they will be serialized.\n */\n constructor(\n public prefix: string,\n ...fields: T[]\n ) {\n this._fields = fields\n }\n\n /**\n * Build a callback data string\n *\n * @param obj Object containing the data\n */\n build(obj: Record<T, string>): string {\n const ret =\n this.prefix +\n this.sep +\n this._fields\n .map((f) => {\n const val = obj[f]\n\n if (val.includes(this.sep)) {\n throw new MtArgumentError(\n `Value for ${f} ${val} contains separator ${this.sep} and cannot be used.`,\n )\n }\n\n return val\n })\n .join(this.sep)\n\n if (ret.length > 64) {\n throw new MtArgumentError('Resulting callback data is too long.')\n }\n\n return ret\n }\n\n /**\n * Parse callback data to object\n *\n * @param data Callback data as string\n */\n parse(data: string): Record<T, string> {\n const parts = data.split(this.sep)\n\n if (parts[0] !== this.prefix) {\n throw new MtArgumentError('Invalid data passed')\n }\n\n if (parts.length !== this._fields.length + 1) {\n throw new MtArgumentError('Invalid data passed')\n }\n\n const ret = {} as Record<T, string>\n parts.forEach((it, idx) => {\n ret[this._fields[idx - 1]] = it\n })\n\n return ret\n }\n\n /**\n * Create a filter for this callback data.\n *\n * > **Note**: `params` object will be compiled to a RegExp,\n * > so avoid using characters that have special meaning in regex,\n * > or use RegExp directly to let the IDE guide you.\n *\n * @param params\n */\n filter(params: Partial<Record<T, MaybeArray<string | RegExp>>>): UpdateFilter<\n CallbackQuery,\n {\n match: Record<T, string>\n }\n > {\n const parts: string[] = []\n\n this._fields.forEach((field) => {\n if (!(field in params)) {\n parts.push(`[^${this.sep}]*?`)\n\n return\n }\n\n const value = params[field]\n\n if (Array.isArray(value)) {\n parts.push(`(${value.map((i) => (typeof i === 'string' ? i : i.source)).join('|')})`)\n } else {\n // noinspection SuspiciousTypeOfGuard\n parts.push(typeof value === 'string' ? value : (value as RegExp).source)\n }\n })\n\n const regex = new RegExp(`^${this.prefix}${this.sep}${parts.join(this.sep)}$`)\n\n return (query) => {\n const m = query.dataStr?.match(regex)\n if (!m) return false\n ;(\n query as CallbackQuery & {\n match: Record<T, string>\n }\n ).match = this.parse(m[0])\n\n return true\n }\n }\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import { ParsedUpdate, TelegramClient } from '@mtcute/client';
2
+ export type UpdateContext<T> = T & {
3
+ client: TelegramClient;
4
+ _name: Extract<ParsedUpdate, {
5
+ data: T;
6
+ }>['name'];
7
+ };
8
+ export type UpdateContextDistributed<T> = T extends never ? never : UpdateContext<T>;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/context/base.ts"],"names":[],"mappings":"","sourcesContent":["import { ParsedUpdate, TelegramClient } from '@mtcute/client'\n\nexport type UpdateContext<T> = T & {\n client: TelegramClient\n _name: Extract<ParsedUpdate, { data: T }>['name']\n}\n\nexport type UpdateContextDistributed<T> = T extends never ? never : UpdateContext<T>\n"]}
@@ -0,0 +1,27 @@
1
+ import { CallbackQuery, TelegramClient } from '@mtcute/client';
2
+ import { UpdateContext } from './base.js';
3
+ /**
4
+ * Context of a callback query update.
5
+ *
6
+ * This is a subclass of {@link CallbackQuery}, so all its fields are also available.
7
+ */
8
+ export declare class CallbackQueryContext extends CallbackQuery implements UpdateContext<CallbackQuery> {
9
+ readonly client: TelegramClient;
10
+ readonly _name = "callback_query";
11
+ constructor(client: TelegramClient, query: CallbackQuery);
12
+ /** Answer to this callback query */
13
+ answer(params: Parameters<TelegramClient['answerCallbackQuery']>[1]): Promise<void>;
14
+ /**
15
+ * * Message that contained the callback button that was clicked.
16
+ *
17
+ * Note that the message may have been deleted, in which case
18
+ * `MessageNotFoundError` is thrown.
19
+ *
20
+ * Can only be used if `isInline = false`
21
+ */
22
+ getMessage(): Promise<import("@mtcute/client").Message>;
23
+ /**
24
+ * Edit the message that contained the callback button that was clicked.
25
+ */
26
+ editMessage(params: Omit<Parameters<TelegramClient['editInlineMessage']>[0], 'messageId'>): Promise<void | import("@mtcute/client").Message>;
27
+ }
@@ -0,0 +1,52 @@
1
+ import { CallbackQuery, getMarkedPeerId, MtArgumentError, MtMessageNotFoundError } from '@mtcute/client';
2
+ /**
3
+ * Context of a callback query update.
4
+ *
5
+ * This is a subclass of {@link CallbackQuery}, so all its fields are also available.
6
+ */
7
+ export class CallbackQueryContext extends CallbackQuery {
8
+ constructor(client, query) {
9
+ super(query.raw, query._peers);
10
+ this.client = client;
11
+ this._name = 'callback_query';
12
+ }
13
+ /** Answer to this callback query */
14
+ answer(params) {
15
+ return this.client.answerCallbackQuery(this.id, params);
16
+ }
17
+ /**
18
+ * * Message that contained the callback button that was clicked.
19
+ *
20
+ * Note that the message may have been deleted, in which case
21
+ * `MessageNotFoundError` is thrown.
22
+ *
23
+ * Can only be used if `isInline = false`
24
+ */
25
+ async getMessage() {
26
+ if (this.raw._ !== 'updateBotCallbackQuery') {
27
+ throw new MtArgumentError('Cannot get message for inline callback query');
28
+ }
29
+ const [msg] = await this.client.getMessages(this.raw.peer, this.raw.msgId);
30
+ if (!msg) {
31
+ throw new MtMessageNotFoundError(getMarkedPeerId(this.raw.peer), this.raw.msgId, 'Message not found');
32
+ }
33
+ return msg;
34
+ }
35
+ /**
36
+ * Edit the message that contained the callback button that was clicked.
37
+ */
38
+ async editMessage(params) {
39
+ if (this.raw._ === 'updateInlineBotCallbackQuery') {
40
+ return this.client.editInlineMessage({
41
+ messageId: this.raw.msgId,
42
+ ...params,
43
+ });
44
+ }
45
+ return this.client.editMessage({
46
+ chatId: this.raw.peer,
47
+ message: this.raw.msgId,
48
+ ...params,
49
+ });
50
+ }
51
+ }
52
+ //# sourceMappingURL=callback-query.js.map