@appthen/host-sdk 0.0.0-stage → 1.0.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.
- package/dist/client.d.ts +24 -0
- package/dist/client.js +70 -0
- package/dist/contract.d.ts +92 -0
- package/dist/contract.js +14 -0
- package/dist/desktop.d.ts +152 -0
- package/dist/desktop.js +102 -0
- package/dist/dispatcher.d.ts +55 -0
- package/dist/dispatcher.js +121 -0
- package/dist/host-mode.d.ts +26 -0
- package/dist/host-mode.js +62 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +36 -0
- package/dist/index.mjs +565 -0
- package/dist/injectedScript.d.ts +17 -0
- package/dist/injectedScript.js +82 -0
- package/dist/web-providers.d.ts +21 -0
- package/dist/web-providers.js +247 -0
- package/package.json +23 -3
- package/src/client.ts +87 -0
- package/src/contract.ts +109 -0
- package/src/desktop.ts +209 -0
- package/src/dispatcher.ts +167 -0
- package/src/host-mode.ts +62 -0
- package/src/index.ts +16 -0
- package/src/injectedScript.ts +79 -0
- package/src/web-providers.ts +278 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +16 -0
- package/README.md +0 -3
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.appthenHostInjectedScript = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* 注入 WebView / 页面的脚本(移动端经 `injectedJavaScriptBeforeContentLoaded`,
|
|
6
|
+
* 桌面端由 preload 在页面脚本运行前注入到主 world)。
|
|
7
|
+
*
|
|
8
|
+
* 在页面加载早期装好 `window.appthenHost`,业务代码只认它;这里不暴露任何
|
|
9
|
+
* RN / iOS / Android / Electron 专属对象。
|
|
10
|
+
*
|
|
11
|
+
* 通信通道(两端各喂一个 `post` 即可,脚本本体完全通用):
|
|
12
|
+
* - Web → Native:
|
|
13
|
+
* `window.__appthenHostTx.post(JSON.stringify({type:'appthen:request', req}))`
|
|
14
|
+
* - 移动端:RN WebView 里脚本找不到 `window.__appthenHostTx` 时,回落到
|
|
15
|
+
* `window.ReactNativeWebView.postMessage(...)`(保持向后兼容)。
|
|
16
|
+
* - 桌面端:preload 通过 contextBridge 暴露 `window.__appthenHostTx = { post }`,
|
|
17
|
+
* 底层走 `ipcRenderer.send('appthen:toMain', raw)`。
|
|
18
|
+
* - Native → Web:native 侧统一调 `window.appthenHost.__dispatchResponse/_dispatchEvent`。
|
|
19
|
+
*/
|
|
20
|
+
exports.appthenHostInjectedScript = String.raw `
|
|
21
|
+
(function () {
|
|
22
|
+
if (window.__appthenHostInstalled) return;
|
|
23
|
+
window.__appthenHostInstalled = true;
|
|
24
|
+
|
|
25
|
+
var pending = Object.create(null);
|
|
26
|
+
var listeners = Object.create(null);
|
|
27
|
+
var seed = 0;
|
|
28
|
+
var seq = function () { seed += 1; return Date.now().toString(36) + '-' + seed; };
|
|
29
|
+
|
|
30
|
+
var post = function (payload) {
|
|
31
|
+
var raw = JSON.stringify(payload);
|
|
32
|
+
if (window.__appthenHostTx && window.__appthenHostTx.post) {
|
|
33
|
+
window.__appthenHostTx.post(raw);
|
|
34
|
+
} else if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
|
35
|
+
window.ReactNativeWebView.postMessage(raw);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function request(req) {
|
|
40
|
+
return new Promise(function (resolve) {
|
|
41
|
+
var id = req && req.id ? req.id : seq();
|
|
42
|
+
var envelope = {
|
|
43
|
+
type: 'appthen:request',
|
|
44
|
+
req: {
|
|
45
|
+
id: id,
|
|
46
|
+
version: 1,
|
|
47
|
+
method: req.method,
|
|
48
|
+
params: req.params,
|
|
49
|
+
context: req.context || {}
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
pending[id] = resolve;
|
|
53
|
+
post(envelope);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function subscribe(eventType, listener) {
|
|
58
|
+
(listeners[eventType] = listeners[eventType] || []).push(listener);
|
|
59
|
+
return function unsubscribe() {
|
|
60
|
+
var arr = listeners[eventType] || [];
|
|
61
|
+
var idx = arr.indexOf(listener);
|
|
62
|
+
if (idx >= 0) arr.splice(idx, 1);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
window.appthenHost = { request: request, subscribe: subscribe };
|
|
67
|
+
|
|
68
|
+
window.appthenHost.__dispatchResponse = function (resp) {
|
|
69
|
+
var r = typeof resp === 'string' ? JSON.parse(resp) : resp;
|
|
70
|
+
var cb = pending[r.id];
|
|
71
|
+
if (cb) { delete pending[r.id]; cb(r); }
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
window.appthenHost.__dispatchEvent = function (ev) {
|
|
75
|
+
var e = typeof ev === 'string' ? JSON.parse(ev) : ev;
|
|
76
|
+
var arr = listeners[e.eventType] || [];
|
|
77
|
+
for (var i = 0; i < arr.length; i++) {
|
|
78
|
+
try { arr[i](e); } catch (err) { }
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
})();
|
|
82
|
+
`;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* web 降级提供者(web capability providers)
|
|
3
|
+
*
|
|
4
|
+
* 部分能力在纯浏览器里可以用原生 Web API「将就着用」(native 体验更好但缺了也能跑):
|
|
5
|
+
* 剪贴板、系统通知、外链打开、目录/文件选择、TTS/STT、系统分享。
|
|
6
|
+
* 每个提供者实现与 native 方法**同一份返回形状**(见 desktop.ts / contract.ts 的 DTO),
|
|
7
|
+
* 由 `client.ts` 的 resolver 按主机模式决定调用 native 还是这里。
|
|
8
|
+
*
|
|
9
|
+
* 说明:SDK 开启 `types:[]`(无 node / 全局 DOM 类型污染),所以浏览器全局构造
|
|
10
|
+
* (Notification / SpeechSynthesisUtterance / SpeechRecognition 等)都经 `globalThis`
|
|
11
|
+
* 取,避免与两端各自的全局声明打架。
|
|
12
|
+
*
|
|
13
|
+
* 明确**不做** web 降级的能力(native-only):`push.register`(厂商通道)、
|
|
14
|
+
* `daemon.*` / `updater.*`(本机进程)、`voice.wakeup`(常驻唤醒)、`device.identity`。
|
|
15
|
+
*/
|
|
16
|
+
import type { AppthenHostContext } from './contract';
|
|
17
|
+
export interface WebCapabilityProvider {
|
|
18
|
+
/** 浏览器里执行能力调用,返回与 native 方法一致的出参形状。 */
|
|
19
|
+
run(params: unknown, context?: AppthenHostContext): Promise<unknown>;
|
|
20
|
+
}
|
|
21
|
+
export declare const webCapabilityProviders: Record<string, WebCapabilityProvider>;
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* web 降级提供者(web capability providers)
|
|
4
|
+
*
|
|
5
|
+
* 部分能力在纯浏览器里可以用原生 Web API「将就着用」(native 体验更好但缺了也能跑):
|
|
6
|
+
* 剪贴板、系统通知、外链打开、目录/文件选择、TTS/STT、系统分享。
|
|
7
|
+
* 每个提供者实现与 native 方法**同一份返回形状**(见 desktop.ts / contract.ts 的 DTO),
|
|
8
|
+
* 由 `client.ts` 的 resolver 按主机模式决定调用 native 还是这里。
|
|
9
|
+
*
|
|
10
|
+
* 说明:SDK 开启 `types:[]`(无 node / 全局 DOM 类型污染),所以浏览器全局构造
|
|
11
|
+
* (Notification / SpeechSynthesisUtterance / SpeechRecognition 等)都经 `globalThis`
|
|
12
|
+
* 取,避免与两端各自的全局声明打架。
|
|
13
|
+
*
|
|
14
|
+
* 明确**不做** web 降级的能力(native-only):`push.register`(厂商通道)、
|
|
15
|
+
* `daemon.*` / `updater.*`(本机进程)、`voice.wakeup`(常驻唤醒)、`device.identity`。
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.webCapabilityProviders = void 0;
|
|
19
|
+
function hasWindow() {
|
|
20
|
+
return typeof window !== 'undefined';
|
|
21
|
+
}
|
|
22
|
+
function requireWindow(what) {
|
|
23
|
+
if (!hasWindow()) {
|
|
24
|
+
throw { code: 'web_unavailable', message: `能力需要浏览器环境(${what})。`, retryable: false };
|
|
25
|
+
}
|
|
26
|
+
return window;
|
|
27
|
+
}
|
|
28
|
+
/** 内联创建一个临时的 `<input type=file>` 并从文件选择中解析出结果。 */
|
|
29
|
+
function pickWithInput(options) {
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
const input = document.createElement('input');
|
|
32
|
+
input.type = 'file';
|
|
33
|
+
if (options.webkitdirectory)
|
|
34
|
+
input.setAttribute('webkitdirectory', '');
|
|
35
|
+
if (options.multiple)
|
|
36
|
+
input.multiple = true;
|
|
37
|
+
if (options.accept)
|
|
38
|
+
input.accept = options.accept;
|
|
39
|
+
input.style.position = 'fixed';
|
|
40
|
+
input.style.opacity = '0';
|
|
41
|
+
input.style.pointerEvents = 'none';
|
|
42
|
+
document.body.appendChild(input);
|
|
43
|
+
const cleanup = () => {
|
|
44
|
+
if (input.parentNode)
|
|
45
|
+
input.parentNode.removeChild(input);
|
|
46
|
+
};
|
|
47
|
+
input.onchange = () => {
|
|
48
|
+
const files = Array.from(input.files ?? []);
|
|
49
|
+
cleanup();
|
|
50
|
+
resolve({
|
|
51
|
+
canceled: false,
|
|
52
|
+
files: files.map((f) => ({
|
|
53
|
+
name: f.name,
|
|
54
|
+
size: f.size,
|
|
55
|
+
relativePath: 'webkitRelativePath' in f && f.webkitRelativePath ? f.webkitRelativePath : undefined,
|
|
56
|
+
})),
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
input.oncancel = () => {
|
|
60
|
+
cleanup();
|
|
61
|
+
resolve({ canceled: true, files: [] });
|
|
62
|
+
};
|
|
63
|
+
input.click();
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const globalWindow = () => typeof globalThis !== 'undefined' ? globalThis : {};
|
|
67
|
+
/** 进行中的 web 语音识别会话(供 `voice.stopListening` 中止)。 */
|
|
68
|
+
let activeWebRecognition = null;
|
|
69
|
+
exports.webCapabilityProviders = {
|
|
70
|
+
'navigation.openExternal': {
|
|
71
|
+
async run(params) {
|
|
72
|
+
const { url } = (params ?? {});
|
|
73
|
+
if (!url || typeof url !== 'string') {
|
|
74
|
+
throw { code: 'invalid_arg', message: 'navigation.openExternal 需要 url。', retryable: false };
|
|
75
|
+
}
|
|
76
|
+
const win = requireWindow('window.open');
|
|
77
|
+
win.open(url, '_blank', 'noopener,noreferrer');
|
|
78
|
+
return { ok: true };
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
'navigation.openDeepLink': {
|
|
82
|
+
async run(params) {
|
|
83
|
+
const { url } = (params ?? {});
|
|
84
|
+
if (!url || typeof url !== 'string') {
|
|
85
|
+
throw { code: 'invalid_arg', message: 'navigation.openDeepLink 需要 url。', retryable: false };
|
|
86
|
+
}
|
|
87
|
+
// web 只能对标准 http(s) 外链降级;app scheme 深链在浏览器里无对应宿主。
|
|
88
|
+
if (/^https?:\/\//i.test(url)) {
|
|
89
|
+
const win = requireWindow('window.open');
|
|
90
|
+
win.open(url, '_blank', 'noopener,noreferrer');
|
|
91
|
+
return { ok: true, open: true };
|
|
92
|
+
}
|
|
93
|
+
return { ok: true, open: false };
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
'device.registerPresence': {
|
|
97
|
+
async run(params) {
|
|
98
|
+
// 桌面端 native 才做真实的 daemon 侧登记;web 视为无害占位。
|
|
99
|
+
return params ?? { ok: true };
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
'notifications.show': {
|
|
103
|
+
async run(params) {
|
|
104
|
+
const NotificationCtor = globalWindow().Notification;
|
|
105
|
+
if (!NotificationCtor) {
|
|
106
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持系统通知。', retryable: false };
|
|
107
|
+
}
|
|
108
|
+
const { title, body, tag } = (params ?? {});
|
|
109
|
+
if (!title)
|
|
110
|
+
throw { code: 'invalid_arg', message: 'notifications.show 需要 title。', retryable: false };
|
|
111
|
+
if (NotificationCtor.permission === 'denied') {
|
|
112
|
+
throw { code: 'web_unavailable', message: '系统通知权限被拒绝。', retryable: true };
|
|
113
|
+
}
|
|
114
|
+
if (NotificationCtor.permission === 'default')
|
|
115
|
+
await NotificationCtor.requestPermission();
|
|
116
|
+
if (NotificationCtor.permission !== 'granted') {
|
|
117
|
+
throw { code: 'web_unavailable', message: '未获得系统通知权限。', retryable: true };
|
|
118
|
+
}
|
|
119
|
+
new NotificationCtor(title, { body, tag });
|
|
120
|
+
return { ok: true };
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
'clipboard.read': {
|
|
124
|
+
async run() {
|
|
125
|
+
const win = requireWindow('navigator.clipboard');
|
|
126
|
+
if (!win.navigator?.clipboard?.readText) {
|
|
127
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持剪贴板读取。', retryable: false };
|
|
128
|
+
}
|
|
129
|
+
const text = await win.navigator.clipboard.readText();
|
|
130
|
+
return { text };
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
'clipboard.write': {
|
|
134
|
+
async run(params) {
|
|
135
|
+
const win = requireWindow('navigator.clipboard');
|
|
136
|
+
const { text } = (params ?? {});
|
|
137
|
+
if (typeof text !== 'string') {
|
|
138
|
+
throw { code: 'invalid_arg', message: 'clipboard.write 需要 text。', retryable: false };
|
|
139
|
+
}
|
|
140
|
+
if (!win.navigator?.clipboard?.writeText) {
|
|
141
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持剪贴板写入。', retryable: false };
|
|
142
|
+
}
|
|
143
|
+
await win.navigator.clipboard.writeText(text);
|
|
144
|
+
return { ok: true };
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
'dialog.chooseDirectory': {
|
|
148
|
+
async run() {
|
|
149
|
+
const result = await pickWithInput({ webkitdirectory: true });
|
|
150
|
+
return { canceled: result.canceled, paths: result.files.map((f) => f.relativePath ?? f.name) };
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
'files.pick': {
|
|
154
|
+
async run(params) {
|
|
155
|
+
const { multiple } = (params ?? {});
|
|
156
|
+
const result = await pickWithInput({ multiple: Boolean(multiple) });
|
|
157
|
+
return { canceled: result.canceled, files: result.files };
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
'voice.speak': {
|
|
161
|
+
async run(params) {
|
|
162
|
+
const win = requireWindow('speechSynthesis');
|
|
163
|
+
const { text } = (params ?? {});
|
|
164
|
+
if (!text)
|
|
165
|
+
throw { code: 'invalid_arg', message: 'voice.speak 需要 text。', retryable: false };
|
|
166
|
+
if (!win.speechSynthesis) {
|
|
167
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持语音播报。', retryable: false };
|
|
168
|
+
}
|
|
169
|
+
const UtteranceCtor = globalWindow()
|
|
170
|
+
.SpeechSynthesisUtterance;
|
|
171
|
+
if (!UtteranceCtor) {
|
|
172
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持语音播报。', retryable: false };
|
|
173
|
+
}
|
|
174
|
+
win.speechSynthesis.speak(new UtteranceCtor(text));
|
|
175
|
+
return { ok: true };
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
'voice.stopSpeaking': {
|
|
179
|
+
async run() {
|
|
180
|
+
const win = requireWindow('speechSynthesis');
|
|
181
|
+
win.speechSynthesis?.cancel?.();
|
|
182
|
+
return { ok: true };
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
'voice.listen': {
|
|
186
|
+
async run(params) {
|
|
187
|
+
const globals = globalWindow();
|
|
188
|
+
const RecCtor = globals.SpeechRecognition ?? globals.webkitSpeechRecognition;
|
|
189
|
+
if (!RecCtor) {
|
|
190
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持语音识别。', retryable: false };
|
|
191
|
+
}
|
|
192
|
+
const { language } = (params ?? {});
|
|
193
|
+
const rec = new RecCtor();
|
|
194
|
+
rec.interimResults = false;
|
|
195
|
+
if (language)
|
|
196
|
+
rec.lang = language;
|
|
197
|
+
activeWebRecognition = rec;
|
|
198
|
+
return new Promise((resolve, reject) => {
|
|
199
|
+
rec.onresult = (event) => {
|
|
200
|
+
const transcript = Array.from(event.results).map((r) => r[0]?.transcript).join('');
|
|
201
|
+
rec.stop();
|
|
202
|
+
resolve({ transcript, isFinal: true, language });
|
|
203
|
+
};
|
|
204
|
+
rec.onerror = (event) => {
|
|
205
|
+
rec.stop();
|
|
206
|
+
reject({ code: 'web_recognition_error', message: `语音识别失败:${event?.error ?? 'unknown'}`, retryable: true });
|
|
207
|
+
};
|
|
208
|
+
rec.onend = () => {
|
|
209
|
+
if (activeWebRecognition === rec)
|
|
210
|
+
activeWebRecognition = null;
|
|
211
|
+
resolve({ transcript: '', isFinal: true, language });
|
|
212
|
+
};
|
|
213
|
+
rec.start();
|
|
214
|
+
});
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
'voice.stopListening': {
|
|
218
|
+
async run() {
|
|
219
|
+
const rec = activeWebRecognition;
|
|
220
|
+
activeWebRecognition = null;
|
|
221
|
+
if (rec) {
|
|
222
|
+
try {
|
|
223
|
+
rec.stop();
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// 会话已结束,忽略
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return { ok: true };
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
'share': {
|
|
233
|
+
async run(params) {
|
|
234
|
+
const win = requireWindow('navigator.share');
|
|
235
|
+
if (!win.navigator?.share) {
|
|
236
|
+
throw { code: 'web_unavailable', message: '当前浏览器不支持系统分享。', retryable: false };
|
|
237
|
+
}
|
|
238
|
+
const payload = (params ?? {});
|
|
239
|
+
await win.navigator.share({
|
|
240
|
+
title: payload.title,
|
|
241
|
+
text: payload.text,
|
|
242
|
+
url: payload.url,
|
|
243
|
+
});
|
|
244
|
+
return { ok: true };
|
|
245
|
+
},
|
|
246
|
+
},
|
|
247
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@appthen/host-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "协同工作台 —— appthenHost 统一桥共享 SDK。桌面端 / 移动端(RN WebView)围绕这一份契约、注入脚本与分发逻辑对齐。",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"author": "Appthen",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"module": "dist/index.mjs",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.mjs",
|
|
14
|
+
"require": "./dist/index.js",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"esbuild": "^0.25.0",
|
|
20
|
+
"typescript": "^5.8.3"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsc -p tsconfig.build.json && esbuild src/index.ts --bundle --format=esm --platform=browser --outfile=dist/index.mjs",
|
|
24
|
+
"typecheck": "tsc --noEmit"
|
|
25
|
+
}
|
|
6
26
|
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AppthenHostContext,
|
|
3
|
+
AppthenHostRequest,
|
|
4
|
+
AppthenHostResponse,
|
|
5
|
+
WindowAppthenHost,
|
|
6
|
+
} from './contract';
|
|
7
|
+
import {
|
|
8
|
+
getHostMode,
|
|
9
|
+
hostModeAllowsNative,
|
|
10
|
+
hostModeAllowsWebFallback,
|
|
11
|
+
} from './host-mode';
|
|
12
|
+
import { webCapabilityProviders } from './web-providers';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Web 侧统一客户端:把 `window.appthenHost` 的 request/subscribe 收敛成一组
|
|
16
|
+
* 低样板助手,供 Workbench / 扩展直接调用,避免各自手拼 envelope。
|
|
17
|
+
*
|
|
18
|
+
* 能力解析(host mode):native 宿主存在且当前模式允许 → 走 native;
|
|
19
|
+
* 否则若该能力配了 web 降级且当前模式允许 → 用浏览器原生 API 将就;
|
|
20
|
+
* 两样都没有 → 抛 `host_unavailable` / `web_unavailable`。见 `host-mode.ts`。
|
|
21
|
+
*
|
|
22
|
+
* 用法:
|
|
23
|
+
* ```ts
|
|
24
|
+
* const result = await appthenRequest('daemon.start', { ... });
|
|
25
|
+
* const serverUrl = await appthenRequest<string>('server.getUrl');
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export function getAppthenHost(): WindowAppthenHost | null {
|
|
30
|
+
if (typeof window === 'undefined') return null;
|
|
31
|
+
return window.appthenHost ?? null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let seqSeed = 0;
|
|
35
|
+
|
|
36
|
+
export function nextRequestId(): string {
|
|
37
|
+
seqSeed += 1;
|
|
38
|
+
return `${Date.now().toString(36)}-${seqSeed}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 发一次能力调用。成功 resolve 出 `result`;失败 throw `{ code, message, retryable }`。
|
|
43
|
+
* 宿主不存在(纯浏览器)时 reject,由调用方按「无此能力」处理。
|
|
44
|
+
*/
|
|
45
|
+
export async function appthenRequest<T = unknown>(
|
|
46
|
+
method: string,
|
|
47
|
+
params?: unknown,
|
|
48
|
+
context?: AppthenHostContext,
|
|
49
|
+
): Promise<T> {
|
|
50
|
+
const ctx = context ?? {};
|
|
51
|
+
const host = getAppthenHost();
|
|
52
|
+
const useNative = Boolean(host) && hostModeAllowsNative();
|
|
53
|
+
|
|
54
|
+
// 1) native 优先(除非显式 force web)
|
|
55
|
+
if (useNative && host) {
|
|
56
|
+
const req: AppthenHostRequest = {
|
|
57
|
+
id: nextRequestId(),
|
|
58
|
+
version: 1,
|
|
59
|
+
method,
|
|
60
|
+
params,
|
|
61
|
+
context: ctx,
|
|
62
|
+
};
|
|
63
|
+
const res: AppthenHostResponse = await host.request(req);
|
|
64
|
+
if (!res.ok) throw res.error;
|
|
65
|
+
return res.result as T;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 2) native 不可用或被强制关掉 → 查 web 降级
|
|
69
|
+
const provider = webCapabilityProviders[method];
|
|
70
|
+
if (provider && hostModeAllowsWebFallback()) {
|
|
71
|
+
return (await provider.run(params, ctx)) as T;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
throw host
|
|
75
|
+
? { code: 'web_disabled', message: `能力「${method}」被强制走 native,但当前终端没有它。`, retryable: false }
|
|
76
|
+
: { code: 'host_unavailable', message: '当前环境没有 appthenHost(非客户端页面),且该能力没有 web 降级。', retryable: false };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 订阅 native → web 事件,返回取消函数。 */
|
|
80
|
+
export function appthenSubscribe<E = unknown>(
|
|
81
|
+
eventType: string,
|
|
82
|
+
listener: (payload: E) => void,
|
|
83
|
+
): () => void {
|
|
84
|
+
const host = getAppthenHost();
|
|
85
|
+
if (!host) return () => undefined;
|
|
86
|
+
return host.subscribe<E>(eventType, (event) => listener(event.payload));
|
|
87
|
+
}
|
package/src/contract.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* appthenHost 统一契约(v1)
|
|
3
|
+
*
|
|
4
|
+
* 桌面端(Electron)与移动端(RN WebView)共用这一份契约与 `window.appthenHost`
|
|
5
|
+
* Web 侧入口。业务代码只认这里定义的接口,不关心底层是 Electron IPC 还是 RN
|
|
6
|
+
* `postMessage`;更不要在本模块暴露任何 RN / Electron 专属对象名。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface AppthenHostContext {
|
|
10
|
+
tenantId?: string;
|
|
11
|
+
projectId?: string;
|
|
12
|
+
workspaceId?: string;
|
|
13
|
+
userGestureId?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface AppthenHostRequest<M extends string = string> {
|
|
17
|
+
id: string;
|
|
18
|
+
version: 1;
|
|
19
|
+
method: M;
|
|
20
|
+
params?: unknown;
|
|
21
|
+
context: AppthenHostContext;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface AppthenHostResponseOk {
|
|
25
|
+
id: string;
|
|
26
|
+
ok: true;
|
|
27
|
+
result: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface AppthenHostResponseErr {
|
|
31
|
+
id: string;
|
|
32
|
+
ok: false;
|
|
33
|
+
error: {
|
|
34
|
+
code: string;
|
|
35
|
+
message: string;
|
|
36
|
+
retryable?: boolean;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type AppthenHostResponse = AppthenHostResponseOk | AppthenHostResponseErr;
|
|
41
|
+
|
|
42
|
+
export interface AppthenHostEvent<E = unknown> {
|
|
43
|
+
eventType: string;
|
|
44
|
+
eventId: string;
|
|
45
|
+
correlationId?: string;
|
|
46
|
+
timestamp: number;
|
|
47
|
+
payload: E;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type AppthenHostEventListener<E> = (event: AppthenHostEvent<E>) => void;
|
|
51
|
+
|
|
52
|
+
/** 握手响应(启动第一件事)。capabilities 由各端按自己实装的能力组动态声明。 */
|
|
53
|
+
export interface AppthenHostHandshakeResponse {
|
|
54
|
+
protocolVersion: 1;
|
|
55
|
+
hostKind: 'ios' | 'android' | 'desktop';
|
|
56
|
+
appVersion: string;
|
|
57
|
+
capabilities: string[];
|
|
58
|
+
deviceId: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ---- voice 能力的方法入参 / 出参 / 事件(语义见 H 线「APP 壳必备 native 能力底座 · 语音」) ----
|
|
62
|
+
|
|
63
|
+
/** `voice.speak` 入参:把一段文字播报出来(TTS)。 */
|
|
64
|
+
export interface VoiceSpeakParams {
|
|
65
|
+
text: string;
|
|
66
|
+
/** 可选:语音标识,缺省用系统默认。 */
|
|
67
|
+
voice?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `voice.listen` 入参:开始一段语音听写,识别完返回最终文本(STT)。 */
|
|
71
|
+
export interface VoiceListenParams {
|
|
72
|
+
/** BCP-47 语言,缺省用系统默认。 */
|
|
73
|
+
language?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `voice.listen` 出参。 */
|
|
77
|
+
export interface VoiceListenResult {
|
|
78
|
+
transcript: string;
|
|
79
|
+
isFinal: true;
|
|
80
|
+
language?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `voice.onInterimTranscript` 事件:听写过程中滚动出现的中间结果。 */
|
|
84
|
+
export interface VoiceInterimTranscriptEvent {
|
|
85
|
+
transcript: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** voice 域对外事件名约定。 */
|
|
89
|
+
export const voiceEventTypes = {
|
|
90
|
+
onInterimTranscript: 'voice.onInterimTranscript',
|
|
91
|
+
} as const;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 全局 window 上的宿主入口
|
|
95
|
+
*
|
|
96
|
+
* WebView / 网页侧只认这一个接口,不关心宿主是 Electron 还是 RN iOS/Android。
|
|
97
|
+
* 桌面端虽然由 preload 的 contextBridge 注入,移动端由 injectedJavaScript 注入,
|
|
98
|
+
* 但暴露给业务的表面(request / subscribe)完全一致。
|
|
99
|
+
*/
|
|
100
|
+
export interface WindowAppthenHost {
|
|
101
|
+
request(req: AppthenHostRequest): Promise<AppthenHostResponse>;
|
|
102
|
+
subscribe<E>(eventType: string, listener: AppthenHostEventListener<E>): () => void;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
declare global {
|
|
106
|
+
interface Window {
|
|
107
|
+
appthenHost?: WindowAppthenHost;
|
|
108
|
+
}
|
|
109
|
+
}
|