@tbox.cn/app-module-mall-core 0.1.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.
@@ -0,0 +1,242 @@
1
+ /**
2
+ * 域装配专项测试(W3-1;迁移自 mall 模板 tests/deployment-loader.test.ts 派生段):
3
+ * - createScopeAssembly:投影穿透 / validateScope / buildScope(+mallName) / instanceIdOf /
4
+ * scopeDefaults / defaultMallContext(v4 mallId-only)/ enhanceHelloContext(回填 + fail-soft)
5
+ * - 隐式默认单实例:provider 声明惰性融合(晚声明失效 / ref 缓存 / 函数成员稳定标识 / stub 兼容)
6
+ * - register 装配:raw 在场 → 注册于 SCOPE_ASSEMBLY_KIND(ctx.scopeDefaults 视图活性)+
7
+ * mall-directory 服务;raw 缺席 → 不注册(无控制面降级语义)
8
+ */
9
+ import { describe, expect, it } from 'vitest';
10
+ import type { IntegrationsRegistry, ServerContext } from '@tbox.cn/app-sdk/server';
11
+ import { createServerContext, parseIntegrationsConfig, registerServerModules } from '@tbox.cn/app-sdk/server';
12
+ import { SCOPE_ASSEMBLY_KIND } from '@tbox.cn/app-contracts';
13
+ import type { ProviderInstanceDeclarations } from '@tbox.cn/app-contracts';
14
+ import type { IntegrationsRaw } from '@tbox.cn/app-sdk/server';
15
+ import { createScopeAssembly, buildDefaultMallContext, serverModule } from '../src/server/index.js';
16
+
17
+ /** 模拟 real-env 素材形态:root instances 注册表 + defaultInstanceId + services */
18
+ const fullConfig = {
19
+ provider: 'acme',
20
+ instances: [
21
+ {
22
+ id: 'mall-demo',
23
+ name: '示例商场',
24
+ attributes: {
25
+ miniAppId: 'demo-app',
26
+ contactPhone: '0571-88888888',
27
+ location: { lat: 30.2741, lon: 120.1551, address: '湖滨示范点' },
28
+ },
29
+ },
30
+ ],
31
+ defaultInstanceId: 'mall-demo',
32
+ services: { 'member.account': {} },
33
+ };
34
+
35
+ function rawOf(config: unknown, source = '/tmp/integrations.json'): IntegrationsRaw {
36
+ return { config: parseIntegrationsConfig(config), source };
37
+ }
38
+
39
+ /** 最小 fake ServerContext 面(仅 createScopeAssembly 依赖的 integrations 通道) */
40
+ function fakeCtx(registry: IntegrationsRegistry | undefined): ServerContext {
41
+ return { integrations: registry } as unknown as ServerContext;
42
+ }
43
+
44
+ function fakeRegistry(raw: IntegrationsRaw | undefined): IntegrationsRegistry {
45
+ return {
46
+ raw,
47
+ async resolveService() {
48
+ return null;
49
+ },
50
+ } as unknown as IntegrationsRegistry;
51
+ }
52
+
53
+ describe('createScopeAssembly:投影与消费面', () => {
54
+ it('投影穿透(contactPhone/location/miniAppId 存活)+ 四消费点活性', () => {
55
+ const raw = rawOf(fullConfig);
56
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
57
+ expect(assembly.controlPlane.malls[0]).toMatchObject({
58
+ mallId: 'mall-demo',
59
+ name: '示例商场',
60
+ miniAppId: 'demo-app',
61
+ contactPhone: '0571-88888888',
62
+ location: { lat: 30.2741, lon: 120.1551, address: '湖滨示范点' },
63
+ });
64
+ expect(assembly.controlPlane.defaultMallId).toBe('mall-demo');
65
+ // validateScope(HTTP/WS 同核)
66
+ expect(assembly.validateScope({ mall: { mallId: 'mall-demo' } })).toBe(true); // v4 mallId-only 合法
67
+ expect(assembly.validateScope({ mall: { miniAppId: 'a' } })).toBe(false); // 缺会话边界键
68
+ expect(
69
+ assembly.extractScopeKey({
70
+ identity: { userId: 'u', source: 'external' },
71
+ attributes: { mall: { mallId: 'mall-demo' } },
72
+ } as never),
73
+ ).toBe('mall-demo');
74
+ expect(assembly.buildScope({ mall: { mallId: 'mall-demo' } })).toEqual({ mallId: 'mall-demo' });
75
+ expect(assembly.instanceIdOf({ mallId: 'mall-demo' })).toBe('mall-demo');
76
+ expect(assembly.instanceIdOf({})).toBe('');
77
+ expect(assembly.rootMiniAppId).toBeUndefined(); // root config.miniAppId 缺席(instances attributes 非 root)
78
+ });
79
+
80
+ it('buildScopeWithMallName:参考表命中回填 / miss 降级(无 fallback 缓存 → 原样)', () => {
81
+ const raw = rawOf(fullConfig);
82
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
83
+ expect(assembly.buildScopeWithMallName({ mall: { mallId: 'mall-demo' } })).toEqual({
84
+ mallId: 'mall-demo',
85
+ mallName: '示例商场',
86
+ });
87
+ expect(assembly.buildScopeWithMallName({ mall: { mallId: '动态-id' } })).toEqual({ mallId: '动态-id' });
88
+ });
89
+
90
+ it('scopeDefaults:defaultMallId 在场 → { defaultMallId };缺省 → undefined', () => {
91
+ const raw = rawOf(fullConfig);
92
+ expect(createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!.scopeDefaults).toEqual({
93
+ defaultMallId: 'mall-demo',
94
+ });
95
+ const noDefault = rawOf({ provider: 'globex', services: {} });
96
+ expect(createScopeAssembly(noDefault, fakeCtx(fakeRegistry(noDefault)))!.scopeDefaults).toBeUndefined();
97
+ });
98
+
99
+ it('raw 缺席(无 integrations.json)→ undefined(无控制面降级)', () => {
100
+ expect(createScopeAssembly(undefined, fakeCtx(undefined))).toBeUndefined();
101
+ });
102
+
103
+ it('拼错 attributes 键 → 投影 fail-fast(strict——报错含实例 id 与允许键清单;惰性投影 = 访问期触发)', () => {
104
+ // W3-1:严格校验随投影自模板装载链迁入;隐式默认单实例:投影惰性化——
105
+ // 构造不抛、首次访问触发(部署链首次访问 = start() defaultMallContext(),boot fail-fast 等价)
106
+ const raw = rawOf({ instances: [{ id: 'm1', name: 'x', attributes: { miniAppid: 'typo' } }], services: {} });
107
+ const assembly = createScopeAssembly(raw, fakeCtx(undefined))!;
108
+ expect(() => assembly.controlPlane).toThrow(/m1.*允许键|允许键.*miniAppId/s);
109
+ });
110
+ });
111
+
112
+ describe('buildDefaultMallContext:v4 mallId-only 注入', () => {
113
+ it('defaultMallId + miniAppId 齐备 → 拼装完整 context', () => {
114
+ const raw = rawOf(fullConfig);
115
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
116
+ expect(assembly.defaultMallContext()).toEqual({ mall: { mallId: 'mall-demo', miniAppId: 'demo-app' } });
117
+ // root miniAppId 优先
118
+ expect(buildDefaultMallContext(assembly.controlPlane, 'root-app')).toEqual({
119
+ mall: { mallId: 'mall-demo', miniAppId: 'root-app' },
120
+ });
121
+ });
122
+
123
+ it('双缺 miniAppId → mallId-only 注入(v4:不再 warn-refuse 静默失效)', () => {
124
+ const cp = createScopeAssembly(rawOf({ defaultInstanceId: 'm9', services: {} }), fakeCtx(undefined))!
125
+ .controlPlane;
126
+ expect(buildDefaultMallContext(cp)).toEqual({ mall: { mallId: 'm9' } });
127
+ });
128
+
129
+ it('无 defaultMallId → undefined(不兜底)', () => {
130
+ const cp = createScopeAssembly(rawOf({ services: {} }), fakeCtx(undefined))!.controlPlane;
131
+ expect(buildDefaultMallContext(cp)).toBeUndefined();
132
+ });
133
+ });
134
+
135
+ describe('enhanceHelloContext:miniAppId 回填 + fail-soft', () => {
136
+ it('缺 miniAppId + root config.miniAppId 在场 → 回填;无 mallId → 原样', async () => {
137
+ const raw = rawOf({ ...fullConfig, config: { miniAppId: 'root-wx' } });
138
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
139
+ expect(assembly.rootMiniAppId).toBe('root-wx');
140
+ const backfilled = await assembly.enhanceHelloContext({ mall: { mallId: 'mall-demo' } });
141
+ expect(backfilled).toEqual({ mall: { mallId: 'mall-demo', miniAppId: 'root-wx' } });
142
+ const untouched = await assembly.enhanceHelloContext({ other: 1 });
143
+ expect(untouched).toEqual({ other: 1 });
144
+ });
145
+
146
+ it('mallId 未命中参考表 → 预热 fail-soft(槽缺席仍原 context 继续)', async () => {
147
+ const raw = rawOf(fullConfig);
148
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
149
+ const next = await assembly.enhanceHelloContext({ mall: { mallId: '未知动态' } });
150
+ expect(next).toEqual({ mall: { mallId: '未知动态' } });
151
+ });
152
+ });
153
+
154
+ describe('register 装配:注册表 + 服务', () => {
155
+ it('raw 在场 → 注册于 SCOPE_ASSEMBLY_KIND + mall-directory 服务 + ctx.scopeDefaults 视图活性', async () => {
156
+ const ctx = createServerContext({ integrations: fakeRegistry(rawOf(fullConfig)) });
157
+ await registerServerModules(ctx, [serverModule] as never);
158
+ const assembly = ctx.domainAssemblies.resolve(SCOPE_ASSEMBLY_KIND);
159
+ expect(assembly).toBeDefined();
160
+ // SDK scopeDefaults 读取视图(注册表惰性优先)
161
+ expect(ctx.scopeDefaults?.['defaultMallId']).toBe('mall-demo');
162
+ // mall-directory 服务(shopping-guide/customer-service 消费)
163
+ const directory = ctx.services.resolve('mall-directory') as {
164
+ nearbyMalls(): { mallId: string }[];
165
+ contactPhone(mallId: string): string | undefined;
166
+ } | undefined;
167
+ expect(directory?.nearbyMalls().map((m) => m.mallId)).toEqual(['mall-demo']);
168
+ expect(directory?.contactPhone('mall-demo')).toBe('0571-88888888');
169
+ });
170
+
171
+ it('raw 缺席 → 不注册(无控制面降级;scopeDefaults 视图回落 undefined)', async () => {
172
+ const ctx = createServerContext();
173
+ await registerServerModules(ctx, [serverModule] as never);
174
+ expect(ctx.domainAssemblies.resolve(SCOPE_ASSEMBLY_KIND)).toBeUndefined();
175
+ expect(ctx.scopeDefaults?.['defaultMallId']).toBeUndefined();
176
+ expect(ctx.services.resolve('mall-directory')).toBeUndefined();
177
+ });
178
+ });
179
+
180
+ // ── 隐式默认单实例:惰性投影(provider 声明融合) ─────────────────────────────
181
+
182
+ type Declared = ProviderInstanceDeclarations;
183
+
184
+ const DECLARED_MOCK: Declared = {
185
+ mock: [{ id: 'mall-demo', name: '星河 Mock 小镇', attributes: { miniAppId: 'mock-demo-app' } }],
186
+ };
187
+ const zeroTopology = { provider: 'mock', services: {} };
188
+
189
+ /** 声明感知 fake registry(可变声明源——晚声明失效用例;仅补 providerInstanceDeclarations) */
190
+ function declaringRegistry(raw: IntegrationsRaw, getDeclared: () => Declared): IntegrationsRegistry {
191
+ return {
192
+ raw,
193
+ async resolveService() {
194
+ return null;
195
+ },
196
+ providerInstanceDeclarations: () => getDeclared(),
197
+ } as unknown as IntegrationsRegistry;
198
+ }
199
+
200
+ describe('createScopeAssembly:隐式默认单实例惰性投影', () => {
201
+ it('stub 无声明方法(存量兼容)→ 行为同旧:零拓扑空平面 + scopeDefaults undefined', () => {
202
+ const raw = rawOf(zeroTopology);
203
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
204
+ expect(assembly.controlPlane.malls).toEqual([]);
205
+ expect(assembly.scopeDefaults).toBeUndefined();
206
+ expect(assembly.defaultMallContext()).toBeUndefined();
207
+ });
208
+
209
+ it('带声明 → controlPlane.malls / scopeDefaults / defaultMallContext 三面生效', () => {
210
+ const raw = rawOf(zeroTopology);
211
+ const assembly = createScopeAssembly(raw, fakeCtx(declaringRegistry(raw, () => DECLARED_MOCK)))!;
212
+ expect(assembly.controlPlane.malls).toEqual([
213
+ { mallId: 'mall-demo', name: '星河 Mock 小镇', miniAppId: 'mock-demo-app' },
214
+ ]);
215
+ expect(assembly.scopeDefaults).toEqual({ defaultMallId: 'mall-demo' });
216
+ expect(assembly.defaultMallContext()).toEqual({
217
+ mall: { mallId: 'mall-demo', miniAppId: 'mock-demo-app' },
218
+ });
219
+ });
220
+
221
+ it('晚声明失效:先读(缓存空平面)→ 声明 ref 变 → 再读出新 mall-demo', () => {
222
+ const raw = rawOf(zeroTopology);
223
+ let declared: Declared = {};
224
+ const assembly = createScopeAssembly(raw, fakeCtx(declaringRegistry(raw, () => declared)))!;
225
+ expect(assembly.controlPlane.malls).toEqual([]);
226
+ declared = DECLARED_MOCK; // 新快照引用 = 声明变化信号
227
+ expect(assembly.controlPlane.malls.map((m) => m.mallId)).toEqual(['mall-demo']);
228
+ });
229
+
230
+ it('声明 ref 不变 → 投影缓存复用(两次 controlPlane 访问同引用)', () => {
231
+ const raw = rawOf(zeroTopology);
232
+ const assembly = createScopeAssembly(raw, fakeCtx(declaringRegistry(raw, () => DECLARED_MOCK)))!;
233
+ expect(assembly.controlPlane).toBe(assembly.controlPlane);
234
+ });
235
+
236
+ it('函数成员标识稳定:buildScopeWithMallName 两次访问同引用(契约加固)', () => {
237
+ const raw = rawOf(zeroTopology);
238
+ const assembly = createScopeAssembly(raw, fakeCtx(fakeRegistry(raw)))!;
239
+ expect(assembly.buildScopeWithMallName).toBe(assembly.buildScopeWithMallName);
240
+ expect(assembly.validateScope).toBe(assembly.validateScope);
241
+ });
242
+ });
@@ -0,0 +1,20 @@
1
+ /**
2
+ * mall.info-cache 服务注册回归(W3-3 单一模板统一化):
3
+ * register 注册缓存读面(闭包 integrations)——形状守卫短路 + 缓存缺席路径不抛错。
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+ import { createServerContext } from '@tbox.cn/app-sdk/server';
7
+ import { MALL_INFO_CACHE_SERVICE, type MallInfoCachePort } from '@tbox.cn/app-contracts-mall';
8
+ import { serverModule } from '../src/server/index';
9
+
10
+ describe('mall.info-cache 服务(register 注册)', () => {
11
+ it('注册期纯净:服务可 resolve,读面闭包 integrations(缺席 → fail-soft)', async () => {
12
+ const ctx = createServerContext();
13
+ serverModule.register(ctx);
14
+ const port = ctx.resolveService<MallInfoCachePort>(MALL_INFO_CACHE_SERVICE);
15
+ expect(port).toBeDefined();
16
+ expect(port!.cachedMallName('!!bad!')).toBeUndefined();
17
+ // 形状守卫短路(MALL_ID_RE 不匹配)→ undefined,不触 integrations
18
+ await expect(port!.resolveMallInfo('!!bad!')).resolves.toBeUndefined();
19
+ });
20
+ });
@@ -0,0 +1,99 @@
1
+ /**
2
+ * mall.info 缓存模块专项测试(自 mall 模板 tests/mall-info-cache.test.ts 迁入——W3-1):
3
+ * - resolveMallInfo:缓存 → single-flight → 槽拉取;失败/未知 → undefined(fail-soft)
4
+ * - cachedMallName:同步回退通道(TTL/负缓存语义)
5
+ * - S1 防线:负缓存 / LRU 封顶 / 形状守卫(畸形 ID 零上游调用)
6
+ *
7
+ * mock IntegrationsRegistry(只实现 resolveService 调用计数与返回)。
8
+ */
9
+ import { describe, expect, it } from 'vitest';
10
+ import type { IntegrationsRegistry } from '@tbox.cn/app-sdk/server';
11
+ import type { MallInfo, MallInfoPort } from '@tbox.cn/app-contracts-mall';
12
+ import { cachedMallName, resolveMallInfo } from '../src/server/mall-info-cache.js';
13
+
14
+ interface FakeRegistry {
15
+ service?: MallInfoPort;
16
+ error?: boolean;
17
+ calls: number;
18
+ }
19
+
20
+ function fakeRegistry(fake: FakeRegistry): IntegrationsRegistry {
21
+ return {
22
+ async resolveService() {
23
+ fake.calls += 1;
24
+ if (fake.error) throw new Error('槽未装配');
25
+ if (!fake.service) return null;
26
+ return fake.service;
27
+ },
28
+ } as unknown as IntegrationsRegistry;
29
+ }
30
+
31
+ const INFO: MallInfo = { mallId: '1105288', name: '示例广场', latitude: 39.9, longitude: 116.4 };
32
+
33
+ /** 每个用例独立 mallId 前缀(模块级缓存单例——测试互不污染) */
34
+ let seq = 0;
35
+ const freshMallId = () => `m${Date.now()}_${++seq}`;
36
+
37
+ function fakePort(impl: (mallId: string) => Promise<MallInfo | undefined>): MallInfoPort {
38
+ return { getMallInfo: impl };
39
+ }
40
+
41
+ describe('resolveMallInfo:缓存与 single-flight', () => {
42
+ it('正缓存 TTL 内二次 resolve → 零额外 service 调用', async () => {
43
+ const mallId = freshMallId();
44
+ const fake = { calls: 0, service: fakePort(async (id) => ({ ...INFO, mallId: id })) };
45
+ const reg = fakeRegistry(fake);
46
+ await resolveMallInfo(mallId, reg);
47
+ expect(fake.calls).toBe(1);
48
+ await resolveMallInfo(mallId, reg);
49
+ expect(fake.calls).toBe(1); // 缓存命中,零上游
50
+ });
51
+
52
+ it('负缓存:拉取失败 → 5min 内零重试', async () => {
53
+ const mallId = freshMallId();
54
+ const fake = { calls: 0, service: fakePort(async () => { throw new Error('boom'); }) };
55
+ const reg = fakeRegistry(fake);
56
+ await resolveMallInfo(mallId, reg);
57
+ expect(fake.calls).toBe(1);
58
+ await resolveMallInfo(mallId, reg);
59
+ expect(fake.calls).toBe(1); // 负缓存命中
60
+ expect(await cachedMallName(mallId)).toBeUndefined();
61
+ });
62
+
63
+ it('并发同 ID → service 单次调用(single-flight)', async () => {
64
+ const mallId = freshMallId();
65
+ const fake = { calls: 0, service: fakePort(async (id) => ({ ...INFO, mallId: id })) };
66
+ const reg = fakeRegistry(fake);
67
+ await Promise.all([resolveMallInfo(mallId, reg), resolveMallInfo(mallId, reg), resolveMallInfo(mallId, reg)]);
68
+ expect(fake.calls).toBe(1);
69
+ });
70
+
71
+ it('cachedMallName:成功缓存后同步可见', async () => {
72
+ const mallId = freshMallId();
73
+ const fake = { calls: 0, service: fakePort(async (id) => ({ ...INFO, mallId: id })) };
74
+ const reg = fakeRegistry(fake);
75
+ await resolveMallInfo(mallId, reg);
76
+ expect(cachedMallName(mallId)).toBe('示例广场');
77
+ });
78
+
79
+ it('形状守卫:畸形 mallId → undefined 且零 service 调用', async () => {
80
+ const fake = { calls: 0, service: fakePort(async () => INFO) };
81
+ const reg = fakeRegistry(fake);
82
+ expect(await resolveMallInfo('a/b?c', reg)).toBeUndefined();
83
+ expect(await resolveMallInfo('a'.repeat(40), reg)).toBeUndefined();
84
+ expect(fake.calls).toBe(0);
85
+ });
86
+
87
+ it('槽未装配(resolveService 抛错)→ 负缓存 + undefined(fail-soft)', async () => {
88
+ const mallId = freshMallId();
89
+ const fake = { calls: 0, error: true };
90
+ const reg = fakeRegistry(fake);
91
+ expect(await resolveMallInfo(mallId, reg)).toBeUndefined();
92
+ expect(await resolveMallInfo(mallId, reg)).toBeUndefined();
93
+ expect(fake.calls).toBe(1);
94
+ });
95
+
96
+ it('integrations 缺席(undefined)→ undefined 不抛', async () => {
97
+ expect(await resolveMallInfo(freshMallId(), undefined)).toBeUndefined();
98
+ });
99
+ });
@@ -0,0 +1,157 @@
1
+ /**
2
+ * mall-info 工具 + preTool 声明专项测试(自 mall 模板 tests/mall-info-tool.test.ts 迁入——W3-1):
3
+ * - execute:found:true 投影 / 槽 fail-soft / 无 integrations / mallId 缺失
4
+ * - preTool decide:mall scope → run+args(mallId 入参化);无 scope → skip
5
+ * - dedup accepts:found:true 落键 / found:false 不落键(防钉死)
6
+ * - 引擎级:声明式 preTools 经 registerServerModules 装配(实例一致性)
7
+ *
8
+ * mock IntegrationsRegistry(对齐 mall-info-cache.test.ts 模式);
9
+ * 每用例独立 mallId(resolveMallInfo 模块级缓存单例——测试互不污染)。
10
+ */
11
+ import { describe, expect, it } from 'vitest';
12
+ import type { IntegrationsRegistry, ServerContext } from '@tbox.cn/app-sdk/server';
13
+ import { createServerContext, createEngineFromContext, registerServerModules } from '@tbox.cn/app-sdk/server';
14
+ import type { MallInfo, MallInfoPort } from '@tbox.cn/app-contracts-mall';
15
+ import { serverModule } from '../src/server/index.js';
16
+ import { preTools } from '../src/server/pre-tools.js';
17
+ import { mallInfoTool, bindMallInfoContext } from '../src/server/mall-info-tool.js';
18
+
19
+ // ── fixture ──────────────────────────────────────────────
20
+
21
+ interface FakeRegistry {
22
+ service?: MallInfoPort;
23
+ error?: boolean;
24
+ calls: number;
25
+ lastInput?: { service?: string; scope?: Record<string, string> };
26
+ }
27
+
28
+ function fakeRegistry(fake: FakeRegistry): IntegrationsRegistry {
29
+ return {
30
+ async resolveService(input: { service?: string; scope?: Record<string, string> }) {
31
+ fake.calls += 1;
32
+ fake.lastInput = input;
33
+ if (fake.error) throw new Error('槽未装配');
34
+ if (!fake.service) return null;
35
+ return fake.service;
36
+ },
37
+ } as unknown as IntegrationsRegistry;
38
+ }
39
+
40
+ /** 绑定 fake ctx(bindMallInfoContext 直调——单测不经完整注册面) */
41
+ function bindRegistry(reg: IntegrationsRegistry | undefined): void {
42
+ bindMallInfoContext(reg ? ({ integrations: reg } as ServerContext) : undefined);
43
+ }
44
+
45
+ let seq = 0;
46
+ const freshMallId = () => `mi${Date.now()}_${++seq}`;
47
+
48
+ const INFO: MallInfo = { mallId: 'x', name: '示例广场', address: '示例路 1 号', latitude: 30.0, longitude: 120.0 };
49
+
50
+ const preToolOf = (id: string) => {
51
+ const def = preTools[id as keyof typeof preTools];
52
+ if (!def) throw new Error(`preTool ${id} 未声明`);
53
+ return def;
54
+ };
55
+
56
+ // ── execute ──────────────────────────────────────────────
57
+
58
+ /** 直调 helper:inputSchema 必填 mallId 的类型面在这里放宽(空串/缺席是本次被测分支) */
59
+ const callExecute = (input: { mallId?: string }) =>
60
+ mallInfoTool.execute!(input as never, {} as never) as Promise<Record<string, unknown>>;
61
+
62
+ describe('mallInfoTool.execute(槽位轴 + fail-soft)', () => {
63
+ it('found:true → 五字段投影(service=mall.info + scope.mallId 透传)', async () => {
64
+ const mallId = freshMallId();
65
+ const fake: FakeRegistry = {
66
+ calls: 0,
67
+ service: { getMallInfo: async (id) => ({ ...INFO, mallId: id }) },
68
+ };
69
+ bindRegistry(fakeRegistry(fake));
70
+ const r = await callExecute({ mallId });
71
+ expect(r).toMatchObject({ found: true, mallId, name: '示例广场', address: '示例路 1 号', latitude: 30.0, longitude: 120.0 });
72
+ expect(fake.lastInput?.service).toBe('mall.info');
73
+ expect(fake.lastInput?.scope).toEqual({ mallId });
74
+ });
75
+
76
+ it('槽 fail-soft(getMallInfo → undefined)→ found:false + reason', async () => {
77
+ bindRegistry(fakeRegistry({ calls: 0, service: { getMallInfo: async () => undefined } }));
78
+ const r = await callExecute({ mallId: freshMallId() });
79
+ expect(r['found']).toBe(false);
80
+ expect(typeof r['reason']).toBe('string');
81
+ });
82
+
83
+ it('无 integrations(裸 ctx)→ found:false 不抛', async () => {
84
+ bindRegistry(undefined);
85
+ const r = await callExecute({ mallId: freshMallId() });
86
+ expect(r['found']).toBe(false);
87
+ });
88
+
89
+ it('mallId 空串/纯空白 → found:false + reason(零槽调用);缺席 → mastra schema 校验错误', async () => {
90
+ const fake: FakeRegistry = { calls: 0, service: { getMallInfo: async () => INFO } };
91
+ bindRegistry(fakeRegistry(fake));
92
+ // schema 合法但语义为空 → 工具内 found:false 分支
93
+ for (const input of [{ mallId: '' }, { mallId: ' ' }]) {
94
+ const r = await callExecute(input);
95
+ expect(r['found']).toBe(false);
96
+ }
97
+ // 必填缺席 → mastra 直调校验错误对象(工具函数不执行)
98
+ const invalid = await callExecute({});
99
+ expect(invalid['error']).toBe(true);
100
+ expect(fake.calls).toBe(0);
101
+ });
102
+ });
103
+
104
+ // ── preTool decide / dedup ───────────────────────────────
105
+
106
+ describe('mall-info preTool 声明(always + mallId 入参化 + dedup)', () => {
107
+ const def = preToolOf('mall-info');
108
+
109
+ it('attributes 含 mall scope → run + args.mallId(入参化)', async () => {
110
+ const r = await def.decide({
111
+ text: '你好',
112
+ history: [],
113
+ attributes: { mall: { mallId: 'm-1', miniAppId: 'app-1' } },
114
+ });
115
+ expect(r).toEqual({ decision: 'run', args: { mallId: 'm-1' } });
116
+ });
117
+
118
+ it('无 mall scope / attributes 缺席 → skip(不抛)', async () => {
119
+ for (const attributes of [undefined, {}, { mall: { miniAppId: 'app-1' } }]) {
120
+ const r = await def.decide({ text: '你好', history: [], ...(attributes ? { attributes } : {}) });
121
+ expect(r).toMatchObject({ decision: 'skip' });
122
+ }
123
+ });
124
+
125
+ it('routing = always(每轮候选)', () => {
126
+ expect(def.routing).toEqual({ mode: 'always' });
127
+ });
128
+
129
+ it('dedup.accepts:found:true → true;found:false/坏形状 → false(防钉死)', () => {
130
+ const accepts = def.dedup?.accepts as (r: unknown) => boolean;
131
+ expect(accepts({ found: true, mallId: 'm', name: 'n' })).toBe(true);
132
+ expect(accepts({ found: false, reason: 'x' })).toBe(false);
133
+ expect(accepts({})).toBe(false);
134
+ expect(accepts(null)).toBe(false);
135
+ });
136
+
137
+ it('silent 声明在场', () => {
138
+ expect(def.silent).toBe(true);
139
+ });
140
+ });
141
+
142
+ // ── 引擎级装配链路 ────────────────────────────────────────
143
+
144
+ describe('mall-info 引擎装配(registerServerModules 声明式 preTools)', () => {
145
+ it('createEngineFromContext 后 listPreTools 含 mall-info(实例一致性全链)', async () => {
146
+ const ctx = createServerContext();
147
+ await registerServerModules(ctx, [serverModule] as never);
148
+ const engine = await createEngineFromContext(ctx, {
149
+ instructions: 'test',
150
+ model: {} as never,
151
+ loadPlugins: async () => ({ tools: {}, references: [] }),
152
+ });
153
+ const ids = engine.listPreTools().map((d) => d.toolId);
154
+ expect(ids).toContain('mall-info');
155
+ expect(Object.keys(ctx.tools.getAll())).toContain('mall-info');
156
+ });
157
+ });
@@ -0,0 +1,71 @@
1
+ /**
2
+ * withMallName 三级回退(自 mall 模板 tests/mall-name.test.ts 迁入——W3-1;
3
+ * 实现真源 = contracts-mall assembly.ts,本模块 buildScopeWithMallName 消费单源)。
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+ import { createMallRuntimeAssembly, withMallName } from '@tbox.cn/app-contracts-mall';
7
+
8
+ const controlPlane = {
9
+ malls: [{ mallId: 'mall-demo', name: '示例商场' }],
10
+ providerInstances: [],
11
+ };
12
+
13
+ describe('withMallName(014 T1:buildScope 回显 mallName——ChatHeader 品牌区服务端真源)', () => {
14
+ it('mallId 命中白名单 → scope 含 mallName', () => {
15
+ const build = withMallName(createMallRuntimeAssembly(controlPlane), controlPlane);
16
+ expect(build({ mall: { miniAppId: 'wx', mallId: 'mall-demo' } })).toEqual({
17
+ miniAppId: 'wx',
18
+ mallId: 'mall-demo',
19
+ mallName: '示例商场',
20
+ });
21
+ });
22
+
23
+ it('mallId 不在白名单 → scope 原样(validateScope 前置拒绝,此处防御兜底)', () => {
24
+ const build = withMallName(createMallRuntimeAssembly(controlPlane), controlPlane);
25
+ expect(build({ mall: { miniAppId: 'wx', mallId: 'other-mall' } })).toEqual({
26
+ miniAppId: 'wx',
27
+ mallId: 'other-mall',
28
+ });
29
+ });
30
+
31
+ it('无 mall scope → 空对象(装配器原语义)', () => {
32
+ const build = withMallName(createMallRuntimeAssembly(controlPlane), controlPlane);
33
+ expect(build({})).toEqual({});
34
+ });
35
+ });
36
+
37
+ describe('withMallName 三级回退(动态商场 D2:fallbackName 缓存通道)', () => {
38
+ it('malls 未命中 + fallbackName 有值 → scope 含回退 mallName', () => {
39
+ const build = withMallName(
40
+ createMallRuntimeAssembly(controlPlane),
41
+ controlPlane,
42
+ (mallId) => (mallId === '1105288' ? '动态商场名' : undefined),
43
+ );
44
+ expect(build({ mall: { miniAppId: 'wx', mallId: '1105288' } })).toEqual({
45
+ miniAppId: 'wx',
46
+ mallId: '1105288',
47
+ mallName: '动态商场名',
48
+ });
49
+ });
50
+
51
+ it('malls 命中 → malls.name 优先(fallbackName 不覆盖)', () => {
52
+ const build = withMallName(
53
+ createMallRuntimeAssembly(controlPlane),
54
+ controlPlane,
55
+ () => '不应被用',
56
+ );
57
+ expect(build({ mall: { miniAppId: 'wx', mallId: 'mall-demo' } })).toEqual({
58
+ miniAppId: 'wx',
59
+ mallId: 'mall-demo',
60
+ mallName: '示例商场',
61
+ });
62
+ });
63
+
64
+ it('双 miss → scope 原样(无 mallName 键,降级)', () => {
65
+ const build = withMallName(createMallRuntimeAssembly(controlPlane), controlPlane, () => undefined);
66
+ expect(build({ mall: { miniAppId: 'wx', mallId: 'other-mall' } })).toEqual({
67
+ miniAppId: 'wx',
68
+ mallId: 'other-mall',
69
+ });
70
+ });
71
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "types": ["node"]
5
+ },
6
+ "include": ["src", "tests"]
7
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,18 @@
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
+ },
8
+ format: ['esm'],
9
+ target: 'node20',
10
+ platform: 'node',
11
+ outDir: 'dist',
12
+ clean: true,
13
+ sourcemap: false,
14
+ // dts worker 以命令行式传参会撞 TS5074(incremental 需单文件 emit 或 tsBuildInfoFile);
15
+ // 声明产物一次性构建无需增量——仅 dts 关闭,typecheck 的增量缓存不受影响。
16
+ dts: { compilerOptions: { incremental: false } },
17
+ external: ['@tbox.cn/app-sdk', '@tbox.cn/app-contracts', '@tbox.cn/app-contracts-mall', 'zod'],
18
+ });