1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.isSessionContext = exports.MemorySessionStore = exports.session = void 0;
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | function session(options) {
|
20 | var _a, _b;
|
21 | const getSessionKey = (_a = options === null || options === void 0 ? void 0 : options.getSessionKey) !== null && _a !== void 0 ? _a : defaultGetSessionKey;
|
22 | const store = (_b = options === null || options === void 0 ? void 0 : options.store) !== null && _b !== void 0 ? _b : new MemorySessionStore();
|
23 | return async (ctx, next) => {
|
24 | const key = await getSessionKey(ctx);
|
25 | if (key == null) {
|
26 | return await next();
|
27 | }
|
28 | ctx.session = await store.get(key);
|
29 | await next();
|
30 | if (ctx.session == null) {
|
31 | await store.delete(key);
|
32 | }
|
33 | else {
|
34 | await store.set(key, ctx.session);
|
35 | }
|
36 | };
|
37 | }
|
38 | exports.session = session;
|
39 | async function defaultGetSessionKey(ctx) {
|
40 | var _a, _b;
|
41 | const fromId = (_a = ctx.from) === null || _a === void 0 ? void 0 : _a.id;
|
42 | const chatId = (_b = ctx.chat) === null || _b === void 0 ? void 0 : _b.id;
|
43 | if (fromId == null || chatId == null) {
|
44 | return undefined;
|
45 | }
|
46 | return `${fromId}:${chatId}`;
|
47 | }
|
48 |
|
49 | class MemorySessionStore {
|
50 | constructor(ttl = Infinity) {
|
51 | this.ttl = ttl;
|
52 | this.store = new Map();
|
53 | }
|
54 | get(name) {
|
55 | const entry = this.store.get(name);
|
56 | if (entry == null) {
|
57 | return undefined;
|
58 | }
|
59 | else if (entry.expires < Date.now()) {
|
60 | this.delete(name);
|
61 | return undefined;
|
62 | }
|
63 | return entry.session;
|
64 | }
|
65 | set(name, value) {
|
66 | const now = Date.now();
|
67 | this.store.set(name, { session: value, expires: now + this.ttl });
|
68 | }
|
69 | delete(name) {
|
70 | this.store.delete(name);
|
71 | }
|
72 | }
|
73 | exports.MemorySessionStore = MemorySessionStore;
|
74 | function isSessionContext(ctx) {
|
75 | return 'session' in ctx;
|
76 | }
|
77 | exports.isSessionContext = isSessionContext;
|