@tbox.cn/app-miniapp-container-alipay 0.2.5 → 0.2.7

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.
@@ -8,14 +8,16 @@
8
8
  * 页面耦合能力(车牌键盘,需 setData/pending 簿记)不在此注册,由 index.ts 按名分发;
9
9
  * - 新增能力 = 此处注册一行 + H5 侧 callCapability('xxx', params)。
10
10
  */
11
- import { callCloudContainer } from './cloud-container';
12
- import { callCloudFunction } from './cloud-function';
11
+ import { createCloudContainerHandler } from './cloud-container';
12
+ import { createCloudFunctionHandler } from './cloud-function';
13
13
 
14
14
  export type TboxCapabilityHandler = (params: Record<string, unknown>) => Promise<unknown>;
15
15
 
16
+ const demoCloud = { appId: '2021004107679215', env: 'env-00jy61udznyh' };
17
+
16
18
  const capabilities = new Map<string, TboxCapabilityHandler>();
17
- capabilities.set('app.callCloudFunction', callCloudFunction);
18
- capabilities.set('app.callContainer', callCloudContainer);
19
+ capabilities.set('app.callCloudFunction', createCloudFunctionHandler(demoCloud));
20
+ capabilities.set('app.callContainer', createCloudContainerHandler(demoCloud));
19
21
 
20
22
  /** 查注册表;未注册返回 undefined(调用方回执 CAPABILITY_NOT_REGISTERED) */
