@tbox.cn/app-provider-mock 0.2.0 → 0.4.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,92 @@
1
+ /**
2
+ * config schema 双锁(供给面 ↔ 消费面一致性):
3
+ * ① 键集双向锁(schema.properties ≡ DEFAULTS——死字段/漏字段一次全拦)
4
+ * ② default 漂移锁(schema 表单缺省 ≡ 实现缺省——面板不改动时的运行时真值)
5
+ * ③ 整数对偶锁(schema type:'integer' ⟺ INT_KEYS——消费点整数守卫与表单引导同源)
6
+ * ④ manifest 分发面锁(17 槽 configSchema 引用齐全 + 文件随包存在 + 槽→域文件映射)
7
+ * ⑤ 楼层白名单同值锁(shopping enum ≡ SHOPPING_FLOORS——消费点守卫与引导同源)
8
+ */
9
+ import { describe, expect, it } from 'vitest';
10
+ import { existsSync, readFileSync } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { MEMBER_CFG_DEFAULTS, MEMBER_CFG_INT_KEYS } from '../src/server/member';
14
+ import { PARKING_CFG_DEFAULTS, PARKING_CFG_INT_KEYS } from '../src/server/parking';
15
+ import { PROMOTION_CFG_DEFAULTS, PROMOTION_CFG_INT_KEYS } from '../src/server/promotion';
16
+ import { SHOPPING_CFG_DEFAULTS, SHOPPING_CFG_INT_KEYS, SHOPPING_FLOORS } from '../src/server/shopping';
17
+ import { MALL_INFO_CFG_DEFAULTS, MALL_INFO_CFG_INT_KEYS } from '../src/server/mall-info';
18
+
19
+ const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
+
21
+ interface SchemaProperty { type?: string; default?: unknown; enum?: readonly string[] }
22
+ interface SchemaFile { properties: Record<string, SchemaProperty> }
23
+
24
+ interface DomainCase {
25
+ name: string;
26
+ file: string;
27
+ defaults: Readonly<Record<string, string | number | boolean>>;
28
+ intKeys: readonly string[];
29
+ }
30
+
31
+ const DOMAINS: readonly DomainCase[] = [
32
+ { name: 'member', file: 'member.config.json', defaults: MEMBER_CFG_DEFAULTS, intKeys: MEMBER_CFG_INT_KEYS },
33
+ { name: 'parking', file: 'parking.config.json', defaults: PARKING_CFG_DEFAULTS, intKeys: PARKING_CFG_INT_KEYS },
34
+ { name: 'promotion', file: 'promotion.config.json', defaults: PROMOTION_CFG_DEFAULTS, intKeys: PROMOTION_CFG_INT_KEYS },
35
+ { name: 'shopping', file: 'shopping.config.json', defaults: SHOPPING_CFG_DEFAULTS, intKeys: SHOPPING_CFG_INT_KEYS },
36
+ { name: 'mall-info', file: 'mall-info.config.json', defaults: MALL_INFO_CFG_DEFAULTS, intKeys: MALL_INFO_CFG_INT_KEYS },
37
+ ];
38
+
39
+ const readSchema = (file: string): SchemaFile =>
40
+ JSON.parse(readFileSync(path.join(pkgRoot, 'schemas', file), 'utf8')) as SchemaFile;
41
+
42
+ describe('provider-mock:config schema 双锁(供给面 ≡ 消费面)', () => {
43
+ it('① 键集双向锁:schema.properties ≡ DEFAULTS 键集', () => {
44
+ for (const d of DOMAINS) {
45
+ const schema = readSchema(d.file);
46
+ expect(Object.keys(schema.properties).sort(), `${d.name} 键集`).toEqual(Object.keys(d.defaults).sort());
47
+ }
48
+ });
49
+
50
+ it('② default 漂移锁:schema 缺省 ≡ 实现缺省', () => {
51
+ for (const d of DOMAINS) {
52
+ const schema = readSchema(d.file);
53
+ for (const [key, value] of Object.entries(d.defaults)) {
54
+ expect(schema.properties[key]?.default, `${d.name}.${key} default 漂移`).toEqual(value);
55
+ }
56
+ }
57
+ });
58
+
59
+ it('③ 整数对偶锁:schema type=integer ⟺ INT_KEYS(分式字段不得入 intKeys)', () => {
60
+ for (const d of DOMAINS) {
61
+ const schema = readSchema(d.file);
62
+ for (const [key, prop] of Object.entries(schema.properties)) {
63
+ expect(prop.type === 'integer', `${d.name}.${key} 整数对偶`).toBe(d.intKeys.includes(key));
64
+ }
65
+ }
66
+ });
67
+
68
+ it('④ manifest 分发面锁:17 槽引用齐全 + 槽→域映射 + 文件随包', () => {
69
+ const manifest = JSON.parse(readFileSync(path.join(pkgRoot, 'tbox.module.json'), 'utf8')) as {
70
+ contributes: { providers: { slots: Array<{ service: string; configSchema?: string }> } };
71
+ };
72
+ const slots = manifest.contributes.providers.slots;
73
+ expect(slots).toHaveLength(17);
74
+ const fileOfPrefix: Record<string, string> = {
75
+ member: 'member.config.json',
76
+ parking: 'parking.config.json',
77
+ promotion: 'promotion.config.json',
78
+ 'shopping-guide': 'shopping.config.json',
79
+ mall: 'mall-info.config.json',
80
+ };
81
+ for (const slot of slots) {
82
+ const prefix = slot.service.slice(0, slot.service.indexOf('.'));
83
+ expect(slot.configSchema, `${slot.service} configSchema 缺失`).toBe(`schemas/${fileOfPrefix[prefix]}`);
84
+ expect(existsSync(path.join(pkgRoot, slot.configSchema!)), `${slot.service} schema 文件不存在`).toBe(true);
85
+ }
86
+ });
87
+
88
+ it('⑤ 楼层 enum ≡ SHOPPING_FLOORS(消费点守卫与表单引导同源)', () => {
89
+ const schema = readSchema('shopping.config.json');
90
+ expect(schema.properties.extraShopFloor?.enum).toEqual([...SHOPPING_FLOORS]);
91
+ });
92
+ });
@@ -6,7 +6,8 @@
6
6
  */
