@tbox.cn/app-module-activity-play 0.0.0-stage → 0.3.2

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 (49) hide show
  1. package/INTEGRATION.md +94 -0
  2. package/LICENSE +21 -0
  3. package/README.md +30 -2
  4. package/dist/chunk-CM4OEPC3.js +689 -0
  5. package/dist/chunk-HUBEOW44.js +98 -0
  6. package/dist/client/index.css +107 -0
  7. package/dist/client/index.d.ts +11 -0
  8. package/dist/client/index.js +6 -0
  9. package/dist/index.css +107 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +46 -0
  12. package/dist/server/index.d.ts +309 -0
  13. package/dist/server/index.js +42 -0
  14. package/package.json +67 -3
  15. package/skills/activity-play/SKILL.md +55 -0
  16. package/src/client/cards/activity-play/ActivityPlayCard.tsx +77 -0
  17. package/src/client/cards/activity-play/index.ts +1 -0
  18. package/src/client/cards/view.ts +42 -0
  19. package/src/client/index.ts +22 -0
  20. package/src/client/styles/activity-play.css +136 -0
  21. package/src/index.ts +6 -0
  22. package/src/server/cards/activity-play/meta.ts +26 -0
  23. package/src/server/cards/activity-play/samples.ts +116 -0
  24. package/src/server/cards/activity-play-prize-detail/meta.ts +29 -0
  25. package/src/server/cards/activity-play-prize-detail/samples.ts +54 -0
  26. package/src/server/cards/activity-play-prize-list/meta.ts +41 -0
  27. package/src/server/cards/activity-play-prize-list/samples.ts +78 -0
  28. package/src/server/cards/index.ts +7 -0
  29. package/src/server/errors.ts +101 -0
  30. package/src/server/index.ts +72 -0
  31. package/src/server/ports.ts +50 -0
  32. package/src/server/prizes/cards.ts +79 -0
  33. package/src/server/prizes/errors.ts +88 -0
  34. package/src/server/prizes/query.ts +101 -0
  35. package/src/server/prizes/subject.ts +29 -0
  36. package/src/server/query.ts +98 -0
  37. package/src/server/routes.ts +371 -0
  38. package/src/server/tools.ts +187 -0
  39. package/tbox.module.json +65 -0
  40. package/tests/cards-capture.test.ts +110 -0
  41. package/tests/entry.test.ts +458 -0
  42. package/tests/ports.test.ts +83 -0
  43. package/tests/prizes.test.ts +357 -0
  44. package/tests/routes.test.ts +271 -0
  45. package/tests/samples.test.ts +53 -0
  46. package/tests/smoke.test.ts +27 -0
  47. package/tests/tools.test.ts +251 -0
  48. package/tsconfig.json +8 -0
  49. package/tsup.config.ts +27 -0
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { serverModule } from '../src/server/index';
3
+ import { clientModule } from '../src/client/index';
4
+
5
+ describe('module-activity-play 模块形态(铁律冒烟)', () => {
6
+ it('双端描述对象在场且自洽(satisfies ServerModule/ClientModule 编译期锁)', () => {
7
+ expect(serverModule).toBeTruthy();
8
+ expect(clientModule).toBeTruthy();
9
+ // 2026-11-16 起含授权占位 renderer(单卡型与 server 侧对齐——铁律 cards key = meta.cardType)
10
+ expect(Object.keys(clientModule.cards)).toEqual(['activity-play']);
11
+ });
12
+
13
+ it('cards key 约定 = meta.cardType(key 恒等于 meta.cardType——铁律位)', () => {
14
+ for (const [key, meta] of Object.entries(serverModule.cards)) {
15
+ expect(key).toBe(meta.cardType);
16
+ }
17
+ });
18
+
19
+ it('出卡卡型唯一(activity-play——mode 承载列表/详情,不拆多卡型)', () => {
20
+ expect(Object.keys(serverModule.cards)).toEqual(['activity-play']);
21
+ });
22
+
23
+ it('本地技能声明接线(skills map 键 = skill 名,前置 name=activity-play)', () => {
24
+ expect(Object.keys(serverModule.skills)).toContain('activity-play');
25
+ expect(serverModule.skills['activity-play']?.name).toBe('activity-play');
26
+ });
27
+ });
@@ -0,0 +1,251 @@
1
+ /**
2
+ * 活动玩法只读工具行为测试(直接 execute 真实工具实例 + stub integrations ctx)。
3
+ * 覆盖风险≡验收点:
4
+ * - 输入契约:无 mallId/userId 等 scope 字段;limit 归一(缺省/非法显性拒绝);
5
+ * keyword=invalid 是普通关键词(不哨兵化);
6
+ * - 出卡契约:非空 → cards 候选(cardType/activity-play + data 过卡契约 + note ≤120);
7
+ * 空结果/失败路径无 cards 键;失败 fact 含可辨识 errorCode,原始异常不透出;
8
+ * - 上下文:mallId/身份恒取 execCtx(跨用户/跨商圈连续调用各自解析——stub 逐次断言);
9
+ * - 复用:与 errors.ts 分类单源(三个缺席码 → NOT_CONFIGURED;供给异常 → PROVIDER_ERROR)。
10
+ */
11
+ import { describe, expect, it, vi } from 'vitest';
12
+ import { createToolExecContext } from '@tbox.cn/app-agent-sdk-server';
13
+ import type { RequestContext } from '@tbox.cn/app-contracts';
14
+ import { activityPlayActivitySchema, activityPlayCardDataSchema } from '@tbox.cn/app-contracts-mall';
15
+ import { createActivityPlayTools, ACTIVITY_PLAY_CARD_TYPE } from '../src/server/tools';
16
+ import { resolveActivityPlayQueryPort } from '../src/server/ports';
17
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
18
+
19
+ vi.mock('../src/server/ports', () => ({
20
+ resolveActivityPlayQueryPort: vi.fn(),
21
+ }));
22
+
23
+ const resolvePortMock = vi.mocked(resolveActivityPlayQueryPort);
24
+
25
+ /** reqCtx:登录态 guest + 绑定商圈(工具路径无 query 注入——scope 恒取上下文绑定) */
26
+ const reqCtxOf = (mallId: string, userId = 'guest_1'): RequestContext => ({
27
+ identity: { userId, source: 'guest' },
28
+ attributes: { mall: { mallId } },
29
+ });
30
+
31
+ const ITEM = {
32
+ activityRef: 'demo:wheel',
33
+ title: '幸运大转盘',
34
+ description: '进入活动页面查看参与规则',
35
+ status: 'active' as const,
36
+ loginRequired: false,
37
+ };
38
+ const ITEM_B = {
39
+ activityRef: 'demo:checkin',
40
+ title: '签到有礼',
41
+ startsAt: '2027-01-01T00:00:00+08:00',
42
+ status: 'not_started' as const,
43
+ loginRequired: true,
44
+ };
45
+
46
+ function makeTools(port: unknown) {
47
+ resolvePortMock.mockImplementation(async () => port as never);
48
+ const ctx = {} as ServerContext;
49
+ return createActivityPlayTools({ getCtx: () => ctx });
50
+ }
51
+
52
+ /** 真实端口行为替身(provenance: supplier 语义下沉到 stub——工具层只编排) */
53
+ const listPort = (items: readonly unknown[]) => ({
54
+ listActivities: vi.fn(async (q: unknown, input: { keyword?: string; limit?: number }) => {
55
+ lastListCall = { q, input };
56
+ return { items: (items as never[]) };
57
+ }),
58
+ getActivity: vi.fn(async (_q: unknown, ref: string) => (items as never[]).find((i: { activityRef?: string }) => i.activityRef === ref) ?? null),
59
+ });
60
+ let lastListCall: { q: unknown; input: { keyword?: string; limit?: number } } | undefined;
61
+
62
+ describe('listActivityPlays', () => {
63
+ it('非空目录:答话事实 + 一张 mode=list 卡候选;data 过卡契约;note ≤120', async () => {
64
+ const tools = makeTools(listPort([ITEM, ITEM_B]));
65
+ const result = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
66
+ expect(result['found']).toBe(true);
67
+ expect(result['count']).toBe(2);
68
+ expect((result['items'] as Array<{ activityRef: string }>).map((i) => i.activityRef)).toEqual(['demo:wheel', 'demo:checkin']);
69
+ const cards = result['cards'] as Array<{ cardType: string; data: unknown; note: string }>;
70
+ expect(cards).toHaveLength(1);
71
+ expect(cards[0]?.cardType).toBe(ACTIVITY_PLAY_CARD_TYPE);
72
+ activityPlayCardDataSchema.parse(cards[0]?.data);
73
+ for (const item of (cards[0]?.data as { items: unknown[] }).items) {
74
+ expect(activityPlayActivitySchema.safeParse(item).success).toBe(true);
75
+ }
76
+ expect(cards[0]?.note.length).toBeLessThanOrEqual(120);
77
+ expect(cards[0]?.note).toContain('幸运大转盘');
78
+ // mallId 取自可信上下文(result facts/native data 双处一致)
79
+ expect((result['mallId'] as string)).toBe('mall-a');
80
+ expect((cards[0]?.data as { mallId: string }).mallId).toBe('mall-a');
81
+ // 透传供给入参:缺省 limit 20;keyword 缺席
82
+ expect(lastListCall?.input).toEqual({ limit: 20 });
83
+ expect((lastListCall?.q as { scope: { mallId: string } }).scope.mallId).toBe('mall-a');
84
+ });
85
+
86
+ it('keyword/limit 处理:透传;缺省 limit 20;非法整数字串 = 显性失败 fact;小数/负数字串 = 框架输入校验拒绝', async () => {
87
+ const tools = makeTools(listPort([ITEM]));
88
+ const ok = await tools.listActivityPlays.execute!({ keyword: ' invalid ', limit: '3' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
89
+ expect(ok['found']).toBe(true);
90
+ expect(lastListCall?.input).toEqual({ keyword: 'invalid', limit: 3 }); // trim;'invalid' 是普通关键词
91
+
92
+ // 空串/纯空白 = 非法值显性拒绝(评审返修:不静默当缺省——"未传"才走缺省)
93
+ for (const blank of ['', ' ']) {
94
+ const result = await tools.listActivityPlays.execute!({ limit: blank }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
95
+ expect(result['found'], `limit=${JSON.stringify(blank)}`).toBe(false);
96
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
97
+ expect(result['cards']).toBeUndefined();
98
+ }
99
+ // 评审点名用例:'20.0'/'2e1' 是非规范数字格式——与 HTTP 同拒(JSON 转换移除后不再
100
+ // 折叠成功);'20.5'/'-1' 同由归一拒绝
101
+ for (const bad of ['20.0', '2e1', '1e3', '20.5', '-1']) {
102
+ const result = await tools.listActivityPlays.execute!({ limit: bad }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
103
+ expect(result['found'], `limit=${bad}`).toBe(false);
104
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
105
+ expect(result['cards']).toBeUndefined();
106
+ }
107
+ // 纯整数字串('0'/'51')过 coerce 保留 string,进入工具归一 → INVALID_REQUEST 失败事实
108
+ for (const bad of ['abc', '0', '51']) {
109
+ const result = await tools.listActivityPlays.execute!({ limit: bad }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
110
+ expect(result['found'], `limit=${bad}`).toBe(false);
111
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
112
+ expect(result['cards']).toBeUndefined();
113
+ }
114
+ });
115
+
116
+ it('空目录/关键词无匹配:明确空结果事实,无 cards 键,不是错误', async () => {
117
+ const tools = makeTools(listPort([]));
118
+ const empty = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
119
+ expect(empty['found']).toBe(false);
120
+ expect(empty['count']).toBe(0);
121
+ expect(empty['noResultsReason']).toContain('暂未登记');
122
+ expect(empty['cards']).toBeUndefined();
123
+
124
+ const kw = await tools.listActivityPlays.execute!({ keyword: '不存在的活动' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
125
+ expect(kw['noResultsReason']).toContain('不存在的活动');
126
+ expect(kw['cards']).toBeUndefined();
127
+ });
128
+
129
+ it('供给失败分类(errors.ts 单源):配置缺席族 → NOT_CONFIGURED;异常 → PROVIDER_ERROR 不透原始内容', async () => {
130
+ resolvePortMock.mockImplementation(async () => { throw Object.assign(new Error('原始敏感配置细节'), { code: 'PROVIDER_SERVICE_NOT_CONFIGURED' }); });
131
+ const ctx = {} as ServerContext;
132
+ const tools = createActivityPlayTools({ getCtx: () => ctx });
133
+ const result = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
134
+ expect(result['errorCode']).toBe('NOT_CONFIGURED');
135
+ expect(JSON.stringify(result)).not.toContain('敏感');
136
+
137
+ resolvePortMock.mockImplementation(async () => { throw new Error('boom 原始异常'); });
138
+ const result2 = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
139
+ expect(result2['errorCode']).toBe('PROVIDER_ERROR');
140
+ expect(result2['cards']).toBeUndefined();
141
+ expect(JSON.stringify(result2)).not.toContain('boom');
142
+ });
143
+
144
+ it('无商圈 → SCOPE_REQUIRED 显性失败(不默认其他商圈)', async () => {
145
+ const tools = makeTools(listPort([ITEM]));
146
+ const result = await tools.listActivityPlays.execute!({}, createToolExecContext({ identity: { userId: 'u', source: 'guest' } }) as never) as Record<string, unknown>;
147
+ expect(result['errorCode']).toBe('SCOPE_REQUIRED');
148
+ expect(result['cards']).toBeUndefined();
149
+ });
150
+
151
+ it('上下文隔离:连续两商圈各自解析(目录不同、mallId 各自出口)', async () => {
152
+ const portA = listPort([ITEM]);
153
+ const portB = listPort([ITEM_B]);
154
+ resolvePortMock.mockImplementation(async () => (lastMall === 'mall-a' ? portA : portB) as never);
155
+ let lastMall = 'mall-a';
156
+ const ctx = {} as ServerContext;
157
+ const tools = createActivityPlayTools({ getCtx: () => ctx });
158
+ const a = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
159
+ expect((a['cards'] as { data: { mallId: string } }[])[0]?.data.mallId).toBe('mall-a');
160
+
161
+ lastMall = 'mall-b';
162
+ const b = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-b')) as never) as Record<string, unknown>;
163
+ expect((b['cards'] as { data: { mallId: string } }[])[0]?.data.mallId).toBe('mall-b');
164
+ // 上一轮成功卡片不残留到本轮失败路径:接下来让供给抛错,b 之后再查 a 失败
165
+ resolvePortMock.mockImplementation(async () => { throw Object.assign(new Error('x'), { code: 'PROVIDER_INSTANCE_DISABLED' }); });
166
+ const fail = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
167
+ expect(fail['errorCode']).toBe('NOT_CONFIGURED');
168
+ expect(fail['cards']).toBeUndefined();
169
+ });
170
+ });
171
+
172
+ describe('getActivityPlayDetail', () => {
173
+ it('命中:一张 mode=detail 卡(items 恰一);facts 含状态/时间/说明', async () => {
174
+ const tools = makeTools(listPort([ITEM, ITEM_B]));
175
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:checkin' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
176
+ expect(result['found']).toBe(true);
177
+ expect(result['activityRef']).toBe('demo:checkin');
178
+ expect(result['statusText']).toBe('未开始');
179
+ expect((result['items'] as unknown[] | undefined)).toBeUndefined(); // detail = 扁平 facts(非列表嵌套)
180
+ const cards = result['cards'] as Array<{ cardType: string; data: { mode: string; items: unknown[] } }>;
181
+ expect(cards).toHaveLength(1);
182
+ expect(cards[0]?.cardType).toBe(ACTIVITY_PLAY_CARD_TYPE);
183
+ expect(cards[0]?.data.mode).toBe('detail');
184
+ expect(cards[0]?.data.items).toHaveLength(1);
185
+ activityPlayCardDataSchema.parse(cards[0]?.data);
186
+ });
187
+
188
+ it('detail 允许返回 disabled(状态说明用),卡 data 不携带 enabled', async () => {
189
+ const disabledItem = { activityRef: 'demo:hidden', title: '停用活动', status: 'disabled' as const, loginRequired: false };
190
+ const tools = makeTools(listPort([disabledItem]));
191
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:hidden' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
192
+ expect(result['found']).toBe(true);
193
+ expect(result['statusText']).toBe('已停用');
194
+ const card = (result['cards'] as Array<{ data: Record<string, unknown> }>)[0];
195
+ const item = (card?.data['items'] as Array<Record<string, unknown>>)[0];
196
+ expect(item['enabled']).toBeUndefined();
197
+ });
198
+
199
+ it('未知引用 → ACTIVITY_NOT_FOUND 失败事实,无 cards(不猜首项/不造演示详情)', async () => {
200
+ const tools = makeTools(listPort([ITEM]));
201
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:none' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
202
+ expect(result['found']).toBe(false);
203
+ expect(result['errorCode']).toBe('ACTIVITY_NOT_FOUND');
204
+ expect(result['cards']).toBeUndefined();
205
+ });
206
+
207
+ it('非法 activityRef → INVALID_REQUEST(契约引用形状单源)', async () => {
208
+ const tools = makeTools(listPort([ITEM]));
209
+ for (const bad of ['', ' ', 'bad ref!', 'x'.repeat(129)]) {
210
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: bad }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
211
+ expect(result['errorCode'], JSON.stringify(bad)).toBe('INVALID_REQUEST');
212
+ expect(result['cards']).toBeUndefined();
213
+ }
214
+ });
215
+
216
+ it('评审返修回归:数字/布尔形态合法字面量引用(原始字串保留,数字串同型不撞车)', async () => {
217
+ const weirdRefs = ['1.2', 'true', '0.12345', '42'];
218
+ const items = weirdRefs.map((ref) => ({ ...ITEM, activityRef: ref }));
219
+ const tools = makeTools(listPort(items));
220
+ for (const ref of weirdRefs) {
221
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: ref }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
222
+ expect(result['found'], `activityRef=${ref}`).toBe(true);
223
+ expect(result['activityRef']).toBe(ref);
224
+ const cards = result['cards'] as Array<{ data: { items: Array<{ activityRef: string }> } }>;
225
+ expect(cards[0]?.data.items[0]?.activityRef).toBe(ref); // 卡 data 原样保留字面量
226
+ }
227
+ });
228
+
229
+ it('评审返修二轮:数字同型不同值引用不串答(JSON 转换已移除——1.20 不再折叠成 1.2、1e3 不再折叠成 1000)', async () => {
230
+ // 目录同时含 1.2/1.20 与 1e3/1000 四个独立活动:每个引用必须精确命中自己
231
+ const refs = ['1.2', '1.20', '1e3', '1000'];
232
+ const items = refs.map((ref) => ({ ...ITEM, activityRef: ref, title: `活动${ref}` }));
233
+ const tools = makeTools(listPort(items));
234
+ for (const ref of refs) {
235
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: ref }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
236
+ expect(result['found'], `activityRef=${ref}`).toBe(true);
237
+ expect(result['activityRef']).toBe(ref);
238
+ expect(result['title']).toBe(`活动${ref}`); // 撞车即串答——此处必须各自命中
239
+ }
240
+ });
241
+
242
+ it('名称→引用不隐式回退:非 ref 形状 = INVALID_REQUEST;合法形状未知 = NOT_FOUND(无首项/演示回退)', async () => {
243
+ const tools = makeTools(listPort([ITEM]));
244
+ // 标题字面量不是 activityRef(形状非法——技能引导模型先查列表拿引用,不猜)
245
+ const byTitle = await tools.getActivityPlayDetail.execute!({ activityRef: '幸运大转盘' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
246
+ expect(byTitle['errorCode']).toBe('INVALID_REQUEST');
247
+ // 形状合法但目录中不存在
248
+ const byUnknownRef = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:none' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
249
+ expect(byUnknownRef['errorCode']).toBe('ACTIVITY_NOT_FOUND');
250
+ });
251
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "jsx": "react-jsx",
5
+ "types": ["node"]
6
+ },
7
+ "include": ["src", "tests"]
8
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: {
5
+ index: 'src/index.ts',
6
+ 'server/index': 'src/server/index.ts',
7
+ 'client/index': 'src/client/index.ts',
8
+ },
9
+ format: ['esm'],
10
+ target: 'node20',
11
+ platform: 'node',
12
+ outDir: 'dist',
13
+ clean: true,
14
+ sourcemap: false,
15
+ dts: { compilerOptions: { incremental: false } },
16
+ external: [
17
+ '@tbox.cn/app-agent-sdk-client',
18
+ '@tbox.cn/app-agent-sdk-server',
19
+ '@tbox.cn/app-contracts',
20
+ '@tbox.cn/app-contracts-mall',
21
+ 'react',
22
+ 'react-dom',
23
+ 'zod',
24
+ '@mastra/core',
25
+ 'express',
26
+ ],
27
+ });