21
23
  export function getTboxCapability(apiName: string): TboxCapabilityHandler | undefined {
@@ -7,7 +7,8 @@ describe('通用云容器桥', () => {
7
7
  const callContainer = vi.fn(async () => response);
8
8
  const createCloudContext = vi.fn(() => ({ init, callContainer }));
9
9
  vi.stubGlobal('my', { cloud: { createCloudContext } });
10
- const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
10
+ const { getTboxCapability } = await import('../pages/ai-agent/tbox-capabilities');
11
+ const callCloudContainer = getTboxCapability('app.callContainer')!;
11
12
  const first = { path: '/example/one', method: 'POST', header: { 'X-Alipay-Service': 'example' }, data: { value: 1 } };
12
13
  const second = { path: '/example/two', method: 'GET' };
13
14
  const results = await Promise.all([callCloudContainer(first), callCloudContainer(second)]);
@@ -21,7 +22,8 @@ describe('通用云容器桥', () => {
21
22
  const init = vi.fn().mockRejectedValueOnce(new Error('初始化失败')).mockResolvedValue(undefined);
22
23
  const callContainer = vi.fn().mockResolvedValueOnce({ statusCode: 400, data: {} }).mockRejectedValueOnce(new Error('网络失败'));
23
24
  vi.stubGlobal('my', { cloud: { createCloudContext: () => ({ init, callContainer }) } });
24
- const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
25
+ const { getTboxCapability } = await import('../pages/ai-agent/tbox-capabilities');
26
+ const callCloudContainer = getTboxCapability('app.callContainer')!;
25
27
  await expect(callCloudContainer({ path: '/example' })).rejects.toThrow('初始化失败');
26
28
  await expect(callCloudContainer({ path: '/example' })).resolves.toEqual({ statusCode: 400, data: {} });
27
29
  await expect(callCloudContainer({ path: '/example' })).rejects.toThrow('网络失败');
@@ -34,7 +36,8 @@ describe('通用云容器桥', () => {
34
36
  return context;
35
37
  });
36
38
  vi.stubGlobal('my', { cloud: { createCloudContext } });
37
- const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
39
+ const { getTboxCapability } = await import('../pages/ai-agent/tbox-capabilities');
40
+ const callCloudContainer = getTboxCapability('app.callContainer')!;
38
41
  const options = { path: '/example' };
39
42
  const results = await Promise.all([
40
43
  callCloudContainer(options),
@@ -42,7 +45,7 @@ describe('通用云容器桥', () => {
42
45
  callCloudContainer({ env: 'custom-env', ...options }),
43
46
  ]);
44
47
  expect(createCloudContext).toHaveBeenCalledTimes(2);
45
- expect(results.map(result => result.data)).toEqual(['env-00jy61udznyh', 'custom-env', 'custom-env']);
48
+ expect(results.map(result => (result as { data: unknown }).data)).toEqual(['env-00jy61udznyh', 'custom-env', 'custom-env']);
46
49
  expect(contexts.get('custom-env')!.init).toHaveBeenCalledTimes(1);
47
50
  expect(contexts.get('custom-env')!.callContainer).toHaveBeenNthCalledWith(1, options);
48
51
  expect(contexts.get('custom-env')!.callContainer).toHaveBeenNthCalledWith(2, options);
@@ -50,7 +53,8 @@ describe('通用云容器桥', () => {
50
53
  it('拒绝无效环境,不初始化云上下文', async () => {
51
54
  const createCloudContext = vi.fn();
52
55
  vi.stubGlobal('my', { cloud: { createCloudContext } });
53
- const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
56
+ const { getTboxCapability } = await import('../pages/ai-agent/tbox-capabilities');
57
+ const callCloudContainer = getTboxCapability('app.callContainer')!;
54
58
  for (const env of ['', ' ', null, 123]) {
55
59
  await expect(callCloudContainer({ env, path: '/example' })).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
56
60
  }
@@ -0,0 +1,135 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { createContainerPage, buildWebViewUrl } from '../pages/ai-agent/runtime-page';
3
+ import { createRecorderAdapter } from '../pages/ai-agent/recorder-handler';
4
+ import { createCloudFunctionHandler } from '../pages/ai-agent/cloud-function';
5
+ import { createCloudContainerHandler } from '../pages/ai-agent/cloud-container';
6
+
7
+ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });
8
+ const request = (apiName: string, requestId = 'r1', action = 'my', params = {}) => ({ detail: { bridge: 'open-mini-webview-bridge', action, apiName, requestId, params } });
9
+ function page(options: Parameters<typeof createContainerPage>[0]) {
10
+ const definition = createContainerPage(options);
11
+ const instance = { ...definition, data: { ...definition.data }, setData(data: object) { Object.assign(this.data, data); } } as any;
12
+ instance.onLoad({});
13
+ instance.onReady();
14
+ return instance;
15
+ }
16
+
17
+ describe('可接入页面运行时', () => {
18
+ it('默认不触碰录音、登录或云 API,保留完整 H5 路径与片段', async () => {
19
+ const postMessage = vi.fn();
20
+ const recorder = vi.fn();
21
+ const navigateTo = vi.fn();
22
+ const createCloudContext = vi.fn();
23
+ vi.stubGlobal('my', { createWebViewContext: () => ({ postMessage }), getRecorderManager: recorder, navigateTo, cloud: { createCloudContext } });
24
+ const instance = page({ h5Url: 'https://example.com/path?x=1#chat', pagePath: 'custom/agent/index' });
25
+ expect(instance.data.webViewUrl).toBe('https://example.com/path?x=1&container=alipay-miniapp#chat');
26
+ await instance.onWebViewMessage(request('startRecord'));
27
+ expect(postMessage).toHaveBeenLastCalledWith(expect.objectContaining({ code: 'API_NOT_SUPPORTED' }));
28
+ await instance.onWebViewMessage(request('getLoginState', 'login', 'tbox'));
29
+ expect(postMessage).toHaveBeenLastCalledWith(expect.objectContaining({ code: 'CAPABILITY_NOT_REGISTERED' }));
30
+ expect(recorder).not.toHaveBeenCalled();
31
+ expect(navigateTo).not.toHaveBeenCalled();
32
+ expect(createCloudContext).not.toHaveBeenCalled();
33
+ expect(instance.onShareAppMessage().path).toBe('custom/agent/index');
34
+ instance.onUnload();
35
+ expect(buildWebViewUrl('https://example.com/?container=wrong', { container: 'bad' })).toBe('https://example.com/?container=alipay-miniapp');
36
+ });
37
+
38
+ it('页面实例的录音适配器、pending 与晚到回执隔离', async () => {
39
+ const posts: ReturnType<typeof vi.fn>[] = [];
40
+ const adapters: Array<{ handle: ReturnType<typeof vi.fn>; dispose: ReturnType<typeof vi.fn> }> = [];
41
+ let resolveFirst!: (value: unknown) => void;
42
+ vi.stubGlobal('my', { createWebViewContext: () => { const postMessage = vi.fn(); posts.push(postMessage); return { postMessage }; } });
43
+ const definition = { h5Url: 'https://example.com', pagePath: 'pages/agent/index', recorder: () => {
44
+ const adapter = { handle: vi.fn().mockResolvedValue({ audioBase64: 'x' }), dispose: vi.fn() };
45
+ adapters.push(adapter); return adapter;
46
+ }, capabilities: { 'app.slow': () => new Promise(resolve => { resolveFirst = resolve; }) } };
47
+ const first = page(definition);
48
+ const second = page(definition);
49
+ const pending = first.onWebViewMessage(request('app.slow', 'late', 'tbox'));
50
+ first.onUnload();
51
+ resolveFirst('done');
52
+ await pending;
53
+ expect(posts[0]).not.toHaveBeenCalled();
54
+ expect(adapters[0].dispose).toHaveBeenCalledOnce();
55
+ expect(adapters[1].dispose).not.toHaveBeenCalled();
56
+ await second.onWebViewMessage(request('stopRecord', 'second'));
57
+ expect(adapters[1].handle).toHaveBeenCalledWith('stopRecord', expect.any(Object));
58
+ expect(posts[1]).toHaveBeenCalledWith(expect.objectContaining({ requestId: 'second', success: true }));
59
+ second.onUnload();
60
+ });
61
+
62
+ it('旧导航事件不能结算后发请求,卸载清理计时器', async () => {
63
+ vi.useFakeTimers();
64
+ const navigations: any[] = [];
65
+ const postMessage = vi.fn();
66
+ vi.stubGlobal('my', { createWebViewContext: () => ({ postMessage }), navigateTo: (options: unknown) => navigations.push(options) });
67
+ const instance = page({ h5Url: 'https://example.com', pagePath: 'pages/agent/index' });
68
+ await instance.onWebViewMessage(request('navigateTo', 'old', 'my', { url: '/old', awaitEvent: 'pay' }));
69
+ await instance.onWebViewMessage(request('navigateTo', 'new', 'my', { url: '/new', awaitEvent: 'pay' }));
70
+ expect(postMessage).toHaveBeenCalledWith(expect.objectContaining({ requestId: 'old', code: 'REQUEST_REPLACED' }));
71
+ postMessage.mockClear();
72
+ navigations[0].events.pay({ value: 'late old' });
73
+ expect(postMessage).not.toHaveBeenCalled();
74
+ navigations[1].events.pay({ value: 'new result' });
75
+ expect(postMessage).toHaveBeenCalledWith(expect.objectContaining({ requestId: 'new', data: { value: 'new result' } }));
76
+ instance.onUnload();
77
+ expect(vi.getTimerCount()).toBe(0);
78
+ });
79
+
80
+ it('录音释放只解除自己的回调,其他宿主回调保留', () => {
81
+ const callbacks = { start: new Set<Function>(), stop: new Set<Function>(), error: new Set<Function>() };
82
+ const hostCallback = () => {};
83
+ callbacks.stop.add(hostCallback);
84
+ const manager = {
85
+ onStart: (cb: Function) => callbacks.start.add(cb), onStop: (cb: Function) => callbacks.stop.add(cb), onError: (cb: Function) => callbacks.error.add(cb),
86
+ offStart: (cb: Function) => callbacks.start.delete(cb), offStop: (cb: Function) => callbacks.stop.delete(cb), offError: (cb: Function) => callbacks.error.delete(cb), stop: vi.fn(),
87
+ };
88
+ const getRecorderManager = vi.fn(() => manager);
89
+ vi.stubGlobal('my', { getRecorderManager });
90
+ const adapter = createRecorderAdapter();
91
+ expect(getRecorderManager).not.toHaveBeenCalled();
92
+ adapter.prewarm();
93
+ expect(callbacks.stop.size).toBe(2);
94
+ adapter.dispose();
95
+ adapter.dispose();
96
+ expect(callbacks.stop).toEqual(new Set([hostCallback]));
97
+ expect(callbacks.start.size).toBe(0);
98
+ expect(callbacks.error.size).toBe(0);
99
+ expect(manager.stop).not.toHaveBeenCalled();
100
+ });
101
+
102
+ it('两个容器页面不会同时驱动同一个原生录音管理器', async () => {
103
+ const callbacks = { start: new Set<() => void>(), stop: new Set<(value: unknown) => void>(), error: new Set<() => void>() };
104
+ const manager = {
105
+ onStart: (cb: () => void) => callbacks.start.add(cb), onStop: (cb: (value: unknown) => void) => callbacks.stop.add(cb), onError: (cb: () => void) => callbacks.error.add(cb),
106
+ offStart: (cb: () => void) => callbacks.start.delete(cb), offStop: (cb: (value: unknown) => void) => callbacks.stop.delete(cb), offError: (cb: () => void) => callbacks.error.delete(cb),
107
+ start: vi.fn(() => callbacks.start.forEach(cb => cb())),
108
+ stop: vi.fn(() => callbacks.stop.forEach(cb => cb({ tempFilePath: 'audio.mp3' }))),
109
+ };
110
+ vi.stubGlobal('my', { getRecorderManager: () => manager, getFileSystemManager: () => ({ readFile: ({ success }: any) => success({ data: 'audio-data' }) }) });
111
+ const first = createRecorderAdapter();
112
+ const second = createRecorderAdapter();
113
+ first.prewarm(); second.prewarm();
114
+ await first.handle('startRecord', {});
115
+ await expect(second.handle('startRecord', {})).rejects.toMatchObject({ code: 'RECORDER_BUSY' });
116
+ expect(manager.start).toHaveBeenCalledOnce();
117
+ const result = await first.handle('stopRecord', {});
118
+ expect(result).toMatchObject({ audioBase64: 'audio-data', format: 'mp3' });
119
+ await second.handle('startRecord', {});
120
+ await second.handle('stopRecord', {});
121
+ first.dispose(); second.dispose();
122
+ expect(manager.start).toHaveBeenCalledTimes(2);
123
+ expect(callbacks.stop.size).toBe(0);
124
+ });
125
+
126
+ it('通用云 handler 不继承演示环境,配置实例不串环境', async () => {
127
+ const createCloudContext = vi.fn(() => ({ callFunction: vi.fn().mockResolvedValue({ ok: true }), init: vi.fn(), callContainer: vi.fn() }));
128
+ vi.stubGlobal('my', { cloud: { createCloudContext } });
129
+ await expect(createCloudFunctionHandler()({ name: 'x' })).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
130
+ expect(createCloudContext).not.toHaveBeenCalled();
131
+ await createCloudFunctionHandler({ appId: 'host-app', env: 'host-env' })({ name: 'x' });
132
+ await createCloudContainerHandler({ appId: 'other-app', env: 'other-env' })({ path: '/example' });
133
+ expect(createCloudContext.mock.calls).toEqual([[{ appId: 'host-app', env: 'host-env' }], [{ appId: 'other-app', env: 'other-env' }]]);
134
+ });
135
+ });