@mtcute/dispatcher 0.17.2 → 0.18.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 (111) hide show
  1. package/callback-data-builder.cjs +126 -0
  2. package/callback-data-builder.d.cts +49 -0
  3. package/callback-data-builder.js +121 -0
  4. package/callback-data-builder.test.d.cts +1 -0
  5. package/context/base.d.cts +9 -0
  6. package/context/business-message.cjs +143 -0
  7. package/context/business-message.d.cts +60 -0
  8. package/context/business-message.js +138 -0
  9. package/context/callback-query.cjs +92 -0
  10. package/context/callback-query.d.cts +62 -0
  11. package/context/callback-query.js +87 -0
  12. package/context/chat-join-request.cjs +32 -0
  13. package/context/chat-join-request.d.cts +17 -0
  14. package/context/chat-join-request.d.ts +1 -1
  15. package/context/chat-join-request.js +27 -0
  16. package/context/chosen-inline-result.cjs +30 -0
  17. package/context/chosen-inline-result.d.cts +22 -0
  18. package/context/chosen-inline-result.d.ts +1 -1
  19. package/context/chosen-inline-result.js +25 -0
  20. package/context/index.d.cts +9 -0
  21. package/context/inline-query.cjs +20 -0
  22. package/context/inline-query.d.cts +15 -0
  23. package/context/inline-query.js +15 -0
  24. package/context/message.cjs +182 -0
  25. package/context/message.d.cts +82 -0
  26. package/context/message.d.ts +2 -2
  27. package/context/message.js +177 -0
  28. package/context/parse.cjs +45 -0
  29. package/context/parse.d.cts +13 -0
  30. package/context/parse.js +40 -0
  31. package/context/pre-checkout-query.cjs +24 -0
  32. package/context/pre-checkout-query.d.cts +17 -0
  33. package/context/pre-checkout-query.d.ts +1 -1
  34. package/context/pre-checkout-query.js +19 -0
  35. package/context/scene-transition.cjs +52 -0
  36. package/context/scene-transition.d.cts +24 -0
  37. package/context/scene-transition.d.ts +1 -1
  38. package/context/scene-transition.js +47 -0
  39. package/dispatcher.cjs +860 -0
  40. package/dispatcher.d.cts +880 -0
  41. package/dispatcher.d.ts +4 -4
  42. package/dispatcher.js +855 -0
  43. package/filters/bots.cjs +94 -0
  44. package/filters/bots.d.cts +62 -0
  45. package/filters/bots.d.ts +2 -4
  46. package/filters/bots.js +89 -0
  47. package/filters/bots.test.d.cts +1 -0
  48. package/filters/bundle.cjs +79 -0
  49. package/filters/bundle.d.cts +10 -0
  50. package/filters/bundle.js +74 -0
  51. package/filters/chat.cjs +43 -0
  52. package/filters/chat.d.cts +29 -0
  53. package/filters/chat.d.ts +8 -6
  54. package/filters/chat.js +38 -0
  55. package/filters/group.cjs +49 -0
  56. package/filters/group.d.cts +26 -0
  57. package/filters/group.js +44 -0
  58. package/filters/index.d.cts +4 -0
  59. package/filters/logic.cjs +57 -0
  60. package/filters/logic.d.cts +29 -0
  61. package/filters/logic.js +52 -0
  62. package/filters/logic.test.d.cts +1 -0
  63. package/filters/message.cjs +130 -0
  64. package/filters/message.d.cts +223 -0
  65. package/filters/message.d.ts +5 -1
  66. package/filters/message.js +125 -0
  67. package/filters/state.cjs +21 -0
  68. package/filters/state.d.cts +15 -0
  69. package/filters/state.js +16 -0
  70. package/filters/text.cjs +87 -0
  71. package/filters/text.d.cts +64 -0
  72. package/filters/text.d.ts +2 -2
  73. package/filters/text.js +82 -0
  74. package/filters/types.d.cts +91 -0
  75. package/filters/updates.cjs +27 -0
  76. package/filters/updates.d.cts +39 -0
  77. package/filters/updates.js +22 -0
  78. package/filters/user.cjs +57 -0
  79. package/filters/user.d.cts +24 -0
  80. package/filters/user.js +52 -0
  81. package/handler.d.cts +41 -0
  82. package/handler.d.ts +1 -1
  83. package/index.cjs +37 -2528
  84. package/index.js +16 -2507
  85. package/package.json +10 -9
  86. package/propagation.cjs +15 -0
  87. package/propagation.d.cts +22 -0
  88. package/propagation.js +10 -0
  89. package/state/index.d.cts +5 -0
  90. package/state/key.cjs +32 -0
  91. package/state/key.d.cts +24 -0
  92. package/state/key.js +27 -0
  93. package/state/provider.d.cts +5 -0
  94. package/state/providers/index.d.cts +2 -0
  95. package/state/providers/memory.cjs +79 -0
  96. package/state/providers/memory.d.cts +29 -0
  97. package/state/providers/memory.js +74 -0
  98. package/state/providers/sqlite.cjs +99 -0
  99. package/state/providers/sqlite.d.cts +28 -0
  100. package/state/providers/sqlite.js +94 -0
  101. package/state/repository.d.cts +62 -0
  102. package/state/service.cjs +69 -0
  103. package/state/service.d.cts +20 -0
  104. package/state/service.js +64 -0
  105. package/state/update-state.cjs +206 -0
  106. package/state/update-state.d.cts +151 -0
  107. package/state/update-state.d.ts +1 -1
  108. package/state/update-state.js +201 -0
  109. package/wizard.cjs +90 -0
  110. package/wizard.d.cts +64 -0
  111. package/wizard.js +85 -0