7
7
  import { beforeEach, describe, expect, it } from 'vitest';
8
8
  import { createIntegrationsRegistry, createAuthStrategyRegistry, createEnvironmentSecretProvider, createServerContext } from '@tbox.cn/app-sdk/server';
9
- import { serverModule, MOCK_SHELL_USER_ID, enrollMockMember, logoutMockMember, __resetMockMemberState } from '../src/server/index';
9
+ import { serverModule, enrollMockMember, logoutMockMember, __resetMockMemberState } from '../src/server/index';
10
+ import { mallControlPlaneOf } from '@tbox.cn/app-contracts-mall/server';
10
11
  import type { IntegrationsConfig } from '@tbox.cn/app-contracts';
11
12
  import type { RequestContext } from '@tbox.cn/app-contracts';
12
13
 
@@ -48,15 +49,15 @@ const catalog = {
48
49
 
49
50
  function requestContext(mallId = 'mall-demo'): RequestContext {
50
51
  return {
51
- identity: { userId: 'u_1', source: 'dev' },
52
- credentials: { provider: 'dev', token: 't' },
52
+ identity: { userId: 'local_u1', source: 'local' },
53
+ credentials: { provider: 'mock', token: 't' },
53
54
  attributes: { mall: { mallId } },
54
55
  };
55
56
  }
56
57
 
57
- function fixtureCtx() {
58
+ function fixtureCtx(integrationsOverride?: IntegrationsConfig) {
58
59
  const registry = createIntegrationsRegistry({
59
- integrations,
60
+ integrations: integrationsOverride ?? integrations,
60
61
  catalog,
61
62
  authStrategies: createAuthStrategyRegistry(),
62
63
  secretProvider: createEnvironmentSecretProvider({ source: {}, production: false }),
@@ -168,52 +169,185 @@ describe('C5:scoped mock 换码器(入会闭环身份供给)', () => {
168
169
  it('未选择商场(无 mallId)→ exchangeByCode 抛 AUTH_NOT_CONFIGURED 未选择商场', async () => {
169
170
  const { ctx } = fixtureCtx();
170
171
  const exchanger = ctx.authExchanges.get('alipay')!;
171
- await expect(exchanger.exchangeByCode('any-authcode', 'alipay')).rejects.toThrow(/未选择商场/);
172
+ await expect(exchanger.exchangeByCode({ code: 'any-authcode' })).rejects.toThrow(/未选择商场/);
172
173
  });
173
174
 
174
- it('GUEST 形态(对齐真实档潜客分支):token="" + openid 身份——合法登录未入会', async () => {
175
+ it('随机访客身份 + GUEST 形态(T17):guest_<32hex> 每次新随机;token="" + openid 键控', async () => {
175
176
  const { ctx } = fixtureCtx();
176
177
  const exchanger = ctx.authExchanges.get('alipay', { mall: { mallId: 'mall-demo' } })!;
177
- const result = await exchanger.exchangeByCode('any-authcode', 'alipay', { mall: { mallId: 'mall-demo' } });
178
- expect(result).toEqual({
179
- identity: { userId: 'demo-user', source: 'external' },
180
- credentials: { token: '', provider: 'mock', attributes: { openid: 'demo:openid:demo-user' } },
181
- });
178
+ const r1 = await exchanger.exchangeByCode({ code: 'c1', context: { mall: { mallId: 'mall-demo' } } });
179
+ expect(r1.identity.source).toBe('guest');
180
+ expect(r1.identity.userId).toMatch(/^guest_[0-9a-f]{32}$/);
181
+ expect(r1.credentials).toEqual({ token: '', provider: 'mock', attributes: { openid: `demo:openid:${r1.identity.userId}` } });
182
+ // 每次冷登新随机(无 previousIdentity)
183
+ const r2 = await exchanger.exchangeByCode({ code: 'c2', context: { mall: { mallId: 'mall-demo' } } });
184
+ expect(r2.identity.userId).not.toBe(r1.identity.userId);
182
185
  });
183
186
 
184
- it('MEMBER 形态(对齐真实档会员换码输出):入会后冷登 → token + memberId', async () => {
185
- enrollMockMember(MOCK_SHELL_USER_ID);
187
+ it('previousIdentity 复用轨:guest 同 sub 续签(enroll 后 MEMBER 形态、会话归属连续)', async () => {
186
188
  const { ctx } = fixtureCtx();
187
189
  const exchanger = ctx.authExchanges.get('alipay', { mall: { mallId: 'mall-demo' } })!;
188
- const result = await exchanger.exchangeByCode('any-authcode', 'alipay', { mall: { mallId: 'mall-demo' } });
189
- expect(result).toEqual({
190
- identity: { userId: 'demo-user', source: 'external' },
191
- credentials: { token: 'demo:token:demo-user', provider: 'mock', attributes: { memberId: 'demo-user' } },
190
+ const first = await exchanger.exchangeByCode({ code: 'c1', context: { mall: { mallId: 'mall-demo' } } });
191
+ enrollMockMember(first.identity.userId);
192
+ const renewed = await exchanger.exchangeByCode({
193
+ code: 'c2',
194
+ context: { mall: { mallId: 'mall-demo' } },
195
+ previousIdentity: { userId: first.identity.userId, source: 'guest' },
196
+ });
197
+ expect(renewed.identity).toEqual({ userId: first.identity.userId, source: 'guest' });
198
+ expect(renewed.credentials).toEqual({
199
+ token: `demo:token:${first.identity.userId}`,
200
+ provider: 'mock',
201
+ attributes: { memberId: first.identity.userId },
192
202
  });
193
203
  });
194
204
 
195
- it('刻意不实现 devExternalCredentials:dev-login 走协议 fail-soft 无 claim 签发', () => {
205
+ it('声明 allowsGuestLogin(browser 轴 auto 档 → guest 签发)', () => {
196
206
  const { ctx } = fixtureCtx();
197
- const exchanger = ctx.authExchanges.get('alipay', { mall: { mallId: 'mall-demo' } });
198
- // 能力口缺席(typeof 守卫语义——login-routes 同款消费形态)
199
- expect(typeof (exchanger as { devExternalCredentials?: unknown })?.devExternalCredentials).toBe('undefined');
207
+ const exchanger = ctx.authExchanges.get('alipay', { mall: { mallId: 'mall-demo' } })!;
208
+ expect(typeof (exchanger as { allowsGuestLogin?: unknown }).allowsGuestLogin).toBe('function');
209
+ expect((exchanger as { allowsGuestLogin: () => boolean }).allowsGuestLogin()).toBe(true);
200
210
  });
201
211
 
202
212
  it('登出态换码降级 GUEST 形态(对齐真实档 silentLogin 非 200 → 访客结果,2026-09-02 真机实测)', async () => {
203
- enrollMockMember(MOCK_SHELL_USER_ID);
204
- logoutMockMember(MOCK_SHELL_USER_ID);
205
213
  const { ctx } = fixtureCtx();
206
214
  const exchanger = ctx.authExchanges.get('alipay', { mall: { mallId: 'mall-demo' } })!;
207
- const degraded = await exchanger.exchangeByCode('any-authcode', 'alipay', { mall: { mallId: 'mall-demo' } });
208
- expect(degraded.identity).toEqual({ userId: MOCK_SHELL_USER_ID, source: 'external' });
215
+ const first = await exchanger.exchangeByCode({ code: 'c1', context: { mall: { mallId: 'mall-demo' } } });
216
+ const userId = first.identity.userId;
217
+ enrollMockMember(userId);
218
+ logoutMockMember(userId);
219
+ const degraded = await exchanger.exchangeByCode({
220
+ code: 'c2',
221
+ context: { mall: { mallId: 'mall-demo' } },
222
+ previousIdentity: { userId, source: 'guest' },
223
+ });
224
+ expect(degraded.identity).toEqual({ userId, source: 'guest' });
209
225
  expect(degraded.credentials).toEqual({
210
226
  token: '',
211
227
  provider: 'mock',
212
- attributes: { openid: 'demo:openid:demo-user' },
228
+ attributes: { openid: `demo:openid:${userId}` },
213
229
  });
214
230
  // 重登录(enroll 清登出态)后恢复 MEMBER 形态——H5 半屏成功登录后冷登即恢复
215
- enrollMockMember(MOCK_SHELL_USER_ID);
216
- const result = await exchanger.exchangeByCode('any-authcode', 'alipay', { mall: { mallId: 'mall-demo' } });
217
- expect(result.credentials?.token).toBe('demo:token:demo-user');
231
+ enrollMockMember(userId);
232
+ const result = await exchanger.exchangeByCode({
233
+ code: 'c3',
234
+ context: { mall: { mallId: 'mall-demo' } },
235
+ previousIdentity: { userId, source: 'guest' },
236
+ });
237
+ expect(result.credentials?.token).toBe(`demo:token:${userId}`);
238
+ });
239
+ });
240
+
241
+ describe('F2 端到端:config 级联(resolveService 全链——五层浅合并消费)', () => {
242
+ it('槽级 config 流入:parking.query.config.feeCents=200 → 报价同源', async () => {
243
+ const override: IntegrationsConfig = {
244
+ ...integrations,
245
+ services: {
246
+ ...integrations.services,
247
+ 'parking.query': { ...integrations.services['parking.query'], config: { feeCents: 200 } },
248
+ },
249
+ };
250
+ const { ctx } = fixtureCtx(override);
251
+ const parking = (await ctx.integrations!.resolveService({
252
+ service: 'parking.query',
253
+ scope: { mallId: 'mall-demo' },
254
+ request: requestContext(),
255
+ })) as { queryFee(q: unknown, input: { plateNo: string }): Promise<Array<{ totalCents: number; payableCents: number }>> };
256
+ const quotes = await parking.queryFee({ scope: {} } as never, { plateNo: 'demo-plate' });
257
+ expect(quotes[0]?.totalCents).toBe(200);
258
+ expect(quotes[0]?.payableCents).toBe(200);
259
+ });
260
+
261
+ it('root config 级联:根 config.cardName → member 槽实例同源', async () => {
262
+ const override: IntegrationsConfig = { ...integrations, config: { cardName: 'Root 卡' } };
263
+ const { ctx } = fixtureCtx(override);
264
+ const member = (await ctx.integrations!.resolveService({
265
+ service: 'member.account',
266
+ scope: { mallId: 'mall-demo' },
267
+ request: requestContext(),
268
+ })) as { queryPoints(u: string): Promise<{ membershipLabel: string }> };
269
+ await expect(member.queryPoints('u1')).resolves.toMatchObject({ membershipLabel: 'Root 卡' });
270
+ });
271
+
272
+ it('浅合并键级覆盖:root 共享键 + slot 差异键并行生效(面板分层配置语义)', async () => {
273
+ const override: IntegrationsConfig = {
274
+ ...integrations,
275
+ config: { parkName: 'RootP' },
276
+ services: {
277
+ ...integrations.services,
278
+ 'parking.query': { ...integrations.services['parking.query'], config: { feeCents: 200 } },
279
+ },
280
+ };
281
+ const { ctx } = fixtureCtx(override);
282
+ const parking = (await ctx.integrations!.resolveService({
283
+ service: 'parking.query',
284
+ scope: { mallId: 'mall-demo' },
285
+ request: requestContext(),
286
+ })) as {
287
+ queryFee(q: unknown, input: { plateNo: string }): Promise<Array<{ totalCents: number }>>;
288
+ queryParkingInfo(q: unknown, kind: string): Promise<{ title: string }>;
289
+ };
290
+ const quotes = await parking.queryFee({ scope: {} } as never, { plateNo: 'demo-plate' });
291
+ expect(quotes[0]?.totalCents).toBe(200); // slot 差异键
292
+ const info = await parking.queryParkingInfo({ scope: {} } as never, 'chargeRules');
293
+ expect(info.title).toBe('RootP'); // root 共享键
294
+ });
295
+
296
+ it('domain 层级联 + slot 胜 domain:域级键流入 + 槽级同名键覆盖(键级层序)', async () => {
297
+ const override: IntegrationsConfig = {
298
+ ...integrations,
299
+ domains: { parking: { config: { parkName: 'DomainP', remainingSpaces: 99 } } },
300
+ services: {
301
+ ...integrations.services,
302
+ 'parking.query': { ...integrations.services['parking.query'], config: { feeCents: 250, parkName: 'SlotP' } },
303
+ },
304
+ };
305
+ const { ctx } = fixtureCtx(override);
306
+ const parking = (await ctx.integrations!.resolveService({
307
+ service: 'parking.query',
308
+ scope: { mallId: 'mall-demo' },
309
+ request: requestContext(),
310
+ })) as {
311
+ queryFee(q: unknown, input: { plateNo: string }): Promise<Array<{ totalCents: number }>>;
312
+ queryParkingInfo(q: unknown, kind: string): Promise<{ title: string; entries: Array<{ label: string; value: string }> }>;
313
+ };
314
+ const quotes = await parking.queryFee({ scope: {} } as never, { plateNo: 'demo-plate' });
315
+ expect(quotes[0]?.totalCents).toBe(250); // 槽级差异键
316
+ const info = await parking.queryParkingInfo({ scope: {} } as never, 'chargeRules');
317
+ expect(info.title).toBe('SlotP'); // slot 胜 domain(同名键)
318
+ expect(info.entries).toContainEqual({ label: '剩余车位', value: '99' }); // 域级键流入(槽未覆盖)
319
+ });
320
+ });
321
+
322
+ // ── 隐式默认单实例声明(零拓扑兜底——provider-mock declareProviderInstances) ──
323
+
324
+ describe('隐式默认单实例声明(零拓扑兜底)', () => {
325
+ it('register → 声明快照三键断言(id/name/attributes.miniAppId)', () => {
326
+ const { registry } = fixtureCtx();
327
+ expect(registry.providerInstanceDeclarations()['mock']).toEqual([
328
+ { id: 'mall-demo', name: '星河 Mock 小镇', attributes: { miniAppId: 'mock-demo-app' } },
329
+ ]);
330
+ });
331
+
332
+ it('零拓扑 config + 声明 → mallControlPlaneOf 融合产出 mall-demo', () => {
333
+ const { registry } = fixtureCtx();
334
+ const cp = mallControlPlaneOf(
335
+ { provider: 'mock', services: {} },
336
+ registry.providerInstanceDeclarations(),
337
+ );
338
+ expect(cp.malls).toEqual([
339
+ { mallId: 'mall-demo', name: '星河 Mock 小镇', miniAppId: 'mock-demo-app' },
340
+ ]);
341
+ expect(cp.defaultMallId).toBe('mall-demo');
342
+ });
343
+
344
+ it('异构形态(无 root.provider 逐槽绑定)→ 不融合(边界锁定)', () => {
345
+ const { registry } = fixtureCtx();
346
+ const cp = mallControlPlaneOf(
347
+ { services: { 'parking.query': { provider: 'mock', implementation: 'mock-parking@1' } } },
348
+ registry.providerInstanceDeclarations(),
349
+ );
350
+ expect(cp.malls).toEqual([]);
351
+ expect(cp.defaultMallId).toBeUndefined();
218
352
  });
219
353
  });
@@ -6,12 +6,12 @@
6
6
  import { describe, expect, it } from 'vitest';
7
7
  import { mockMallInfoFactory, MOCK_MALL_INFO_PROVIDER, MOCK_MALL_INFO_IMPL } from '../src/server/mall-info';
8
8
 
9
- function makePort() {
9
+ function makePort(config: unknown = {}) {
10
10
  return mockMallInfoFactory({
11
11
  provider: MOCK_MALL_INFO_PROVIDER,
12
12
  implementation: MOCK_MALL_INFO_IMPL,
13
13
  instanceId: '',
14
- config: {},
14
+ config,
15
15
  logger: { info: () => undefined, warn: () => undefined, error: () => undefined },
16
16
  service: 'mall.info',
17
17
  } as never) as { getMallInfo(mallId: string): Promise<{ mallId: string; name: string } | undefined> };
@@ -44,4 +44,13 @@ describe('mockMallInfoFactory:请求形状守卫', () => {
44
44
  expect(MOCK_MALL_INFO_PROVIDER).toBe('mock');
45
45
  expect(MOCK_MALL_INFO_IMPL).toBe('mock-mall-info@1');
46
46
  });
47
+
48
+ it('config 驱动:name 直出 / 空串回退动态别名 / 分式经纬度合法', async () => {
49
+ const named = makePort({ name: '星河 Mock 小镇' });
50
+ await expect(named.getMallInfo('1102588')).resolves.toMatchObject({ name: '星河 Mock 小镇' });
51
+ const fallback = makePort({ name: '', latitude: 31.2304 });
52
+ const info = await fallback.getMallInfo('1102588');
53
+ expect(info?.name).toBe('示例商场(1102588)');
54
+ expect((info as { latitude?: number })?.latitude).toBe(31.2304);
55
+ });
47
56
  });
@@ -281,20 +281,20 @@ describe('provider-mock:入会闭环共享 store(C5)', () => {
281
281
 
282
282
  describe('provider-mock:mock 入会落地路由(resolveMockEnroll 纯决策)', () => {
283
283
 
284
- it('有身份 + 无参 → 缺省 demo-user 翻状态返 200', () => {
285
- const outcome = resolveMockEnroll({ body: {}, identity: { source: 'dev' } });
286
- expect(outcome).toEqual({ status: 200, body: { state: 'active', memberRef: 'demo:member:demo-user' } });
287
- expect(isMockMemberEnrolled('demo-user')).toBe(true);
284
+ it('有身份 + 无参 → 缺省调用方身份翻状态返 200(T11 收口:固定 demo-user 缺省退役)', () => {
285
+ const outcome = resolveMockEnroll({ body: {}, identity: { source: 'guest', userId: 'guest_a1' } });
286
+ expect(outcome).toEqual({ status: 200, body: { state: 'active', memberRef: 'demo:member:guest_a1' } });
287
+ expect(isMockMemberEnrolled('guest_a1')).toBe(true);
288
288
  });
289
289
 
290
- it('定向 userId(curl 翻浏览器 dev 用户)', () => {
291
- const outcome = resolveMockEnroll({ body: { userId: 'dev_h5' }, identity: { source: 'dev' } });
292
- expect(outcome).toEqual({ status: 200, body: { state: 'active', memberRef: 'demo:member:dev_h5' } });
293
- expect(isMockMemberEnrolled('dev_h5')).toBe(true);
290
+ it('定向 userId(gate 页经 query 透传 H5 身份 / curl 调试声明主体)', () => {
291
+ const outcome = resolveMockEnroll({ body: { userId: 'guest_h5' }, identity: { source: 'guest', userId: 'guest_caller' } });
292
+ expect(outcome).toEqual({ status: 200, body: { state: 'active', memberRef: 'demo:member:guest_h5' } });
293
+ expect(isMockMemberEnrolled('guest_h5')).toBe(true);
294
294
  });
295
295
 
296
296
  it('幂等:同 userId 两次均 200', () => {
297
- const identity = { source: 'dev' as const };
297
+ const identity = { source: 'local' as const };
298
298
  expect(resolveMockEnroll({ body: {}, identity }).status).toBe(200);
299
299
  expect(resolveMockEnroll({ body: {}, identity }).status).toBe(200);
300
300
  });
@@ -306,29 +306,29 @@ describe('provider-mock:mock 入会落地路由(resolveMockEnroll 纯决策
306
306
  });
307
307
 
308
308
  it('NODE_ENV=production → 503(mock 不进生产装配,双保险)', () => {
309
- expect(resolveMockEnroll({ body: {}, identity: { source: 'dev' }, nodeEnv: 'production' }).status).toBe(503);
309
+ expect(resolveMockEnroll({ body: {}, identity: { source: 'local' }, nodeEnv: 'production' }).status).toBe(503);
310
310
  expect(isMockMemberEnrolled('demo-user')).toBe(false);
311
311
  });
312
312
  });
313
313
 
314
314
  describe('provider-mock:登出态(logout 路由 + 换码降级 GUEST 形态 + getAccount 感知)', () => {
315
- it('resolveMockLogout:有身份 → 200 翻登出态;enroll 清除登出态', () => {
315
+ it('resolveMockLogout:有身份 → 200 翻登出态(缺省调用方);enroll 清除登出态', () => {
316
316
  __resetMockMemberState();
317
- enrollMockMember('demo-user');
318
- expect(isMockMemberLoggedOut('demo-user')).toBe(false);
319
- const outcome = resolveMockLogout({ body: {}, identity: { source: 'dev' } });
317
+ enrollMockMember('guest_a1');
318
+ expect(isMockMemberLoggedOut('guest_a1')).toBe(false);
319
+ const outcome = resolveMockLogout({ body: {}, identity: { source: 'guest', userId: 'guest_a1' } });
320
320
  expect(outcome).toEqual({ status: 200, body: { state: 'logged_out' } });
321
- expect(isMockMemberLoggedOut('demo-user')).toBe(true);
321
+ expect(isMockMemberLoggedOut('guest_a1')).toBe(true);
322
322
  // 重登录(enroll)清除登出态——与真实链同构(gate 页登录成功后厂商侧登录态恢复)
323
- enrollMockMember('demo-user');
324
- expect(isMockMemberLoggedOut('demo-user')).toBe(false);
323
+ enrollMockMember('guest_a1');
324
+ expect(isMockMemberLoggedOut('guest_a1')).toBe(false);
325
325
  });
326
326
 
327
327
  it('resolveMockLogout:匿名/无身份 → 401;production → 503(与 enroll 同形)', () => {
328
328
  __resetMockMemberState();
329
329
  expect(resolveMockLogout({ body: {}, identity: null }).status).toBe(401);
330
330
  expect(resolveMockLogout({ body: {}, identity: { source: 'anonymous' } }).status).toBe(401);
331
- expect(resolveMockLogout({ body: {}, identity: { source: 'dev' }, nodeEnv: 'production' }).status).toBe(503);
331
+ expect(resolveMockLogout({ body: {}, identity: { source: 'local' }, nodeEnv: 'production' }).status).toBe(503);
332
332
  expect(isMockMemberLoggedOut('demo-user')).toBe(false);
333
333
  });
334
334
 
@@ -346,3 +346,106 @@ describe('provider-mock:登出态(logout 路由 + 换码降级 GUEST 形态
346
346
  await expect(member.getAccount(MOCK_SHELL_USER_ID)).resolves.toMatchObject({ state: 'active' });
347
347
  });
348
348
  });
349
+
350
+ describe('provider-mock:config 驱动(fail-soft 快照)', () => {
351
+ const enroll = (member: MockMemberServiceImpl, userId: string) =>
352
+ member.enroll({ userId, identity: 'enrollment_submission', fieldValues: {}, acceptedConsentIds: [], idempotencyKey: `k-${userId}` });
353
+
354
+ it('member 全字段:卡名/初值积分/等级/名称/深链/流水同源', async () => {
355
+ const member = new MockMemberServiceImpl({}, { cardName: '黑金卡', initialPoints: 800, levelName: '金卡', memberName: '张三' });
356
+ await enroll(member, 'u1');
357
+ await expect(member.getCard('u1')).resolves.toMatchObject({ cardDisplay: '黑金卡', levelName: '金卡' });
358
+ await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 800, membershipLabel: '黑金卡' });
359
+ await expect(member.getProfile('u1')).resolves.toMatchObject({ labels: [{ labelRef: 'demo:label:1', name: '张三' }] });
360
+ const usage = await member.listPointUsage('u1', 1, 10);
361
+ expect(usage.items[0].amount).toBe('+800');
362
+ });
363
+
364
+ it('member 非法值回退缺省:类型族/空串/NaN/分式整数(intKeys)', async () => {
365
+ const member = new MockMemberServiceImpl({}, { initialPoints: 'x', cardName: '', enrollUrl: '', levelName: '' });
366
+ await enroll(member, 'u1');
367
+ await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 300, membershipLabel: '示例会员卡' });
368
+ const card = (await member.getCard('u1'))!;
369
+ expect('levelName' in card).toBe(false);
370
+ expect(member.enrollUrl).toMatch(/^alipays:\/\//);
371
+ const nan = new MockMemberServiceImpl({}, { initialPoints: Number.NaN });
372
+ await enroll(nan, 'u2');
373
+ await expect(nan.queryPoints('u2')).resolves.toMatchObject({ balance: 300 });
374
+ const fractional = new MockMemberServiceImpl({}, { initialPoints: 1500.5 });
375
+ await enroll(fractional, 'u3');
376
+ await expect(fractional.queryPoints('u3')).resolves.toMatchObject({ balance: 300 });
377
+ });
378
+
379
+ it('member 余额惰性读:入会不写种子 + 显式增减单源(queryPoints ≡ getBenefits)', async () => {
380
+ const member = new MockMemberServiceImpl({}, { initialPoints: 500 });
381
+ await expect(member.queryPoints('nobody')).resolves.toMatchObject({ balance: 0 });
382
+ await enroll(member, 'u1');
383
+ await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 500 });
384
+ await expect(member.getBenefits('u1')).resolves.toMatchObject({ availablePoints: 500 });
385
+ await expect(member.deductPoints('u1', 100, 'd1')).resolves.toBe(true);
386
+ await expect(member.deductPoints('u1', 1000, 'd2')).resolves.toBe(false);
387
+ await expect(member.getBenefits('u1')).resolves.toMatchObject({ availablePoints: 400 });
388
+ await expect(member.awardPoints('u1', 50)).resolves.toBe(true);
389
+ await expect(member.refundPoints('u1', 25, 'r1')).resolves.toBe(true);
390
+ await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 475 });
391
+ });
392
+
393
+ it('parking 驱动:费用/权益开关/开票开关/信息/记录/寻车同源', async () => {
394
+ const parking = new MockParkingServiceImpl('mall-demo', {
395
+ feeCents: 200, parkName: 'P2 停车场', memberBenefitEnabled: false, invoiceEnabled: false, remainingSpaces: 56, vehicleSpaceNo: 'C-9',
396
+ });
397
+ const quote = (await parking.queryFee(parkCtx, { plateNo: 'demo-plate' }))[0];
398
+ expect(quote).toMatchObject({ totalCents: 200, payableCents: 200 });
399
+ expect(quote.feeItems[0]).toEqual({ name: '停车费(3 小时)', amountCents: 200 });
400
+ const benefits = await parking.queryApplicableBenefits(parkCtx, 'demo-plate');
401
+ expect(benefits).toHaveLength(1);
402
+ expect(benefits[0].kind).toBe('points');
403
+ await expect(parking.getInvoiceSettings()).resolves.toEqual({ parkingInvoiceEnabled: false });
404
+ const info = await parking.queryParkingInfo(parkCtx, 'chargeRules');
405
+ expect(info.title).toBe('P2 停车场');
406
+ expect(info.entries).toContainEqual({ label: '剩余车位', value: '56' });
407
+ expect(info.entries).toContainEqual({ label: '会员权益', value: '—' });
408
+ await expect(parking.getOrderInfo(parkCtx, 'r')).resolves.toMatchObject({ payableFeeCents: 200 });
409
+ const records = await parking.listPaymentRecords(parkCtx, 1, 10);
410
+ expect(records.items[0]).toMatchObject({ parkName: 'P2 停车场', amountCents: 200 });
411
+ expect((await parking.locateVehicle(parkCtx, 'demo-plate'))?.spaceNo).toBe('C-9');
412
+ });
413
+
414
+ it('promotion 驱动:券标题/面额/门槛 + 团购开关 + 资产/活动派生', async () => {
415
+ const promotion = new MockPromotionServiceImpl({
416
+ couponTitle: '满 200 减 50 元券', couponValueCents: 5000, couponThresholdCents: 20000, couponValidityDays: 7, grouponEnabled: false, activityTitle: '周年庆',
417
+ });
418
+ const page = await promotion.searchOffers(promoCtx, { keyword: '' });
419
+ expect(page.items).toHaveLength(1);
420
+ expect(page.items[0].title).toBe('满 200 减 50 元券');
421
+ expect(page.items[0].facets[0]).toMatchObject({ value: 5000, thresholdCents: 20000 });
422
+ const ents = await promotion.listEntitlements(promoCtx, {});
423
+ expect(ents.items[0].title).toBe('满 200 减 50 元券');
424
+ const acts = await promotion.listActivities();
425
+ expect(acts.items[0].title).toBe('周年庆');
426
+ await expect(promotion.getOfferDetail(promoCtx, { offerRef: 'demo:coupon:1001' })).resolves.toMatchObject({ title: '满 200 减 50 元券' });
427
+ });
428
+
429
+ it('shopping 驱动:追加门店进列表/类目/楼层目录', async () => {
430
+ const impl = new MockShoppingServiceImpl(undefined, {
431
+ extraShopName: '新店', extraShopFloor: '2 楼', extraShopCategory: '文创', extraShopUnit: '203', extraShopOpen: false,
432
+ });
433
+ const page = await impl.searchShops({ ctx: shopCtx, page: 1, pageSize: 20 });
434
+ expect(page.total).toBe(13);
435
+ const extra = page.items.find((s) => s.merchantId === 'demo-shop-1013');
436
+ expect(extra).toMatchObject({ name: '新店', location: { floorName: '2 楼', unitName: '203' }, status: { code: 'disabled', label: '休息中' } });
437
+ const cats = await impl.listCategories(shopCtx);
438
+ expect(cats.find((c) => c.name === '文创')?.merchantCount).toBe(1);
439
+ const dir = await impl.getDirectory(shopCtx);
440
+ expect(dir?.buildings[0].floors.find((f) => f.floorName === '2 楼')?.merchantCount).toBe(3);
441
+ expect((await impl.searchShops({ ctx: shopCtx, page: 1, pageSize: 20, floorCode: '2 楼' })).total).toBe(3);
442
+ });
443
+
444
+ it('shopping 消费点守卫:空白名不追加 + 未知楼层回退 3 楼', async () => {
445
+ const blank = new MockShoppingServiceImpl(undefined, { extraShopName: ' ' });
446
+ expect((await blank.searchShops({ ctx: shopCtx, page: 1, pageSize: 20 })).total).toBe(12);
447
+ const badFloor = new MockShoppingServiceImpl(undefined, { extraShopName: 'X 店', extraShopFloor: '5 楼' });
448
+ const page = await badFloor.searchShops({ ctx: shopCtx, page: 1, pageSize: 20, floorCode: '3 楼' });
449
+ expect(page.items.some((s) => s.merchantId === 'demo-shop-1013')).toBe(true);
450
+ });
451
+ });