@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,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 主机模式(host mode):决定一次能力调用「优先走 native 宿主还是 web 降级」。
|
|
4
|
+
*
|
|
5
|
+
* 背景:同一份 `appthenHost` 契约,桌面端(Electron)+ 移动端(RN WebView)由
|
|
6
|
+
* native 宿主提供能力;纯浏览器没有 `window.appthenHost`,但部分能力(剪贴板、
|
|
7
|
+
* 通知、外链、TTS/STT、选目录等)可以用浏览器原生 API「将就着用」。
|
|
8
|
+
* 这份模块统一这套切换逻辑,避免各个消费点自己判 `window.appthenHost`。
|
|
9
|
+
*
|
|
10
|
+
* 优先级(高 → 低):
|
|
11
|
+
* 1. 运行时 `setHostMode(mode)` 覆盖;
|
|
12
|
+
* 2. 环境变量 `APPTHEN_HOST_MODE`(Node):取值 auto | native | web;
|
|
13
|
+
* 3. `globalThis.APPTHEN_HOST_MODE`(Vite 可用 `define` 注入 / 页面自设);
|
|
14
|
+
* 4. 默认 `'auto'`。
|
|
15
|
+
*
|
|
16
|
+
* Vite 的 `VITE_` 变量不会进入预编译的 CommonJS dist,web 侧如有需要请用
|
|
17
|
+
* `define` 注入 `globalThis.APPTHEN_HOST_MODE`,或直接调用 `setHostMode`。
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.setHostMode = setHostMode;
|
|
21
|
+
exports.getHostMode = getHostMode;
|
|
22
|
+
exports.hostModeAllowsWebFallback = hostModeAllowsWebFallback;
|
|
23
|
+
exports.hostModeAllowsNative = hostModeAllowsNative;
|
|
24
|
+
let runtimeMode;
|
|
25
|
+
/** 运行时强制覆盖主机模式(例如在桌面里临时切到 web 路径做回归测试)。 */
|
|
26
|
+
function setHostMode(mode) {
|
|
27
|
+
runtimeMode = mode;
|
|
28
|
+
}
|
|
29
|
+
function normalize(value) {
|
|
30
|
+
if (typeof value !== 'string')
|
|
31
|
+
return undefined;
|
|
32
|
+
const v = value.trim().toLowerCase();
|
|
33
|
+
if (v === 'auto' || v === 'native' || v === 'web')
|
|
34
|
+
return v;
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
/** 当前生效的主机模式(调用时读取,允许运行时切换)。 */
|
|
38
|
+
function getHostMode() {
|
|
39
|
+
if (runtimeMode)
|
|
40
|
+
return runtimeMode;
|
|
41
|
+
// Node 侧 `process.env`(SDK 开启 `types:[]`,故经 globalThis 取,避免静态引用 process)
|
|
42
|
+
const nodeProc = globalThis.process;
|
|
43
|
+
if (nodeProc?.env?.APPTHEN_HOST_MODE) {
|
|
44
|
+
const fromEnv = normalize(nodeProc.env.APPTHEN_HOST_MODE);
|
|
45
|
+
if (fromEnv)
|
|
46
|
+
return fromEnv;
|
|
47
|
+
}
|
|
48
|
+
if (typeof globalThis !== 'undefined') {
|
|
49
|
+
const onGlobal = normalize(globalThis.APPTHEN_HOST_MODE);
|
|
50
|
+
if (onGlobal)
|
|
51
|
+
return onGlobal;
|
|
52
|
+
}
|
|
53
|
+
return 'auto';
|
|
54
|
+
}
|
|
55
|
+
/** web 降级是否在该模式下可用(`native` 模式返回 false)。 */
|
|
56
|
+
function hostModeAllowsWebFallback() {
|
|
57
|
+
return getHostMode() !== 'native';
|
|
58
|
+
}
|
|
59
|
+
/** 当前是否允许优先使用 native 宿主(`web` 模式返回 false)。 */
|
|
60
|
+
function hostModeAllowsNative() {
|
|
61
|
+
return getHostMode() !== 'web';
|
|
62
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @appthen/host-sdk —— appthenHost 统一桥共享 SDK
|
|
3
|
+
*
|
|
4
|
+
* 桌面端(Electron)与移动端(RN WebView)围绕这份包对齐:
|
|
5
|
+
* - `contract`:契约类型(request/response/event/handshake/voice + window.appthenHost)
|
|
6
|
+
* - `injectedScript`:注入页面的 Web JSSDK(transport 无关,两端同一份脚本)
|
|
7
|
+
* - `dispatcher`:native 侧统一分发逻辑(host.* / device.* 内建)
|
|
8
|
+
* - `client`:Web 侧统一客户端助手(appthenRequest / appthenSubscribe)
|
|
9
|
+
*/
|
|
10
|
+
export * from './contract';
|
|
11
|
+
export * from './host-mode';
|
|
12
|
+
export { webCapabilityProviders, type WebCapabilityProvider } from './web-providers';
|
|
13
|
+
export * from './client';
|
|
14
|
+
export * from './desktop';
|
|
15
|
+
export { AppthenHost, type MethodHandler, type AppthenHostOptions, type WebViewHostSink } from './dispatcher';
|
|
16
|
+
export { appthenHostInjectedScript } from './injectedScript';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.appthenHostInjectedScript = exports.AppthenHost = exports.webCapabilityProviders = void 0;
|
|
18
|
+
/**
|
|
19
|
+
* @appthen/host-sdk —— appthenHost 统一桥共享 SDK
|
|
20
|
+
*
|
|
21
|
+
* 桌面端(Electron)与移动端(RN WebView)围绕这份包对齐:
|
|
22
|
+
* - `contract`:契约类型(request/response/event/handshake/voice + window.appthenHost)
|
|
23
|
+
* - `injectedScript`:注入页面的 Web JSSDK(transport 无关,两端同一份脚本)
|
|
24
|
+
* - `dispatcher`:native 侧统一分发逻辑(host.* / device.* 内建)
|
|
25
|
+
* - `client`:Web 侧统一客户端助手(appthenRequest / appthenSubscribe)
|
|
26
|
+
*/
|
|
27
|
+
__exportStar(require("./contract"), exports);
|
|
28
|
+
__exportStar(require("./host-mode"), exports);
|
|
29
|
+
var web_providers_1 = require("./web-providers");
|
|
30
|
+
Object.defineProperty(exports, "webCapabilityProviders", { enumerable: true, get: function () { return web_providers_1.webCapabilityProviders; } });
|
|
31
|
+
__exportStar(require("./client"), exports);
|
|
32
|
+
__exportStar(require("./desktop"), exports);
|
|
33
|
+
var dispatcher_1 = require("./dispatcher");
|
|
34
|
+
Object.defineProperty(exports, "AppthenHost", { enumerable: true, get: function () { return dispatcher_1.AppthenHost; } });
|
|
35
|
+
var injectedScript_1 = require("./injectedScript");
|
|
36
|
+
Object.defineProperty(exports, "appthenHostInjectedScript", { enumerable: true, get: function () { return injectedScript_1.appthenHostInjectedScript; } });
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
// src/contract.ts
|
|
2
|
+
var voiceEventTypes = {
|
|
3
|
+
onInterimTranscript: "voice.onInterimTranscript"
|
|
4
|
+
};
|
|
5
|
+
|
|
6
|
+
// src/host-mode.ts
|
|
7
|
+
var runtimeMode;
|
|
8
|
+
function setHostMode(mode) {
|
|
9
|
+
runtimeMode = mode;
|
|
10
|
+
}
|
|
11
|
+
function normalize(value) {
|
|
12
|
+
if (typeof value !== "string") return void 0;
|
|
13
|
+
const v = value.trim().toLowerCase();
|
|
14
|
+
if (v === "auto" || v === "native" || v === "web") return v;
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
function getHostMode() {
|
|
18
|
+
if (runtimeMode) return runtimeMode;
|
|
19
|
+
const nodeProc = globalThis.process;
|
|
20
|
+
if (nodeProc?.env?.APPTHEN_HOST_MODE) {
|
|
21
|
+
const fromEnv = normalize(nodeProc.env.APPTHEN_HOST_MODE);
|
|
22
|
+
if (fromEnv) return fromEnv;
|
|
23
|
+
}
|
|
24
|
+
if (typeof globalThis !== "undefined") {
|
|
25
|
+
const onGlobal = normalize(globalThis.APPTHEN_HOST_MODE);
|
|
26
|
+
if (onGlobal) return onGlobal;
|
|
27
|
+
}
|
|
28
|
+
return "auto";
|
|
29
|
+
}
|
|
30
|
+
function hostModeAllowsWebFallback() {
|
|
31
|
+
return getHostMode() !== "native";
|
|
32
|
+
}
|
|
33
|
+
function hostModeAllowsNative() {
|
|
34
|
+
return getHostMode() !== "web";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/web-providers.ts
|
|
38
|
+
function hasWindow() {
|
|
39
|
+
return typeof window !== "undefined";
|
|
40
|
+
}
|
|
41
|
+
function requireWindow(what) {
|
|
42
|
+
if (!hasWindow()) {
|
|
43
|
+
throw { code: "web_unavailable", message: `\u80FD\u529B\u9700\u8981\u6D4F\u89C8\u5668\u73AF\u5883\uFF08${what}\uFF09\u3002`, retryable: false };
|
|
44
|
+
}
|
|
45
|
+
return window;
|
|
46
|
+
}
|
|
47
|
+
function pickWithInput(options) {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
const input = document.createElement("input");
|
|
50
|
+
input.type = "file";
|
|
51
|
+
if (options.webkitdirectory) input.setAttribute("webkitdirectory", "");
|
|
52
|
+
if (options.multiple) input.multiple = true;
|
|
53
|
+
if (options.accept) input.accept = options.accept;
|
|
54
|
+
input.style.position = "fixed";
|
|
55
|
+
input.style.opacity = "0";
|
|
56
|
+
input.style.pointerEvents = "none";
|
|
57
|
+
document.body.appendChild(input);
|
|
58
|
+
const cleanup = () => {
|
|
59
|
+
if (input.parentNode) input.parentNode.removeChild(input);
|
|
60
|
+
};
|
|
61
|
+
input.onchange = () => {
|
|
62
|
+
const files = Array.from(input.files ?? []);
|
|
63
|
+
cleanup();
|
|
64
|
+
resolve({
|
|
65
|
+
canceled: false,
|
|
66
|
+
files: files.map((f) => ({
|
|
67
|
+
name: f.name,
|
|
68
|
+
size: f.size,
|
|
69
|
+
relativePath: "webkitRelativePath" in f && f.webkitRelativePath ? f.webkitRelativePath : void 0
|
|
70
|
+
}))
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
input.oncancel = () => {
|
|
74
|
+
cleanup();
|
|
75
|
+
resolve({ canceled: true, files: [] });
|
|
76
|
+
};
|
|
77
|
+
input.click();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
var globalWindow = () => typeof globalThis !== "undefined" ? globalThis : {};
|
|
81
|
+
var activeWebRecognition = null;
|
|
82
|
+
var webCapabilityProviders = {
|
|
83
|
+
"navigation.openExternal": {
|
|
84
|
+
async run(params) {
|
|
85
|
+
const { url } = params ?? {};
|
|
86
|
+
if (!url || typeof url !== "string") {
|
|
87
|
+
throw { code: "invalid_arg", message: "navigation.openExternal \u9700\u8981 url\u3002", retryable: false };
|
|
88
|
+
}
|
|
89
|
+
const win = requireWindow("window.open");
|
|
90
|
+
win.open(url, "_blank", "noopener,noreferrer");
|
|
91
|
+
return { ok: true };
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
"navigation.openDeepLink": {
|
|
95
|
+
async run(params) {
|
|
96
|
+
const { url } = params ?? {};
|
|
97
|
+
if (!url || typeof url !== "string") {
|
|
98
|
+
throw { code: "invalid_arg", message: "navigation.openDeepLink \u9700\u8981 url\u3002", retryable: false };
|
|
99
|
+
}
|
|
100
|
+
if (/^https?:\/\//i.test(url)) {
|
|
101
|
+
const win = requireWindow("window.open");
|
|
102
|
+
win.open(url, "_blank", "noopener,noreferrer");
|
|
103
|
+
return { ok: true, open: true };
|
|
104
|
+
}
|
|
105
|
+
return { ok: true, open: false };
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
"device.registerPresence": {
|
|
109
|
+
async run(params) {
|
|
110
|
+
return params ?? { ok: true };
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
"notifications.show": {
|
|
114
|
+
async run(params) {
|
|
115
|
+
const NotificationCtor = globalWindow().Notification;
|
|
116
|
+
if (!NotificationCtor) {
|
|
117
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u7CFB\u7EDF\u901A\u77E5\u3002", retryable: false };
|
|
118
|
+
}
|
|
119
|
+
const { title, body, tag } = params ?? {};
|
|
120
|
+
if (!title) throw { code: "invalid_arg", message: "notifications.show \u9700\u8981 title\u3002", retryable: false };
|
|
121
|
+
if (NotificationCtor.permission === "denied") {
|
|
122
|
+
throw { code: "web_unavailable", message: "\u7CFB\u7EDF\u901A\u77E5\u6743\u9650\u88AB\u62D2\u7EDD\u3002", retryable: true };
|
|
123
|
+
}
|
|
124
|
+
if (NotificationCtor.permission === "default") await NotificationCtor.requestPermission();
|
|
125
|
+
if (NotificationCtor.permission !== "granted") {
|
|
126
|
+
throw { code: "web_unavailable", message: "\u672A\u83B7\u5F97\u7CFB\u7EDF\u901A\u77E5\u6743\u9650\u3002", retryable: true };
|
|
127
|
+
}
|
|
128
|
+
new NotificationCtor(title, { body, tag });
|
|
129
|
+
return { ok: true };
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
"clipboard.read": {
|
|
133
|
+
async run() {
|
|
134
|
+
const win = requireWindow("navigator.clipboard");
|
|
135
|
+
if (!win.navigator?.clipboard?.readText) {
|
|
136
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u526A\u8D34\u677F\u8BFB\u53D6\u3002", retryable: false };
|
|
137
|
+
}
|
|
138
|
+
const text = await win.navigator.clipboard.readText();
|
|
139
|
+
return { text };
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
"clipboard.write": {
|
|
143
|
+
async run(params) {
|
|
144
|
+
const win = requireWindow("navigator.clipboard");
|
|
145
|
+
const { text } = params ?? {};
|
|
146
|
+
if (typeof text !== "string") {
|
|
147
|
+
throw { code: "invalid_arg", message: "clipboard.write \u9700\u8981 text\u3002", retryable: false };
|
|
148
|
+
}
|
|
149
|
+
if (!win.navigator?.clipboard?.writeText) {
|
|
150
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u526A\u8D34\u677F\u5199\u5165\u3002", retryable: false };
|
|
151
|
+
}
|
|
152
|
+
await win.navigator.clipboard.writeText(text);
|
|
153
|
+
return { ok: true };
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
"dialog.chooseDirectory": {
|
|
157
|
+
async run() {
|
|
158
|
+
const result = await pickWithInput({ webkitdirectory: true });
|
|
159
|
+
return { canceled: result.canceled, paths: result.files.map((f) => f.relativePath ?? f.name) };
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
"files.pick": {
|
|
163
|
+
async run(params) {
|
|
164
|
+
const { multiple } = params ?? {};
|
|
165
|
+
const result = await pickWithInput({ multiple: Boolean(multiple) });
|
|
166
|
+
return { canceled: result.canceled, files: result.files };
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
"voice.speak": {
|
|
170
|
+
async run(params) {
|
|
171
|
+
const win = requireWindow("speechSynthesis");
|
|
172
|
+
const { text } = params ?? {};
|
|
173
|
+
if (!text) throw { code: "invalid_arg", message: "voice.speak \u9700\u8981 text\u3002", retryable: false };
|
|
174
|
+
if (!win.speechSynthesis) {
|
|
175
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u8BED\u97F3\u64AD\u62A5\u3002", retryable: false };
|
|
176
|
+
}
|
|
177
|
+
const UtteranceCtor = globalWindow().SpeechSynthesisUtterance;
|
|
178
|
+
if (!UtteranceCtor) {
|
|
179
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u8BED\u97F3\u64AD\u62A5\u3002", retryable: false };
|
|
180
|
+
}
|
|
181
|
+
win.speechSynthesis.speak(new UtteranceCtor(text));
|
|
182
|
+
return { ok: true };
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
"voice.stopSpeaking": {
|
|
186
|
+
async run() {
|
|
187
|
+
const win = requireWindow("speechSynthesis");
|
|
188
|
+
win.speechSynthesis?.cancel?.();
|
|
189
|
+
return { ok: true };
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
"voice.listen": {
|
|
193
|
+
async run(params) {
|
|
194
|
+
const globals = globalWindow();
|
|
195
|
+
const RecCtor = globals.SpeechRecognition ?? globals.webkitSpeechRecognition;
|
|
196
|
+
if (!RecCtor) {
|
|
197
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u8BED\u97F3\u8BC6\u522B\u3002", retryable: false };
|
|
198
|
+
}
|
|
199
|
+
const { language } = params ?? {};
|
|
200
|
+
const rec = new RecCtor();
|
|
201
|
+
rec.interimResults = false;
|
|
202
|
+
if (language) rec.lang = language;
|
|
203
|
+
activeWebRecognition = rec;
|
|
204
|
+
return new Promise((resolve, reject) => {
|
|
205
|
+
rec.onresult = (event) => {
|
|
206
|
+
const transcript = Array.from(event.results).map((r) => r[0]?.transcript).join("");
|
|
207
|
+
rec.stop();
|
|
208
|
+
resolve({ transcript, isFinal: true, language });
|
|
209
|
+
};
|
|
210
|
+
rec.onerror = (event) => {
|
|
211
|
+
rec.stop();
|
|
212
|
+
reject({ code: "web_recognition_error", message: `\u8BED\u97F3\u8BC6\u522B\u5931\u8D25\uFF1A${event?.error ?? "unknown"}`, retryable: true });
|
|
213
|
+
};
|
|
214
|
+
rec.onend = () => {
|
|
215
|
+
if (activeWebRecognition === rec) activeWebRecognition = null;
|
|
216
|
+
resolve({ transcript: "", isFinal: true, language });
|
|
217
|
+
};
|
|
218
|
+
rec.start();
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
"voice.stopListening": {
|
|
223
|
+
async run() {
|
|
224
|
+
const rec = activeWebRecognition;
|
|
225
|
+
activeWebRecognition = null;
|
|
226
|
+
if (rec) {
|
|
227
|
+
try {
|
|
228
|
+
rec.stop();
|
|
229
|
+
} catch {
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return { ok: true };
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
"share": {
|
|
236
|
+
async run(params) {
|
|
237
|
+
const win = requireWindow("navigator.share");
|
|
238
|
+
if (!win.navigator?.share) {
|
|
239
|
+
throw { code: "web_unavailable", message: "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u7CFB\u7EDF\u5206\u4EAB\u3002", retryable: false };
|
|
240
|
+
}
|
|
241
|
+
const payload = params ?? {};
|
|
242
|
+
await win.navigator.share({
|
|
243
|
+
title: payload.title,
|
|
244
|
+
text: payload.text,
|
|
245
|
+
url: payload.url
|
|
246
|
+
});
|
|
247
|
+
return { ok: true };
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
// src/client.ts
|
|
253
|
+
function getAppthenHost() {
|
|
254
|
+
if (typeof window === "undefined") return null;
|
|
255
|
+
return window.appthenHost ?? null;
|
|
256
|
+
}
|
|
257
|
+
var seqSeed = 0;
|
|
258
|
+
function nextRequestId() {
|
|
259
|
+
seqSeed += 1;
|
|
260
|
+
return `${Date.now().toString(36)}-${seqSeed}`;
|
|
261
|
+
}
|
|
262
|
+
async function appthenRequest(method, params, context) {
|
|
263
|
+
const ctx = context ?? {};
|
|
264
|
+
const host = getAppthenHost();
|
|
265
|
+
const useNative = Boolean(host) && hostModeAllowsNative();
|
|
266
|
+
if (useNative && host) {
|
|
267
|
+
const req = {
|
|
268
|
+
id: nextRequestId(),
|
|
269
|
+
version: 1,
|
|
270
|
+
method,
|
|
271
|
+
params,
|
|
272
|
+
context: ctx
|
|
273
|
+
};
|
|
274
|
+
const res = await host.request(req);
|
|
275
|
+
if (!res.ok) throw res.error;
|
|
276
|
+
return res.result;
|
|
277
|
+
}
|
|
278
|
+
const provider = webCapabilityProviders[method];
|
|
279
|
+
if (provider && hostModeAllowsWebFallback()) {
|
|
280
|
+
return await provider.run(params, ctx);
|
|
281
|
+
}
|
|
282
|
+
throw host ? { code: "web_disabled", message: `\u80FD\u529B\u300C${method}\u300D\u88AB\u5F3A\u5236\u8D70 native\uFF0C\u4F46\u5F53\u524D\u7EC8\u7AEF\u6CA1\u6709\u5B83\u3002`, retryable: false } : { code: "host_unavailable", message: "\u5F53\u524D\u73AF\u5883\u6CA1\u6709 appthenHost\uFF08\u975E\u5BA2\u6237\u7AEF\u9875\u9762\uFF09\uFF0C\u4E14\u8BE5\u80FD\u529B\u6CA1\u6709 web \u964D\u7EA7\u3002", retryable: false };
|
|
283
|
+
}
|
|
284
|
+
function appthenSubscribe(eventType, listener) {
|
|
285
|
+
const host = getAppthenHost();
|
|
286
|
+
if (!host) return () => void 0;
|
|
287
|
+
return host.subscribe(eventType, (event) => listener(event.payload));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// src/desktop.ts
|
|
291
|
+
var desktopRpcMethods = {
|
|
292
|
+
appVersion: "app.version",
|
|
293
|
+
serverGetUrl: "server.getUrl",
|
|
294
|
+
dialogChooseDirectory: "dialog.chooseDirectory",
|
|
295
|
+
daemonStatus: "daemon.status",
|
|
296
|
+
daemonStatusAll: "daemon.statusAll",
|
|
297
|
+
daemonStart: "daemon.start",
|
|
298
|
+
daemonStop: "daemon.stop",
|
|
299
|
+
daemonRestart: "daemon.restart",
|
|
300
|
+
daemonLogs: "daemon.logs",
|
|
301
|
+
logsOpenDirectory: "logs.openDirectory",
|
|
302
|
+
notificationsShow: "notifications.show",
|
|
303
|
+
eventsPublish: "events.publish",
|
|
304
|
+
updaterCheck: "updater.check",
|
|
305
|
+
updaterDownload: "updater.download",
|
|
306
|
+
updaterInstall: "updater.install",
|
|
307
|
+
navigationOpenExternal: "navigation.openExternal"
|
|
308
|
+
};
|
|
309
|
+
var desktopRpcEvents = {
|
|
310
|
+
daemonStatus: "daemon:status",
|
|
311
|
+
notification: "events:notification",
|
|
312
|
+
updaterState: "updater:state"
|
|
313
|
+
};
|
|
314
|
+
var desktopHostCapabilities = [
|
|
315
|
+
desktopRpcMethods.appVersion,
|
|
316
|
+
desktopRpcMethods.serverGetUrl,
|
|
317
|
+
desktopRpcMethods.dialogChooseDirectory,
|
|
318
|
+
desktopRpcMethods.daemonStatus,
|
|
319
|
+
desktopRpcMethods.daemonStatusAll,
|
|
320
|
+
desktopRpcMethods.daemonStart,
|
|
321
|
+
desktopRpcMethods.daemonStop,
|
|
322
|
+
desktopRpcMethods.daemonRestart,
|
|
323
|
+
desktopRpcMethods.daemonLogs,
|
|
324
|
+
desktopRpcMethods.logsOpenDirectory,
|
|
325
|
+
desktopRpcMethods.notificationsShow,
|
|
326
|
+
desktopRpcMethods.eventsPublish,
|
|
327
|
+
desktopRpcMethods.updaterCheck,
|
|
328
|
+
desktopRpcMethods.updaterDownload,
|
|
329
|
+
desktopRpcMethods.updaterInstall,
|
|
330
|
+
desktopRpcMethods.navigationOpenExternal
|
|
331
|
+
];
|
|
332
|
+
var desktopClient = {
|
|
333
|
+
getVersion: () => appthenRequest(desktopRpcMethods.appVersion),
|
|
334
|
+
server: {
|
|
335
|
+
getUrl: () => appthenRequest(desktopRpcMethods.serverGetUrl)
|
|
336
|
+
},
|
|
337
|
+
device: {
|
|
338
|
+
identity: () => appthenRequest("device.identity")
|
|
339
|
+
},
|
|
340
|
+
dialog: {
|
|
341
|
+
chooseDirectory: () => appthenRequest(desktopRpcMethods.dialogChooseDirectory)
|
|
342
|
+
},
|
|
343
|
+
daemon: {
|
|
344
|
+
status: (target) => appthenRequest(desktopRpcMethods.daemonStatus, target),
|
|
345
|
+
statusAll: () => appthenRequest(desktopRpcMethods.daemonStatusAll),
|
|
346
|
+
start: (config) => appthenRequest(desktopRpcMethods.daemonStart, config),
|
|
347
|
+
stop: (target) => appthenRequest(desktopRpcMethods.daemonStop, target),
|
|
348
|
+
restart: (config) => appthenRequest(desktopRpcMethods.daemonRestart, config),
|
|
349
|
+
logs: (target, limit) => appthenRequest(desktopRpcMethods.daemonLogs, { target, limit }),
|
|
350
|
+
/** 订阅 daemon 状态事件,返回取消函数。 */
|
|
351
|
+
onStatus: (listener) => appthenSubscribe(desktopRpcEvents.daemonStatus, listener)
|
|
352
|
+
},
|
|
353
|
+
logs: {
|
|
354
|
+
openDirectory: () => appthenRequest(desktopRpcMethods.logsOpenDirectory)
|
|
355
|
+
},
|
|
356
|
+
notifications: {
|
|
357
|
+
show: (payload) => appthenRequest(desktopRpcMethods.notificationsShow, payload)
|
|
358
|
+
},
|
|
359
|
+
events: {
|
|
360
|
+
publish: (payload) => appthenRequest(desktopRpcMethods.eventsPublish, payload),
|
|
361
|
+
/** 订阅应用内事件通知,返回取消函数。 */
|
|
362
|
+
onNotification: (listener) => appthenSubscribe(desktopRpcEvents.notification, listener)
|
|
363
|
+
},
|
|
364
|
+
updater: {
|
|
365
|
+
check: () => appthenRequest(desktopRpcMethods.updaterCheck),
|
|
366
|
+
download: () => appthenRequest(desktopRpcMethods.updaterDownload),
|
|
367
|
+
install: () => appthenRequest(desktopRpcMethods.updaterInstall),
|
|
368
|
+
/** 订阅更新状态,返回取消函数。 */
|
|
369
|
+
onState: (listener) => appthenSubscribe(desktopRpcEvents.updaterState, listener)
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// src/dispatcher.ts
|
|
374
|
+
var mkError = (id, code, message, retryable = false) => ({
|
|
375
|
+
id,
|
|
376
|
+
ok: false,
|
|
377
|
+
error: { code, message, retryable }
|
|
378
|
+
});
|
|
379
|
+
var mkOk = (id, result) => ({ id, ok: true, result });
|
|
380
|
+
var AppthenHost = class {
|
|
381
|
+
constructor(options) {
|
|
382
|
+
this.sink = null;
|
|
383
|
+
this.handlers = /* @__PURE__ */ new Map();
|
|
384
|
+
this.hostKind = options.hostKind;
|
|
385
|
+
this.appVersion = options.appVersion;
|
|
386
|
+
this.deviceId = options.deviceId;
|
|
387
|
+
this.capabilities = [...options.capabilities];
|
|
388
|
+
this.registerDefaults(options.notYetImplemented);
|
|
389
|
+
}
|
|
390
|
+
/** 绑定回写 sink(App / main 进程在拿到 WebView/WebContents 后调用)。 */
|
|
391
|
+
attach(sink) {
|
|
392
|
+
this.sink = sink;
|
|
393
|
+
}
|
|
394
|
+
/** 供各端能力注册专用方法(调用方自行保证 method 在 capabilities 里)。 */
|
|
395
|
+
registerMethod(method, handler) {
|
|
396
|
+
this.handlers.set(method, handler);
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* 处理收到的原文消息。
|
|
400
|
+
* 移动端:`react-native-webview` onMessage 的 `event.nativeEvent.data`。
|
|
401
|
+
* 桌面端:preload `ipcRenderer.send('appthen:toMain', raw)` 的 raw。
|
|
402
|
+
*/
|
|
403
|
+
handleIncoming(raw) {
|
|
404
|
+
let payload;
|
|
405
|
+
try {
|
|
406
|
+
payload = JSON.parse(raw);
|
|
407
|
+
} catch {
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (payload?.type !== "appthen:request" || !payload.req) return;
|
|
411
|
+
void this.handleRequest(payload.req);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Native → Web 事件(通知点击、语音转写/播报、daemon 状态等)。
|
|
415
|
+
* 业务用 `window.appthenHost.subscribe(eventType, listener)` 订阅。
|
|
416
|
+
*/
|
|
417
|
+
emit(eventType, payload, correlationId) {
|
|
418
|
+
if (!this.sink) return;
|
|
419
|
+
const event = {
|
|
420
|
+
eventType,
|
|
421
|
+
eventId: Math.random().toString(36).slice(2),
|
|
422
|
+
correlationId,
|
|
423
|
+
timestamp: Date.now(),
|
|
424
|
+
payload
|
|
425
|
+
};
|
|
426
|
+
this.sink.injectJavaScript(
|
|
427
|
+
`window.appthenHost && window.appthenHost.__dispatchEvent(${JSON.stringify(event)});`
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
registerDefaults(notYetImplemented) {
|
|
431
|
+
this.handlers.set("host.handshake", () => this.makeHandshake());
|
|
432
|
+
this.handlers.set("host.info", () => ({
|
|
433
|
+
hostKind: this.hostKind,
|
|
434
|
+
appVersion: this.appVersion,
|
|
435
|
+
deviceId: this.deviceId,
|
|
436
|
+
capabilities: this.capabilities
|
|
437
|
+
}));
|
|
438
|
+
this.handlers.set("device.identity", () => ({ deviceId: this.deviceId }));
|
|
439
|
+
this.handlers.set("device.registerPresence", (params) => params ?? { ok: true });
|
|
440
|
+
for (const method of notYetImplemented) {
|
|
441
|
+
this.handlers.set(method, () => {
|
|
442
|
+
throw {
|
|
443
|
+
code: "not_yet_implemented",
|
|
444
|
+
message: `\u80FD\u529B\u300C${method}\u300D\u7684\u539F\u751F\u6A21\u5757\u5C1A\u672A\u63A5\u5165\uFF08\u534F\u540C\u5DE5\u4F5C\u53F0\u540E\u7EED\u7248\u672C\u63D0\u4F9B\uFF09\u3002`,
|
|
445
|
+
retryable: false
|
|
446
|
+
};
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
makeHandshake() {
|
|
451
|
+
return {
|
|
452
|
+
protocolVersion: 1,
|
|
453
|
+
hostKind: this.hostKind,
|
|
454
|
+
appVersion: this.appVersion,
|
|
455
|
+
capabilities: [...this.capabilities],
|
|
456
|
+
deviceId: this.deviceId
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
async handleRequest(req) {
|
|
460
|
+
const respond = (resp) => {
|
|
461
|
+
this.sink?.injectJavaScript(
|
|
462
|
+
`window.appthenHost && window.appthenHost.__dispatchResponse(${JSON.stringify(resp)});`
|
|
463
|
+
);
|
|
464
|
+
};
|
|
465
|
+
if (req.version !== 1) {
|
|
466
|
+
respond(mkError(req.id, "unsupported_protocol", "\u4E0D\u652F\u6301\u7684\u534F\u8BAE\u7248\u672C\u3002"));
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
const handler = this.handlers.get(req.method);
|
|
470
|
+
if (!handler) {
|
|
471
|
+
respond(mkError(req.id, "method_not_found", `\u672A\u77E5\u65B9\u6CD5 ${req.method}\u3002`));
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
try {
|
|
475
|
+
const result = await handler(req.params, req.context);
|
|
476
|
+
respond(mkOk(req.id, result));
|
|
477
|
+
} catch (err) {
|
|
478
|
+
const e = err ?? {};
|
|
479
|
+
respond(mkError(req.id, e.code ?? "internal_error", e.message ?? "\u80FD\u529B\u6267\u884C\u5931\u8D25\u3002", Boolean(e.retryable)));
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
// src/injectedScript.ts
|
|
485
|
+
var appthenHostInjectedScript = String.raw`
|
|
486
|
+
(function () {
|
|
487
|
+
if (window.__appthenHostInstalled) return;
|
|
488
|
+
window.__appthenHostInstalled = true;
|
|
489
|
+
|
|
490
|
+
var pending = Object.create(null);
|
|
491
|
+
var listeners = Object.create(null);
|
|
492
|
+
var seed = 0;
|
|
493
|
+
var seq = function () { seed += 1; return Date.now().toString(36) + '-' + seed; };
|
|
494
|
+
|
|
495
|
+
var post = function (payload) {
|
|
496
|
+
var raw = JSON.stringify(payload);
|
|
497
|
+
if (window.__appthenHostTx && window.__appthenHostTx.post) {
|
|
498
|
+
window.__appthenHostTx.post(raw);
|
|
499
|
+
} else if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
|
500
|
+
window.ReactNativeWebView.postMessage(raw);
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
function request(req) {
|
|
505
|
+
return new Promise(function (resolve) {
|
|
506
|
+
var id = req && req.id ? req.id : seq();
|
|
507
|
+
var envelope = {
|
|
508
|
+
type: 'appthen:request',
|
|
509
|
+
req: {
|
|
510
|
+
id: id,
|
|
511
|
+
version: 1,
|
|
512
|
+
method: req.method,
|
|
513
|
+
params: req.params,
|
|
514
|
+
context: req.context || {}
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
pending[id] = resolve;
|
|
518
|
+
post(envelope);
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function subscribe(eventType, listener) {
|
|
523
|
+
(listeners[eventType] = listeners[eventType] || []).push(listener);
|
|
524
|
+
return function unsubscribe() {
|
|
525
|
+
var arr = listeners[eventType] || [];
|
|
526
|
+
var idx = arr.indexOf(listener);
|
|
527
|
+
if (idx >= 0) arr.splice(idx, 1);
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
window.appthenHost = { request: request, subscribe: subscribe };
|
|
532
|
+
|
|
533
|
+
window.appthenHost.__dispatchResponse = function (resp) {
|
|
534
|
+
var r = typeof resp === 'string' ? JSON.parse(resp) : resp;
|
|
535
|
+
var cb = pending[r.id];
|
|
536
|
+
if (cb) { delete pending[r.id]; cb(r); }
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
window.appthenHost.__dispatchEvent = function (ev) {
|
|
540
|
+
var e = typeof ev === 'string' ? JSON.parse(ev) : ev;
|
|
541
|
+
var arr = listeners[e.eventType] || [];
|
|
542
|
+
for (var i = 0; i < arr.length; i++) {
|
|
543
|
+
try { arr[i](e); } catch (err) { }
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
})();
|
|
547
|
+
`;
|
|
548
|
+
export {
|
|
549
|
+
AppthenHost,
|
|
550
|
+
appthenHostInjectedScript,
|
|
551
|
+
appthenRequest,
|
|
552
|
+
appthenSubscribe,
|
|
553
|
+
desktopClient,
|
|
554
|
+
desktopHostCapabilities,
|
|
555
|
+
desktopRpcEvents,
|
|
556
|
+
desktopRpcMethods,
|
|
557
|
+
getAppthenHost,
|
|
558
|
+
getHostMode,
|
|
559
|
+
hostModeAllowsNative,
|
|
560
|
+
hostModeAllowsWebFallback,
|
|
561
|
+
nextRequestId,
|
|
562
|
+
setHostMode,
|
|
563
|
+
voiceEventTypes,
|
|
564
|
+
webCapabilityProviders
|
|
565
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 注入 WebView / 页面的脚本(移动端经 `injectedJavaScriptBeforeContentLoaded`,
|
|
3
|
+
* 桌面端由 preload 在页面脚本运行前注入到主 world)。
|
|
4
|
+
*
|
|
5
|
+
* 在页面加载早期装好 `window.appthenHost`,业务代码只认它;这里不暴露任何
|
|
6
|
+
* RN / iOS / Android / Electron 专属对象。
|
|
7
|
+
*
|
|
8
|
+
* 通信通道(两端各喂一个 `post` 即可,脚本本体完全通用):
|
|
9
|
+
* - Web → Native:
|
|
10
|
+
* `window.__appthenHostTx.post(JSON.stringify({type:'appthen:request', req}))`
|
|
11
|
+
* - 移动端:RN WebView 里脚本找不到 `window.__appthenHostTx` 时,回落到
|
|
12
|
+
* `window.ReactNativeWebView.postMessage(...)`(保持向后兼容)。
|
|
13
|
+
* - 桌面端:preload 通过 contextBridge 暴露 `window.__appthenHostTx = { post }`,
|
|
14
|
+
* 底层走 `ipcRenderer.send('appthen:toMain', raw)`。
|
|
15
|
+
* - Native → Web:native 侧统一调 `window.appthenHost.__dispatchResponse/_dispatchEvent`。
|
|
16
|
+
*/
|
|
17
|
+
export declare const appthenHostInjectedScript: string;
|