package/dispatcher.js ADDED
@@ -0,0 +1,855 @@
1
+ import { unknownToError } from "@fuman/utils";
2
+ import { MtArgumentError } from "@mtcute/core";
3
+ import { _parsedUpdateToContext } from "./context/parse.js";
4
+ import { SceneTransitionContext } from "./context/scene-transition.js";
5
+ import { StateService } from "./state/service.js";
6
+ import { defaultStateKeyDelegate } from "./state/key.js";
7
+ import { UpdateState } from "./state/update-state.js";
8
+ class Dispatcher {
9
+ _groups = /* @__PURE__ */ new Map();
10
+ _groupsOrder = [];
11
+ _client;
12
+ _parent;
13
+ _children = [];
14
+ _scenes;
15
+ _scene;
16
+ _sceneScoped;
17
+ _storage;
18
+ _stateKeyDelegate;
19
+ _customStateKeyDelegate;
20
+ _customStorage;
21
+ _deps = {};
22
+ _errorHandler;
23
+ _preUpdateHandler;
24
+ _postUpdateHandler;
25
+ _sceneTransitionHandler;
26
+ constructor(client, params) {
27
+ this.dispatchRawUpdate = this.dispatchRawUpdate.bind(this);
28
+ this.dispatchUpdate = this.dispatchUpdate.bind(this);
29
+ let { storage, key, sceneName } = params ?? {};
30
+ if (client) {
31
+ this.bindToClient(client);
32
+ if (storage) {
33
+ this._storage = new StateService(storage);
34
+ this._stateKeyDelegate = key ?? defaultStateKeyDelegate;
35
+ }
36
+ } else {
37
+ if (storage) {
38
+ this._customStorage = new StateService(storage);
39
+ }
40
+ if (key) {
41
+ this._customStateKeyDelegate = key;
42
+ }
43
+ if (sceneName) {
44
+ if (sceneName[0] === "$") {
45
+ throw new MtArgumentError("Scene name cannot start with $");
46
+ }
47
+ this._scene = sceneName;
48
+ }
49
+ }
50
+ }
51
+ static for(client, params) {
52
+ return new Dispatcher(client, params);
53
+ }
54
+ /**
55
+ * Create a new child dispatcher.
56
+ */
57
+ static child(params) {
58
+ return new Dispatcher(void 0, params);
59
+ }
60
+ /**
61
+ * Create a new scene dispatcher
62
+ */
63
+ static scene(name, params) {
64
+ return new Dispatcher(void 0, { sceneName: name, ...params });
65
+ }
66
+ /** For scene dispatchers, name of the scene */
67
+ get sceneName() {
68
+ return this._scene;
69
+ }
70
+ inject(name, value) {
71
+ if (this._parent) {
72
+ throw new MtArgumentError("Cannot inject dependencies to child dispatchers");
73
+ }
74
+ if (typeof name === "object") {
75
+ for (const [k, v] of Object.entries(name)) {
76
+ this._deps[k] = v;
77
+ }
78
+ } else {
79
+ this._deps[name] = value;
80
+ }
81
+ }
82
+ /**
83
+ * Get the dependencies injected into this dispatcher.
84
+ */
85
+ get deps() {
86
+ return this._deps;
87
+ }
88
+ /**
89
+ * Bind the dispatcher to the client.
90
+ * Called by the constructor automatically if
91
+ * `client` was passed.
92
+ *
93
+ * Dispatcher also uses bound client to throw errors
94
+ */
95
+ bindToClient(client) {
96
+ client.onUpdate.add(this.dispatchUpdate);
97
+ client.onRawUpdate.add(this.dispatchRawUpdate);
98
+ this._client = client;
99
+ }
100
+ /**
101
+ * Unbind a dispatcher from the client.
102
+ */
103
+ unbind() {
104
+ if (this._client) {
105
+ this._client.onUpdate.remove(this.dispatchUpdate);
106
+ this._client.onRawUpdate.remove(this.dispatchRawUpdate);
107
+ this._client = void 0;
108
+ }
109
+ }
110
+ /**
111
+ * Destroy the dispatcher and all its children.
112
+ *
113
+ * When destroying, all the registered handlers are removed,
114
+ * and the underlying storage is freed.
115
+ */
116
+ async destroy() {
117
+ if (this._parent && this._customStorage) {
118
+ await this._customStorage.destroy();
119
+ } else if (!this._parent && this._storage) {
120
+ await this._storage.destroy();
121
+ }
122
+ this.removeUpdateHandler("all");
123
+ for (const child of this._children) {
124
+ await child.destroy();
125
+ }
126
+ for (const scene of this._scenes?.values() ?? []) {
127
+ await scene.destroy();
128
+ }
129
+ }
130
+ /**
131
+ * Process a raw update with this dispatcher.
132
+ * Calling this method without bound client will not work.
133
+ *
134
+ * Under the hood asynchronously calls {@link dispatchRawUpdateNow}
135
+ * with error handler set to client's one.
136
+ *
137
+ * @param update Update to process
138
+ * @param peers Peers index
139
+ */
140
+ dispatchRawUpdate({ update, peers }) {
141
+ if (!this._client) return;
142
+ this.dispatchRawUpdateNow(update, peers).catch((err) => this._client.onError.emit(unknownToError(err)));
143
+ }
144
+ /**
145
+ * Process a raw update right now in the current stack.
146
+ *
147
+ * Unlike {@link dispatchRawUpdate}, this does not schedule
148
+ * the update to be dispatched, but dispatches it immediately,
149
+ * and after `await`ing this method you can be certain that the update
150
+ * was fully processed by all the registered handlers, including children.
151
+ *
152
+ * @param update Update to process
153
+ * @param peers Peers map
154
+ * @returns Whether the update was handled
155
+ */
156
+ async dispatchRawUpdateNow(update, peers) {
157
+ if (!this._client) return false;
158
+ let handled = false;
159
+ outer: for (const grp of this._groupsOrder) {
160
+ const group = this._groups.get(grp);
161
+ if (group.has("raw")) {
162
+ const handlers = group.get("raw");
163
+ for (const h of handlers) {
164
+ let result;
165
+ if (!h.check || await h.check(this._client, update, peers)) {
166
+ result = await h.callback(this._client, update, peers);
167
+ handled = true;
168
+ } else {
169
+ continue;
170
+ }
171
+ switch (result) {
172
+ case "continue":
173
+ continue;
174
+ case "stop":
175
+ break outer;
176
+ case "stop-children":
177
+ return handled;
178
+ }
179
+ break;
180
+ }
181
+ }
182
+ }
183
+ for (const child of this._children) {
184
+ const childHandled = await child.dispatchRawUpdateNow(update, peers);
185
+ handled ||= childHandled;
186
+ }
187
+ return handled;
188
+ }
189
+ /**
190
+ * Process an update with this dispatcher.
191
+ * Calling this method without bound client will not work.
192
+ *
193
+ * Under the hood asynchronously calls {@link dispatchUpdateNow}
194
+ * with error handler set to client's one.
195
+ *
196
+ * @param update Update to process
197
+ */
198
+ dispatchUpdate(update) {
199
+ if (!this._client) return;
200
+ this.dispatchUpdateNow(update).catch((err) => this._client.onError.emit(unknownToError(err)));
201
+ }
202
+ /**
203
+ * Process an update right now in the current stack.
204
+ *
205
+ * Unlike {@link dispatchUpdate}, this does not schedule
206
+ * the update to be dispatched, but dispatches it immediately,
207
+ * and after `await`ing this method you can be certain that the update
208
+ * was fully processed by all the registered handlers, including children.
209
+ *
210
+ * @param update Update to process
211
+ * @returns Whether the update was handled
212
+ */
213
+ async dispatchUpdateNow(update) {
214
+ return this._dispatchUpdateNowImpl(update);
215
+ }
216
+ async _dispatchUpdateNowImpl(update, parsedState, parsedScene, forceScene, parsedContext) {
217
+ if (!this._client) return false;
218
+ if (parsedScene === void 0) {
219
+ if (this._storage && this._scenes && (update.name === "new_message" || update.name === "edit_message" || update.name === "callback_query" || update.name === "message_group" || update.name === "new_business_message" || update.name === "edit_business_message" || update.name === "business_message_group")) {
220
+ if (!parsedContext) parsedContext = _parsedUpdateToContext(this._client, update);
221
+ const key = await this._stateKeyDelegate(parsedContext);
222
+ if (key) {
223
+ parsedScene = await this._storage.getCurrentScene(key);
224
+ } else {
225
+ parsedScene = null;
226
+ }
227
+ } else {
228
+ parsedScene = null;
229
+ }
230
+ }
231
+ if (!forceScene && parsedScene !== null) {
232
+ if (this._scene) {
233
+ if (this._scene !== parsedScene) {
234
+ return false;
235
+ }
236
+ } else {
237
+ if (!this._scenes || !this._scenes.has(parsedScene)) {
238
+ return false;
239
+ }
240
+ return this._scenes.get(parsedScene)._dispatchUpdateNowImpl(update, parsedState, parsedScene, true);
241
+ }
242
+ }
243
+ if (parsedState === void 0) {
244
+ if (this._storage && (update.name === "new_message" || update.name === "edit_message" || update.name === "callback_query" || update.name === "message_group" || update.name === "new_business_message" || update.name === "edit_business_message" || update.name === "business_message_group")) {
245
+ if (!parsedContext) parsedContext = _parsedUpdateToContext(this._client, update);
246
+ const key = await this._stateKeyDelegate(parsedContext);
247
+ if (key) {
248
+ let customKey;
249
+ if (!this._customStateKeyDelegate || (customKey = await this._customStateKeyDelegate(parsedContext))) {
250
+ parsedState = new UpdateState(
251
+ this._storage,
252
+ key,
253
+ this._scene ?? null,
254
+ this._sceneScoped,
255
+ this._customStorage,
256
+ customKey
257
+ );
258
+ }
259
+ } else {
260
+ parsedState = null;
261
+ }
262
+ } else {
263
+ parsedState = null;
264
+ }
265
+ }
266
+ let shouldDispatch = true;
267
+ let shouldDispatchChildren = true;
268
+ let handled = false;
269
+ switch (await this._preUpdateHandler?.(update, parsedState)) {
270
+ case "stop":
271
+ shouldDispatch = false;
272
+ break;
273
+ case "stop-children":
274
+ return false;
275
+ }
276
+ if (shouldDispatch) {
277
+ outer: for (const grp of this._groupsOrder) {
278
+ const group = this._groups.get(grp);
279
+ if (group.has(update.name)) {
280
+ const handlers = group.get(update.name);
281
+ try {
282
+ for (const h of handlers) {
283
+ let result;
284
+ if (!parsedContext) parsedContext = _parsedUpdateToContext(this._client, update);
285
+ if (!h.check || await h.check(parsedContext, parsedState)) {
286
+ result = await h.callback(parsedContext, parsedState);
287
+ handled = true;
288
+ } else {
289
+ continue;
290
+ }
291
+ if (parsedState && this._scenes) {
292
+ const newScene = parsedState.scene;
293
+ if (parsedScene !== newScene) {
294
+ const nextDp = newScene ? this._scenes.get(newScene) : this._parent;
295
+ if (!nextDp) {
296
+ throw new MtArgumentError(`Scene ${newScene} not found`);
297
+ }
298
+ if (nextDp._sceneTransitionHandler) {
299
+ const transition = new SceneTransitionContext(parsedScene, parsedContext);
300
+ const transitionResult = await nextDp._sceneTransitionHandler?.(
301
+ transition,
302
+ parsedState
303
+ );
304
+ switch (transitionResult) {
305
+ case "stop":
306
+ return true;
307
+ case "continue":
308
+ continue;
309
+ case "scene": {
310
+ const scene = parsedState.scene;
311
+ const dp = scene ? nextDp._scenes.get(scene) : nextDp._parent;
312
+ return dp._dispatchUpdateNowImpl(update, void 0, scene, true);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ }
318
+ switch (result) {
319
+ case "continue":
320
+ continue;
321
+ case "stop":
322
+ break outer;
323
+ case "stop-children":
324
+ shouldDispatchChildren = false;
325
+ break outer;
326
+ case "scene": {
327
+ if (!parsedState) {
328
+ throw new MtArgumentError("Cannot use ToScene without state");
329
+ }
330
+ const scene = parsedState.scene;
331
+ const dp = scene ? this._scenes.get(scene) : this._parent;
332
+ return dp._dispatchUpdateNowImpl(update, void 0, scene, true);
333
+ }
334
+ }
335
+ break;
336
+ }
337
+ } catch (e) {
338
+ if (this._errorHandler) {
339
+ const handled2 = await this._errorHandler(e, update, parsedState);
340
+ if (!handled2) throw e;
341
+ } else {
342
+ throw e;
343
+ }
344
+ }
345
+ }
346
+ }
347
+ }
348
+ if (shouldDispatchChildren) {
349
+ for (const child of this._children) {
350
+ const childHandled = await child._dispatchUpdateNowImpl(update);
351
+ handled ||= childHandled;
352
+ }
353
+ }
354
+ await this._postUpdateHandler?.(handled, update, parsedState);
355
+ return handled;
356
+ }
357
+ /**
358
+ * Add an update handler to a given handlers group
359
+ *
360
+ * @param handler Update handler
361
+ * @param group Handler group index
362
+ */
363
+ addUpdateHandler(handler, group = 0) {
364
+ if (!this._groups.has(group)) {
365
+ this._groups.set(group, /* @__PURE__ */ new Map());
366
+ this._groupsOrder.push(group);
367
+ this._groupsOrder.sort((a, b) => a - b);
368
+ }
369
+ if (!this._groups.get(group).has(handler.name)) {
370
+ this._groups.get(group).set(handler.name, []);
371
+ }
372
+ this._groups.get(group).get(handler.name).push(handler);
373
+ }
374
+ /**
375
+ * Remove an update handler (or handlers) from a given
376
+ * handler group.
377
+ *
378
+ * @param handler Update handler to remove, its name or `'all'` to remove all
379
+ * @param group Handler group index (null to affect all groups)
380
+ */
381
+ removeUpdateHandler(handler, group = 0) {
382
+ if (group !== null && !this._groups.has(group)) {
383
+ return;
384
+ }
385
+ if (typeof handler === "string") {
386
+ if (handler === "all") {
387
+ if (group === null) {
388
+ this._groups = /* @__PURE__ */ new Map();
389
+ } else {
390
+ this._groups.delete(group);
391
+ }
392
+ } else if (group !== null) {
393
+ this._groups.get(group).delete(handler);
394
+ }
395
+ return;
396
+ }
397
+ if (group === null) return;
398
+ if (!this._groups.get(group).has(handler.name)) {
399
+ return;
400
+ }
401
+ const idx = this._groups.get(group).get(handler.name).indexOf(handler);
402
+ if (idx > -1) {
403
+ this._groups.get(group).get(handler.name).splice(idx, 1);
404
+ }
405
+ }
406
+ /**
407
+ * Register an error handler.
408
+ *
409
+ * This is used locally within this dispatcher
410
+ * (does not affect children/parent) whenever
411
+ * an error is thrown inside an update handler.
412
+ * Not used for raw update handlers
413
+ *
414
+ * When an error is thrown, but there is no error
415
+ * handler, it is propagated to `TelegramClient`.
416
+ *
417
+ * There can be at most one error handler.
418
+ * Pass `null` to remove it.
419
+ *
420
+ * @param handler Error handler
421
+ */
422
+ onError(handler) {
423
+ if (handler) this._errorHandler = handler;
424
+ else this._errorHandler = void 0;
425
+ }
426
+ /**
427
+ * Register pre-update middleware.
428
+ *
429
+ * This is used locally within this dispatcher
430
+ * (does not affect children/parent) before processing
431
+ * an update, and can be used to skip this update.
432
+ *
433
+ * There can be at most one pre-update middleware.
434
+ * Pass `null` to remove it.
435
+ *
436
+ * @param handler Pre-update middleware
437
+ */
438
+ onPreUpdate(handler) {
439
+ if (handler) this._preUpdateHandler = handler;
440
+ else this._preUpdateHandler = void 0;
441
+ }
442
+ /**
443
+ * Register post-update middleware.
444
+ *
445
+ * This is used locally within this dispatcher
446
+ * (does not affect children/parent) after successfully
447
+ * processing an update, and can be used for stats.
448
+ *
449
+ * There can be at most one post-update middleware.
450
+ * Pass `null` to remove it.
451
+ *
452
+ * @param handler Pre-update middleware
453
+ */
454
+ onPostUpdate(handler) {
455
+ if (handler) this._postUpdateHandler = handler;
456
+ else this._postUpdateHandler = void 0;
457
+ }
458
+ /**
459
+ * Set error handler that will propagate
460
+ * the error to the parent dispatcher
461
+ */
462
+ propagateErrorToParent(err, update, state) {
463
+ if (!this.parent) {
464
+ throw new MtArgumentError("This dispatcher is not a child");
465
+ }
466
+ if (this.parent._errorHandler) {
467
+ return this.parent._errorHandler(err, update, state);
468
+ }
469
+ throw err;
470
+ }
471
+ // children //
472
+ /**
473
+ * Get parent dispatcher if current dispatcher is a child.
474
+ * Otherwise, return `null`
475
+ */
476
+ get parent() {
477
+ return this._parent ?? null;
478
+ }
479
+ _prepareChild(child) {
480
+ if (child._client) {
481
+ throw new MtArgumentError(
482
+ `Provided dispatcher is ${child._parent ? "already a child. Use parent.removeChild() before calling addChild()" : "already bound to a client. Use unbind() before calling addChild()"}`
483
+ );
484
+ }
485
+ child._parent = this;
486
+ child._client = this._client;
487
+ child._storage = this._storage;
488
+ child._deps = this._deps;
489
+ child._scenes = this._scenes;
490
+ child._stateKeyDelegate = this._stateKeyDelegate;
491
+ child._customStorage ??= this._customStorage;
492
+ child._customStateKeyDelegate ??= this._customStateKeyDelegate;
493
+ }
494
+ /**
495
+ * Add a child dispatcher.
496
+ *
497
+ * Child dispatchers are called when dispatching updates
498
+ * just like normal, except they can be controlled
499
+ * externally. Additionally, child dispatcher have their own
500
+ * independent handler grouping that does not interfere with parent's,
501
+ * including `StopPropagation` (i.e. returning `StopPropagation` will
502
+ * still call children. To entirely stop, use `StopChildrenPropagation`)
503
+ *
504
+ * Note that child dispatchers share the same TelegramClient and
505
+ * storage binding as the parent, don't bind them manually.
506
+ *
507
+ * @param child Other dispatcher
508
+ */
509
+ addChild(child) {
510
+ if (this._children.includes(child)) return;
511
+ this._prepareChild(child);
512
+ this._children.push(child);
513
+ }
514
+ addScene(scene, scoped = true) {
515
+ if (!this._scenes) this._scenes = /* @__PURE__ */ new Map();
516
+ if (!scene._scene) {
517
+ throw new MtArgumentError(
518
+ "Non-scene dispatcher passed to addScene. Use `Dispatcher.scene()` to create one."
519
+ );
520
+ }
521
+ if (this._scenes.has(scene._scene)) {
522
+ throw new MtArgumentError(`Scene with name ${scene._scene} is already registered!`);
523
+ }
524
+ this._prepareChild(scene);
525
+ scene._sceneScoped = scoped;
526
+ this._scenes.set(scene._scene, scene);
527
+ }
528
+ /**
529
+ * Remove a child dispatcher.
530
+ *
531
+ * Removing child dispatcher will also remove
532
+ * child dispatcher's client binding.
533
+ *
534
+ * If the provided dispatcher is not a child of current,
535
+ * this function will silently fail.
536
+ *
537
+ * @param child Other dispatcher
538
+ */
539
+ removeChild(child) {
540
+ const idx = this._children.indexOf(child);
541
+ if (idx > -1) {
542
+ child._unparent();
543
+ this._children.splice(idx, 1);
544
+ }
545
+ }
546
+ _unparent() {
547
+ this._parent = this._client = void 0;
548
+ this._deps = {};
549
+ this._stateKeyDelegate = void 0;
550
+ this._storage = void 0;
551
+ }
552
+ /**
553
+ * Extend current dispatcher by copying other dispatcher's
554
+ * handlers and children to the current.
555
+ *
556
+ * This might be more efficient for simple cases, but do note that the handler
557
+ * groups, children and scenes will get merged (unlike {@link addChild},
558
+ * where they are independent). Also note that unlike with children,
559
+ * when adding handlers to `other` *after* you extended
560
+ * the current dispatcher, changes will not be applied.
561
+ *
562
+ * @param other Other dispatcher
563
+ */
564
+ extend(other) {
565
+ if (other._customStorage || other._customStateKeyDelegate) {
566
+ throw new MtArgumentError("Provided dispatcher has custom storage and cannot be extended from.");
567
+ }
568
+ other._groupsOrder.forEach((group) => {
569
+ if (!this._groups.has(group)) {
570
+ this._groups.set(group, other._groups.get(group));
571
+ this._groupsOrder.push(group);
572
+ } else {
573
+ const otherGrp = other._groups.get(group);
574
+ const selfGrp = this._groups.get(group);
575
+ for (const typ of otherGrp.keys()) {
576
+ if (!selfGrp.has(typ)) {
577
+ selfGrp.set(typ, otherGrp.get(typ));
578
+ } else {
579
+ selfGrp.get(typ).push(...otherGrp.get(typ));
580
+ }
581
+ }
582
+ }
583
+ });
584
+ other._children.forEach((it) => {
585
+ it._unparent();
586
+ this.addChild(it);
587
+ });
588
+ if (other._scenes) {
589
+ const otherScenes = other._scenes;
590
+ if (!this._scenes) this._scenes = /* @__PURE__ */ new Map();
591
+ const myScenes = this._scenes;
592
+ for (const key of otherScenes.keys()) {
593
+ otherScenes.get(key)._unparent();
594
+ if (myScenes.has(key)) {
595
+ myScenes.delete(key);
596
+ }
597
+ this.addScene(otherScenes.get(key), otherScenes.get(key)._sceneScoped);
598
+ }
599
+ }
600
+ this._groupsOrder.sort((a, b) => a - b);
601
+ }
602
+ /**
603
+ * Create a clone of this dispatcher, that has the same handlers,
604
+ * but is not bound to a client or to a parent dispatcher.
605
+ *
606
+ * Custom Storage and key delegate are copied too.
607
+ *
608
+ * By default, child dispatchers (and scenes) are ignored, since
609
+ * that requires cloning every single one of them recursively
610
+ * and then binding them back.
611
+ *
612
+ * @param children Whether to also clone children and scenes
613
+ */
614
+ clone(children = false) {
615
+ const dp = new Dispatcher();
616
+ for (const key of this._groups.keys()) {
617
+ const idx = key;
618
+ dp._groups.set(idx, /* @__PURE__ */ new Map());
619
+ for (const type of this._groups.get(idx).keys()) {
620
+ dp._groups.get(idx).set(type, [...this._groups.get(idx).get(type)]);
621
+ }
622
+ }
623
+ dp._groupsOrder = [...this._groupsOrder];
624
+ dp._errorHandler = this._errorHandler;
625
+ dp._customStateKeyDelegate = this._customStateKeyDelegate;
626
+ dp._customStorage = this._customStorage;
627
+ if (children) {
628
+ this._children.forEach((it) => {
629
+ const child = it.clone(true);
630
+ dp.addChild(child);
631
+ });
632
+ if (this._scenes) {
633
+ for (const key of this._scenes.keys()) {
634
+ const scene = this._scenes.get(key).clone(true);
635
+ dp.addScene(scene, this._scenes.get(key)._sceneScoped);
636
+ }
637
+ }
638
+ }
639
+ return dp;
640
+ }
641
+ getState(object) {
642
+ if (!this._storage) {
643
+ throw new MtArgumentError("Cannot use getUpdateState() filter without state storage");
644
+ }
645
+ if (typeof object === "string") {
646
+ return new UpdateState(this._storage, object, this._scene ?? null, this._sceneScoped, this._customStorage);
647
+ }
648
+ return Promise.resolve(this._stateKeyDelegate(object)).then((key) => {
649
+ if (!key) {
650
+ throw new MtArgumentError("Cannot derive key from given object");
651
+ }
652
+ if (!this._customStateKeyDelegate) {
653
+ return new UpdateState(this._storage, key, this._scene ?? null, this._sceneScoped, this._customStorage);
654
+ }
655
+ return Promise.resolve(this._customStateKeyDelegate(object)).then((customKey) => {
656
+ if (!customKey) {
657
+ throw new MtArgumentError("Cannot derive custom key from given object");
658
+ }
659
+ return new UpdateState(
660
+ this._storage,
661
+ key,
662
+ this._scene ?? null,
663
+ this._sceneScoped,
664
+ this._customStorage,
665
+ customKey
666
+ );
667
+ });
668
+ });
669
+ }
670
+ /**
671
+ * Get global state.
672
+ *
673
+ * This will load the state for the given object
674
+ * ignoring local custom storage, key delegate and scene scope.
675
+ */
676
+ getGlobalState(object) {
677
+ if (!this._parent) {
678
+ throw new MtArgumentError("This dispatcher does not have a parent");
679
+ }
680
+ return Promise.resolve(this._stateKeyDelegate(object)).then((key) => {
681
+ if (!key) {
682
+ throw new MtArgumentError("Cannot derive key from given object");
683
+ }
684
+ return new UpdateState(this._storage, key, this._scene ?? null, false);
685
+ });
686
+ }
687
+ // addUpdateHandler convenience wrappers //
688
+ _addKnownHandler(name, filter, handler, group) {
689
+ if (typeof handler === "number" || typeof handler === "undefined") {
690
+ this.addUpdateHandler(
691
+ {
692
+ name,
693
+ callback: filter
694
+ },
695
+ handler
696
+ );
697
+ } else {
698
+ this.addUpdateHandler(
699
+ {
700
+ name,
701
+ callback: handler,
702
+ check: filter
703
+ },
704
+ group
705
+ );
706
+ }
707
+ }
708
+ /** @internal */
709
+ onRawUpdate(filter, handler, group) {
710
+ this._addKnownHandler("raw", filter, handler, group);
711
+ }
712
+ /**
713
+ * Register a scene transition handler
714
+ *
715
+ * This handler is called whenever a scene transition occurs
716
+ * in the context of the scene that is being entered,
717
+ * and before any of the its own handlers are called,
718
+ * and can be used to customize the transition behavior:
719
+ * - `Stop` to prevent dispatching the update any further **even if ToScene/ToRoot was used**
720
+ * - `Continue` same as Stop, but still dispatch the update to children
721
+ * - `ToScene` to prevent the transition and dispatch the update to the scene entered in the transition handler
722
+ *
723
+ * > **Note**: if multiple `state.enter()` calls were made within the same update,
724
+ * > this handler will only be called for the last one.
725
+ *
726
+ * @param handler Raw update handler
727
+ * @param group Handler group index
728
+ */
729
+ onSceneTransition(handler) {
730
+ if (handler) this._sceneTransitionHandler = handler;
731
+ else this._sceneTransitionHandler = void 0;
732
+ }
733
+ /** @internal */
734
+ onAnyCallbackQuery(filter, handler, group) {
735
+ this._addKnownHandler("callback_query", filter, handler, group);
736
+ this._addKnownHandler("inline_callback_query", filter, handler, group);
737
+ this._addKnownHandler("business_callback_query", filter, handler, group);
738
+ }
739
+ /** @internal */
740
+ onNewMessage(filter, handler, group) {
741
+ this._addKnownHandler("new_message", filter, handler, group);
742
+ }
743
+ /** @internal */
744
+ onEditMessage(filter, handler, group) {
745
+ this._addKnownHandler("edit_message", filter, handler, group);
746
+ }
747
+ /** @internal */
748
+ onMessageGroup(filter, handler, group) {
749
+ this._addKnownHandler("message_group", filter, handler, group);
750
+ }
751
+ /** @internal */
752
+ onDeleteMessage(filter, handler, group) {
753
+ this._addKnownHandler("delete_message", filter, handler, group);
754
+ }
755
+ /** @internal */
756
+ onChatMemberUpdate(filter, handler, group) {
757
+ this._addKnownHandler("chat_member", filter, handler, group);
758
+ }
759
+ /** @internal */
760
+ onInlineQuery(filter, handler, group) {
761
+ this._addKnownHandler("inline_query", filter, handler, group);
762
+ }
763
+ /** @internal */
764
+ onChosenInlineResult(filter, handler, group) {
765
+ this._addKnownHandler("chosen_inline_result", filter, handler, group);
766
+ }
767
+ /** @internal */
768
+ onCallbackQuery(filter, handler, group) {
769
+ this._addKnownHandler("callback_query", filter, handler, group);
770
+ }
771
+ /** @internal */
772
+ onInlineCallbackQuery(filter, handler, group) {
773
+ this._addKnownHandler("inline_callback_query", filter, handler, group);
774
+ }
775
+ /** @internal */
776
+ onBusinessCallbackQuery(filter, handler, group) {
777
+ this._addKnownHandler("business_callback_query", filter, handler, group);
778
+ }
779
+ /** @internal */
780
+ onPollUpdate(filter, handler, group) {
781
+ this._addKnownHandler("poll", filter, handler, group);
782
+ }
783
+ /** @internal */
784
+ onPollVote(filter, handler, group) {
785
+ this._addKnownHandler("poll_vote", filter, handler, group);
786
+ }
787
+ /** @internal */
788
+ onUserStatusUpdate(filter, handler, group) {
789
+ this._addKnownHandler("user_status", filter, handler, group);
790
+ }
791
+ /** @internal */
792
+ onUserTyping(filter, handler, group) {
793
+ this._addKnownHandler("user_typing", filter, handler, group);
794
+ }
795
+ /** @internal */
796
+ onHistoryRead(filter, handler, group) {
797
+ this._addKnownHandler("history_read", filter, handler, group);
798
+ }
799
+ /** @internal */
800
+ onBotStopped(filter, handler, group) {
801
+ this._addKnownHandler("bot_stopped", filter, handler, group);
802
+ }
803
+ /** @internal */
804
+ onBotChatJoinRequest(filter, handler, group) {
805
+ this._addKnownHandler("bot_chat_join_request", filter, handler, group);
806
+ }
807
+ /** @internal */
808
+ onChatJoinRequest(filter, handler, group) {
809
+ this._addKnownHandler("chat_join_request", filter, handler, group);
810
+ }
811
+ /** @internal */
812
+ onPreCheckoutQuery(filter, handler, group) {
813
+ this._addKnownHandler("pre_checkout_query", filter, handler, group);
814
+ }
815
+ /** @internal */
816
+ onStoryUpdate(filter, handler, group) {
817
+ this._addKnownHandler("story", filter, handler, group);
818
+ }
819
+ /** @internal */
820
+ onDeleteStory(filter, handler, group) {
821
+ this._addKnownHandler("delete_story", filter, handler, group);
822
+ }
823
+ /** @internal */
824
+ onBotReactionUpdate(filter, handler, group) {
825
+ this._addKnownHandler("bot_reaction", filter, handler, group);
826
+ }
827
+ /** @internal */
828
+ onBotReactionCountUpdate(filter, handler, group) {
829
+ this._addKnownHandler("bot_reaction_count", filter, handler, group);
830
+ }
831
+ /** @internal */
832
+ onBusinessConnectionUpdate(filter, handler, group) {
833
+ this._addKnownHandler("business_connection", filter, handler, group);
834
+ }
835
+ /** @internal */
836
+ onNewBusinessMessage(filter, handler, group) {
837
+ this._addKnownHandler("new_business_message", filter, handler, group);
838
+ }
839
+ /** @internal */
840
+ onEditBusinessMessage(filter, handler, group) {
841
+ this._addKnownHandler("edit_business_message", filter, handler, group);
842
+ }
843
+ /** @internal */
844
+ onBusinessMessageGroup(filter, handler, group) {
845
+ this._addKnownHandler("business_message_group", filter, handler, group);
846
+ }
847
+ /** @internal */
848
+ onDeleteBusinessMessage(filter, handler, group) {
849
+ this._addKnownHandler("delete_business_message", filter, handler, group);
850
+ }
851
+ // end-codegen
852
+ }
853
+ export {
854
+ Dispatcher
855
+ };