@heybox/hb-sdk-protocol 0.9.1-alpha.1 → 0.9.1-alpha.11

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.
@@ -1,193 +0,0 @@
1
- import type { MiniProgramBridgeMethod, MiniProgramCapabilityRisk } from './capabilities';
2
-
3
- export const MINI_PROGRAM_PERMISSION_KEYS = [
4
- 'userInfo',
5
- 'steamLibrary',
6
- 'share',
7
- 'storage',
8
- 'filesystem',
9
- 'clipboard',
10
- 'leaderboard',
11
- 'network',
12
- 'companion',
13
- ] as const;
14
-
15
- export type MiniProgramPermissionKey = (typeof MINI_PROGRAM_PERMISSION_KEYS)[number];
16
- export type MiniProgramPermissionRequirement =
17
- | { readonly kind: 'none' }
18
- | { readonly kind: 'all'; readonly permissions: readonly MiniProgramPermissionKey[] };
19
- export type MiniProgramPermissionAccess = 'declaration' | 'platform-approval';
20
-
21
- export interface MiniProgramPermissionConfigFieldDefinition {
22
- readonly type: 'boolean';
23
- readonly required: boolean;
24
- readonly default: boolean;
25
- readonly description: string;
26
- }
27
-
28
- export interface MiniProgramPermissionDefinition {
29
- readonly key: MiniProgramPermissionKey;
30
- readonly name: string;
31
- readonly description: string;
32
- readonly access: MiniProgramPermissionAccess;
33
- readonly risk: MiniProgramCapabilityRisk;
34
- readonly config: Readonly<Record<string, MiniProgramPermissionConfigFieldDefinition>>;
35
- readonly methods: readonly MiniProgramBridgeMethod[];
36
- readonly conditions: readonly string[];
37
- }
38
-
39
- export const MINI_PROGRAM_PERMISSION_CATALOG = [
40
- {
41
- key: 'userInfo',
42
- name: '用户信息',
43
- description: '登录小程序并读取当前用户的授权信息。',
44
- access: 'declaration',
45
- risk: 'medium',
46
- config: {},
47
- methods: ['auth.login', 'user.getInfo'],
48
- conditions: ['继续执行黑盒登录、用户授权和可信手势规则。'],
49
- },
50
- {
51
- key: 'steamLibrary',
52
- name: 'Steam 游戏库',
53
- description: '读取当前用户授权的 Steam 游戏库。',
54
- access: 'declaration',
55
- risk: 'high',
56
- config: {},
57
- methods: ['user.getSteamGameList'],
58
- conditions: ['继续执行账号绑定和数据可用性规则。'],
59
- },
60
- {
61
- key: 'share',
62
- name: '分享',
63
- description: '使用小程序分享、分享菜单和截图能力。',
64
- access: 'declaration',
65
- risk: 'medium',
66
- config: {},
67
- methods: ['share.copyLink', 'share.showShareMenu', 'share.screenshot'],
68
- conditions: ['继续执行分享参数校验和 Host 支持检查。'],
69
- },
70
- {
71
- key: 'storage',
72
- name: '键值存储',
73
- description: '读写按小程序隔离的简单键值数据。',
74
- access: 'declaration',
75
- risk: 'medium',
76
- config: {},
77
- methods: ['storage.getStorage', 'storage.setStorage'],
78
- conditions: ['仅用于简单键值存储,不包含文件系统。'],
79
- },
80
- {
81
- key: 'filesystem',
82
- name: '文件系统',
83
- description: '访问小程序沙盒文件和用户选择的外部文件。',
84
- access: 'declaration',
85
- risk: 'high',
86
- config: {},
87
- methods: [
88
- 'network.download',
89
- 'files.pickFiles',
90
- 'files.pickDirectory',
91
- 'files.saveFile',
92
- 'file.create',
93
- 'file.remove',
94
- 'file.exists',
95
- 'file.readText',
96
- 'file.writeText',
97
- 'file.readBytes',
98
- 'file.writeBytes',
99
- 'file.stat',
100
- 'directory.create',
101
- 'directory.remove',
102
- 'directory.exists',
103
- 'directory.list',
104
- ],
105
- conditions: ['外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。'],
106
- },
107
- {
108
- key: 'clipboard',
109
- name: '剪贴板',
110
- description: '向系统剪贴板写入文本。',
111
- access: 'declaration',
112
- risk: 'medium',
113
- config: {},
114
- methods: ['device.setClipboard'],
115
- conditions: ['继续执行文本长度和 Host 支持限制。'],
116
- },
117
- {
118
- key: 'leaderboard',
119
- name: '排行榜',
120
- description: '读写小程序云排行榜。',
121
- access: 'declaration',
122
- risk: 'medium',
123
- config: {},
124
- methods: [
125
- 'cloud.leaderboard.submit',
126
- 'cloud.leaderboard.getList',
127
- 'cloud.leaderboard.getCurrentUserEntry',
128
- 'cloud.leaderboard.deleteCurrentUserEntry',
129
- 'cloud.leaderboard.getInfo',
130
- ],
131
- conditions: ['排行榜必须已创建,用户和资源规则保持不变。'],
132
- },
133
- {
134
- key: 'network',
135
- name: '网络',
136
- description: '通过 network 模块请求或下载外部资源。',
137
- access: 'platform-approval',
138
- risk: 'high',
139
- config: {
140
- useOfficialDomain: {
141
- type: 'boolean',
142
- required: false,
143
- default: false,
144
- description: '是否申请访问小黑盒官方域名。',
145
- },
146
- },
147
- methods: ['network.request', 'network.download'],
148
- conditions: ['声明后仍需平台批准,并继续执行网络安全策略。'],
149
- },
150
- {
151
- key: 'companion',
152
- name: '桌面辅助应用',
153
- description: '下载、准备并运行随当前小程序版本发布的受管桌面程序。',
154
- access: 'platform-approval',
155
- risk: 'high',
156
- config: {},
157
- methods: [
158
- 'companion.getInfo',
159
- 'companion.getPreparationStatus',
160
- 'companion.prepare',
161
- 'companion.cancelPreparation',
162
- 'companion.getActiveSession',
163
- 'companion.launch',
164
- 'companion.session.write',
165
- 'companion.session.closeStdin',
166
- 'companion.session.terminate',
167
- 'companion.session.ackOutput',
168
- 'companion.openAttachment',
169
- 'companion.showNotification',
170
- ],
171
- conditions: ['声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。'],
172
- },
173
- ] as const satisfies readonly MiniProgramPermissionDefinition[];
174
-
175
- export const MINI_PROGRAM_NO_DECLARATION_METHODS = [
176
- 'user.revokeAuthorization',
177
- 'ui.showToast',
178
- 'ui.showLoading',
179
- 'ui.hideLoading',
180
- 'viewport.getWindowInfo',
181
- 'viewport.setNavigationBarStyle',
182
- 'viewport.setDisplay',
183
- 'device.vibrate',
184
- 'navigation.close',
185
- 'navigation.reload',
186
- 'navigation.openAppPage',
187
- ] as const satisfies readonly MiniProgramBridgeMethod[];
188
-
189
- const PERMISSION_KEY_SET = new Set<string>(MINI_PROGRAM_PERMISSION_KEYS);
190
-
191
- export function isMiniProgramPermissionKey(key: string): key is MiniProgramPermissionKey {
192
- return PERMISSION_KEY_SET.has(key);
193
- }
@@ -1,216 +0,0 @@
1
- import { MINI_PROGRAM_PERMISSION_KEYS, type MiniProgramPermissionKey } from './permission-catalog';
2
-
3
- const MANAGED_RUNTIME_PERMISSION_KEYS = new Set<string>(MINI_PROGRAM_PERMISSION_KEYS);
4
-
5
- /**
6
- * 判断字符串是否是当前协议目录管理的 canonical runtime permission key。
7
- *
8
- * @param key - 已确认类型为 `string` 的候选权限 key;若输入来自 `unknown` 边界,调用方须先完成字符串检查。
9
- * @returns 与 `MINI_PROGRAM_PERMISSION_KEYS` 中某项精确相等时返回 `true`,并将 TypeScript 类型收窄为
10
- * `MiniProgramPermissionKey`;未知、历史或格式不同的字符串返回 `false`。
11
- *
12
- * @remarks
13
- * 当前 canonical key 集合固定为:
14
- *
15
- * - `userInfo`
16
- * - `steamLibrary`
17
- * - `share`
18
- * - `storage`
19
- * - `filesystem`
20
- * - `clipboard`
21
- * - `leaderboard`
22
- * - `network`
23
- * - `companion`
24
- *
25
- * 匹配大小写敏感且按原字符串执行。该 guard 不 trim,因此 `' network '` 返回 `false`;历史权限 key
26
- * `network.request` 也返回 `false`,即使同名 capability method 仍是公开 method。消费完整 schema v1 权限快照时
27
- * 应使用 {@link parseMiniProgramRuntimePermissions},由解析边界统一 trim,并把历史 `network.request` 归一为
28
- * canonical `network`。未知的 future key 同样返回 `false`;本 guard 不负责 parser 的前向兼容忽略策略。
29
- *
30
- * 类型谓词只把字符串收窄为 `MiniProgramPermissionKey` union,不读取权限 entry、status 或 config,也不检查
31
- * Manifest。返回 `true` 不表示权限已声明、平台已批准、Runtime snapshot 中存在、status 为 `enabled`、Host 支持,
32
- * 或当前 capability 已获准执行。尤其 `network` 与 `companion` 还需要平台批准;其他 declaration 权限也继续受
33
- * 各自适用的 Host、用户授权、可信手势、参数与业务策略约束。
34
- *
35
- * `MINI_PROGRAM_PERMISSION_CATALOG` 提供每个 key 的展示信息、access、风险、配置字段和 method 集合;具体 bridge
36
- * method 是否要求某项权限应以 {@link MINI_PROGRAM_PROTOCOL_CAPABILITIES} 的 `requirement` 为准。`kind: 'none'`
37
- * 的 method 不会因为某个 key 被本 guard 识别而新增权限要求。
38
- *
39
- * @example
40
- * ```ts
41
- * import { isManagedMiniProgramRuntimePermissionKey } from '@heybox/hb-sdk/protocol';
42
- *
43
- * function acceptPermissionKey(candidate: unknown) {
44
- * if (typeof candidate !== 'string') return undefined;
45
- * return isManagedMiniProgramRuntimePermissionKey(candidate) ? candidate : undefined;
46
- * }
47
- *
48
- * acceptPermissionKey('filesystem'); // 'filesystem'
49
- * acceptPermissionKey('network'); // 'network'
50
- * acceptPermissionKey(' network '); // undefined:guard 不 trim
51
- * acceptPermissionKey('network.request'); // undefined:legacy key 只由 snapshot parser 归一化
52
- * ```
53
- *
54
- * @see [parseMiniProgramRuntimePermissions](/reference/symbols/protocol/functions/parseMiniProgramRuntimePermissions) 完整 snapshot 的 trim、legacy 归一化与 config 校验。
55
- * @see [MINI_PROGRAM_PROTOCOL_CAPABILITIES](/reference/symbols/protocol/constants/MINI_PROGRAM_PROTOCOL_CAPABILITIES) method 到 permission requirement 的权威映射。
56
- * @see [权限声明](/guide/permissions) Manifest 声明、平台批准与 Runtime 状态的完整流程。
57
- */
58
- export function isManagedMiniProgramRuntimePermissionKey(key: string): key is MiniProgramPermissionKey {
59
- return MANAGED_RUNTIME_PERMISSION_KEYS.has(key);
60
- }
61
- export type MiniProgramRuntimePermissionStatus = 'enabled' | 'disabled';
62
- export interface MiniProgramRuntimePermissionEntry {
63
- key: MiniProgramPermissionKey;
64
- status: MiniProgramRuntimePermissionStatus;
65
- config: Record<string, unknown>;
66
- }
67
- export interface MiniProgramRuntimePermissionsSnapshot {
68
- schema_version: 1;
69
- revision?: number;
70
- entries: MiniProgramRuntimePermissionEntry[];
71
- }
72
- /**
73
- * `parseMiniProgramRuntimePermissions()` 返回的独立 canonical 视图。
74
- *
75
- * @remarks
76
- * 结果不保留输入 snapshot、entries 或 config 的对象引用,也不包含 `schema_version`、`revision`
77
- * 和未知权限。该对象不是授权决定;Runtime 还必须按 capability requirement、entry status、Host
78
- * 能力和后续 policy 判断是否允许调用。
79
- */
80
- export interface ParsedMiniProgramRuntimePermissions {
81
- /**
82
- * 整个 schema v1 snapshot 是否通过结构、重复 key 与已知 config 校验。`true` 不表示存在任何
83
- * permission、任何 entry 为 `enabled`,也不表示 capability 已获授权。
84
- */
85
- valid: boolean;
86
- /**
87
- * 仅包含当前协议认识的 canonical key。缺失 key 表示 snapshot 未声明该权限;`disabled` entry
88
- * 仍会保留。`valid: false` 时该映射必为空,解析器不会暴露部分成功结果。
89
- */
90
- permissions: Partial<Record<MiniProgramPermissionKey, MiniProgramRuntimePermissionEntry>>;
91
- }
92
-
93
- /**
94
- * 将不可信的 schema v1 runtime permission snapshot 解析为独立的 canonical 权限映射。
95
- *
96
- * @param snapshot - Host、服务端、dev context 或持久化边界提供的普通反序列化数据;调用方不需要先做
97
- * 类型断言。Proxy trap 或 getter 自身抛出的异常会原样传播。
98
- * @returns {@link ParsedMiniProgramRuntimePermissions}。完整 snapshot 合法时返回
99
- * `{ valid: true, permissions }`;顶层、entry、状态、重复 key 或已知 config 任一校验失败时统一
100
- * 返回 `{ valid: false, permissions: {} }`,不会保留部分权限。
101
- *
102
- * @remarks
103
- * 顶层必须是对象,`schema_version` 必须严格等于数字 `1`,`entries` 必须是数组。`revision`
104
- * 可省略;存在时必须是大于或等于 `0` 的整数。revision 只参与输入校验,不会复制到返回值。
105
- * 顶层与 entry 的其他字段会被忽略,以便 schema v1 内前向扩展。
106
- *
107
- * 每个 entry 必须是对象,`key` 必须是 trim 后非空的字符串,`status` 必须严格为
108
- * `'enabled'` 或 `'disabled'`。解析器先 trim key,再把唯一的历史别名 `network.request`
109
- * 归一为 canonical `network`;大小写不会转换。重复检查基于归一化后的所有 key,因此
110
- * `network` 与 ` network.request ` 冲突,两个相同未知 future key 也会让整个 snapshot fail
111
- * closed。
112
- *
113
- * 是否属于当前受管 key 由 {@link isManagedMiniProgramRuntimePermissionKey} 与权限目录决定。
114
- * 为兼容较新服务端,非空、状态合法且不重复的未知 key 会被忽略;其 `config` 可以缺失、为
115
- * `null`、数组或任意未来结构,均不会使已认识的权限失效。未知 entry 不会出现在返回映射中。
116
- *
117
- * 已知权限严格执行当前 schema:`network` 必须提供对象 config,且
118
- * `useOfficialDomain` 必须是 boolean;其他额外 network config 字段会丢弃,返回值只复制该
119
- * boolean。其余当前权限是无配置项权限,输入 config 可以缺失、为 `null` 或 `{}`,并统一输出
120
- * `{}`;非空对象、数组或其他值会使整个 snapshot 无效。Runtime snapshot 必须显式包含
121
- * network 的有效 boolean,即使 Manifest 目录把省略 `useOfficialDomain` 的开发者默认值定义为
122
- * `false`。
123
- *
124
- * 返回的 canonical entry/config 都是新对象;修改原 snapshot、entry 或嵌套 network config
125
- * 不会改变解析结果。`permissions` 是 Partial map:合法空 entries、只包含未知权限,或没有某个
126
- * canonical key 时,解析仍可 `valid: true`,对应属性保持缺失。
127
- *
128
- * `valid: true` 只表示 snapshot 可安全消费,不代表 entry 已启用,更不代表某个 capability 已获
129
- * 授权。Runtime consumer 应先查 {@link MINI_PROGRAM_PROTOCOL_CAPABILITIES} 中目标 method 的
130
- * `requirement`:`kind: 'none'` 不读取权限;`kind: 'all'` 要求列出的每个 canonical entry 都存在
131
- * 且 `status === 'enabled'`。之后仍需通过 Host capability、可信手势、用户授权、参数和业务
132
- * policy。当前 Runtime 对 `valid: false` 按空权限表 fail closed,受保护 method 会得到
133
- * `PERMISSION_NOT_DECLARED`,而不是沿用输入中的部分 enabled entry。
134
- *
135
- * @example
136
- * ```ts
137
- * import { parseMiniProgramRuntimePermissions } from '@heybox/hb-sdk/protocol';
138
- *
139
- * const parsed = parseMiniProgramRuntimePermissions({
140
- * schema_version: 1,
141
- * revision: 4,
142
- * entries: [
143
- * {
144
- * key: ' network.request ',
145
- * status: 'enabled',
146
- * config: { useOfficialDomain: false, futureField: 'discarded' },
147
- * },
148
- * { key: 'future.permission', status: 'disabled', config: null },
149
- * ],
150
- * });
151
- *
152
- * // legacy key 已归一化;未知 future key 被忽略。
153
- * if (parsed.valid && parsed.permissions.network?.status === 'enabled') {
154
- * console.log(parsed.permissions.network.config.useOfficialDomain); // false
155
- * // 继续执行 capability requirement、Host 与业务 policy 校验。
156
- * }
157
- * ```
158
- *
159
- * @see {@link ParsedMiniProgramRuntimePermissions}
160
- * @see {@link MiniProgramRuntimePermissionsSnapshot}
161
- * @see {@link isManagedMiniProgramRuntimePermissionKey}
162
- * @see {@link MINI_PROGRAM_PROTOCOL_CAPABILITIES}
163
- * @see {@link https://docs.xiaoheihe.cn/hb_sdk/guide/permissions | 权限声明}
164
- */
165
- export function parseMiniProgramRuntimePermissions(snapshot: unknown): ParsedMiniProgramRuntimePermissions {
166
- if (!isRecord(snapshot) || snapshot.schema_version !== 1 || !Array.isArray(snapshot.entries)) {
167
- return { valid: false, permissions: {} };
168
- }
169
- if (snapshot.revision !== undefined && (typeof snapshot.revision !== 'number' || !Number.isInteger(snapshot.revision) || snapshot.revision < 0)) {
170
- return { valid: false, permissions: {} };
171
- }
172
-
173
- const seenKeys = new Set<string>();
174
- const permissions: Partial<Record<MiniProgramPermissionKey, MiniProgramRuntimePermissionEntry>> = {};
175
- for (const rawEntry of snapshot.entries) {
176
- if (!isRecord(rawEntry) || typeof rawEntry.key !== 'string' || !rawEntry.key.trim()) {
177
- return { valid: false, permissions: {} };
178
- }
179
- const inputKey = rawEntry.key.trim();
180
- const key = inputKey === 'network.request' ? 'network' : inputKey;
181
- if (seenKeys.has(key) || (rawEntry.status !== 'enabled' && rawEntry.status !== 'disabled')) {
182
- return { valid: false, permissions: {} };
183
- }
184
- seenKeys.add(key);
185
- if (!isManagedMiniProgramRuntimePermissionKey(key)) {
186
- // 未知权限必须忽略,不能让 config:null / 缺字段把已认识的批准一起否掉。
187
- // 服务端会对无 config 的 message 字段输出 null(Rylai EmitUnpopulated)。
188
- continue;
189
- }
190
- if (key === 'network') {
191
- const config = rawEntry.config;
192
- if (!isRecord(config) || typeof config.useOfficialDomain !== 'boolean') {
193
- return { valid: false, permissions: {} };
194
- }
195
- permissions[key] = {
196
- key,
197
- status: rawEntry.status,
198
- config: { useOfficialDomain: config.useOfficialDomain },
199
- };
200
- continue;
201
- }
202
- if (rawEntry.config !== null && rawEntry.config !== undefined && (!isRecord(rawEntry.config) || Object.keys(rawEntry.config).length > 0)) {
203
- return { valid: false, permissions: {} };
204
- }
205
- permissions[key] = {
206
- key,
207
- status: rawEntry.status,
208
- config: {},
209
- };
210
- }
211
- return { valid: true, permissions };
212
- }
213
-
214
- function isRecord(value: unknown): value is Record<string, unknown> {
215
- return typeof value === 'object' && value !== null && !Array.isArray(value);
216
- }
package/types/bridge.d.ts DELETED
@@ -1,163 +0,0 @@
1
- import { COMPANION_SESSION_EXIT_EVENT, COMPANION_SESSION_OUTPUT_EVENT, COMPANION_SESSION_OWNERSHIP_LOST_EVENT, MINI_PROGRAM_MESSAGE_NAMESPACE, MINI_PROGRAM_OPERATION_PROGRESS_METHOD } from './constants';
2
- import type { CompanionSessionExitPayload, CompanionSessionOutputPayload, CompanionSessionOwnershipLostPayload, MiniProgramRuntimeEnvironmentInfo, UserInfoAuthorization } from './payloads';
3
- import type { MiniProgramCapabilityProgress, MiniProgramProgressMethod } from './capabilities';
4
- export type MiniProgramBridgeMessageType = 'handshake' | 'request' | 'response' | 'event' | 'cancel';
5
- /**
6
- * 小程序可订阅的生命周期、展示状态及业务事件名。
7
- *
8
- * @remarks
9
- * 每个事件的载荷见 {@link MiniProgramEventPayloadMap}。事件不会向晚订阅者重放;`ready`
10
- * 是握手成功通知,不是可查询的持久状态,也不保证只收到一次。具体事件能否产生取决于
11
- * Host 的能力与生命周期,不能仅凭事件名称推导状态去重或投递保证。
12
- */
13
- export type MiniProgramEventName = 'launch' | 'viewport_change' | 'display_change' | 'ready' | 'show' | 'hide' | 'unload' | 'error' | 'heybox_app_login_change' | 'user_info_authorization_change' | typeof COMPANION_SESSION_OUTPUT_EVENT | typeof COMPANION_SESSION_EXIT_EVENT | typeof COMPANION_SESSION_OWNERSHIP_LOST_EVENT;
14
- export interface MiniProgramBridgeError {
15
- code: string;
16
- message: string;
17
- data?: unknown;
18
- }
19
- export interface SDKHandshakePayload {
20
- href: string;
21
- userAgent: string;
22
- sdkVersion: string;
23
- }
24
- /** Runtime 对 SDK 握手的可选扩展响应。 */
25
- export interface SDKHandshakeResult {
26
- /** Host 与 Runtime 归一化后的环境快照。 */
27
- environment: MiniProgramRuntimeEnvironmentInfo;
28
- }
29
- export interface RuntimeLocationProbePayload {
30
- probeId: string;
31
- timestamp: number;
32
- }
33
- export type SDKLocationReportTrigger = 'probe' | 'history' | 'popstate' | 'hashchange' | 'pageshow' | 'resume';
34
- export interface SDKLocationReportPayload {
35
- probeId?: string;
36
- href: string;
37
- sdkVersion: string;
38
- trigger: SDKLocationReportTrigger;
39
- timestamp: number;
40
- }
41
- export type SDKCSPBlockedResourceType = 'url' | 'inline' | 'eval' | 'unknown';
42
- export interface SDKCSPViolationPayload {
43
- effectiveDirective: string;
44
- violatedDirective: string;
45
- disposition: string;
46
- blockedResourceType: SDKCSPBlockedResourceType;
47
- blockedOrigin?: string;
48
- redactedPathname?: string;
49
- sanitizedPathnameHash?: string;
50
- sdkVersion: string;
51
- timestamp: number;
52
- }
53
- /**
54
- * SDK 与 Host Runtime 跨 iframe 传输时共用的顶层 bridge envelope。
55
- *
56
- * @typeParam TPayload - 当前 method 对应的 payload 类型;未知或尚未按 method 收窄时默认为 `unknown`。
57
- *
58
- * @remarks
59
- * 该类型刻意保留为宽 envelope,以同时表达 handshake、request、response、event 与 cancel。
60
- * 字段组合的运行时约束由 {@link isMiniProgramBridgeMessage} 执行;v2 cancel 和 operation progress
61
- * 可分别使用 {@link MiniProgramBridgeCancelMessage} 与 {@link MiniProgramBridgeProgressMessage}
62
- * 获得更精确的静态类型。
63
- *
64
- * 类型匹配不建立信任边界。从 `postMessage` 接收数据时,先以 `unknown` 交给 guard,再独立校验
65
- * `MessageEvent.source`、预期 nonce、握手状态,以及具体 method 的 payload;当 origin 可以固定且
66
- * 当前协议模式要求时,再校验 `MessageEvent.origin`。
67
- */
68
- export interface MiniProgramBridgeMessage<TPayload = unknown> {
69
- /** 固定协议 namespace,用于从其他页面消息中识别候选 envelope。 */
70
- namespace: typeof MINI_PROGRAM_MESSAGE_NAMESPACE;
71
- /** 当前消息采用的 wire 版本;新消息使用 v2,接收端为兼容握手接受 v1。 */
72
- version: 1 | 2;
73
- /** Runtime 创建 iframe 时分配并由双方逐条回传的实例 nonce。 */
74
- nonce: string;
75
- /** 决定 id、method、payload 与 error 组合规则的消息类别。 */
76
- type: MiniProgramBridgeMessageType;
77
- /** 请求关联 ID;普通生命周期 event 可省略,request、response、handshake、cancel 与 progress 必须提供。 */
78
- id?: string;
79
- /** capability 或事件名;response 可省略,cancel 禁止携带。 */
80
- method?: string;
81
- /** method 对应的 wire payload;必须在按 method 分发后继续校验。 */
82
- payload?: TPayload;
83
- /** 失败 response 的结构化错误;其他消息类型不得携带。 */
84
- error?: MiniProgramBridgeError;
85
- }
86
- export interface MiniProgramBridgeCancelMessage extends MiniProgramBridgeMessage<never> {
87
- version: 2;
88
- type: 'cancel';
89
- id: string;
90
- method?: never;
91
- payload?: never;
92
- error?: never;
93
- }
94
- export interface MiniProgramBridgeProgressMessage<TMethod extends MiniProgramProgressMethod = MiniProgramProgressMethod> extends MiniProgramBridgeMessage<MiniProgramCapabilityProgress<TMethod>> {
95
- version: 2;
96
- type: 'event';
97
- id: string;
98
- method: typeof MINI_PROGRAM_OPERATION_PROGRESS_METHOD;
99
- payload: MiniProgramCapabilityProgress<TMethod>;
100
- error?: never;
101
- }
102
- /**
103
- * 公开事件名与对应载荷的映射,供 SDK 的类型化事件监听使用。
104
- *
105
- * @remarks
106
- * 生命周期 `timestamp` 是 Runtime 发出通知时的 Unix 毫秒时间,不是 iframe 收到事件的
107
- * 时间或单调时钟。事件只通知已注册的监听器;业务需要当前状态时应使用相应读取 API。
108
- */
109
- export interface MiniProgramEventPayloadMap {
110
- /** 展示状态实际变化后通知;不回放初始状态,不支持或失败时不通知。 */
111
- display_change: import('./payloads').MiniProgramDisplayState & {
112
- /** api 为开发者调用;user 为用户点击宿主退出全屏按钮。同目标合并时保留首次发起来源。旧宿主可能不提供。 */
113
- source?: 'api' | 'user';
114
- };
115
- /** 窗口信息变化通知;载荷与 `viewport.getWindowInfo()` 的结果结构一致。 */
116
- viewport_change: import('./payloads').MiniProgramWindowInfoResult;
117
- /** 初次握手时的启动通知;晚订阅不能补收。 */
118
- launch: {
119
- /** Runtime 发出通知时的 Unix 毫秒时间。 */
120
- timestamp: number;
121
- /** Host 加载 iframe 时的启动 URL;可缺失,不代表页面当前导航地址。 */
122
- url?: string;
123
- };
124
- /** 握手成功通知;重复握手可再次产生,应查询持久握手状态驱动 UI。 */
125
- ready: {
126
- /** Runtime 发出通知时的 Unix 毫秒时间。 */
127
- timestamp: number;
128
- };
129
- /** Host 通知小程序进入展示状态。 */
130
- show: {
131
- /** Runtime 发出通知时的 Unix 毫秒时间。 */
132
- timestamp: number;
133
- /** Host 可选提供的来源描述;不保证存在或采用固定枚举。 */
134
- source?: string;
135
- };
136
- /** Host 通知小程序进入隐藏状态。 */
137
- hide: {
138
- /** Runtime 发出通知时的 Unix 毫秒时间。 */
139
- timestamp: number;
140
- /** Host 可选提供的来源描述;不保证存在或采用固定枚举。 */
141
- source?: string;
142
- };
143
- /** Runtime 卸载的尽力通知;不能保证页面销毁前一定收到。 */
144
- unload: {
145
- /** Runtime 发出通知时的 Unix 毫秒时间。 */
146
- timestamp: number;
147
- };
148
- /** 结构化 Runtime 错误通知;载荷不是 JavaScript `Error` 实例。 */
149
- error: MiniProgramBridgeError;
150
- /** Host 当前登录状态通知;相同状态可能重复出现,不能仅凭事件判断账号身份是否变化。 */
151
- heybox_app_login_change: {
152
- /** Host 当前是否有已登录的小黑盒账号,不表示开发者服务端会话状态。 */
153
- isHeyboxAppLoggedIn: boolean;
154
- };
155
- /** 当前用户授权状态通知;可包含可选 `steam_account`,不是 Manifest 权限状态。 */
156
- user_info_authorization_change: UserInfoAuthorization;
157
- /** 当前 Companion controller 收到的输出片段;去重与确认依据见载荷中的 sequence。 */
158
- [COMPANION_SESSION_OUTPUT_EVENT]: CompanionSessionOutputPayload;
159
- /** Companion session 的进程退出通知。 */
160
- [COMPANION_SESSION_EXIT_EVENT]: CompanionSessionExitPayload;
161
- /** 当前 controller 失去 Companion session 控制权的通知。 */
162
- [COMPANION_SESSION_OWNERSHIP_LOST_EVENT]: CompanionSessionOwnershipLostPayload;
163
- }