@mtcute/dispatcher 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/callback-data-builder.d.ts +1 -1
- package/cjs/callback-data-builder.js +5 -5
- package/cjs/callback-data-builder.js.map +1 -1
- package/cjs/callback-data-builder.test.js +8 -8
- package/cjs/callback-data-builder.test.js.map +1 -1
- package/cjs/context/base.d.ts +1 -1
- package/cjs/context/base.js.map +1 -1
- package/cjs/context/callback-query.d.ts +2 -2
- package/cjs/context/callback-query.js +3 -3
- package/cjs/context/callback-query.js.map +1 -1
- package/cjs/context/chat-join-request.d.ts +1 -1
- package/cjs/context/chat-join-request.js +2 -2
- package/cjs/context/chat-join-request.js.map +1 -1
- package/cjs/context/chosen-inline-result.d.ts +1 -1
- package/cjs/context/chosen-inline-result.js +3 -3
- package/cjs/context/chosen-inline-result.js.map +1 -1
- package/cjs/context/inline-query.d.ts +1 -1
- package/cjs/context/inline-query.js +2 -2
- package/cjs/context/inline-query.js.map +1 -1
- package/cjs/context/message.d.ts +6 -6
- package/cjs/context/message.js +3 -3
- package/cjs/context/message.js.map +1 -1
- package/cjs/context/parse.js.map +1 -1
- package/cjs/context/pre-checkout-query.d.ts +1 -1
- package/cjs/context/pre-checkout-query.js +2 -2
- package/cjs/context/pre-checkout-query.js.map +1 -1
- package/cjs/dispatcher.d.ts +14 -9
- package/cjs/dispatcher.js +41 -78
- package/cjs/dispatcher.js.map +1 -1
- package/cjs/filters/bots.d.ts +6 -6
- package/cjs/filters/bots.js +2 -2
- package/cjs/filters/bots.js.map +1 -1
- package/cjs/filters/bots.test.js +6 -5
- package/cjs/filters/bots.test.js.map +1 -1
- package/cjs/filters/chat.d.ts +1 -1
- package/cjs/filters/chat.js +1 -1
- package/cjs/filters/chat.js.map +1 -1
- package/cjs/filters/group.d.ts +1 -1
- package/cjs/filters/group.js.map +1 -1
- package/cjs/filters/logic.js.map +1 -1
- package/cjs/filters/message.d.ts +75 -67
- package/cjs/filters/message.js +3 -3
- package/cjs/filters/message.js.map +1 -1
- package/cjs/filters/state.d.ts +2 -2
- package/cjs/filters/state.js.map +1 -1
- package/cjs/filters/text.d.ts +1 -1
- package/cjs/filters/text.js.map +1 -1
- package/cjs/filters/types.d.ts +2 -2
- package/cjs/filters/types.js.map +1 -1
- package/cjs/filters/updates.d.ts +1 -1
- package/cjs/filters/updates.js.map +1 -1
- package/cjs/filters/user.d.ts +1 -1
- package/cjs/filters/user.js +4 -4
- package/cjs/filters/user.js.map +1 -1
- package/cjs/handler.d.ts +3 -3
- package/cjs/handler.js.map +1 -1
- package/cjs/propagation.js +1 -1
- package/cjs/propagation.js.map +1 -1
- package/cjs/state/index.d.ts +3 -1
- package/cjs/state/index.js +3 -1
- package/cjs/state/index.js.map +1 -1
- package/cjs/state/key.d.ts +2 -2
- package/cjs/state/key.js +2 -2
- package/cjs/state/key.js.map +1 -1
- package/cjs/state/provider.d.ts +5 -0
- package/cjs/state/provider.js +3 -0
- package/cjs/state/provider.js.map +1 -0
- package/cjs/state/providers/index.d.ts +2 -0
- package/cjs/state/providers/index.js +19 -0
- package/cjs/state/providers/index.js.map +1 -0
- package/cjs/state/providers/memory.d.ts +29 -0
- package/cjs/state/providers/memory.js +76 -0
- package/cjs/state/providers/memory.js.map +1 -0
- package/cjs/state/providers/sqlite.d.ts +29 -0
- package/cjs/state/providers/sqlite.js +89 -0
- package/cjs/state/providers/sqlite.js.map +1 -0
- package/cjs/state/repository.d.ts +62 -0
- package/cjs/state/repository.js +3 -0
- package/cjs/state/repository.js.map +1 -0
- package/cjs/state/service.d.ts +19 -0
- package/cjs/state/service.js +68 -0
- package/cjs/state/service.js.map +1 -0
- package/cjs/state/update-state.d.ts +3 -3
- package/cjs/state/update-state.js +7 -7
- package/cjs/state/update-state.js.map +1 -1
- package/cjs/wizard.d.ts +2 -2
- package/cjs/wizard.js +1 -1
- package/cjs/wizard.js.map +1 -1
- package/esm/callback-data-builder.d.ts +1 -1
- package/esm/callback-data-builder.js +1 -1
- package/esm/callback-data-builder.js.map +1 -1
- package/esm/callback-data-builder.test.js +2 -2
- package/esm/callback-data-builder.test.js.map +1 -1
- package/esm/context/base.d.ts +1 -1
- package/esm/context/base.js.map +1 -1
- package/esm/context/callback-query.d.ts +2 -2
- package/esm/context/callback-query.js +1 -1
- package/esm/context/callback-query.js.map +1 -1
- package/esm/context/chat-join-request.d.ts +1 -1
- package/esm/context/chat-join-request.js +1 -1
- package/esm/context/chat-join-request.js.map +1 -1
- package/esm/context/chosen-inline-result.d.ts +1 -1
- package/esm/context/chosen-inline-result.js +1 -1
- package/esm/context/chosen-inline-result.js.map +1 -1
- package/esm/context/inline-query.d.ts +1 -1
- package/esm/context/inline-query.js +1 -1
- package/esm/context/inline-query.js.map +1 -1
- package/esm/context/message.d.ts +6 -6
- package/esm/context/message.js +1 -1
- package/esm/context/message.js.map +1 -1
- package/esm/context/parse.js.map +1 -1
- package/esm/context/pre-checkout-query.d.ts +1 -1
- package/esm/context/pre-checkout-query.js +1 -1
- package/esm/context/pre-checkout-query.js.map +1 -1
- package/esm/dispatcher.d.ts +14 -9
- package/esm/dispatcher.js +29 -66
- package/esm/dispatcher.js.map +1 -1
- package/esm/filters/bots.d.ts +6 -6
- package/esm/filters/bots.js +2 -2
- package/esm/filters/bots.js.map +1 -1
- package/esm/filters/bots.test.js +4 -3
- package/esm/filters/bots.test.js.map +1 -1
- package/esm/filters/chat.d.ts +2 -2
- package/esm/filters/chat.js +1 -1
- package/esm/filters/chat.js.map +1 -1
- package/esm/filters/group.d.ts +1 -1
- package/esm/filters/group.js.map +1 -1
- package/esm/filters/logic.js.map +1 -1
- package/esm/filters/message.d.ts +77 -69
- package/esm/filters/message.js +1 -1
- package/esm/filters/message.js.map +1 -1
- package/esm/filters/state.d.ts +2 -2
- package/esm/filters/state.js.map +1 -1
- package/esm/filters/text.d.ts +1 -1
- package/esm/filters/text.js.map +1 -1
- package/esm/filters/types.d.ts +2 -2
- package/esm/filters/types.js.map +1 -1
- package/esm/filters/updates.d.ts +1 -1
- package/esm/filters/updates.js.map +1 -1
- package/esm/filters/user.d.ts +1 -1
- package/esm/filters/user.js +3 -3
- package/esm/filters/user.js.map +1 -1
- package/esm/handler.d.ts +3 -3
- package/esm/handler.js.map +1 -1
- package/esm/propagation.js +1 -1
- package/esm/propagation.js.map +1 -1
- package/esm/state/index.d.ts +3 -1
- package/esm/state/index.js +3 -1
- package/esm/state/index.js.map +1 -1
- package/esm/state/key.d.ts +2 -2
- package/esm/state/key.js +1 -1
- package/esm/state/key.js.map +1 -1
- package/esm/state/provider.d.ts +5 -0
- package/esm/state/provider.js +2 -0
- package/esm/state/provider.js.map +1 -0
- package/esm/state/providers/index.d.ts +2 -0
- package/esm/state/providers/index.js +3 -0
- package/esm/state/providers/index.js.map +1 -0
- package/esm/state/providers/memory.d.ts +29 -0
- package/esm/state/providers/memory.js +72 -0
- package/esm/state/providers/memory.js.map +1 -0
- package/esm/state/providers/sqlite.d.ts +29 -0
- package/esm/state/providers/sqlite.js +85 -0
- package/esm/state/providers/sqlite.js.map +1 -0
- package/esm/state/repository.d.ts +62 -0
- package/esm/state/repository.js +2 -0
- package/esm/state/repository.js.map +1 -0
- package/esm/state/service.d.ts +19 -0
- package/esm/state/service.js +64 -0
- package/esm/state/service.js.map +1 -0
- package/esm/state/update-state.d.ts +3 -3
- package/esm/state/update-state.js +2 -2
- package/esm/state/update-state.js.map +1 -1
- package/esm/wizard.d.ts +2 -2
- package/esm/wizard.js +1 -1
- package/esm/wizard.js.map +1 -1
- package/package.json +10 -3
- package/cjs/state/storage.d.ts +0 -96
- package/cjs/state/storage.js +0 -17
- package/cjs/state/storage.js.map +0 -1
- package/esm/state/storage.d.ts +0 -96
- package/esm/state/storage.js +0 -13
- package/esm/state/storage.js.map +0 -1
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { asyncResettable, LruMap } from '@mtcute/core/utils.js';
|
|
2
|
+
const makeCurrentSceneKey = (key) => `$current_scene_${key}`;
|
|
3
|
+
export class StateService {
|
|
4
|
+
constructor(provider) {
|
|
5
|
+
this.provider = provider;
|
|
6
|
+
this._cache = new LruMap(100);
|
|
7
|
+
this._loaded = false;
|
|
8
|
+
this._load = asyncResettable(async () => {
|
|
9
|
+
await this.provider.driver.load?.();
|
|
10
|
+
this._loaded = true;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
async load() {
|
|
14
|
+
await this._load.run();
|
|
15
|
+
this._vacuumTimer = setInterval(() => {
|
|
16
|
+
Promise.resolve(this.provider.state.vacuum(Date.now())).catch(() => { });
|
|
17
|
+
}, 300000);
|
|
18
|
+
}
|
|
19
|
+
async destroy() {
|
|
20
|
+
await this.provider.driver.save?.();
|
|
21
|
+
await this.provider.driver.destroy?.();
|
|
22
|
+
clearInterval(this._vacuumTimer);
|
|
23
|
+
this._loaded = false;
|
|
24
|
+
}
|
|
25
|
+
async getState(key) {
|
|
26
|
+
if (!this._loaded)
|
|
27
|
+
await this.load();
|
|
28
|
+
const cached = this._cache.get(key);
|
|
29
|
+
if (cached)
|
|
30
|
+
return cached;
|
|
31
|
+
const state = await this.provider.state.getState(key, Date.now());
|
|
32
|
+
if (!state)
|
|
33
|
+
return null;
|
|
34
|
+
return JSON.parse(state);
|
|
35
|
+
}
|
|
36
|
+
async setState(key, state, ttl) {
|
|
37
|
+
if (!this._loaded)
|
|
38
|
+
await this.load();
|
|
39
|
+
this._cache.set(key, state);
|
|
40
|
+
await this.provider.state.setState(key, JSON.stringify(state), ttl);
|
|
41
|
+
}
|
|
42
|
+
async deleteState(key) {
|
|
43
|
+
if (!this._loaded)
|
|
44
|
+
await this.load();
|
|
45
|
+
this._cache.delete(key);
|
|
46
|
+
await this.provider.state.deleteState(key);
|
|
47
|
+
}
|
|
48
|
+
getCurrentScene(key) {
|
|
49
|
+
return this.getState(makeCurrentSceneKey(key));
|
|
50
|
+
}
|
|
51
|
+
setCurrentScene(key, scene, ttl) {
|
|
52
|
+
return this.setState(makeCurrentSceneKey(key), scene, ttl);
|
|
53
|
+
}
|
|
54
|
+
deleteCurrentScene(key) {
|
|
55
|
+
return this.deleteState(makeCurrentSceneKey(key));
|
|
56
|
+
}
|
|
57
|
+
getRateLimit(key, limit, window) {
|
|
58
|
+
return this.provider.state.getRateLimit(key, Date.now(), limit, window);
|
|
59
|
+
}
|
|
60
|
+
resetRateLimit(key) {
|
|
61
|
+
return this.provider.state.resetRateLimit(key);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/state/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAI/D,MAAM,mBAAmB,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,kBAAkB,GAAG,EAAE,CAAA;AAEpE,MAAM,OAAO,YAAY;IACrB,YAAqB,QAA+B;QAA/B,aAAQ,GAAR,QAAQ,CAAuB;QAE5C,WAAM,GAA4B,IAAI,MAAM,CAAC,GAAG,CAAC,CAAA;QAGjD,YAAO,GAAG,KAAK,CAAA;QACf,UAAK,GAAG,eAAe,CAAC,KAAK,IAAI,EAAE;YACvC,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAA;YACnC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;QACvB,CAAC,CAAC,CAAA;IATqD,CAAC;IAUxD,KAAK,CAAC,IAAI;QACN,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAA;QACtB,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE;YACjC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAA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C,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,CAAC,IAAI,EAAE,CAAA;QAEpC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QACvB,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IAC9C,CAAC;IAED,eAAe,CAAC,GAAW;QACvB,OAAO,IAAI,CAAC,QAAQ,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,CAAA;IAClD,CAAC;IAED,eAAe,CAAC,GAAW,EAAE,KAAa,EAAE,GAAY;QACpD,OAAO,IAAI,CAAC,QAAQ,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAA;IAC9D,CAAC;IAED,kBAAkB,CAAC,GAAW;QAC1B,OAAO,IAAI,CAAC,WAAW,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,CAAA;IACrD,CAAC;IAED,YAAY,CAAC,GAAW,EAAE,KAAa,EAAE,MAAc;QACnD,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;IAC3E,CAAC;IAED,cAAc,CAAC,GAAW;QACtB,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAA;IAClD,CAAC;CACJ","sourcesContent":["import { asyncResettable, LruMap } from '@mtcute/core/utils.js'\n\nimport { IStateStorageProvider } from './provider.js'\n\nconst makeCurrentSceneKey = (key: string) => `$current_scene_${key}`\n\nexport class StateService {\n constructor(readonly provider: IStateStorageProvider) {}\n\n private _cache: LruMap<string, unknown> = new LruMap(100)\n private _vacuumTimer?: NodeJS.Timeout\n\n private _loaded = false\n private _load = asyncResettable(async () => {\n await this.provider.driver.load?.()\n this._loaded = true\n })\n async load() {\n await this._load.run()\n this._vacuumTimer = setInterval(() => {\n Promise.resolve(this.provider.state.vacuum(Date.now())).catch(() => {})\n }, 300_000)\n }\n\n async destroy() {\n await this.provider.driver.save?.()\n await this.provider.driver.destroy?.()\n clearInterval(this._vacuumTimer)\n this._loaded = false\n }\n\n async getState<T>(key: string): Promise<T | null> {\n if (!this._loaded) await this.load()\n\n const cached = this._cache.get(key)\n if (cached) return cached as T\n\n const state = await this.provider.state.getState(key, Date.now())\n if (!state) return null\n\n return JSON.parse(state) as T\n }\n\n async setState<T>(key: string, state: T, ttl?: number): Promise<void> {\n if (!this._loaded) await this.load()\n\n this._cache.set(key, state)\n await this.provider.state.setState(key, JSON.stringify(state), ttl)\n }\n\n async deleteState(key: string): Promise<void> {\n if (!this._loaded) await this.load()\n\n this._cache.delete(key)\n await this.provider.state.deleteState(key)\n }\n\n getCurrentScene(key: string): Promise<string | null> {\n return this.getState(makeCurrentSceneKey(key))\n }\n\n setCurrentScene(key: string, scene: string, ttl?: number): Promise<void> {\n return this.setState(makeCurrentSceneKey(key), scene, ttl)\n }\n\n deleteCurrentScene(key: string): Promise<void> {\n return this.deleteState(makeCurrentSceneKey(key))\n }\n\n getRateLimit(key: string, limit: number, window: number) {\n return this.provider.state.getRateLimit(key, Date.now(), limit, window)\n }\n\n resetRateLimit(key: string) {\n return this.provider.state.resetRateLimit(key)\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { MtcuteError } from '@mtcute/
|
|
1
|
+
import { MtcuteError } from '@mtcute/core';
|
|
2
2
|
import type { Dispatcher } from '../dispatcher.js';
|
|
3
|
-
import {
|
|
3
|
+
import { StateService } from './service.js';
|
|
4
4
|
/**
|
|
5
5
|
* Error thrown by `.rateLimit()`
|
|
6
6
|
*/
|
|
@@ -23,7 +23,7 @@ export declare class UpdateState<State extends object> {
|
|
|
23
23
|
private _cached?;
|
|
24
24
|
private _localStorage;
|
|
25
25
|
private _localKeyBase;
|
|
26
|
-
constructor(storage:
|
|
26
|
+
constructor(storage: StateService, key: string, scene: string | null, scoped?: boolean, customStorage?: StateService, customKey?: string);
|
|
27
27
|
/** Name of the current scene */
|
|
28
28
|
get scene(): string | null;
|
|
29
29
|
private _updateLocalKey;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/* eslint-disable dot-notation */
|
|
2
2
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
3
|
-
import { MtArgumentError, MtcuteError } from '@mtcute/
|
|
4
|
-
import { sleep } from '@mtcute/
|
|
3
|
+
import { MtArgumentError, MtcuteError } from '@mtcute/core';
|
|
4
|
+
import { sleep } from '@mtcute/core/utils.js';
|
|
5
5
|
/**
|
|
6
6
|
* Error thrown by `.rateLimit()`
|
|
7
7
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update-state.js","sourceRoot":"","sources":["../../../src/state/update-state.ts"],"names":[],"mappings":"AAAA,iCAAiC;AACjC,uDAAuD;AACvD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAA;AAK/C;;GAEG;AACH,MAAM,OAAO,cAAe,SAAQ,WAAW;IAC3C,YAAqB,KAAa;QAC9B,KAAK,CAAC,6BAA6B,CAAC,CAAA;QADnB,UAAK,GAAL,KAAK,CAAQ;IAElC,CAAC;CACJ;AAED;;;;;GAKG;AACH,MAAM,OAAO,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,SAAS,IA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AAC,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,KAAK,CAAC,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","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"]}
|
|
1
|
+
{"version":3,"file":"update-state.js","sourceRoot":"","sources":["../../../src/state/update-state.ts"],"names":[],"mappings":"AAAA,iCAAiC;AACjC,uDAAuD;AACvD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAA;AAK7C;;GAEG;AACH,MAAM,OAAO,cAAe,SAAQ,WAAW;IAC3C,YAAqB,KAAa;QAC9B,KAAK,CAAC,6BAA6B,CAAC,CAAA;QADnB,UAAK,GAAL,KAAK,CAAQ;IAElC,CAAC;CACJ;AAED;;;;;GAKG;AACH,MAAM,OAAO,WAAW;IAapB,YACI,OAAqB,EACrB,GAAW,EACX,KAAoB,EACpB,MAAgB,EAChB,aAA4B,EAC5B,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,SAAS,IAAI,GAAG,CAAA;QAErC,IAAI,CAAC,eAAe,EAAE,CAAA;IAC1B,CAAC;IAED,gCAAgC;IAChC,IAAI,KAAK;QACL,OAAO,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;IAEO,eAAe;QACnB,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,aAAa,CAAA;aACjD;YACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAA;SAC7F;IACL,CAAC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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,KAAK,CAAC,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","sourcesContent":["/* eslint-disable dot-notation */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { MtArgumentError, MtcuteError } from '@mtcute/core'\nimport { sleep } from '@mtcute/core/utils.js'\n\nimport type { Dispatcher } from '../dispatcher.js'\nimport { StateService } from './service.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: StateService\n\n private _scene: string | null\n private _scoped?: boolean\n private _cached?: State | null\n\n private _localStorage: StateService\n private _localKeyBase: string\n\n constructor(\n storage: StateService,\n key: string,\n scene: string | null,\n scoped?: boolean,\n customStorage?: StateService,\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"]}
|
package/esm/wizard.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { MaybePromise } from '@mtcute/core';
|
|
2
2
|
import { MessageContext } from './context/message.js';
|
|
3
3
|
import { Dispatcher } from './dispatcher.js';
|
|
4
4
|
import { filters } from './filters/index.js';
|
|
@@ -55,6 +55,6 @@ export declare class WizardScene<State extends object> extends Dispatcher<State
|
|
|
55
55
|
/**
|
|
56
56
|
* Add a step to the wizard
|
|
57
57
|
*/
|
|
58
|
-
addStep(handler: (msg: MessageContext, state: UpdateState<State & WizardInternalState>) =>
|
|
58
|
+
addStep(handler: (msg: MessageContext, state: UpdateState<State & WizardInternalState>) => MaybePromise<WizardSceneAction | number>): void;
|
|
59
59
|
}
|
|
60
60
|
export {};
|
package/esm/wizard.js
CHANGED
|
@@ -17,7 +17,7 @@ export var WizardSceneAction;
|
|
|
17
17
|
WizardSceneAction["Next"] = "next";
|
|
18
18
|
WizardSceneAction["Stay"] = "stay";
|
|
19
19
|
WizardSceneAction["Exit"] = "exit";
|
|
20
|
-
})(WizardSceneAction
|
|
20
|
+
})(WizardSceneAction || (WizardSceneAction = {}));
|
|
21
21
|
/**
|
|
22
22
|
* Wizard is a special type of Dispatcher
|
|
23
23
|
* that can be used to simplify implementing
|
package/esm/wizard.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wizard.js","sourceRoot":"","sources":["../../src/wizard.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAG5C;;;;;;;;;;;GAWG;AACH,MAAM,CAAN,IAAY,iBAIX;AAJD,WAAY,iBAAiB;IACzB,kCAAa,CAAA;IACb,kCAAa,CAAA;IACb,kCAAa,CAAA;AACjB,CAAC,EAJW,iBAAiB,
|
|
1
|
+
{"version":3,"file":"wizard.js","sourceRoot":"","sources":["../../src/wizard.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAG5C;;;;;;;;;;;GAWG;AACH,MAAM,CAAN,IAAY,iBAIX;AAJD,WAAY,iBAAiB;IACzB,kCAAa,CAAA;IACb,kCAAa,CAAA;IACb,kCAAa,CAAA;AACjB,CAAC,EAJW,iBAAiB,KAAjB,iBAAiB,QAI5B;AAMD;;;;GAIG;AACH,MAAM,OAAO,WAAkC,SAAQ,UAAuC;IAA9F;;QACY,WAAM,GAAG,CAAC,CAAA;QAEV,kBAAa,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AC;IAED;;OAEG;IACH,OAAO,CACH,OAG6C;QAE7C,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,EAAE,CAAA;QAE1B,IAAI,CAAC,YAAY,CAAC,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE;YAChE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;YAExC,IAAI,OAAO,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","sourcesContent":["import { MaybePromise } from '@mtcute/core'\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 ) => MaybePromise<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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mtcute/dispatcher",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Updates dispatcher and bot framework for @mtcute/client",
|
|
5
5
|
"author": "Alina Sireneva <alina@tei.su>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -8,10 +8,17 @@
|
|
|
8
8
|
"type": "module",
|
|
9
9
|
"scripts": {},
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@mtcute/
|
|
12
|
-
"@mtcute/test": "^0.6.0",
|
|
11
|
+
"@mtcute/core": "^0.7.0",
|
|
13
12
|
"events": "3.2.0"
|
|
14
13
|
},
|
|
14
|
+
"peerDependencies": {
|
|
15
|
+
"@mtcute/sqlite": "^0.7.0"
|
|
16
|
+
},
|
|
17
|
+
"peerDependenciesMeta": {
|
|
18
|
+
"@mtcute/sqlite": {
|
|
19
|
+
"optional": true
|
|
20
|
+
}
|
|
21
|
+
},
|
|
15
22
|
"module": "esm/index.js",
|
|
16
23
|
"exports": {
|
|
17
24
|
".": {
|
package/cjs/state/storage.d.ts
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { MaybeAsync } from '@mtcute/client';
|
|
2
|
-
/**
|
|
3
|
-
* Interface for FSM storage for the dispatcher.
|
|
4
|
-
*
|
|
5
|
-
* All of the officially supported storages already implement
|
|
6
|
-
* this interface, so you can just re-use it.
|
|
7
|
-
*
|
|
8
|
-
* Current scene is a special case of a `string` state,
|
|
9
|
-
* Most of the time you can just store it the same way
|
|
10
|
-
* as normal state, prefixing with something like `$current_state_`
|
|
11
|
-
* (scene name can't start with `$`).
|
|
12
|
-
* Alternatively, you can store them as simple strings
|
|
13
|
-
*/
|
|
14
|
-
export interface IStateStorage {
|
|
15
|
-
/**
|
|
16
|
-
* Load state from some external storage.
|
|
17
|
-
* Should be used either to load session content from file/network/etc
|
|
18
|
-
* to memory, or to open required connections to fetch session content later
|
|
19
|
-
*
|
|
20
|
-
* This method may be called multiple times and should handle that.
|
|
21
|
-
*/
|
|
22
|
-
load?(): MaybeAsync<void>;
|
|
23
|
-
/**
|
|
24
|
-
* Save state to some external storage.
|
|
25
|
-
* Should be used to commit pending changes in the session.
|
|
26
|
-
* For example, saving session content to file/network/etc,
|
|
27
|
-
* or committing a database transaction
|
|
28
|
-
*/
|
|
29
|
-
save?(): MaybeAsync<void>;
|
|
30
|
-
/**
|
|
31
|
-
* Cleanup storage and release all used resources.
|
|
32
|
-
*
|
|
33
|
-
* This method may be called multiple times and should handle that.
|
|
34
|
-
*/
|
|
35
|
-
destroy?(): MaybeAsync<void>;
|
|
36
|
-
/**
|
|
37
|
-
* Retrieve state from the storage
|
|
38
|
-
*
|
|
39
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
40
|
-
*/
|
|
41
|
-
getState(key: string): MaybeAsync<unknown>;
|
|
42
|
-
/**
|
|
43
|
-
* Save state to the storage
|
|
44
|
-
*
|
|
45
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
46
|
-
* @param state Object representing the state
|
|
47
|
-
* @param ttl TTL for the state, in seconds
|
|
48
|
-
*/
|
|
49
|
-
setState(key: string, state: unknown, ttl?: number): MaybeAsync<void>;
|
|
50
|
-
/**
|
|
51
|
-
* Delete state from the storage
|
|
52
|
-
*
|
|
53
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
54
|
-
*/
|
|
55
|
-
deleteState(key: string): MaybeAsync<void>;
|
|
56
|
-
/**
|
|
57
|
-
* Retrieve the current scene UID from the storage
|
|
58
|
-
*
|
|
59
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
60
|
-
*/
|
|
61
|
-
getCurrentScene(key: string): MaybeAsync<string | null>;
|
|
62
|
-
/**
|
|
63
|
-
* Change current scene's UID from the storage
|
|
64
|
-
*
|
|
65
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
66
|
-
* @param scene New scene
|
|
67
|
-
* @param ttl TTL for the scene, in seconds
|
|
68
|
-
*/
|
|
69
|
-
setCurrentScene(key: string, scene: string, ttl?: number): MaybeAsync<void>;
|
|
70
|
-
/**
|
|
71
|
-
* Delete current scene from the storage, effectively "exiting" to root.
|
|
72
|
-
*
|
|
73
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
74
|
-
*/
|
|
75
|
-
deleteCurrentScene(key: string): MaybeAsync<void>;
|
|
76
|
-
/**
|
|
77
|
-
* Get information about a rate limit.
|
|
78
|
-
*
|
|
79
|
-
* It is recommended that you use sliding window or leaky bucket
|
|
80
|
-
* to implement rate limiting ([learn more](https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm/)),
|
|
81
|
-
*
|
|
82
|
-
* @param key Key of the rate limit
|
|
83
|
-
* @param limit Maximum number of requests in `window`
|
|
84
|
-
* @param window Window size in seconds
|
|
85
|
-
* @returns Tuple containing the number of remaining and
|
|
86
|
-
* unix time in ms when the user can try again
|
|
87
|
-
*/
|
|
88
|
-
getRateLimit(key: string, limit: number, window: number): MaybeAsync<[number, number]>;
|
|
89
|
-
/**
|
|
90
|
-
* Reset a rate limit.
|
|
91
|
-
*
|
|
92
|
-
* @param key Key of the rate limit
|
|
93
|
-
*/
|
|
94
|
-
resetRateLimit(key: string): MaybeAsync<void>;
|
|
95
|
-
}
|
|
96
|
-
export declare function isCompatibleStorage(storage: unknown): storage is IStateStorage;
|
package/cjs/state/storage.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isCompatibleStorage = void 0;
|
|
4
|
-
function isCompatibleStorage(storage) {
|
|
5
|
-
return (typeof storage === 'object' &&
|
|
6
|
-
storage !== null &&
|
|
7
|
-
'getState' in storage &&
|
|
8
|
-
'setState' in storage &&
|
|
9
|
-
'deleteState' in storage &&
|
|
10
|
-
'getCurrentScene' in storage &&
|
|
11
|
-
'setCurrentScene' in storage &&
|
|
12
|
-
'deleteCurrentScene' in storage &&
|
|
13
|
-
'getRateLimit' in storage &&
|
|
14
|
-
'resetRateLimit' in storage);
|
|
15
|
-
}
|
|
16
|
-
exports.isCompatibleStorage = isCompatibleStorage;
|
|
17
|
-
//# sourceMappingURL=storage.js.map
|
package/cjs/state/storage.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../src/state/storage.ts"],"names":[],"mappings":";;;AA4GA,SAAgB,mBAAmB,CAAC,OAAgB;IAChD,OAAO,CACH,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,KAAK,IAAI;QAChB,UAAU,IAAI,OAAO;QACrB,UAAU,IAAI,OAAO;QACrB,aAAa,IAAI,OAAO;QACxB,iBAAiB,IAAI,OAAO;QAC5B,iBAAiB,IAAI,OAAO;QAC5B,oBAAoB,IAAI,OAAO;QAC/B,cAAc,IAAI,OAAO;QACzB,gBAAgB,IAAI,OAAO,CAC9B,CAAA;AACL,CAAC;AAbD,kDAaC","sourcesContent":["import { MaybeAsync } from '@mtcute/client'\n\n// ⚠️ Important: when modifying the below interface, also update it\n// in packages/core/src/storage/storage.test-utils.ts\n\n/**\n * Interface for FSM storage for the dispatcher.\n *\n * All of the officially supported storages already implement\n * this interface, so you can just re-use it.\n *\n * Current scene is a special case of a `string` state,\n * Most of the time you can just store it the same way\n * as normal state, prefixing with something like `$current_state_`\n * (scene name can't start with `$`).\n * Alternatively, you can store them as simple strings\n */\nexport interface IStateStorage {\n /**\n * Load state from some external storage.\n * Should be used either to load session content from file/network/etc\n * to memory, or to open required connections to fetch session content later\n *\n * This method may be called multiple times and should handle that.\n */\n load?(): MaybeAsync<void>\n /**\n * Save state to some external storage.\n * Should be used to commit pending changes in the session.\n * For example, saving session content to file/network/etc,\n * or committing a database transaction\n */\n save?(): MaybeAsync<void>\n /**\n * Cleanup storage and release all used resources.\n *\n * This method may be called multiple times and should handle that.\n */\n destroy?(): MaybeAsync<void>\n\n /**\n * Retrieve state from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n getState(key: string): MaybeAsync<unknown>\n\n /**\n * Save state to the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n * @param state Object representing the state\n * @param ttl TTL for the state, in seconds\n */\n setState(key: string, state: unknown, ttl?: number): MaybeAsync<void>\n\n /**\n * Delete state from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n deleteState(key: string): MaybeAsync<void>\n\n /**\n * Retrieve the current scene UID from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n getCurrentScene(key: string): MaybeAsync<string | null>\n\n /**\n * Change current scene's UID from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n * @param scene New scene\n * @param ttl TTL for the scene, in seconds\n */\n setCurrentScene(key: string, scene: string, ttl?: number): MaybeAsync<void>\n\n /**\n * Delete current scene from the storage, effectively \"exiting\" to root.\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n deleteCurrentScene(key: string): MaybeAsync<void>\n\n /**\n * Get information about a rate limit.\n *\n * It is recommended that you use sliding window or leaky bucket\n * to implement rate limiting ([learn more](https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm/)),\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 getRateLimit(key: string, limit: number, window: number): MaybeAsync<[number, number]>\n\n /**\n * Reset a rate limit.\n *\n * @param key Key of the rate limit\n */\n resetRateLimit(key: string): MaybeAsync<void>\n}\n\nexport function isCompatibleStorage(storage: unknown): storage is IStateStorage {\n return (\n typeof storage === 'object' &&\n storage !== null &&\n 'getState' in storage &&\n 'setState' in storage &&\n 'deleteState' in storage &&\n 'getCurrentScene' in storage &&\n 'setCurrentScene' in storage &&\n 'deleteCurrentScene' in storage &&\n 'getRateLimit' in storage &&\n 'resetRateLimit' in storage\n )\n}\n"]}
|
package/esm/state/storage.d.ts
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { MaybeAsync } from '@mtcute/client';
|
|
2
|
-
/**
|
|
3
|
-
* Interface for FSM storage for the dispatcher.
|
|
4
|
-
*
|
|
5
|
-
* All of the officially supported storages already implement
|
|
6
|
-
* this interface, so you can just re-use it.
|
|
7
|
-
*
|
|
8
|
-
* Current scene is a special case of a `string` state,
|
|
9
|
-
* Most of the time you can just store it the same way
|
|
10
|
-
* as normal state, prefixing with something like `$current_state_`
|
|
11
|
-
* (scene name can't start with `$`).
|
|
12
|
-
* Alternatively, you can store them as simple strings
|
|
13
|
-
*/
|
|
14
|
-
export interface IStateStorage {
|
|
15
|
-
/**
|
|
16
|
-
* Load state from some external storage.
|
|
17
|
-
* Should be used either to load session content from file/network/etc
|
|
18
|
-
* to memory, or to open required connections to fetch session content later
|
|
19
|
-
*
|
|
20
|
-
* This method may be called multiple times and should handle that.
|
|
21
|
-
*/
|
|
22
|
-
load?(): MaybeAsync<void>;
|
|
23
|
-
/**
|
|
24
|
-
* Save state to some external storage.
|
|
25
|
-
* Should be used to commit pending changes in the session.
|
|
26
|
-
* For example, saving session content to file/network/etc,
|
|
27
|
-
* or committing a database transaction
|
|
28
|
-
*/
|
|
29
|
-
save?(): MaybeAsync<void>;
|
|
30
|
-
/**
|
|
31
|
-
* Cleanup storage and release all used resources.
|
|
32
|
-
*
|
|
33
|
-
* This method may be called multiple times and should handle that.
|
|
34
|
-
*/
|
|
35
|
-
destroy?(): MaybeAsync<void>;
|
|
36
|
-
/**
|
|
37
|
-
* Retrieve state from the storage
|
|
38
|
-
*
|
|
39
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
40
|
-
*/
|
|
41
|
-
getState(key: string): MaybeAsync<unknown>;
|
|
42
|
-
/**
|
|
43
|
-
* Save state to the storage
|
|
44
|
-
*
|
|
45
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
46
|
-
* @param state Object representing the state
|
|
47
|
-
* @param ttl TTL for the state, in seconds
|
|
48
|
-
*/
|
|
49
|
-
setState(key: string, state: unknown, ttl?: number): MaybeAsync<void>;
|
|
50
|
-
/**
|
|
51
|
-
* Delete state from the storage
|
|
52
|
-
*
|
|
53
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
54
|
-
*/
|
|
55
|
-
deleteState(key: string): MaybeAsync<void>;
|
|
56
|
-
/**
|
|
57
|
-
* Retrieve the current scene UID from the storage
|
|
58
|
-
*
|
|
59
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
60
|
-
*/
|
|
61
|
-
getCurrentScene(key: string): MaybeAsync<string | null>;
|
|
62
|
-
/**
|
|
63
|
-
* Change current scene's UID from the storage
|
|
64
|
-
*
|
|
65
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
66
|
-
* @param scene New scene
|
|
67
|
-
* @param ttl TTL for the scene, in seconds
|
|
68
|
-
*/
|
|
69
|
-
setCurrentScene(key: string, scene: string, ttl?: number): MaybeAsync<void>;
|
|
70
|
-
/**
|
|
71
|
-
* Delete current scene from the storage, effectively "exiting" to root.
|
|
72
|
-
*
|
|
73
|
-
* @param key Key of the state, as defined by {@link StateKeyDelegate}
|
|
74
|
-
*/
|
|
75
|
-
deleteCurrentScene(key: string): MaybeAsync<void>;
|
|
76
|
-
/**
|
|
77
|
-
* Get information about a rate limit.
|
|
78
|
-
*
|
|
79
|
-
* It is recommended that you use sliding window or leaky bucket
|
|
80
|
-
* to implement rate limiting ([learn more](https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm/)),
|
|
81
|
-
*
|
|
82
|
-
* @param key Key of the rate limit
|
|
83
|
-
* @param limit Maximum number of requests in `window`
|
|
84
|
-
* @param window Window size in seconds
|
|
85
|
-
* @returns Tuple containing the number of remaining and
|
|
86
|
-
* unix time in ms when the user can try again
|
|
87
|
-
*/
|
|
88
|
-
getRateLimit(key: string, limit: number, window: number): MaybeAsync<[number, number]>;
|
|
89
|
-
/**
|
|
90
|
-
* Reset a rate limit.
|
|
91
|
-
*
|
|
92
|
-
* @param key Key of the rate limit
|
|
93
|
-
*/
|
|
94
|
-
resetRateLimit(key: string): MaybeAsync<void>;
|
|
95
|
-
}
|
|
96
|
-
export declare function isCompatibleStorage(storage: unknown): storage is IStateStorage;
|
package/esm/state/storage.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export function isCompatibleStorage(storage) {
|
|
2
|
-
return (typeof storage === 'object' &&
|
|
3
|
-
storage !== null &&
|
|
4
|
-
'getState' in storage &&
|
|
5
|
-
'setState' in storage &&
|
|
6
|
-
'deleteState' in storage &&
|
|
7
|
-
'getCurrentScene' in storage &&
|
|
8
|
-
'setCurrentScene' in storage &&
|
|
9
|
-
'deleteCurrentScene' in storage &&
|
|
10
|
-
'getRateLimit' in storage &&
|
|
11
|
-
'resetRateLimit' in storage);
|
|
12
|
-
}
|
|
13
|
-
//# sourceMappingURL=storage.js.map
|
package/esm/state/storage.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../src/state/storage.ts"],"names":[],"mappings":"AA4GA,MAAM,UAAU,mBAAmB,CAAC,OAAgB;IAChD,OAAO,CACH,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,KAAK,IAAI;QAChB,UAAU,IAAI,OAAO;QACrB,UAAU,IAAI,OAAO;QACrB,aAAa,IAAI,OAAO;QACxB,iBAAiB,IAAI,OAAO;QAC5B,iBAAiB,IAAI,OAAO;QAC5B,oBAAoB,IAAI,OAAO;QAC/B,cAAc,IAAI,OAAO;QACzB,gBAAgB,IAAI,OAAO,CAC9B,CAAA;AACL,CAAC","sourcesContent":["import { MaybeAsync } from '@mtcute/client'\n\n// ⚠️ Important: when modifying the below interface, also update it\n// in packages/core/src/storage/storage.test-utils.ts\n\n/**\n * Interface for FSM storage for the dispatcher.\n *\n * All of the officially supported storages already implement\n * this interface, so you can just re-use it.\n *\n * Current scene is a special case of a `string` state,\n * Most of the time you can just store it the same way\n * as normal state, prefixing with something like `$current_state_`\n * (scene name can't start with `$`).\n * Alternatively, you can store them as simple strings\n */\nexport interface IStateStorage {\n /**\n * Load state from some external storage.\n * Should be used either to load session content from file/network/etc\n * to memory, or to open required connections to fetch session content later\n *\n * This method may be called multiple times and should handle that.\n */\n load?(): MaybeAsync<void>\n /**\n * Save state to some external storage.\n * Should be used to commit pending changes in the session.\n * For example, saving session content to file/network/etc,\n * or committing a database transaction\n */\n save?(): MaybeAsync<void>\n /**\n * Cleanup storage and release all used resources.\n *\n * This method may be called multiple times and should handle that.\n */\n destroy?(): MaybeAsync<void>\n\n /**\n * Retrieve state from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n getState(key: string): MaybeAsync<unknown>\n\n /**\n * Save state to the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n * @param state Object representing the state\n * @param ttl TTL for the state, in seconds\n */\n setState(key: string, state: unknown, ttl?: number): MaybeAsync<void>\n\n /**\n * Delete state from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n deleteState(key: string): MaybeAsync<void>\n\n /**\n * Retrieve the current scene UID from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n getCurrentScene(key: string): MaybeAsync<string | null>\n\n /**\n * Change current scene's UID from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n * @param scene New scene\n * @param ttl TTL for the scene, in seconds\n */\n setCurrentScene(key: string, scene: string, ttl?: number): MaybeAsync<void>\n\n /**\n * Delete current scene from the storage, effectively \"exiting\" to root.\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n deleteCurrentScene(key: string): MaybeAsync<void>\n\n /**\n * Get information about a rate limit.\n *\n * It is recommended that you use sliding window or leaky bucket\n * to implement rate limiting ([learn more](https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm/)),\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 getRateLimit(key: string, limit: number, window: number): MaybeAsync<[number, number]>\n\n /**\n * Reset a rate limit.\n *\n * @param key Key of the rate limit\n */\n resetRateLimit(key: string): MaybeAsync<void>\n}\n\nexport function isCompatibleStorage(storage: unknown): storage is IStateStorage {\n return (\n typeof storage === 'object' &&\n storage !== null &&\n 'getState' in storage &&\n 'setState' in storage &&\n 'deleteState' in storage &&\n 'getCurrentScene' in storage &&\n 'setCurrentScene' in storage &&\n 'deleteCurrentScene' in storage &&\n 'getRateLimit' in storage &&\n 'resetRateLimit' in storage\n )\n}\n"]}
|