@tbox.cn/app-miniapp-container-alipay 0.2.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,90 @@
1
+ .mock-pay {
2
+ display: flex;
3
+ flex-direction: column;
4
+ align-items: center;
5
+ padding: 48rpx 32rpx;
6
+ min-height: 100vh;
7
+ background: #f5f6f8;
8
+ box-sizing: border-box;
9
+
10
+ &__head {
11
+ display: flex;
12
+ flex-direction: column;
13
+ align-items: center;
14
+ margin-bottom: 32rpx;
15
+ }
16
+
17
+ &__icon {
18
+ width: 120rpx;
19
+ height: 120rpx;
20
+ border-radius: 60rpx;
21
+ background: #1677ff;
22
+ color: #fff;
23
+ font-size: 64rpx;
24
+ line-height: 120rpx;
25
+ text-align: center;
26
+ margin-bottom: 16rpx;
27
+ }
28
+
29
+ &__title {
30
+ font-size: 36rpx;
31
+ font-weight: 600;
32
+ color: #1f2329;
33
+ }
34
+
35
+ &__sub {
36
+ font-size: 24rpx;
37
+ color: #8a9099;
38
+ margin-top: 8rpx;
39
+ }
40
+
41
+ &__row {
42
+ width: 100%;
43
+ display: flex;
44
+ justify-content: space-between;
45
+ padding: 24rpx 28rpx;
46
+ margin-bottom: 16rpx;
47
+ background: #fff;
48
+ border-radius: 16rpx;
49
+ }
50
+
51
+ &__label {
52
+ font-size: 28rpx;
53
+ color: #8a9099;
54
+ }
55
+
56
+ &__value {
57
+ font-size: 28rpx;
58
+ color: #1f2329;
59
+ word-break: break-all;
60
+ text-align: right;
61
+ max-width: 420rpx;
62
+ }
63
+
64
+ &__hint {
65
+ width: 100%;
66
+ font-size: 26rpx;
67
+ color: #8a9099;
68
+ line-height: 1.6;
69
+ margin: 16rpx 8rpx 40rpx;
70
+ }
71
+
72
+ &__actions {
73
+ width: 100%;
74
+ display: flex;
75
+ flex-direction: column;
76
+ gap: 20rpx;
77
+ }
78
+
79
+ &__btn {
80
+ width: 100%;
81
+ height: 88rpx;
82
+ border-radius: 44rpx;
83
+ font-size: 30rpx;
84
+
85
+ &--primary {
86
+ background: #1677ff;
87
+ color: #fff;
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 模拟支付页(本地桥闭环测试用,不接真实厂商支付;按 openParkingPay/openParkingUnpaidOrder 协议回执形态)。
3
+ *
4
+ * 由 ai-agent 桥页经 my.navigateTo({ url, events:{ pay } }) 拉起(壳 callTboxCapabilityForWebView 按名分发到这);
5
+ * 用户点「完成支付/取消订单/未付返回」后,经 this.getOpenerEventChannel().emit('pay', { payStatus, orderNo, message })
6
+ * 把回执回传给桥页 → 壳 receiveEvent 转发 webViewContext.postMessage(receipt) → H5 卡按 pyStatus 刷新。
7
+ * 生产用真实厂商缴费页接入后,此页可删(仅本地联调脚手架)。
8
+ *
9
+ * payStatus 语义对齐桥协议:
10
+ * success → 确认页/待支付页 支付成功
11
+ * cancelled → 待支付页取消了该订单(作废;确认页取消支付是 unpaid,不在此模拟)
12
+ * unpaid → 未付款离开(单仍待支付,可续付)
13
+ * fail/none 不在此页模拟(shell 协议层 success:false/INVALID_PARAMS 走 .catch)
14
+ */
15
+ interface MockPaymentData {
16
+ tradeOrderNo: string;
17
+ parkingId: string;
18
+ }
19
+
20
+ type MockPayStatus = 'success' | 'unpaid' | 'cancelled';
21
+
22
+ interface MockPaymentPageExtraThis {
23
+ query: Record<string, string>;
24
+ onPay(): void;
25
+ onCancelOrder(): void;
26
+ onUnpaidReturn(): void;
27
+ emitPay(payload: { payStatus: MockPayStatus; orderNo: string; message: string }): void;
28
+ }
29
+
30
+ const MOCK_PAY_MESSAGES: Record<MockPayStatus, string> = {
31
+ success: '支付成功',
32
+ cancelled: '已取消',
33
+ unpaid: '未支付返回',
34
+ };
35
+
36
+ Page<MockPaymentData, MockPaymentPageExtraThis>({
37
+ query: {},
38
+ data: {
39
+ tradeOrderNo: '',
40
+ parkingId: '',
41
+ },
42
+
43
+ onLoad(query: Record<string, string>) {
44
+ this.query = query ?? {};
45
+ const tradeOrderNo = typeof query.tradeOrderNo === 'string' ? query.tradeOrderNo : '';
46
+ const parkingId = typeof query.parkingId === 'string' ? query.parkingId : '';
47
+ this.setData({
48
+ tradeOrderNo: tradeOrderNo || parkingId,
49
+ parkingId,
50
+ });
51
+ },
52
+
53
+ onPay() {
54
+ this.emitPay({ payStatus: 'success', orderNo: this.data.tradeOrderNo, message: MOCK_PAY_MESSAGES.success });
55
+ },
56
+
57
+ onCancelOrder() {
58
+ this.emitPay({ payStatus: 'cancelled', orderNo: this.data.tradeOrderNo, message: MOCK_PAY_MESSAGES.cancelled });
59
+ },
60
+
61
+ onUnpaidReturn() {
62
+ this.emitPay({ payStatus: 'unpaid', orderNo: this.data.tradeOrderNo, message: MOCK_PAY_MESSAGES.unpaid });
63
+ },
64
+
65
+ emitPay(payload) {
66
+ this.getOpenerEventChannel().emit('pay', payload);
67
+ my.navigateBack();
68
+ },
69
+ });
@@ -0,0 +1,261 @@
1
+ /**
2
+ * 桥纯函数测试(B1–B10)+ 三档处置门禁 + tbox 分发 + 与 SDK 公开出口的协议一致性测试(防单边漂移)。
3
+ */
4
+ import { describe, expect, it } from 'vitest';
5
+ import {
6
+ appendQueryParamsToUrl,
7
+ buildMiniProgramReceipt,
8
+ getWebViewJsapiCall,
9
+ normalizeWebViewMessageQueue,
10
+ resolveMessageDisposition,
11
+ WEB_VIEW_BRIDGE_NAME,
12
+ WEB_VIEW_BRIDGE_VERSION,
13
+ WEB_VIEW_MY_ACTION,
14
+ WEB_VIEW_MY_CALL_ACTION,
15
+ WEB_VIEW_TBOX_ACTION,
16
+ isAwaitEventNavigateTo,
17
+ getAwaitEventName,
18
+ } from '../pages/ai-agent/bridge';
19
+ import { getTboxCapability } from '../pages/ai-agent/tbox-capabilities';
20
+ import { isRecorderApi } from '../pages/ai-agent/recorder-handler';
21
+ import { resolveMiniJsapiExecutionMode } from '../pages/ai-agent/jsapi-execution';
22
+
23
+ describe('normalizeWebViewMessageQueue(B1–B4)', () => {
24
+ it('B1: 平面对象 → 1 条,action/requestId 正确', () => {
25
+ const queue = normalizeWebViewMessageQueue({
26
+ bridge: WEB_VIEW_BRIDGE_NAME,
27
+ action: 'my',
28
+ requestId: 'r1',
29
+ apiName: 'getAuthCode',
30
+ });
31
+ expect(queue).toHaveLength(1);
32
+ expect(queue[0].action).toBe('my');
33
+ expect(queue[0].requestId).toBe('r1');
34
+ });
35
+
36
+ it('B2: message/detail 双层包装 → 逐层解包成功', () => {
37
+ const queue = normalizeWebViewMessageQueue({
38
+ detail: { bridge: WEB_VIEW_BRIDGE_NAME, action: 'my.call', requestId: 'r2', apiName: 'getConfig' },
39
+ });
40
+ expect(queue).toHaveLength(1);
41
+ expect(queue[0].action).toBe('my.call');
42
+ expect(queue[0].requestId).toBe('r2');
43
+ });
44
+
45
+ it('B3: JSON 字符串形态 → 解析成功', () => {
46
+ const queue = normalizeWebViewMessageQueue(
47
+ JSON.stringify({ bridge: WEB_VIEW_BRIDGE_NAME, action: 'my', requestId: 'r3', apiName: 'tradePay' }),
48
+ );
49
+ expect(queue).toHaveLength(1);
50
+ expect(queue[0].requestId).toBe('r3');
51
+ });
52
+
53
+ it('B4: 数组批量 → 有效全解析、无效项过滤', () => {
54
+ const queue = normalizeWebViewMessageQueue([
55
+ { action: 'my', requestId: 'a' },
56
+ { action: 'my.call', requestId: 'b' },
57
+ 'garbage-string',
58
+ 42,
59
+ { noAction: true },
60
+ ]);
61
+ expect(queue).toHaveLength(2);
62
+ expect(queue.map((m) => m.requestId)).toEqual(['a', 'b']);
63
+ });
64
+ });
65
+
66
+ describe('getWebViewJsapiCall(B5–B7,规范键直取)', () => {
67
+ it('B5: action my → mode invoke,apiName/params 顶层直取', () => {
68
+ const call = getWebViewJsapiCall(
69
+ { action: 'my', requestId: 'r', apiName: 'chooseImage', params: { count: 1 } },
70
+ 'my',
71
+ );
72
+ expect(call).toEqual({ mode: 'invoke', apiName: 'chooseImage', params: { count: 1 } });
73
+ });
74
+
75
+ it('B6: action my.call → mode call', () => {
76
+ const call = getWebViewJsapiCall(
77
+ { action: 'my.call', requestId: 'r', apiName: 'getConfig', params: {} },
78
+ 'my.call',
79
+ );
80
+ expect(call?.mode).toBe('call');
81
+ });
82
+
83
+ it('B7: 缺 apiName / action 不匹配 → null', () => {
84
+ expect(getWebViewJsapiCall({ action: 'my', requestId: 'r' }, 'my')).toBeNull();
85
+ expect(getWebViewJsapiCall({ action: 'my', apiName: 'x' }, 'other')).toBeNull();
86
+ });
87
+
88
+ it('B7.1: 候选键不再宽容——method 不当 apiName、data 不当 params', () => {
89
+ // 收紧后:apiName 只认显式 apiName 键;params 只认显式 params 键(缺失 → {})
90
+ expect(getWebViewJsapiCall({ action: 'my', method: 'x' }, 'my')).toBeNull();
91
+ const call = getWebViewJsapiCall({ action: 'my', apiName: 'x', data: { a: 1 } }, 'my');
92
+ expect(call?.params).toEqual({});
93
+ });
94
+
95
+ it('B7.2: action tbox → mode 恒 invoke(tbox 路径不消费 mode)', () => {
96
+ const call = getWebViewJsapiCall(
97
+ { action: 'tbox', requestId: 'r', apiName: 'openPlateKeyboard', params: {} },
98
+ 'tbox',
99
+ );
100
+ expect(call).toEqual({ mode: 'invoke', apiName: 'openPlateKeyboard', params: {} });
101
+ });
102
+ });
103
+
104
+ describe('buildMiniProgramReceipt(B8)', () => {
105
+ it('成功态全字段:bridge/version/sendToWebView/action/requestId/success/code + 可选 data/received', () => {
106
+ const receipt = buildMiniProgramReceipt({
107
+ action: 'my',
108
+ requestId: 'r1',
109
+ success: true,
110
+ code: 'OK',
111
+ data: { x: 1 },
112
+ received: { orig: true },
113
+ });
114
+ expect(receipt).toEqual({
115
+ bridge: 'open-mini-webview-bridge',
116
+ version: '1.0.0',
117
+ sendToWebView: '1',
118
+ action: 'my',
119
+ requestId: 'r1',
120
+ success: true,
121
+ code: 'OK',
122
+ data: { x: 1 },
123
+ received: { orig: true },
124
+ errorMessage: '',
125
+ });
126
+ });
127
+
128
+ it('无 data/received 时键缺省,errorMessage 缺省空串', () => {
129
+ const receipt = buildMiniProgramReceipt({
130
+ action: 'my.call',
131
+ requestId: 'r2',
132
+ success: false,
133
+ code: 'REQUEST_FAILED',
134
+ });
135
+ expect('data' in receipt).toBe(false);
136
+ expect('received' in receipt).toBe(false);
137
+ expect(receipt.errorMessage).toBe('');
138
+ });
139
+ });
140
+
141
+ describe('appendQueryParamsToUrl(B9)', () => {
142
+ it('已有 query + hash:合并去重、hash 保留、值 encode', () => {
143
+ expect(appendQueryParamsToUrl('http://h/?a=1#frag', { a: '2', b: 'x y' })).toBe(
144
+ 'http://h/?a=2&b=x%20y#frag',
145
+ );
146
+ });
147
+
148
+ it('空 query → url 原样', () => {
149
+ expect(appendQueryParamsToUrl('http://h/', {})).toBe('http://h/');
150
+ });
151
+ });
152
+
153
+ describe('resolveMiniJsapiExecutionMode(B10)', () => {
154
+ it('getLocation 强制 invoke(白名单)', () => {
155
+ expect(resolveMiniJsapiExecutionMode('getLocation', 'call')).toBe('invoke');
156
+ expect(resolveMiniJsapiExecutionMode('chooseLocation', 'call')).toBe('invoke');
157
+ });
158
+
159
+ it('非白名单用 fallback;空 apiName 用 fallback', () => {
160
+ expect(resolveMiniJsapiExecutionMode('getAuthCode', 'call')).toBe('call');
161
+ expect(resolveMiniJsapiExecutionMode('getAuthCode', 'invoke')).toBe('invoke');
162
+ expect(resolveMiniJsapiExecutionMode('', 'invoke')).toBe('invoke');
163
+ });
164
+ });
165
+
166
+ describe('处置门禁 resolveMessageDisposition(default-deny)', () => {
167
+ const marked = (action: string, requestId = 'r1') => ({
168
+ action,
169
+ requestId,
170
+ raw: { bridge: WEB_VIEW_BRIDGE_NAME, action, requestId },
171
+ });
172
+ const unmarked = (action: string, requestId?: string) => ({
173
+ action,
174
+ requestId: requestId ?? '',
175
+ raw: requestId ? { action, requestId } : { action },
176
+ });
177
+
178
+ it('T1a: 有标记 + 词表 action(my/my.call/tbox)→ execute', () => {
179
+ expect(resolveMessageDisposition(marked('my'))).toEqual({ kind: 'execute' });
180
+ expect(resolveMessageDisposition(marked('my.call'))).toEqual({ kind: 'execute' });
181
+ expect(resolveMessageDisposition(marked('tbox'))).toEqual({ kind: 'execute' });
182
+ });
183
+
184
+ it('T1b: 有标记 + 未知 action → execute(分发 fallthrough 回 ACTION_NOT_ALLOWED)', () => {
185
+ expect(resolveMessageDisposition(marked('tbox.hello'))).toEqual({ kind: 'execute' });
186
+ });
187
+
188
+ it('T1c: 无标记 + 词表 action + requestId 在场 → reply-mark-required(偏斜 fast-fail)', () => {
189
+ expect(resolveMessageDisposition(unmarked('my', 'r1'))).toEqual({ kind: 'reply-mark-required' });
190
+ expect(resolveMessageDisposition(unmarked('tbox', 'r1'))).toEqual({ kind: 'reply-mark-required' });
191
+ });
192
+
193
+ it('T1d: 无标记 + 词表 action 但无 requestId → drop(第三方噪音)', () => {
194
+ expect(resolveMessageDisposition(unmarked('my'))).toEqual({ kind: 'drop' });
195
+ });
196
+
197
+ it('T1e: 无标记 + 陌生 action → drop', () => {
198
+ expect(resolveMessageDisposition(unmarked('type-my'))).toEqual({ kind: 'drop' });
199
+ expect(resolveMessageDisposition(unmarked('app'))).toEqual({ kind: 'drop' });
200
+ });
201
+
202
+ it('T2: 混合批量逐条独立处置(marked + unmarked 词表 + 陌生)', () => {
203
+ const queue = normalizeWebViewMessageQueue([
204
+ { bridge: WEB_VIEW_BRIDGE_NAME, action: 'my', requestId: 'a', apiName: 'getLocation' },
205
+ { action: 'my', requestId: 'b', apiName: 'getLocation' },
206
+ { action: 'type-my' },
207
+ ]);
208
+ expect(queue).toHaveLength(3);
209
+ expect(resolveMessageDisposition(queue[0])).toEqual({ kind: 'execute' });
210
+ expect(resolveMessageDisposition(queue[1])).toEqual({ kind: 'reply-mark-required' });
211
+ expect(resolveMessageDisposition(queue[2])).toEqual({ kind: 'drop' });
212
+ });
213
+ });
214
+
215
+ describe('tbox 能力注册表', () => {
216
+ it('录音两能力走 my JSAPI,不注册到 tbox', () => {
217
+ expect(isRecorderApi('startRecord')).toBe(true);
218
+ expect(isRecorderApi('stopRecord')).toBe(true);
219
+ expect(getTboxCapability('startRecord')).toBeUndefined();
220
+ expect(getTboxCapability('stopRecord')).toBeUndefined();
221
+ });
222
+
223
+ it('未注册 apiName → undefined(调用方回 CAPABILITY_NOT_REGISTERED)', () => {
224
+ expect(getTboxCapability('app.unknown')).toBeUndefined();
225
+ });
226
+ });
227
+
228
+ describe('桥协议一致性(防单边漂移)', () => {
229
+ it('壳内桥常量与 @tbox.cn/app-sdk/client 公开导出一致', async () => {
230
+ const sdk = await import('@tbox.cn/app-sdk/client');
231
+ expect(WEB_VIEW_BRIDGE_NAME).toBe(sdk.BRIDGE_NAME);
232
+ expect(WEB_VIEW_BRIDGE_VERSION).toBe(sdk.BRIDGE_VERSION);
233
+ expect(WEB_VIEW_MY_ACTION).toBe(sdk.MY_ACTION);
234
+ expect(WEB_VIEW_MY_CALL_ACTION).toBe(sdk.MY_CALL_ACTION);
235
+ expect(WEB_VIEW_TBOX_ACTION).toBe(sdk.TBOX_ACTION);
236
+ });
237
+
238
+ it('协议字面量钉死(SDK breaking 时双端任一变红)', () => {
239
+ expect(WEB_VIEW_BRIDGE_NAME).toBe('open-mini-webview-bridge');
240
+ expect(WEB_VIEW_BRIDGE_VERSION).toBe('1.0.0');
241
+ expect(WEB_VIEW_MY_ACTION).toBe('my');
242
+ expect(WEB_VIEW_MY_CALL_ACTION).toBe('my.call');
243
+ expect(WEB_VIEW_TBOX_ACTION).toBe('tbox');
244
+ });
245
+ });
246
+
247
+ describe('navigateTo + awaitEvent(延迟回执)', () => {
248
+ it('isAwaitEventNavigateTo:navigateTo 带 awaitEvent 字符串才命中', () => {
249
+ expect(isAwaitEventNavigateTo('navigateTo', { url: '/pages/x', awaitEvent: 'pay' })).toBe(true);
250
+ expect(isAwaitEventNavigateTo('navigateTo', { url: '/pages/x' })).toBe(false);
251
+ expect(isAwaitEventNavigateTo('navigateTo', { url: '/pages/x', awaitEvent: '' })).toBe(false);
252
+ expect(isAwaitEventNavigateTo('navigateTo', undefined)).toBe(false);
253
+ expect(isAwaitEventNavigateTo('getLocation', { awaitEvent: 'pay' })).toBe(false);
254
+ });
255
+
256
+ it('getAwaitEventName:取 awaitEvent 字面量', () => {
257
+ expect(getAwaitEventName({ url: '/pages/x', awaitEvent: 'pay' })).toBe('pay');
258
+ expect(getAwaitEventName({ url: '/pages/x' })).toBe('');
259
+ expect(getAwaitEventName(undefined)).toBe('');
260
+ });
261
+ });
@@ -0,0 +1,86 @@
1
+ /**
2
+ * h5Base 解析与 web-view URL 组装测试(H1–H6)。
3
+ * index.ts 顶层执行 Page({...}),node 环境先注入 Page stub 再动态 import。
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ type IndexModule = typeof import('../pages/ai-agent/index');
8
+
9
+ async function loadIndexModule(): Promise<IndexModule> {
10
+ const globalScope = globalThis as Record<string, unknown>;
11
+ if (typeof globalScope.Page !== 'function') {
12
+ globalScope.Page = () => undefined;
13
+ }
14
+ return import('../pages/ai-agent/index');
15
+ }
16
+
17
+ describe('resolveH5Base(H1–H4)', () => {
18
+ it('H1: 本地默认 + query.h5Base 为 http 地址 → 接受覆盖(真机联调注入 LAN IP)', async () => {
19
+ const { resolveH5Base } = await loadIndexModule();
20
+ expect(
21
+ resolveH5Base('http://127.0.0.1:8000', { h5Base: 'http://192.168.1.5:8000' }),
22
+ ).toBe('http://192.168.1.5:8000');
23
+ });
24
+
25
+ it('H1 变体: localhost 默认同样接受覆盖', async () => {
26
+ const { resolveH5Base } = await loadIndexModule();
27
+ expect(
28
+ resolveH5Base('http://localhost:8000', { h5Base: 'http://10.0.0.2:8000' }),
29
+ ).toBe('http://10.0.0.2:8000');
30
+ });
31
+
32
+ it('H2: 本地默认 + 无 h5Base → 返回默认', async () => {
33
+ const { resolveH5Base } = await loadIndexModule();
34
+ expect(resolveH5Base('http://127.0.0.1:8000', {})).toBe('http://127.0.0.1:8000');
35
+ });
36
+
37
+ it('H3: 覆盖值非 http(s) 协议 → 拒绝(防 javascript: 等注入)', async () => {
38
+ const { resolveH5Base } = await loadIndexModule();
39
+ expect(
40
+ resolveH5Base('http://127.0.0.1:8000', { h5Base: 'javascript:alert(1)' }),
41
+ ).toBe('http://127.0.0.1:8000');
42
+ });
43
+
44
+ it('H4: 生产默认(远程域名)+ 任意 h5Base → 覆盖通道关闭(安全守卫)', async () => {
45
+ const { resolveH5Base } = await loadIndexModule();
46
+ expect(
47
+ resolveH5Base('https://agent.example.com', { h5Base: 'https://evil.example.net' }),
48
+ ).toBe('https://agent.example.com');
49
+ });
50
+
51
+ it('H4 变体: 默认值非法(常量误填)→ 不抛错,按生产语义返回默认(通道关)', async () => {
52
+ const { resolveH5Base } = await loadIndexModule();
53
+ expect(resolveH5Base('not-a-url', { h5Base: 'http://192.168.1.5:8000' })).toBe('not-a-url');
54
+ });
55
+ });
56
+
57
+ describe('buildWebViewUrl(H5–H6)', () => {
58
+ it('H5: 无其他参数 → src 恒含 container 标记、不含 h5Base', async () => {
59
+ const { buildWebViewUrl } = await loadIndexModule();
60
+ expect(buildWebViewUrl('http://127.0.0.1:8000', {})).toBe(
61
+ 'http://127.0.0.1:8000/?container=alipay-miniapp',
62
+ );
63
+ });
64
+
65
+ it('H6: 业务参数透传、壳内旋钮 h5Base 剥离', async () => {
66
+ const { buildWebViewUrl } = await loadIndexModule();
67
+ const url = buildWebViewUrl('http://127.0.0.1:8000', {
68
+ h5Base: 'http://192.168.1.5:8000',
69
+ user_id: 'u1',
70
+ mallId: 'm1',
71
+ });
72
+ expect(url).toBe(
73
+ 'http://127.0.0.1:8000/?container=alipay-miniapp&user_id=u1&mallId=m1',
74
+ );
75
+ expect(url).not.toContain('h5Base=');
76
+ });
77
+
78
+ it('H7: 启动参数含 container 键 → 不覆盖契约标记(恒为 alipay-miniapp)', async () => {
79
+ const { buildWebViewUrl } = await loadIndexModule();
80
+ const url = buildWebViewUrl('http://127.0.0.1:8000', {
81
+ container: 'browser',
82
+ user_id: 'u1',
83
+ });
84
+ expect(url).toBe('http://127.0.0.1:8000/?container=alipay-miniapp&user_id=u1');
85
+ });
86
+ });
@@ -0,0 +1,132 @@
1
+ /**
2
+ * 壳内 log-kit 测试:脱敏向量 / 截断 / 级别解析 / 级别过滤 +
3
+ * 与 @tbox.cn/app-sdk/client 公开导出(sanitizeForLog/detailForLog)的镜像一致性门禁。
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+ import {
7
+ resolveLevel,
8
+ formatLocalTime,
9
+ sanitizeForLog,
10
+ truncateForLog,
11
+ detailForLog,
12
+ initShellLogLevel,
13
+ createShellLogger,
14
+ } from '../pages/ai-agent/log';
15
+
16
+ describe('脱敏(L1)', () => {
17
+ it('authCode/token/mobile/refreshToken 键(含嵌套)替换为 ***', () => {
18
+ const input = {
19
+ authCode: 'x',
20
+ token: 'y',
21
+ nested: { mobile: '1', keep: 'ok' },
22
+ refreshToken: 'z',
23
+ tradeNO: 't1', // 订单标识非密钥,保留
24
+ };
25
+ expect(sanitizeForLog(input)).toEqual({
26
+ authCode: '***',
27
+ token: '***',
28
+ nested: { mobile: '***', keep: 'ok' },
29
+ refreshToken: '***',
30
+ tradeNO: 't1',
31
+ });
32
+ });
33
+
34
+ it('数组递归脱敏', () => {
35
+ expect(sanitizeForLog([{ password: 'p' }, { safe: 1 }])).toEqual([{ password: '***' }, { safe: 1 }]);
36
+ });
37
+ });
38
+
39
+ describe('截断(L2)', () => {
40
+ it('1024 字符内原样', () => {
41
+ expect(truncateForLog({ a: 'x' })).toBe('{"a":"x"}');
42
+ });
43
+
44
+ it('超长 → 后缀计数提示', () => {
45
+ const long = 'x'.repeat(2000);
46
+ const out = truncateForLog({ a: long }, 100);
47
+ expect(out).toMatch(/…\[truncated \+\d+ chars\]$/);
48
+ expect(out.length).toBeLessThanOrEqual(100 + 30);
49
+ });
50
+
51
+ it('detailForLog = 脱敏 + 截断一步到位', () => {
52
+ expect(detailForLog({ authCode: 'abc', b: 'v' }, 50)).toBe('{"authCode":"***","b":"v"}');
53
+ });
54
+ });
55
+
56
+ describe('resolveLevel(L3)', () => {
57
+ it('合法值直取 / 非法与缺省回退 fallback', () => {
58
+ expect(resolveLevel('debug', 'info')).toBe('debug');
59
+ expect(resolveLevel('verbose', 'info')).toBe('info');
60
+ expect(resolveLevel(undefined, 'warn')).toBe('warn');
61
+ });
62
+ });
63
+
64
+ describe('formatLocalTime', () => {
65
+ it('逐段 pad 的本地时间格式', () => {
66
+ const d = new Date(2026, 7, 30, 9, 5, 3, 12);
67
+ expect(formatLocalTime(d)).toBe('2026-08-30 09:05:03.012');
68
+ });
69
+ });
70
+
71
+ describe('级别过滤(L5)', () => {
72
+ it('silent 全吞;info 级下 debug 不 emit', () => {
73
+ const calls: string[] = [];
74
+ const sink = {
75
+ debug: (m: string) => calls.push(`debug:${m}`),
76
+ log: (m: string) => calls.push(`log:${m}`),
77
+ warn: (m: string) => calls.push(`warn:${m}`),
78
+ error: (m: string) => calls.push(`error:${m}`),
79
+ };
80
+ const origConsole = { ...console };
81
+ Object.assign(console, sink);
82
+ try {
83
+ initShellLogLevel({ logLevel: 'info' });
84
+ const logger = createShellLogger('t');
85
+ logger.debug('hidden');
86
+ logger.info('shown');
87
+ logger.warn('warned');
88
+ expect(calls.some((c) => c.startsWith('log:'))).toBe(true);
89
+ expect(calls.some((c) => c.startsWith('warn:'))).toBe(true);
90
+ expect(calls.some((c) => c.includes('hidden'))).toBe(false);
91
+
92
+ calls.length = 0;
93
+ initShellLogLevel({ logLevel: 'silent' });
94
+ logger.error('swallowed');
95
+ expect(calls).toHaveLength(0);
96
+ } finally {
97
+ Object.assign(console, origConsole);
98
+ }
99
+ });
100
+
101
+ it('initShellLogLevel:query.logLevel 生效,缺省回退 info', () => {
102
+ // 仅验证解析不抛错(级别过滤行为已在上一用例覆盖)
103
+ initShellLogLevel({});
104
+ initShellLogLevel({ logLevel: 'debug' });
105
+ });
106
+ });
107
+
108
+ describe('镜像一致性门禁(L4):壳 log-kit ↔ SDK logger-core 公开导出', () => {
109
+ const SHARED_VECTORS: unknown[] = [
110
+ { authCode: 'a', token: 'b', refreshToken: 'c', nested: { mobile: '1', sign: 's', keep: true } },
111
+ [{ password: 'p' }, { apiSecret: 'k', sessionId: 'keep-me' }],
112
+ { phoneNumber: '13800000000', orderStr: 'trade', tradeNO: 't' },
113
+ 'plain-string',
114
+ 42,
115
+ null,
116
+ ];
117
+
118
+ it('sanitizeForLog:共享向量输出与 SDK 全等', async () => {
119
+ const sdk = await import('@tbox.cn/app-sdk/client');
120
+ for (const v of SHARED_VECTORS) {
121
+ expect(sanitizeForLog(v)).toEqual(sdk.sanitizeForLog(v));
122
+ }
123
+ });
124
+
125
+ it('detailForLog / truncateForLog:共享向量输出与 SDK 全等', async () => {
126
+ const sdk = await import('@tbox.cn/app-sdk/client');
127
+ for (const v of SHARED_VECTORS) {
128
+ expect(detailForLog(v)).toBe(sdk.detailForLog(v));
129
+ expect(truncateForLog(v, 64)).toBe(sdk.truncateForLog(v, 64));
130
+ }
131
+ });
132
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * mock 登录门禁页纯函数测试(入会体验闭环 C6):
3
+ * - 三动作回执形态(对齐真实厂商 getLoginState 窄面:loginStatus/message 门控信号);
4
+ * - dev-login / enroll URL 构造(serverBase 归一 + 非法值跳过网络链)。
5
+ * 页 index.ts 含 Page() 调用不可直测(沿 mock-payment 无页测先例——网络/回执链由
6
+ * E2E 手动清单覆盖);special-case 分发锁在 bridge.test 的 url 构造语义。
7
+ */
8
+ import { describe, expect, it } from 'vitest';
9
+ import { buildMockLoginReceipt, buildDevLoginUrl, buildEnrollUrl } from '../pages/mock-enrollment/receipt';
10
+
11
+ describe('buildMockLoginReceipt(getLoginState 门禁回执)', () => {
12
+ it('confirm → success(hasLogin=true,对齐 gate 登录+开卡一体语义)', () => {
13
+ expect(buildMockLoginReceipt('confirm')).toEqual({
14
+ loginStatus: 'success',
15
+ message: '登录成功',
16
+ hasLogin: true,
17
+ fromLoginGate: true,
18
+ });
19
+ });
20
+
21
+ it('browse → cancel(用户拒绝,仅浏览)', () => {
22
+ expect(buildMockLoginReceipt('browse')).toEqual({
23
+ loginStatus: 'cancel',
24
+ message: '未执行登录,仅浏览',
25
+ hasLogin: false,
26
+ fromLoginGate: true,
27
+ });
28
+ });
29
+
30
+ it('fail → fail(测 H5 fail 收场分支)', () => {
31
+ expect(buildMockLoginReceipt('fail')).toEqual({
32
+ loginStatus: 'fail',
33
+ message: '登录失败',
34
+ hasLogin: false,
35
+ fromLoginGate: true,
36
+ });
37
+ });
38
+ });
39
+
40
+ describe('mock-enrollment URL 构造(best-effort 网络链)', () => {
41
+ it('合法 serverBase → dev-login / enroll 路由(尾斜杠归一)', () => {
42
+ expect(buildDevLoginUrl('http://127.0.0.1:8000')).toBe('http://127.0.0.1:8000/api/auth/dev-login');
43
+ expect(buildEnrollUrl('http://127.0.0.1:8000/')).toBe('http://127.0.0.1:8000/api/m/provider-mock/demo/member-enroll');
44
+ expect(buildDevLoginUrl('https://lan.example.com:9000/')).toBe('https://lan.example.com:9000/api/auth/dev-login');
45
+ });
46
+
47
+ it('非法/缺省 serverBase → 空串(跳过网络链,直接回执)', () => {
48
+ expect(buildEnrollUrl(undefined)).toBe('');
49
+ expect(buildEnrollUrl('')).toBe('');
50
+ expect(buildEnrollUrl('ftp://bad.example.com')).toBe('');
51
+ expect(buildDevLoginUrl('alipays://platformapi/startapp')).toBe('');
52
+ });
53
+ });