@yaebal/scenes 0.0.1
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/LICENSE +21 -0
- package/README.md +13 -0
- package/lib/index.d.ts +49 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +87 -0
- package/lib/index.js.map +1 -0
- package/lib/index.test.d.ts +2 -0
- package/lib/index.test.d.ts.map +1 -0
- package/lib/index.test.js +112 -0
- package/lib/index.test.js.map +1 -0
- package/package.json +50 -0
- package/src/index.test.ts +142 -0
- package/src/index.ts +141 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 neverlane
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# @yaebal/scenes
|
|
2
|
+
|
|
3
|
+
context inside a scene: the base context plus the scene control.
|
|
4
|
+
|
|
5
|
+
## install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @yaebal/scenes
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
part of [**yaebal**](https://github.com/neverlane/yaebal) — a type-safe, runtime-agnostic Telegram Bot API framework. MIT.
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Context, Plugin } from "@yaebal/core";
|
|
2
|
+
import { type StorageAdapter } from "@yaebal/session";
|
|
3
|
+
/** context inside a scene: the base context plus the scene control. */
|
|
4
|
+
export type SceneContext = Context & {
|
|
5
|
+
scene: SceneControl;
|
|
6
|
+
};
|
|
7
|
+
/** a scene step. reads the user's input (`ctx.text`), then `next()` / `leave()`. */
|
|
8
|
+
export type Step = (ctx: SceneContext) => unknown | Promise<unknown>;
|
|
9
|
+
/** a scene: an optional entry hook (asks the first question) and ordered steps. */
|
|
10
|
+
export interface SceneDef {
|
|
11
|
+
enter?: Step;
|
|
12
|
+
steps: Step[];
|
|
13
|
+
}
|
|
14
|
+
export interface SceneControl {
|
|
15
|
+
/** enter a scene (runs its `enter` hook). */
|
|
16
|
+
enter(name: string): Promise<void>;
|
|
17
|
+
/** advance to the next step (the new step runs on the next message). */
|
|
18
|
+
next(): void;
|
|
19
|
+
/** leave the current scene. */
|
|
20
|
+
leave(): Promise<void>;
|
|
21
|
+
/** the active scene name, if any. */
|
|
22
|
+
readonly current: string | undefined;
|
|
23
|
+
/** the current step index. */
|
|
24
|
+
readonly step: number;
|
|
25
|
+
}
|
|
26
|
+
interface SceneState {
|
|
27
|
+
scene: string;
|
|
28
|
+
step: number;
|
|
29
|
+
}
|
|
30
|
+
export interface ScenesOptions {
|
|
31
|
+
/** where to persist scene state. defaults to in-memory. */
|
|
32
|
+
storage?: StorageAdapter<SceneState>;
|
|
33
|
+
/** scene key for an update. defaults to per-chat (`ctx.chat.id`). */
|
|
34
|
+
getKey?: (ctx: Context) => string | undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* scenes plugin: step-by-step wizards. each step handles one user message and
|
|
38
|
+
* asks the next question; `next()` advances, `leave()` exits. state lives per
|
|
39
|
+
* chat, so this is safe under the sequential update loop (no suspended promises).
|
|
40
|
+
*
|
|
41
|
+
* while in a scene every message is consumed and never reaches other handlers —
|
|
42
|
+
* so a `/cancel` won't fire its command unless a step checks for it
|
|
43
|
+
* (`if (ctx.text === "/cancel") return ctx.scene.leave()`).
|
|
44
|
+
*/
|
|
45
|
+
export declare function scenes(defs: Record<string, SceneDef>, options?: ScenesOptions): Plugin<Context, {
|
|
46
|
+
scene: SceneControl;
|
|
47
|
+
}>;
|
|
48
|
+
export {};
|
|
49
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAiB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAErE,uEAAuE;AACvE,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG;IAAE,KAAK,EAAE,YAAY,CAAA;CAAE,CAAC;AAE7D,oFAAoF;AACpF,MAAM,MAAM,IAAI,GAAG,CAAC,GAAG,EAAE,YAAY,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAErE,mFAAmF;AACnF,MAAM,WAAW,QAAQ;IACxB,KAAK,CAAC,EAAE,IAAI,CAAC;IACb,KAAK,EAAE,IAAI,EAAE,CAAC;CACd;AAED,MAAM,WAAW,YAAY;IAC5B,6CAA6C;IAC7C,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,wEAAwE;IACxE,IAAI,IAAI,IAAI,CAAC;IACb,+BAA+B;IAC/B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,qCAAqC;IACrC,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,8BAA8B;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACtB;AAED,UAAU,UAAU;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,aAAa;IAC7B,2DAA2D;IAC3D,OAAO,CAAC,EAAE,cAAc,CAAC,UAAU,CAAC,CAAC;IACrC,qEAAqE;IACrE,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC;CAC9C;AAED;;;;;;;;GAQG;AACH,wBAAgB,MAAM,CACrB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EAC9B,OAAO,GAAE,aAAkB,GACzB,MAAM,CAAC,OAAO,EAAE;IAAE,KAAK,EAAE,YAAY,CAAA;CAAE,CAAC,CAwF1C"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { MemoryStorage } from "@yaebal/session";
|
|
2
|
+
/**
|
|
3
|
+
* scenes plugin: step-by-step wizards. each step handles one user message and
|
|
4
|
+
* asks the next question; `next()` advances, `leave()` exits. state lives per
|
|
5
|
+
* chat, so this is safe under the sequential update loop (no suspended promises).
|
|
6
|
+
*
|
|
7
|
+
* while in a scene every message is consumed and never reaches other handlers —
|
|
8
|
+
* so a `/cancel` won't fire its command unless a step checks for it
|
|
9
|
+
* (`if (ctx.text === "/cancel") return ctx.scene.leave()`).
|
|
10
|
+
*/
|
|
11
|
+
export function scenes(defs, options = {}) {
|
|
12
|
+
const storage = options.storage ?? new MemoryStorage();
|
|
13
|
+
const getKey = options.getKey ?? ((ctx) => ctx.chat?.id?.toString());
|
|
14
|
+
// per-request consume step, shared from `derive` (which builds the control and
|
|
15
|
+
// owns the mutable state) to the routing `use` that runs after it.
|
|
16
|
+
const runners = new WeakMap();
|
|
17
|
+
const plugin = (composer) => composer
|
|
18
|
+
.derive(async (ctx) => {
|
|
19
|
+
const key = getKey(ctx);
|
|
20
|
+
let state = key !== undefined ? await storage.get(key) : undefined;
|
|
21
|
+
let advance = false;
|
|
22
|
+
let left = false;
|
|
23
|
+
const persist = async () => {
|
|
24
|
+
if (key === undefined)
|
|
25
|
+
return;
|
|
26
|
+
if (left || !state)
|
|
27
|
+
await storage.delete(key);
|
|
28
|
+
else
|
|
29
|
+
await storage.set(key, state);
|
|
30
|
+
};
|
|
31
|
+
const control = {
|
|
32
|
+
get current() {
|
|
33
|
+
return state?.scene;
|
|
34
|
+
},
|
|
35
|
+
get step() {
|
|
36
|
+
return state?.step ?? 0;
|
|
37
|
+
},
|
|
38
|
+
next() {
|
|
39
|
+
advance = true;
|
|
40
|
+
},
|
|
41
|
+
async enter(name) {
|
|
42
|
+
state = { scene: name, step: 0 };
|
|
43
|
+
advance = false;
|
|
44
|
+
left = false;
|
|
45
|
+
await defs[name]?.enter?.(ctx);
|
|
46
|
+
await persist();
|
|
47
|
+
},
|
|
48
|
+
async leave() {
|
|
49
|
+
left = true;
|
|
50
|
+
state = undefined;
|
|
51
|
+
await persist();
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
// in a scene with a message? run the current step instead of other handlers.
|
|
55
|
+
runners.set(ctx, async () => {
|
|
56
|
+
if (state && ctx.message) {
|
|
57
|
+
const def = defs[state.scene];
|
|
58
|
+
const step = def?.steps[state.step];
|
|
59
|
+
if (step) {
|
|
60
|
+
await step(ctx);
|
|
61
|
+
if (!left && state) {
|
|
62
|
+
if (advance)
|
|
63
|
+
state = { scene: state.scene, step: state.step + 1 };
|
|
64
|
+
// re-resolve from the current scene — a step may have switched it via enter()
|
|
65
|
+
const length = defs[state.scene]?.steps.length ?? 0;
|
|
66
|
+
if (state.step >= length) {
|
|
67
|
+
state = undefined;
|
|
68
|
+
left = true;
|
|
69
|
+
}
|
|
70
|
+
await persist();
|
|
71
|
+
}
|
|
72
|
+
return true; // consumed
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
});
|
|
77
|
+
return { scene: control };
|
|
78
|
+
})
|
|
79
|
+
.use(async (ctx, next) => {
|
|
80
|
+
const consumed = await runners.get(ctx)?.();
|
|
81
|
+
runners.delete(ctx);
|
|
82
|
+
if (!consumed)
|
|
83
|
+
await next();
|
|
84
|
+
});
|
|
85
|
+
return plugin;
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAuB,MAAM,iBAAiB,CAAC;AAuCrE;;;;;;;;GAQG;AACH,MAAM,UAAU,MAAM,CACrB,IAA8B,EAC9B,UAAyB,EAAE;IAE3B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,IAAI,aAAa,EAAc,CAAC;IACnE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,CAAC,CAAC,GAAY,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IAE9E,+EAA+E;IAC/E,mEAAmE;IACnE,MAAM,OAAO,GAAG,IAAI,OAAO,EAAmC,CAAC;IAE/D,MAAM,MAAM,GAA6C,CAAC,QAAQ,EAAE,EAAE,CACrE,QAAQ;SACN,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACrB,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAExB,IAAI,KAAK,GAAG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|
+
{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { Composer, Context } from "@yaebal/core";
|
|
4
|
+
import { MemoryStorage } from "@yaebal/session";
|
|
5
|
+
import { scenes } from "./index.js";
|
|
6
|
+
const noop = async () => { };
|
|
7
|
+
const entry = (c) => c.toMiddleware();
|
|
8
|
+
const api = {};
|
|
9
|
+
const msgCtx = (text, chatId) => new Context({
|
|
10
|
+
api,
|
|
11
|
+
update: {
|
|
12
|
+
update_id: 1,
|
|
13
|
+
message: {
|
|
14
|
+
message_id: 1,
|
|
15
|
+
date: 0,
|
|
16
|
+
chat: { id: chatId, type: "private" },
|
|
17
|
+
from: { id: chatId, is_bot: false, first_name: "u" },
|
|
18
|
+
text,
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
updateType: "message",
|
|
22
|
+
});
|
|
23
|
+
test("a wizard collects input across messages and leaves", async () => {
|
|
24
|
+
const collected = {};
|
|
25
|
+
const asked = [];
|
|
26
|
+
const defs = {
|
|
27
|
+
reg: {
|
|
28
|
+
enter: (ctx) => {
|
|
29
|
+
asked.push("name?");
|
|
30
|
+
},
|
|
31
|
+
steps: [
|
|
32
|
+
(ctx) => {
|
|
33
|
+
collected.name = ctx.text ?? "";
|
|
34
|
+
ctx.scene.next();
|
|
35
|
+
asked.push("age?");
|
|
36
|
+
},
|
|
37
|
+
(ctx) => {
|
|
38
|
+
collected.age = ctx.text ?? "";
|
|
39
|
+
return ctx.scene.leave();
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
const storage = new MemoryStorage();
|
|
45
|
+
let fellThrough = 0;
|
|
46
|
+
const mw = entry(new Composer()
|
|
47
|
+
.install(scenes(defs, { storage }))
|
|
48
|
+
.command("reg", (ctx) => ctx.scene.enter("reg"))
|
|
49
|
+
.on("message:text", () => {
|
|
50
|
+
fellThrough++;
|
|
51
|
+
}));
|
|
52
|
+
await mw(msgCtx("/reg", 1), noop); // enter → asks name
|
|
53
|
+
assert.deepEqual(asked, ["name?"]);
|
|
54
|
+
assert.deepEqual((await storage.get("1")) ?? null, { scene: "reg", step: 0 });
|
|
55
|
+
await mw(msgCtx("Alice", 1), noop); // step 0 → name, advance, asks age
|
|
56
|
+
assert.equal(collected.name, "Alice");
|
|
57
|
+
assert.deepEqual((await storage.get("1")) ?? null, { scene: "reg", step: 1 });
|
|
58
|
+
await mw(msgCtx("30", 1), noop); // step 1 → age, leave
|
|
59
|
+
assert.equal(collected.age, "30");
|
|
60
|
+
assert.equal(await storage.get("1"), undefined); // scene cleared
|
|
61
|
+
// scene messages were consumed — the fallthrough handler never saw them
|
|
62
|
+
assert.equal(fellThrough, 0);
|
|
63
|
+
});
|
|
64
|
+
test("messages outside a scene fall through to normal handlers", async () => {
|
|
65
|
+
let seen = "";
|
|
66
|
+
const mw = entry(new Composer().install(scenes({ reg: { steps: [] } })).on("message:text", (ctx) => {
|
|
67
|
+
seen = ctx.text;
|
|
68
|
+
}));
|
|
69
|
+
await mw(msgCtx("hello", 2), noop);
|
|
70
|
+
assert.equal(seen, "hello");
|
|
71
|
+
});
|
|
72
|
+
test("a step can switch scenes via enter()", async () => {
|
|
73
|
+
const defs = {
|
|
74
|
+
a: { steps: [(ctx) => ctx.scene.enter("b")] },
|
|
75
|
+
b: { steps: [(ctx) => ctx.scene.leave()] },
|
|
76
|
+
};
|
|
77
|
+
const storage = new MemoryStorage();
|
|
78
|
+
const mw = entry(new Composer()
|
|
79
|
+
.install(scenes(defs, { storage }))
|
|
80
|
+
.command("a", (ctx) => ctx.scene.enter("a")));
|
|
81
|
+
await mw(msgCtx("/a", 5), noop); // in scene a
|
|
82
|
+
await mw(msgCtx("go", 5), noop); // step a[0] → enter("b")
|
|
83
|
+
assert.deepEqual((await storage.get("5")) ?? null, { scene: "b", step: 0 });
|
|
84
|
+
await mw(msgCtx("done", 5), noop); // step b[0] → leave
|
|
85
|
+
assert.equal(await storage.get("5"), undefined);
|
|
86
|
+
});
|
|
87
|
+
test("a step that does not advance re-runs (validation)", async () => {
|
|
88
|
+
let attempts = 0;
|
|
89
|
+
const defs = {
|
|
90
|
+
ask: {
|
|
91
|
+
steps: [
|
|
92
|
+
(ctx) => {
|
|
93
|
+
attempts++;
|
|
94
|
+
if (ctx.text === "ok")
|
|
95
|
+
return ctx.scene.leave();
|
|
96
|
+
// invalid → stay on the same step
|
|
97
|
+
},
|
|
98
|
+
],
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
const storage = new MemoryStorage();
|
|
102
|
+
const mw = entry(new Composer()
|
|
103
|
+
.install(scenes(defs, { storage }))
|
|
104
|
+
.command("ask", (ctx) => ctx.scene.enter("ask")));
|
|
105
|
+
await mw(msgCtx("/ask", 3), noop);
|
|
106
|
+
await mw(msgCtx("nope", 3), noop); // stays
|
|
107
|
+
assert.deepEqual((await storage.get("3")) ?? null, { scene: "ask", step: 0 });
|
|
108
|
+
await mw(msgCtx("ok", 3), noop); // leaves
|
|
109
|
+
assert.equal(await storage.get("3"), undefined);
|
|
110
|
+
assert.equal(attempts, 2);
|
|
111
|
+
});
|
|
112
|
+
//# sourceMappingURL=index.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,oBAAoB,CAAC;AACxC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAmB,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAoC,MAAM,EAAE,MAAM,YAAY,CAAC;AAEtE,MAAM,IAAI,GAAG,KAAK,IAAI,EAAE,GAAE,CAAC,CAAC;AAC5B,M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ACf,IAAI,QAAQ,EAAW;SACrB,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;SAClC,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CACjD,CAAC;IAEF,MAAM,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,QAAQ;IAC3C,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAE9E,MAAM,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;IAC1C,MAAM,CAAC,KAAK,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,SAAS,CAAC,CAAC;IAChD,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;AAC3B,CAAC,CAAC,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@yaebal/scenes",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "yaebal scenes plugin — step-by-step wizards over multiple messages.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./lib/index.js",
|
|
7
|
+
"types": "./lib/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./lib/index.d.ts",
|
|
11
|
+
"import": "./lib/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"lib",
|
|
16
|
+
"src"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@yaebal/core": "0.0.1",
|
|
20
|
+
"@yaebal/session": "0.0.1"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "latest"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"telegram",
|
|
30
|
+
"telegram-bot",
|
|
31
|
+
"yaebal",
|
|
32
|
+
"scenes",
|
|
33
|
+
"wizard",
|
|
34
|
+
"fsm"
|
|
35
|
+
],
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "https://github.com/neverlane/yaebal",
|
|
40
|
+
"directory": "packages/scenes"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsc -p tsconfig.json",
|
|
47
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
48
|
+
"test": "node --test lib"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { Composer, Context, type Middleware } from "@yaebal/core";
|
|
4
|
+
import { MemoryStorage } from "@yaebal/session";
|
|
5
|
+
import { type SceneContext, type SceneDef, scenes } from "./index.js";
|
|
6
|
+
|
|
7
|
+
const noop = async () => {};
|
|
8
|
+
const entry = <C extends Context>(c: Composer<C>) =>
|
|
9
|
+
c.toMiddleware() as unknown as Middleware<Context>;
|
|
10
|
+
|
|
11
|
+
const api = {} as never;
|
|
12
|
+
const msgCtx = (text: string, chatId: number) =>
|
|
13
|
+
new Context({
|
|
14
|
+
api,
|
|
15
|
+
update: {
|
|
16
|
+
update_id: 1,
|
|
17
|
+
message: {
|
|
18
|
+
message_id: 1,
|
|
19
|
+
date: 0,
|
|
20
|
+
chat: { id: chatId, type: "private" },
|
|
21
|
+
from: { id: chatId, is_bot: false, first_name: "u" },
|
|
22
|
+
text,
|
|
23
|
+
},
|
|
24
|
+
} as never,
|
|
25
|
+
updateType: "message",
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("a wizard collects input across messages and leaves", async () => {
|
|
29
|
+
const collected: Record<string, string> = {};
|
|
30
|
+
const asked: string[] = [];
|
|
31
|
+
const defs: Record<string, SceneDef> = {
|
|
32
|
+
reg: {
|
|
33
|
+
enter: (ctx) => {
|
|
34
|
+
asked.push("name?");
|
|
35
|
+
},
|
|
36
|
+
steps: [
|
|
37
|
+
(ctx: SceneContext) => {
|
|
38
|
+
collected.name = ctx.text ?? "";
|
|
39
|
+
ctx.scene.next();
|
|
40
|
+
|
|
41
|
+
asked.push("age?");
|
|
42
|
+
},
|
|
43
|
+
(ctx: SceneContext) => {
|
|
44
|
+
collected.age = ctx.text ?? "";
|
|
45
|
+
|
|
46
|
+
return ctx.scene.leave();
|
|
47
|
+
},
|
|
48
|
+
],
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const storage = new MemoryStorage<{ scene: string; step: number }>();
|
|
53
|
+
let fellThrough = 0;
|
|
54
|
+
|
|
55
|
+
const mw = entry(
|
|
56
|
+
new Composer<Context>()
|
|
57
|
+
.install(scenes(defs, { storage }))
|
|
58
|
+
.command("reg", (ctx) => ctx.scene.enter("reg"))
|
|
59
|
+
.on("message:text", () => {
|
|
60
|
+
fellThrough++;
|
|
61
|
+
}),
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
await mw(msgCtx("/reg", 1), noop); // enter → asks name
|
|
65
|
+
assert.deepEqual(asked, ["name?"]);
|
|
66
|
+
assert.deepEqual((await storage.get("1")) ?? null, { scene: "reg", step: 0 });
|
|
67
|
+
|
|
68
|
+
await mw(msgCtx("Alice", 1), noop); // step 0 → name, advance, asks age
|
|
69
|
+
assert.equal(collected.name, "Alice");
|
|
70
|
+
assert.deepEqual((await storage.get("1")) ?? null, { scene: "reg", step: 1 });
|
|
71
|
+
|
|
72
|
+
await mw(msgCtx("30", 1), noop); // step 1 → age, leave
|
|
73
|
+
assert.equal(collected.age, "30");
|
|
74
|
+
assert.equal(await storage.get("1"), undefined); // scene cleared
|
|
75
|
+
|
|
76
|
+
// scene messages were consumed — the fallthrough handler never saw them
|
|
77
|
+
assert.equal(fellThrough, 0);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("messages outside a scene fall through to normal handlers", async () => {
|
|
81
|
+
let seen = "";
|
|
82
|
+
|
|
83
|
+
const mw = entry(
|
|
84
|
+
new Composer<Context>().install(scenes({ reg: { steps: [] } })).on("message:text", (ctx) => {
|
|
85
|
+
seen = ctx.text;
|
|
86
|
+
}),
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
await mw(msgCtx("hello", 2), noop);
|
|
90
|
+
assert.equal(seen, "hello");
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("a step can switch scenes via enter()", async () => {
|
|
94
|
+
const defs: Record<string, SceneDef> = {
|
|
95
|
+
a: { steps: [(ctx: SceneContext) => ctx.scene.enter("b")] },
|
|
96
|
+
b: { steps: [(ctx: SceneContext) => ctx.scene.leave()] },
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const storage = new MemoryStorage<{ scene: string; step: number }>();
|
|
100
|
+
const mw = entry(
|
|
101
|
+
new Composer<Context>()
|
|
102
|
+
.install(scenes(defs, { storage }))
|
|
103
|
+
.command("a", (ctx) => ctx.scene.enter("a")),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
await mw(msgCtx("/a", 5), noop); // in scene a
|
|
107
|
+
await mw(msgCtx("go", 5), noop); // step a[0] → enter("b")
|
|
108
|
+
assert.deepEqual((await storage.get("5")) ?? null, { scene: "b", step: 0 });
|
|
109
|
+
|
|
110
|
+
await mw(msgCtx("done", 5), noop); // step b[0] → leave
|
|
111
|
+
assert.equal(await storage.get("5"), undefined);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("a step that does not advance re-runs (validation)", async () => {
|
|
115
|
+
let attempts = 0;
|
|
116
|
+
const defs: Record<string, SceneDef> = {
|
|
117
|
+
ask: {
|
|
118
|
+
steps: [
|
|
119
|
+
(ctx: SceneContext) => {
|
|
120
|
+
attempts++;
|
|
121
|
+
if (ctx.text === "ok") return ctx.scene.leave();
|
|
122
|
+
// invalid → stay on the same step
|
|
123
|
+
},
|
|
124
|
+
],
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const storage = new MemoryStorage<{ scene: string; step: number }>();
|
|
129
|
+
const mw = entry(
|
|
130
|
+
new Composer<Context>()
|
|
131
|
+
.install(scenes(defs, { storage }))
|
|
132
|
+
.command("ask", (ctx) => ctx.scene.enter("ask")),
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
await mw(msgCtx("/ask", 3), noop);
|
|
136
|
+
await mw(msgCtx("nope", 3), noop); // stays
|
|
137
|
+
assert.deepEqual((await storage.get("3")) ?? null, { scene: "ask", step: 0 });
|
|
138
|
+
|
|
139
|
+
await mw(msgCtx("ok", 3), noop); // leaves
|
|
140
|
+
assert.equal(await storage.get("3"), undefined);
|
|
141
|
+
assert.equal(attempts, 2);
|
|
142
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { Context, Plugin } from "@yaebal/core";
|
|
2
|
+
import { MemoryStorage, type StorageAdapter } from "@yaebal/session";
|
|
3
|
+
|
|
4
|
+
/** context inside a scene: the base context plus the scene control. */
|
|
5
|
+
export type SceneContext = Context & { scene: SceneControl };
|
|
6
|
+
|
|
7
|
+
/** a scene step. reads the user's input (`ctx.text`), then `next()` / `leave()`. */
|
|
8
|
+
export type Step = (ctx: SceneContext) => unknown | Promise<unknown>;
|
|
9
|
+
|
|
10
|
+
/** a scene: an optional entry hook (asks the first question) and ordered steps. */
|
|
11
|
+
export interface SceneDef {
|
|
12
|
+
enter?: Step;
|
|
13
|
+
steps: Step[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface SceneControl {
|
|
17
|
+
/** enter a scene (runs its `enter` hook). */
|
|
18
|
+
enter(name: string): Promise<void>;
|
|
19
|
+
/** advance to the next step (the new step runs on the next message). */
|
|
20
|
+
next(): void;
|
|
21
|
+
/** leave the current scene. */
|
|
22
|
+
leave(): Promise<void>;
|
|
23
|
+
/** the active scene name, if any. */
|
|
24
|
+
readonly current: string | undefined;
|
|
25
|
+
/** the current step index. */
|
|
26
|
+
readonly step: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface SceneState {
|
|
30
|
+
scene: string;
|
|
31
|
+
step: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ScenesOptions {
|
|
35
|
+
/** where to persist scene state. defaults to in-memory. */
|
|
36
|
+
storage?: StorageAdapter<SceneState>;
|
|
37
|
+
/** scene key for an update. defaults to per-chat (`ctx.chat.id`). */
|
|
38
|
+
getKey?: (ctx: Context) => string | undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* scenes plugin: step-by-step wizards. each step handles one user message and
|
|
43
|
+
* asks the next question; `next()` advances, `leave()` exits. state lives per
|
|
44
|
+
* chat, so this is safe under the sequential update loop (no suspended promises).
|
|
45
|
+
*
|
|
46
|
+
* while in a scene every message is consumed and never reaches other handlers —
|
|
47
|
+
* so a `/cancel` won't fire its command unless a step checks for it
|
|
48
|
+
* (`if (ctx.text === "/cancel") return ctx.scene.leave()`).
|
|
49
|
+
*/
|
|
50
|
+
export function scenes(
|
|
51
|
+
defs: Record<string, SceneDef>,
|
|
52
|
+
options: ScenesOptions = {},
|
|
53
|
+
): Plugin<Context, { scene: SceneControl }> {
|
|
54
|
+
const storage = options.storage ?? new MemoryStorage<SceneState>();
|
|
55
|
+
const getKey = options.getKey ?? ((ctx: Context) => ctx.chat?.id?.toString());
|
|
56
|
+
|
|
57
|
+
// per-request consume step, shared from `derive` (which builds the control and
|
|
58
|
+
// owns the mutable state) to the routing `use` that runs after it.
|
|
59
|
+
const runners = new WeakMap<Context, () => Promise<boolean>>();
|
|
60
|
+
|
|
61
|
+
const plugin: Plugin<Context, { scene: SceneControl }> = (composer) =>
|
|
62
|
+
composer
|
|
63
|
+
.derive(async (ctx) => {
|
|
64
|
+
const key = getKey(ctx);
|
|
65
|
+
|
|
66
|
+
let state = key !== undefined ? await storage.get(key) : undefined;
|
|
67
|
+
let advance = false;
|
|
68
|
+
let left = false;
|
|
69
|
+
|
|
70
|
+
const persist = async (): Promise<void> => {
|
|
71
|
+
if (key === undefined) return;
|
|
72
|
+
|
|
73
|
+
if (left || !state) await storage.delete(key);
|
|
74
|
+
else await storage.set(key, state);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const control: SceneControl = {
|
|
78
|
+
get current() {
|
|
79
|
+
return state?.scene;
|
|
80
|
+
},
|
|
81
|
+
get step() {
|
|
82
|
+
return state?.step ?? 0;
|
|
83
|
+
},
|
|
84
|
+
next() {
|
|
85
|
+
advance = true;
|
|
86
|
+
},
|
|
87
|
+
async enter(name) {
|
|
88
|
+
state = { scene: name, step: 0 };
|
|
89
|
+
advance = false;
|
|
90
|
+
left = false;
|
|
91
|
+
|
|
92
|
+
await defs[name]?.enter?.(ctx as unknown as SceneContext);
|
|
93
|
+
await persist();
|
|
94
|
+
},
|
|
95
|
+
async leave() {
|
|
96
|
+
left = true;
|
|
97
|
+
state = undefined;
|
|
98
|
+
|
|
99
|
+
await persist();
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// in a scene with a message? run the current step instead of other handlers.
|
|
104
|
+
runners.set(ctx, async () => {
|
|
105
|
+
if (state && ctx.message) {
|
|
106
|
+
const def = defs[state.scene];
|
|
107
|
+
const step = def?.steps[state.step];
|
|
108
|
+
|
|
109
|
+
if (step) {
|
|
110
|
+
await step(ctx as unknown as SceneContext);
|
|
111
|
+
|
|
112
|
+
if (!left && state) {
|
|
113
|
+
if (advance) state = { scene: state.scene, step: state.step + 1 };
|
|
114
|
+
|
|
115
|
+
// re-resolve from the current scene — a step may have switched it via enter()
|
|
116
|
+
const length = defs[state.scene]?.steps.length ?? 0;
|
|
117
|
+
if (state.step >= length) {
|
|
118
|
+
state = undefined;
|
|
119
|
+
left = true;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
await persist();
|
|
123
|
+
}
|
|
124
|
+
return true; // consumed
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return false;
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
return { scene: control };
|
|
132
|
+
})
|
|
133
|
+
.use(async (ctx, next) => {
|
|
134
|
+
const consumed = await runners.get(ctx)?.();
|
|
135
|
+
runners.delete(ctx);
|
|
136
|
+
|
|
137
|
+
if (!consumed) await next();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
return plugin;
|
|
141
|
+
}
|