@dp-bohrium/widget-sdk 0.0.7 → 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.
- package/AGENTS.md +33 -0
- package/CHANGELOG.md +110 -0
- package/README.md +159 -50
- package/dist/index.d.ts +7 -2
- package/dist/index.js +248 -2
- package/dist/lifetime.d.ts +12 -0
- package/dist/manifest.d.ts +13 -0
- package/dist/runtime/bootstrap.d.ts +13 -4
- package/dist/runtime/client.d.ts +9 -1
- package/dist/runtime/index.d.ts +6 -4
- package/dist/runtime/index.js +2 -2
- package/dist/runtime/service.d.ts +47 -0
- package/dist/runtime/version.d.ts +2 -0
- package/dist/{runtime-h-oTCwcs.js → runtime-Dute9ozh.js} +138 -2
- package/dist/widget.d.ts +157 -0
- package/llms.txt +24 -0
- package/package.json +5 -2
package/AGENTS.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Widget SDK Agent 使用说明
|
|
2
|
+
|
|
3
|
+
`@dp-bohrium/widget-sdk` 是 iframe 内 Widget 的运行时 SDK。Agent 先读取 `llms.txt`,再
|
|
4
|
+
根据任务选择高层 Widget API、低层 Runtime API 或测试入口;不要自行实现 Bridge 握手。
|
|
5
|
+
|
|
6
|
+
## 常用动作
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pnpm add @dp-bohrium/widget-sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
1. 用 `activate(context)` 实现 Widget;让 `bohr-widget` 生成 Host 入口。
|
|
13
|
+
2. 在 Manifest 中声明所需 capability,再使用 `context.capabilities`、`context.files`、
|
|
14
|
+
`context.tasks`、`context.ui` 或 `context.network`。
|
|
15
|
+
3. 在测试中使用 `@dp-bohrium/widget-sdk/testing` 的 `MockWidgetHost`;生产 Bundle 使用
|
|
16
|
+
根入口,不把 testing 入口打进产物。
|
|
17
|
+
4. 低层协议集成只从 `@dp-bohrium/widget-sdk/runtime` 导入,并保留 contracts 的精确版本。
|
|
18
|
+
|
|
19
|
+
## 错误恢复
|
|
20
|
+
|
|
21
|
+
- 初始化或 Bridge 失败:记录结构化错误的 `code`、`phase`、`message`、`retryable`、
|
|
22
|
+
`correlationId`,先检查 Bundle、Host API、版本、握手和 channel,再决定是否重试。
|
|
23
|
+
- 能力返回 `{ ok: false }`:根据 `reason` 和 `retryable` 分支处理;不要把拒绝当作异常,也
|
|
24
|
+
不要绕过 Host 直接访问凭据、文件路径或网络。
|
|
25
|
+
- `MESSAGE_INVALID`、`CHANNEL_MISMATCH`、`CAPABILITY_UNDECLARED` 和
|
|
26
|
+
`CAPABILITY_DENIED` 先修 Manifest、Host grant 或协议版本,不要无限重试。
|
|
27
|
+
- render/update 失败保留 `correlationId` 和当前 phase,确保界面仍能显示可恢复的空态。
|
|
28
|
+
|
|
29
|
+
## 边界
|
|
30
|
+
|
|
31
|
+
SDK 不授予权限、不上传或发布 Bundle、不决定 iframe/CSP 策略,也不保证脱离 Host 可以运行。
|
|
32
|
+
`ok=true` 只表示当前调用被 Runtime/Host 接受;真实授权、渲染和生产绑定由 Host 与平台负责。
|
|
33
|
+
发布包使用精确 SemVer;升级 SDK 时同步核对 contracts 版本和生成 Bundle 的 digest。
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# `@dp-bohrium/widget-sdk` 变更记录
|
|
2
|
+
|
|
3
|
+
本文件只记录影响使用者的变更:运行时 API、事件订阅、Manifest 要求。
|
|
4
|
+
|
|
5
|
+
## 0.2.0
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
**1. Host 用户资料读取 facade**
|
|
10
|
+
|
|
11
|
+
- 新增 `WidgetHostUserClient`(`createWidgetHostUserClient`),提供 `readProfile()` / `readEmail()` typed facade,内部仍走精确的 `host.user/profile.read` / `host.user/email.read` service.invoke。
|
|
12
|
+
- 新增 `HostUserProfile`(`{ userId, displayName }`)、`HostUserEmail`(`{ email }`)及对应 Result 类型。
|
|
13
|
+
- 无 grant 时仍在 iframe 内拒绝,不发送 Bridge request。
|
|
14
|
+
|
|
15
|
+
## 0.1.0
|
|
16
|
+
|
|
17
|
+
### 新增
|
|
18
|
+
|
|
19
|
+
**1. 暴露受控文件下载、长任务观察和 UI 状态 API**
|
|
20
|
+
|
|
21
|
+
- 新增 `context.files.download`、`context.tasks.watch` 和 `context.ui.state.read/write`,均受 Host grant、预算和作用域约束。
|
|
22
|
+
|
|
23
|
+
**2. 暴露结构化 Tool Result envelope 类型**
|
|
24
|
+
|
|
25
|
+
- SDK 类型和运行时辅助函数支持带状态、指标、产物引用、provenance、warning 与 missing 的结构化 Tool Result。
|
|
26
|
+
|
|
27
|
+
说明:0.0.9 曾在 Git 中准备,但未创建发布 Tag 或进入 npm;本节变更作为新的兼容性边界随 0.1.0 发布。
|
|
28
|
+
|
|
29
|
+
## 0.0.8
|
|
30
|
+
|
|
31
|
+
### 修复
|
|
32
|
+
|
|
33
|
+
- 与 `@dp-bohrium/widget-contracts` 0.0.8 保持版本一致。运行时 API、事件订阅与 Manifest 要求均无变化,从 0.0.7 升级无需改代码。
|
|
34
|
+
|
|
35
|
+
说明:0.0.8 未单独发布;本节变更最终随 0.1.0 一并发布。
|
|
36
|
+
|
|
37
|
+
## 0.0.7
|
|
38
|
+
|
|
39
|
+
### 破坏性变更
|
|
40
|
+
|
|
41
|
+
**1. onEvent 的事件载荷从 PublicWidgetEvent 变为 WidgetLiveEvent**
|
|
42
|
+
|
|
43
|
+
新载荷只有 `type` 和 `payload` 两个字段。`schemaVersion`、`id`、`occurredAt`、`sessionId`、`workflowId`、`topic` 都不再下发,读这些字段的代码会失效。
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// 0.0.6 及以前
|
|
47
|
+
client.onEvent((event) => {
|
|
48
|
+
if (event.topic === "tools.lifecycle" && event.type === "tool-call") {
|
|
49
|
+
render(event.payload);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// 0.0.7 —— 按 type 分派,不再有 topic
|
|
54
|
+
client.onEvent((event) => {
|
|
55
|
+
if (event.type === "tool-call") {
|
|
56
|
+
render(event.payload);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
需要 `sessionId` / `workflowId` 的,从 `init` 阶段拿到的上下文取,不要再从事件对象上读。
|
|
62
|
+
|
|
63
|
+
**2. Manifest 的 widgetConfig.behaviors 移除,改为 widgetConfig.activationEvents**
|
|
64
|
+
|
|
65
|
+
从对象数组改成字符串数组,保留旧字段的 Manifest 上传会被拒。完整迁移写法见 `@dp-bohrium/widget-contracts` 的变更记录。原先靠 `behaviors` 自动执行 `panel.open` 等 Host 动作的能力没有等价替代。
|
|
66
|
+
|
|
67
|
+
### 新增
|
|
68
|
+
|
|
69
|
+
- onEvent 新增按事件名订阅的重载,回调直接收到该类型的事件,不必再判断 event.type。
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
client.onEvent("tool-call", (event) => render(event.payload));
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
无参数形式仍然接收全部事件,行为不变。
|
|
76
|
+
|
|
77
|
+
## 0.0.6
|
|
78
|
+
|
|
79
|
+
### 新增
|
|
80
|
+
|
|
81
|
+
- 支持接收 Host 通过 MessageChannel 主动推送的实时事件(`onEvent`),无需 HTTP 轮询。
|
|
82
|
+
|
|
83
|
+
## 0.0.5
|
|
84
|
+
|
|
85
|
+
### 新增
|
|
86
|
+
|
|
87
|
+
- 支持消费事件驱动的 Widget 行为。
|
|
88
|
+
|
|
89
|
+
## 0.0.4
|
|
90
|
+
|
|
91
|
+
### 新增
|
|
92
|
+
|
|
93
|
+
- Manifest 支持声明式地在 Session 启动时打开 Panel。
|
|
94
|
+
|
|
95
|
+
## 0.0.3
|
|
96
|
+
|
|
97
|
+
- 仅发布流程调整,无对外变更。
|
|
98
|
+
|
|
99
|
+
## 0.0.2
|
|
100
|
+
|
|
101
|
+
### 破坏性变更
|
|
102
|
+
|
|
103
|
+
- 包迁移至 `@dp-bohrium` scope,旧 scope 不再发布新版本。
|
|
104
|
+
|
|
105
|
+
## 0.0.1
|
|
106
|
+
|
|
107
|
+
首个公开版本。
|
|
108
|
+
|
|
109
|
+
- MessagePort Transport、Widget 生命周期、Host Bridge 能力。
|
|
110
|
+
- Host 代理的网络请求能力。
|
package/README.md
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
# @dp-bohrium/widget-sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Agent 使用入口:先读 [`llms.txt`](./llms.txt) 获取文档索引,再读 [`AGENTS.md`](./AGENTS.md)
|
|
4
|
+
获取安装、运行时调用和错误恢复规则。
|
|
5
|
+
|
|
6
|
+
Widget 开发者 SDK。普通作者只实现 `activate(context)` 和可选的 `deactivate()`;CLI
|
|
7
|
+
会生成 Widget Host 入口,负责向 Host 宣告 Bundle、接收转移过来的 `MessagePort`,并暴露共享的
|
|
8
|
+
生命周期与能力协议。作者无需直接处理 `window.postMessage`,也无需手动启动插件。
|
|
9
|
+
|
|
10
|
+
激活事件目录、`context.events` 与低层 `topic` 的边界以本包的 `AGENTS.md`、本 README
|
|
11
|
+
和 `@dp-bohrium/widget-contracts` 中的类型与 Schema 为准。
|
|
6
12
|
|
|
7
13
|
## 环境要求
|
|
8
14
|
|
|
@@ -25,74 +31,165 @@ pnpm add @dp-bohrium/widget-sdk
|
|
|
25
31
|
yarn add @dp-bohrium/widget-sdk
|
|
26
32
|
```
|
|
27
33
|
|
|
28
|
-
|
|
34
|
+
需要在 TypeScript 中直接声明或在编辑器中解析 Manifest Schema 时,再把
|
|
35
|
+
`@dp-bohrium/widget-contracts` 作为开发依赖安装;它是独立的类型/Schema 包,不需要通过
|
|
36
|
+
`defineManifest()` 工厂获得提示。
|
|
37
|
+
|
|
38
|
+
在自己的 `package.json` 里钉死精确 SemVer,不要用 `^` 或裸 `latest`。SDK 运行时会从已安装
|
|
39
|
+
包自身读取版本,插件源码和 Manifest 不需要再次填写 SDK 版本。
|
|
29
40
|
|
|
30
41
|
## 快速开始
|
|
31
42
|
|
|
32
43
|
```ts
|
|
33
|
-
import {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// 按 Slot 渲染完整快照。
|
|
44
|
-
renderSlot(request.slot, request.content);
|
|
45
|
-
},
|
|
46
|
-
onDispose({ reason, deadlineMs }) {
|
|
47
|
-
// 释放定时器、订阅与 worker。
|
|
48
|
-
releaseLocalResources(reason, deadlineMs);
|
|
49
|
-
},
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
await widget.ready();
|
|
53
|
-
widget.resize({ width: 600, height: 400 });
|
|
44
|
+
import type { WidgetContext } from "@dp-bohrium/widget-sdk";
|
|
45
|
+
|
|
46
|
+
export function activate(context: WidgetContext) {
|
|
47
|
+
context.render((request, renderContext) => {
|
|
48
|
+
renderSlot(request.slot, request.content, renderContext.phase);
|
|
49
|
+
});
|
|
50
|
+
context.events.on("tool-call-result", () => {
|
|
51
|
+
void context.ui.present("floating");
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
+
CLI 生成的 `src/widget-host.ts` 会调用平台入口 `runWidgetHost(widget)`。
|
|
57
|
+
这借鉴 VS Code 的激活入口。最终模型按 Binding 建立一个 Extension Runtime,`activate(context)`
|
|
58
|
+
在 Runtime 内只执行一次;工具、文件或面板目标是挂载到 Runtime 的 Surface Instance,拥有
|
|
59
|
+
独立的快照和释放句柄,不会再次触发 `activate`。开发者实现 `activate(context)`,可选实现
|
|
60
|
+
`deactivate()`;Widget Host/SDK 负责加载、等待初始化、报告启动失败和执行清理。普通插件
|
|
61
|
+
代码不需要调用 `ready()`,也不应该写 `plugin.ready().catch(() => {})`。`whenReady` 只保留
|
|
62
|
+
给测试和高级宿主编排;`whenDisposed` 可用于等待已完成激活插件的异步 `deactivate()`。
|
|
63
|
+
停用不会等待一个永不结束的 `activate()`;若激活在停用后迟到完成,SDK 会在已 abort 的生命周期上补偿释放并调用一次 `deactivate()`,但这不再延长 `whenDisposed`。
|
|
64
|
+
|
|
65
|
+
这是 SDK 的目标生命周期契约;当前 Widget Host 的动态加载仍由 Surface-bound Adapter 接线,
|
|
66
|
+
Binding 级 Runtime Loader 尚未开放。插件可以按 Runtime/Surface 分层设计,但不能把当前版本
|
|
67
|
+
当成“无界面必然已启动”的生产保证。
|
|
68
|
+
|
|
69
|
+
`context.signal` 会在 Host 停用插件或 Bridge 断开时 `abort`。`context.render` 和 `context.events`
|
|
70
|
+
会自动登记到当前插件生命周期;`subscriptions` 只用于
|
|
71
|
+
第三方计时器、观察器或其它需要在停用时释放的资源。
|
|
72
|
+
|
|
56
73
|
三条时序约定:
|
|
57
74
|
|
|
58
|
-
- `ready()` 只在 `
|
|
75
|
+
- `ready()` 只在 `activate(context)` 返回(含其 Promise settle)之后才发给 Host,
|
|
59
76
|
`handshakeTimeoutMs` 同时约束这一步;
|
|
60
|
-
- 初始化失败时,SDK
|
|
61
|
-
|
|
77
|
+
- 初始化失败时,SDK 先报结构化错误,再调用已登记的插件资源清理;成功激活后的释放会
|
|
78
|
+
最多调用一次 `deactivate()`,已完成激活的异步清理可通过 `whenDisposed` 等待;
|
|
79
|
+
- `context.render` 首帧和更新都会收到完整快照,通过 `renderContext.phase` 区分。
|
|
80
|
+
|
|
81
|
+
## 从 Manifest 到插件运行
|
|
82
|
+
|
|
83
|
+
Manifest 是插件的静态声明,SDK 代码是隔离 iframe 内的运行时实现,Host 负责二者之间的生命周期编排。一个插件可以这样声明:
|
|
84
|
+
|
|
85
|
+
```json
|
|
86
|
+
{
|
|
87
|
+
"$schema": "@dp-bohrium/widget-contracts/schemas/widget-plugin-manifest.schema.json",
|
|
88
|
+
"name": "research",
|
|
89
|
+
"version": "1.0.0",
|
|
90
|
+
"entry": "src/widget.ts",
|
|
91
|
+
"displayName": "研究面板",
|
|
92
|
+
"description": "展示研究工具的结构化结果",
|
|
93
|
+
"activationEvents": ["session.start", "tool-call-result:ScholarSearch", "ui-tool-opened"],
|
|
94
|
+
"contributes": {
|
|
95
|
+
"widget": { "type": "panel", "id": "research", "surfaces": ["workspace", "floating"] }
|
|
96
|
+
},
|
|
97
|
+
"capabilities": {
|
|
98
|
+
"files": { "read": true },
|
|
99
|
+
"events": { "topics": ["tool-call-result", "workspace-file-opened"] }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
需要接管完整的会话右侧区域时,在同一个 Panel contribution 上声明结构性放置意图,并同时申请匹配的
|
|
105
|
+
`ui.region` capability:
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"contributes": {
|
|
110
|
+
"widget": {
|
|
111
|
+
"type": "panel",
|
|
112
|
+
"id": "better-sidebar",
|
|
113
|
+
"placement": { "kind": "region", "region": "session.rightRail", "mode": "replace" }
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
"capabilities": {
|
|
117
|
+
"region": { "regions": ["session.rightRail"], "mode": "replace" }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`placement` 只表达贡献点的结构性意图;区域租约、确认、几何、焦点、原生面板恢复和失败回退仍由 Host
|
|
123
|
+
负责。没有匹配 capability 时,SDK 编译阶段直接拒绝清单。
|
|
124
|
+
|
|
125
|
+
`activationEvents` 只决定 Host 何时创建插件运行时;它不授予事件读取权限,也不负责打开思考过程或某个面板。插件激活后通过 `context.events` 和 `context.render` 注册监听与渲染器。Host 会对每个事件和能力请求做白名单投影与授权,插件收到的事件可能是有限回放,也可能是实时事件。
|
|
126
|
+
|
|
127
|
+
实现建议:事件处理器保持幂等,按 `toolCallId` 或 `requestId` 去重;不要从 iframe URL、DOM 或宿主绝对路径推断内部数据;当能力未授予时显示结构化空态并继续保留可渲染的主界面。声明但没有实际使用的能力会被 Host 记录为诊断信息,未声明能力的调用会被拒绝并结束当前 Bridge 会话。
|
|
128
|
+
|
|
129
|
+
### 统一插件入口
|
|
130
|
+
|
|
131
|
+
所有公开插件类型都使用同一个 `activate(context)` 约定。面板和文件预览由
|
|
132
|
+
Manifest 的 `contributes.widget` 决定;运行时代码只认识统一的 `context.events`、
|
|
133
|
+
`context.render`、`context.capabilities` 和 `context.ui`。首帧和后续快照通过
|
|
134
|
+
`renderContext.phase` 区分,不需要维护两套回调。
|
|
135
|
+
|
|
136
|
+
Manifest 的编辑器提示来自 `@dp-bohrium/widget-contracts` 发布的 JSON Schema 和
|
|
137
|
+
TypeScript 类型,不依赖某个 `defineManifest` 工厂。构建工具调用
|
|
138
|
+
`compileWidgetPluginManifest`,自动补齐 `schemaVersion`、`hostApiVersion`、SDK 版本和
|
|
139
|
+
宿主加载字段;它会直接读取 Manifest 内的 `samples`,只有构建器从别处生成样例时
|
|
140
|
+
才需要传入第二个参数。`createWidgetClient` 是协议级基础实现,不属于 Widget 作者 API;当前根入口只提供统一 Widget API,协议级代码应从
|
|
141
|
+
`./runtime` 显式引入。
|
|
142
|
+
|
|
143
|
+
受信任的内部 Host/协议测试仍可直接构造低层 Tool Result RenderRequest,但该能力不属于外部作者清单或公共示例。
|
|
144
|
+
|
|
145
|
+
SDK 发布包会生成 `dist/index.d.ts` 与对应的 declaration map,并通过 `package.json` 的
|
|
146
|
+
`types`/`exports` 暴露。插件安装 `@dp-bohrium/widget-sdk` 后,编辑器会直接获得
|
|
147
|
+
`WidgetContext`、事件名、能力请求、渲染请求和生命周期返回值的类型提示;Manifest
|
|
148
|
+
编辑器提示由 `@dp-bohrium/widget-contracts` 的 JSON Schema 和声明文件提供。
|
|
62
149
|
|
|
63
150
|
## 包入口
|
|
64
151
|
|
|
65
152
|
| 入口 | 内容 | 用途 |
|
|
66
153
|
| --- | --- | --- |
|
|
67
|
-
| `.` | `
|
|
154
|
+
| `.` | `runWidgetHost`、`compileWidgetPluginManifest` 和全部公开类型 | 生成的生产 Bundle |
|
|
68
155
|
| `./testing` | `MemoryTransport`、`MockWidgetHost` | 单元测试 |
|
|
69
156
|
| `./runtime` | 低层 `WidgetClient`、transport 与 bootstrap 常量 | 协议级集成 |
|
|
70
|
-
| `./package.json` | 已安装包的元数据 |
|
|
157
|
+
| `./package.json` | 已安装包的元数据 | SDK 和构建工具自动读取版本,作者无需复制版本字符串 |
|
|
158
|
+
|
|
159
|
+
根入口只导出插件运行时和 Manifest 编译所需的少量值,其余均为类型。低层
|
|
160
|
+
`MessagePortTransport` 与 bootstrap 消息不属于普通 Widget API。
|
|
71
161
|
|
|
72
|
-
|
|
73
|
-
|
|
162
|
+
`runWidgetHost` 是生成的 `widget-host.ts` 使用的 Widget Host 启动边界;
|
|
163
|
+
插件作者只维护 `widget.ts` 中的 `activate/deactivate`。
|
|
74
164
|
|
|
75
165
|
## 能力
|
|
76
166
|
|
|
77
|
-
|
|
78
|
-
|
|
167
|
+
公开能力要在 Manifest 的 `capabilities` 里声明,并由 Host 实际 grant;
|
|
168
|
+
`service.invoke` 需要由 Host binding 显式授权。缺任一侧,调用在 Widget 本地即被拒绝。
|
|
169
|
+
所有能力调用都必须在 `ready()` 之后。
|
|
79
170
|
|
|
80
|
-
|
|
81
|
-
|
|
171
|
+
下面列出的能力是当前 SDK 支持的能力。grant 名与 Manifest 申请键不一定同名 —— `ui.presentation`
|
|
172
|
+
对应的作者侧申请键是 `capabilities.presentation`(编译后的 宿主格式字段才叫
|
|
173
|
+
`requestedCapabilities.presentation`)。
|
|
82
174
|
|
|
83
175
|
| grant 名 | Manifest 申请键 | SDK 调用 |
|
|
84
176
|
| --- | --- | --- |
|
|
85
|
-
| `files.list` / `files.metadata` / `files.read` | `files` | `
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
88
|
-
| `
|
|
89
|
-
| `ui.
|
|
90
|
-
|
|
91
|
-
|
|
177
|
+
| `files.list` / `files.metadata` / `files.read` | `files` | `context.capabilities.request({ operation, input })` |
|
|
178
|
+
| `files.download` | `files.download` | `context.files.download({ file, suggestedName })` |
|
|
179
|
+
| `events.read` | `events`(需列出 `topics`) | 低层分页订阅;`context.events.on(…)` 是 Host 主动推送,不需要该 grant |
|
|
180
|
+
| `tasks.watch` | `tasks.watch` | `context.tasks.watch({ taskId, cursor, limit })` |
|
|
181
|
+
| `ui.state` | `state`(`read` / `write`) | `context.ui.state.read(key)` / `write(key, value)` |
|
|
182
|
+
| `actions.invoke` | `actions` | `context.capabilities.request({ operation: "actions.invoke", input })` |
|
|
183
|
+
| `network.fetch` | `network` | `context.network.fetch(…)` |
|
|
184
|
+
| `service.invoke` | 由 Host binding 显式授权 | `context.services.invoke({ service, action, payload })` |
|
|
185
|
+
| `ui.presentation` | `presentation` | `context.ui.present(…)` / `changeSurface` / `close` |
|
|
186
|
+
| `ui.region` | `region`(固定申请 `session.rightRail`) | `context.ui.region.acquire()` / `release()` |
|
|
187
|
+
|
|
188
|
+
除 Host 主动推送事件外,其余能力共用同一套调用范式,掌握下面这一个就会调其余能力:
|
|
92
189
|
|
|
93
190
|
```ts
|
|
94
191
|
const controller = new AbortController();
|
|
95
|
-
const result = await
|
|
192
|
+
const result = await context.network.fetch(
|
|
96
193
|
{ url: "https://api.example.org/papers", method: "GET", auth: "optional" },
|
|
97
194
|
{ signal: controller.signal, timeoutMs: 15_000 },
|
|
98
195
|
);
|
|
@@ -105,19 +202,30 @@ if (result.ok) {
|
|
|
105
202
|
}
|
|
106
203
|
```
|
|
107
204
|
|
|
108
|
-
|
|
205
|
+
跨能力约定:
|
|
109
206
|
|
|
110
207
|
- 失败以 `{ ok: false, reason, message, retryable }` 正常兑现;只有客户端超时、中止、
|
|
111
208
|
dispose 和畸形响应才 reject。
|
|
112
209
|
- 中止与超时统一用 `{ signal, timeoutMs }`,复用既有 MessageChannel 能力生命周期。
|
|
113
210
|
- Widget 永远拿不到 Host 凭据,也不应直接调用浏览器 `fetch`:是否弹窗、记住 Origin
|
|
114
211
|
授权、跟随重定向还是拒绝,全部由 Host 决定。
|
|
212
|
+
- `context.services` 仅在 Host binding 授予 `service.invoke` 后可用。可调用的服务、操作、请求/响应
|
|
213
|
+
大小和有效期由 Host 的授权策略决定;未获授权时调用会被拒绝。认证状态由宿主侧管理,SDK 只收发
|
|
214
|
+
业务 payload,不会把 Cookie、Bearer Token 或其他凭据放入 iframe。
|
|
215
|
+
- `context.files.download` 只提交文件引用和建议文件名;Host 在用户确认后经宿主
|
|
216
|
+
Download Adapter 惰性打开内容源。Widget 不会收到源 URL、保存路径或凭据。
|
|
217
|
+
- `context.tasks.watch` 只读取一次受限任务快照和事件页;调用方用返回的 cursor 继续轮询。
|
|
218
|
+
它不创建、调度或取消任务,服务端负责任务授权、脱敏和终态保留。
|
|
219
|
+
- `context.ui.state` 只保存按 Widget + Session 隔离的 JSON UI 状态;Host 按 key、单值大小、总字节数和调用
|
|
220
|
+
频率限流。它不能保存任务执行、凭据、文件内容或 Workspace 权限状态。
|
|
221
|
+
- 外部插件的工具结果场景通过 `tool-call-result` 事件作为可选运行时信号;内部 Host/协议测试仍可使用低层 Tool Result RenderRequest
|
|
222
|
+
或展示槽位。插件应把结果转换成自己的 Panel 数据,再通过 `context.render` 更新面板。
|
|
115
223
|
- 呈现只是**请求**。Host 可能降级到别的表面,成功结果里的 `surface` 才是真实表面;
|
|
116
224
|
Widget 不能指定目标 Panel、身份、运行时 generation、坐标或层级。
|
|
117
|
-
-
|
|
118
|
-
|
|
119
|
-
`subscribeEvents` / `onTool
|
|
120
|
-
- `subscribeEvents` / `onTool` 的所有订阅共享同一实例的 events 读预算,并各自遵守
|
|
225
|
+
- 高层插件 API 使用 `context.events.on(handler)` 接收 Host 从当前 Runtime **主动推送**的
|
|
226
|
+
聚合事件,只按 `type` 分发,不依赖 Manifest Topic 或 `events.read` grant。需要直接使用有界
|
|
227
|
+
分页读取时,从 `@dp-bohrium/widget-sdk/runtime` 使用 `subscribeEvents` / `onTool`。
|
|
228
|
+
- 低层 `subscribeEvents` / `onTool` 的所有订阅共享同一实例的 events 读预算,并各自遵守
|
|
121
229
|
topic 最小轮询间隔 —— 订阅越多,单个 topic 刷新越慢。游标只在 `onBatch` 成功后
|
|
122
230
|
提交,重新订阅需显式传回 `events.cursor`。工具 Hook 观察的是**已经发生的**服务端
|
|
123
231
|
事实,不是执行前拦截器。
|
|
@@ -139,9 +247,10 @@ import { MockWidgetHost } from "@dp-bohrium/widget-sdk/testing";
|
|
|
139
247
|
## 限制
|
|
140
248
|
|
|
141
249
|
- SDK 不做授权决策,能力是否可用最终由 Host 判定。
|
|
250
|
+
- `tasks.watch` 是有界观察协议,不是调度器、执行器或取消 API;任务状态和事件由服务端投影。
|
|
142
251
|
- `invokeAction` 不自动重试,回调完成也不代表工具执行完成。
|
|
143
252
|
- `subscribeEvents` 的 `events.read` 是有界分页读取,不是 websocket;实时推送走
|
|
144
|
-
`onEvent
|
|
253
|
+
`onEvent`。当前版本没有单请求取消的独立协议消息:`unsubscribe` 会停止后续轮询并取消
|
|
145
254
|
本地等待,已发出的服务端读取可能完成,但结果被忽略。
|
|
146
255
|
- Host 发来畸形 Bridge 信封或载荷时,transport 报结构化 `MESSAGE_INVALID` 并关闭
|
|
147
256
|
连接,不会让 Widget 悬等。
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,7 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
export {
|
|
1
|
+
export type { WidgetActivationEvent, WidgetActivationEvents, WidgetContribution, WidgetEventName, WidgetFilePreviewContribution, WidgetPanelContribution, WidgetPluginContributions, WidgetPluginManifest, WidgetToolPhase, } from "@dp-bohrium/widget-contracts";
|
|
2
|
+
export { isWidgetActivationEvent, isWidgetEventName, WIDGET_ACTIVATION_EVENTS, WIDGET_EVENT_NAMES, } from "@dp-bohrium/widget-contracts";
|
|
3
|
+
export type { CompileWidgetPluginManifestOptions } from "./manifest.js";
|
|
4
|
+
export { compileWidgetPluginManifest } from "./manifest.js";
|
|
5
|
+
export type { HostUserEmail, HostUserEmailResult, HostUserProfile, HostUserProfileResult, WidgetHostUserClient, } from "./runtime/service.js";
|
|
6
|
+
export type { FileDownloadCapabilityResult, TaskWatchCapabilityResult, UiStateReadCapabilityResult, UiStateWriteCapabilityResult, WidgetActivation, WidgetCapabilityApi, WidgetContext, WidgetDisposable, WidgetEventApi, WidgetFileApi, WidgetHandle, WidgetHostOptions, WidgetModule, WidgetRenderContext, WidgetRenderHandler, WidgetTaskApi, WidgetUiApi, WidgetUiStateApi, } from "./widget.js";
|
|
7
|
+
export { runWidgetHost } from "./widget.js";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,248 @@
|
|
|
1
|
-
import { i as createWidgetClient,
|
|
2
|
-
|
|
1
|
+
import { i as createWidgetClient, l as WIDGET_SDK_VERSION } from "./runtime-Dute9ozh.js";
|
|
2
|
+
import { WIDGET_ACTIVATION_EVENTS, WIDGET_EVENT_NAMES, isWidgetActivationEvent, isWidgetEventName } from "@dp-bohrium/widget-contracts";
|
|
3
|
+
//#region src/manifest.ts
|
|
4
|
+
function compiledSlot(contribution) {
|
|
5
|
+
switch (contribution.type) {
|
|
6
|
+
case "panel": return {
|
|
7
|
+
type: "panel",
|
|
8
|
+
panelType: contribution.id,
|
|
9
|
+
...contribution.placement === void 0 ? {} : { placement: contribution.placement }
|
|
10
|
+
};
|
|
11
|
+
case "file-preview": return {
|
|
12
|
+
type: "file-preview",
|
|
13
|
+
extensions: [...contribution.extensions]
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* 将开发者维护的插件清单编译为宿主可加载的宿主清单。
|
|
19
|
+
*
|
|
20
|
+
* 这是构建工具的边界函数,不是类型提示入口:作者直接编辑带 `$schema` 的 JSON,
|
|
21
|
+
* SDK 版本从当前安装包读取,宿主入口默认落到 dist/widget.js,内部 slot 标识只在这里生成。
|
|
22
|
+
*/
|
|
23
|
+
function compileWidgetPluginManifest(manifest, options = {}) {
|
|
24
|
+
const samples = options.samples ?? manifest.samples;
|
|
25
|
+
if (!samples || samples.length === 0) throw new Error("Widget Plugin Manifest must provide at least one sample before packaging");
|
|
26
|
+
const contribution = manifest.contributes.widget;
|
|
27
|
+
if (contribution.type === "panel" && contribution.placement?.kind === "region" && (manifest.capabilities?.region?.mode !== contribution.placement.mode || !manifest.capabilities.region.regions.includes(contribution.placement.region))) throw new Error("A region Widget contribution must declare a matching region capability");
|
|
28
|
+
const activationEvents = manifest.activationEvents ? [...manifest.activationEvents] : void 0;
|
|
29
|
+
return {
|
|
30
|
+
name: manifest.name,
|
|
31
|
+
...manifest.description === void 0 ? {} : { description: manifest.description },
|
|
32
|
+
widgetConfig: {
|
|
33
|
+
schemaVersion: 1,
|
|
34
|
+
hostApiVersion: 1,
|
|
35
|
+
widgetSdkVersion: WIDGET_SDK_VERSION,
|
|
36
|
+
entry: options.hostEntry ?? "dist/widget.js",
|
|
37
|
+
slot: compiledSlot(manifest.contributes.widget),
|
|
38
|
+
...activationEvents === void 0 ? {} : { activationEvents },
|
|
39
|
+
...manifest.capabilities === void 0 ? {} : { requestedCapabilities: manifest.capabilities },
|
|
40
|
+
...manifest.runtime === void 0 ? {} : { runtime: manifest.runtime },
|
|
41
|
+
samples
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/lifetime.ts
|
|
47
|
+
function createWidgetLifetime(onError) {
|
|
48
|
+
const controller = new AbortController();
|
|
49
|
+
const resources = /* @__PURE__ */ new Map();
|
|
50
|
+
const pending = /* @__PURE__ */ new Set();
|
|
51
|
+
let closePromise;
|
|
52
|
+
function run(callback) {
|
|
53
|
+
const task = Promise.resolve().then(callback).catch((error) => {
|
|
54
|
+
try {
|
|
55
|
+
onError(error);
|
|
56
|
+
} catch {}
|
|
57
|
+
});
|
|
58
|
+
pending.add(task);
|
|
59
|
+
task.then(() => pending.delete(task));
|
|
60
|
+
return task;
|
|
61
|
+
}
|
|
62
|
+
function add(resource) {
|
|
63
|
+
const existing = resources.get(resource);
|
|
64
|
+
if (existing) return existing;
|
|
65
|
+
let disposed;
|
|
66
|
+
const handle = { dispose() {
|
|
67
|
+
if (disposed) return disposed;
|
|
68
|
+
disposed = run(() => typeof resource === "function" ? resource() : resource.dispose());
|
|
69
|
+
return disposed;
|
|
70
|
+
} };
|
|
71
|
+
resources.set(resource, handle);
|
|
72
|
+
if (controller.signal.aborted) handle.dispose();
|
|
73
|
+
return handle;
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
signal: controller.signal,
|
|
77
|
+
add,
|
|
78
|
+
close() {
|
|
79
|
+
if (closePromise) return closePromise;
|
|
80
|
+
controller.abort();
|
|
81
|
+
for (const resource of [...resources.values()].reverse()) resource.dispose();
|
|
82
|
+
closePromise = (async () => {
|
|
83
|
+
while (pending.size) await Promise.all([...pending]);
|
|
84
|
+
})();
|
|
85
|
+
return closePromise;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region src/widget.ts
|
|
91
|
+
/**
|
|
92
|
+
* Generated Widget Host 的唯一运行入口。Widget 作者只导出 activate/deactivate,
|
|
93
|
+
* 不直接调用此函数;CLI 生成的 widget-host.ts 负责调用它。
|
|
94
|
+
*/
|
|
95
|
+
function runWidgetHost(widget, options = {}) {
|
|
96
|
+
const client = createWidgetRuntime(typeof widget === "function" ? { activate: widget } : widget, options);
|
|
97
|
+
const whenReady = client.ready();
|
|
98
|
+
whenReady.catch((reason) => {
|
|
99
|
+
const error = toStartupError(reason);
|
|
100
|
+
if (options.onStartupError) {
|
|
101
|
+
options.onStartupError(error);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
console.error(`[Widget 启动失败] ${error.message}`, error);
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
whenReady,
|
|
108
|
+
whenDisposed: client.disposed(),
|
|
109
|
+
state: client.state,
|
|
110
|
+
dispose: client.dispose
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function createContext(client, payload, renderHandlers, lifetime) {
|
|
114
|
+
return {
|
|
115
|
+
instanceId: payload.instanceId,
|
|
116
|
+
locale: payload.locale,
|
|
117
|
+
theme: payload.theme,
|
|
118
|
+
signal: lifetime.signal,
|
|
119
|
+
capabilities: {
|
|
120
|
+
granted: payload.capabilities,
|
|
121
|
+
request: (request, options) => client.requestCapability(request, options)
|
|
122
|
+
},
|
|
123
|
+
files: { download: (input, options) => client.requestCapability({
|
|
124
|
+
operation: "files.download",
|
|
125
|
+
input
|
|
126
|
+
}, options) },
|
|
127
|
+
tasks: { watch: (input, options) => client.requestCapability({
|
|
128
|
+
operation: "tasks.watch",
|
|
129
|
+
input
|
|
130
|
+
}, options) },
|
|
131
|
+
network: client.network,
|
|
132
|
+
services: client.services,
|
|
133
|
+
hostUser: client.hostUser,
|
|
134
|
+
ui: {
|
|
135
|
+
state: {
|
|
136
|
+
read: (key, options) => client.requestCapability({
|
|
137
|
+
operation: "ui.state",
|
|
138
|
+
input: {
|
|
139
|
+
action: "read",
|
|
140
|
+
key
|
|
141
|
+
}
|
|
142
|
+
}, options),
|
|
143
|
+
write: (key, value, options) => client.requestCapability({
|
|
144
|
+
operation: "ui.state",
|
|
145
|
+
input: {
|
|
146
|
+
action: "write",
|
|
147
|
+
key,
|
|
148
|
+
value
|
|
149
|
+
}
|
|
150
|
+
}, options)
|
|
151
|
+
},
|
|
152
|
+
region: {
|
|
153
|
+
acquire: (region, options) => client.acquireRegion(region, options),
|
|
154
|
+
release: (options) => client.releaseRegion(options)
|
|
155
|
+
},
|
|
156
|
+
present: (surface, options) => client.present(surface, options),
|
|
157
|
+
close: (options) => client.closePresentation(options),
|
|
158
|
+
changeSurface: (surface, options) => client.changePresentationSurface(surface, options)
|
|
159
|
+
},
|
|
160
|
+
events: { on(handlerOrName, maybeHandler) {
|
|
161
|
+
const unsubscribe = typeof handlerOrName === "string" ? client.onEvent(handlerOrName, maybeHandler) : client.onEvent(handlerOrName);
|
|
162
|
+
return lifetime.add(unsubscribe);
|
|
163
|
+
} },
|
|
164
|
+
subscriptions: { add(registration) {
|
|
165
|
+
lifetime.add(registration);
|
|
166
|
+
} },
|
|
167
|
+
render(handler) {
|
|
168
|
+
renderHandlers.add(handler);
|
|
169
|
+
return lifetime.add({ dispose: () => {
|
|
170
|
+
renderHandlers.delete(handler);
|
|
171
|
+
} });
|
|
172
|
+
},
|
|
173
|
+
resize: (width, height) => client.resize(width, height)
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function createWidgetRuntime(module, options = {}) {
|
|
177
|
+
let client;
|
|
178
|
+
const renderHandlers = /* @__PURE__ */ new Set();
|
|
179
|
+
const reportCleanupError = (error) => options.onCleanupError?.(toStartupError(error));
|
|
180
|
+
const lifetime = createWidgetLifetime(reportCleanupError);
|
|
181
|
+
let activation;
|
|
182
|
+
let activationCompleted = false;
|
|
183
|
+
let disposed = false;
|
|
184
|
+
let deactivation;
|
|
185
|
+
let disposal;
|
|
186
|
+
let resolveDisposed;
|
|
187
|
+
const disposedPromise = new Promise((resolve) => {
|
|
188
|
+
resolveDisposed = resolve;
|
|
189
|
+
});
|
|
190
|
+
function runDeactivation() {
|
|
191
|
+
if (deactivation) return deactivation;
|
|
192
|
+
deactivation = Promise.resolve().then(() => module.deactivate?.()).catch((error) => {
|
|
193
|
+
reportCleanupError(error);
|
|
194
|
+
});
|
|
195
|
+
return deactivation;
|
|
196
|
+
}
|
|
197
|
+
function dispose() {
|
|
198
|
+
if (disposal) return;
|
|
199
|
+
disposed = true;
|
|
200
|
+
const cleanup = lifetime.close();
|
|
201
|
+
renderHandlers.clear();
|
|
202
|
+
disposal = (async () => {
|
|
203
|
+
await cleanup;
|
|
204
|
+
if (activationCompleted) await runDeactivation();
|
|
205
|
+
})().catch(reportCleanupError).finally(resolveDisposed);
|
|
206
|
+
}
|
|
207
|
+
client = createWidgetClient({
|
|
208
|
+
...options,
|
|
209
|
+
events: {
|
|
210
|
+
...options.events,
|
|
211
|
+
onInit(payload) {
|
|
212
|
+
const context = createContext(client, payload, renderHandlers, lifetime);
|
|
213
|
+
activation = Promise.resolve().then(async () => {
|
|
214
|
+
if (lifetime.signal.aborted) return;
|
|
215
|
+
const registration = await module.activate(context);
|
|
216
|
+
if (registration !== void 0) {
|
|
217
|
+
const resource = lifetime.add(registration);
|
|
218
|
+
if (lifetime.signal.aborted) await resource.dispose();
|
|
219
|
+
}
|
|
220
|
+
activationCompleted = true;
|
|
221
|
+
if (disposed) runDeactivation();
|
|
222
|
+
});
|
|
223
|
+
return activation;
|
|
224
|
+
},
|
|
225
|
+
onRender(request, update) {
|
|
226
|
+
const renderContext = {
|
|
227
|
+
phase: update ? "update" : "initial",
|
|
228
|
+
signal: lifetime.signal
|
|
229
|
+
};
|
|
230
|
+
for (const handler of [...renderHandlers]) try {
|
|
231
|
+
Promise.resolve(handler(request, renderContext)).catch(() => {});
|
|
232
|
+
} catch {}
|
|
233
|
+
},
|
|
234
|
+
onDispose: dispose
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
return {
|
|
238
|
+
ready: () => client.ready(),
|
|
239
|
+
disposed: () => disposedPromise,
|
|
240
|
+
state: () => client.currentState,
|
|
241
|
+
dispose: () => client.dispose()
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function toStartupError(reason) {
|
|
245
|
+
return reason instanceof Error ? reason : new Error("Widget 启动失败", { cause: reason });
|
|
246
|
+
}
|
|
247
|
+
//#endregion
|
|
248
|
+
export { WIDGET_ACTIVATION_EVENTS, WIDGET_EVENT_NAMES, compileWidgetPluginManifest, isWidgetActivationEvent, isWidgetEventName, runWidgetHost };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Guest 内单次启动的资源所有权;异步启动迟到的资源也必须立即释放。 */
|
|
2
|
+
export interface LifetimeResource {
|
|
3
|
+
dispose(): void | PromiseLike<void>;
|
|
4
|
+
}
|
|
5
|
+
export interface LifetimeRegistration {
|
|
6
|
+
dispose(): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare function createWidgetLifetime(onError: (error: unknown) => void): {
|
|
9
|
+
signal: AbortSignal;
|
|
10
|
+
add: (resource: LifetimeResource | (() => void | PromiseLike<void>)) => LifetimeRegistration;
|
|
11
|
+
close(): Promise<void>;
|
|
12
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { WidgetManifest, WidgetPluginManifest } from "@dp-bohrium/widget-contracts";
|
|
2
|
+
export interface CompileWidgetPluginManifestOptions {
|
|
3
|
+
readonly samples?: NonNullable<WidgetPluginManifest["samples"]>;
|
|
4
|
+
/** Host bundle entry. CLI supplies this after the project is built. */
|
|
5
|
+
readonly hostEntry?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* 将开发者维护的插件清单编译为宿主可加载的宿主清单。
|
|
9
|
+
*
|
|
10
|
+
* 这是构建工具的边界函数,不是类型提示入口:作者直接编辑带 `$schema` 的 JSON,
|
|
11
|
+
* SDK 版本从当前安装包读取,宿主入口默认落到 dist/widget.js,内部 slot 标识只在这里生成。
|
|
12
|
+
*/
|
|
13
|
+
export declare function compileWidgetPluginManifest(manifest: WidgetPluginManifest, options?: CompileWidgetPluginManifestOptions): WidgetManifest;
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import type { CapabilityRequest, CapabilityResult, InitPayload, PresentationCapabilityResult, RenderRequest, WidgetError, WidgetLiveEvent } from "@dp-bohrium/widget-contracts";
|
|
2
|
-
import { type PresentationFocusDirection, type PresentationSurface, type WidgetCapabilityRequestOptions, type WidgetClientEvents, type WidgetClientState } from "./client.js";
|
|
1
|
+
import type { CapabilityRequest, CapabilityResult, InitPayload, PresentationCapabilityResult, RegionCapabilityResult, RenderRequest, WidgetError, WidgetLiveEvent } from "@dp-bohrium/widget-contracts";
|
|
2
|
+
import { type PresentationFocusDirection, type PresentationSurface, type RegionName, type WidgetCapabilityRequestOptions, type WidgetClientEvents, type WidgetClientState } from "./client.js";
|
|
3
3
|
import { type SubscribeWidgetEventsOptions, type WidgetEventSubscription, type WidgetToolHooks } from "./events.js";
|
|
4
4
|
import type { WidgetNetworkClient } from "./network.js";
|
|
5
|
+
import { type WidgetHostUserClient, type WidgetServiceClient } from "./service.js";
|
|
6
|
+
import { WIDGET_SDK_VERSION } from "./version.js";
|
|
5
7
|
export declare const WIDGET_BOOTSTRAP_READY: "widget-bootstrap-ready";
|
|
6
8
|
export declare const WIDGET_HOST_CONNECT: "widget-host-connect";
|
|
9
|
+
export { WIDGET_SDK_VERSION };
|
|
7
10
|
export interface WidgetHostConnectMessage {
|
|
8
11
|
type: typeof WIDGET_HOST_CONNECT;
|
|
9
12
|
protocolVersion: 1;
|
|
@@ -27,8 +30,10 @@ export interface WidgetLiveEventContext {
|
|
|
27
30
|
}
|
|
28
31
|
/** 由 Host 通过当前 MessageChannel 推送的实时 Workflow 事件处理器。 */
|
|
29
32
|
export type WidgetLiveEventHandler = (event: WidgetLiveEvent, context: WidgetLiveEventContext) => void | Promise<void>;
|
|
33
|
+
export type WidgetLiveEventName = WidgetLiveEvent["type"];
|
|
30
34
|
export interface CreateWidgetClientOptions {
|
|
31
|
-
|
|
35
|
+
/** 低层协议字段;Widget Host 会从已安装 SDK 自动读取 SDK 版本。 */
|
|
36
|
+
widgetSdkVersion?: string;
|
|
32
37
|
hostApiVersion?: 1;
|
|
33
38
|
handshakeTimeoutMs?: number;
|
|
34
39
|
capabilityTimeoutMs?: number;
|
|
@@ -56,6 +61,8 @@ export declare function isWidgetHostConnectMessage(value: unknown): value is Wid
|
|
|
56
61
|
*/
|
|
57
62
|
export declare class WidgetRuntimeClient {
|
|
58
63
|
readonly network: WidgetNetworkClient;
|
|
64
|
+
readonly services: WidgetServiceClient;
|
|
65
|
+
readonly hostUser: WidgetHostUserClient;
|
|
59
66
|
private readonly runtimeWindow;
|
|
60
67
|
private readonly options;
|
|
61
68
|
private readonly events;
|
|
@@ -85,12 +92,14 @@ export declare class WidgetRuntimeClient {
|
|
|
85
92
|
present(surface: PresentationSurface, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
86
93
|
closePresentation(options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
87
94
|
changePresentationSurface(surface: PresentationSurface, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
95
|
+
acquireRegion(region: RegionName, options?: WidgetCapabilityRequestOptions): Promise<RegionCapabilityResult>;
|
|
96
|
+
releaseRegion(options?: WidgetCapabilityRequestOptions): Promise<RegionCapabilityResult>;
|
|
88
97
|
focusPresentationBoundary(direction: PresentationFocusDirection, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
89
98
|
subscribeEvents(options: SubscribeWidgetEventsOptions): WidgetEventSubscription;
|
|
90
99
|
/** 订阅 Host 从当前 Workflow 流实时推送的全部聚合事件。 */
|
|
91
100
|
onEvent(handler: WidgetLiveEventHandler): () => void;
|
|
92
101
|
/** 订阅 Host 从当前 Workflow 流实时推送的指定聚合事件。 */
|
|
93
|
-
onEvent(eventName:
|
|
102
|
+
onEvent(eventName: WidgetLiveEventName, handler: WidgetLiveEventHandler): () => void;
|
|
94
103
|
onTool(hooks: WidgetToolHooks, options: Pick<SubscribeWidgetEventsOptions, "cursor" | "onError">): WidgetEventSubscription;
|
|
95
104
|
invokeAction(input: Extract<CapabilityRequest, {
|
|
96
105
|
operation: "actions.invoke";
|
package/dist/runtime/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CapabilityRequest, CapabilityResult, GrantedCapability, InitPayload, PresentationCapabilityRequest, PresentationCapabilityResult, RenderRequest, WidgetError, WidgetLiveEvent } from "@dp-bohrium/widget-contracts";
|
|
1
|
+
import type { CapabilityRequest, CapabilityResult, GrantedCapability, InitPayload, PresentationCapabilityRequest, PresentationCapabilityResult, RegionCapabilityRequest, RegionCapabilityResult, RenderRequest, WidgetError, WidgetLiveEvent } from "@dp-bohrium/widget-contracts";
|
|
2
2
|
import { type WidgetNetworkClient } from "./network.js";
|
|
3
3
|
import type { WidgetTransport } from "./transport.js";
|
|
4
4
|
export type WidgetClientState = "created" | "waiting-ready" | "ready" | "disposed";
|
|
@@ -26,16 +26,22 @@ export interface WidgetCapabilityRequestOptions {
|
|
|
26
26
|
signal?: AbortSignal;
|
|
27
27
|
}
|
|
28
28
|
export declare const PRESENTATION_CONFIRMATION_TIMEOUT_MS = 60000;
|
|
29
|
+
export declare const REGION_CONFIRMATION_TIMEOUT_MS = 60000;
|
|
29
30
|
type SurfacePresentationInput = Extract<PresentationCapabilityRequest["input"], {
|
|
30
31
|
surface: unknown;
|
|
31
32
|
}>;
|
|
32
33
|
type FocusBoundaryPresentationInput = Extract<PresentationCapabilityRequest["input"], {
|
|
33
34
|
action: "focus-boundary";
|
|
34
35
|
}>;
|
|
36
|
+
export type RegionCapabilityInput = RegionCapabilityRequest["input"];
|
|
35
37
|
export type PresentationSurface = SurfacePresentationInput["surface"];
|
|
36
38
|
export type PresentationFocusDirection = FocusBoundaryPresentationInput["direction"];
|
|
39
|
+
export type RegionName = Extract<RegionCapabilityInput, {
|
|
40
|
+
region: unknown;
|
|
41
|
+
}>["region"];
|
|
37
42
|
type PresentationRequest = (request: CapabilityRequest, options: WidgetCapabilityRequestOptions) => Promise<CapabilityResult>;
|
|
38
43
|
export declare function hasOverlayPresentationGrant(capabilities: readonly GrantedCapability[]): boolean;
|
|
44
|
+
export declare function requestRegionCapability(request: PresentationRequest, capabilityRequest: RegionCapabilityRequest, options?: WidgetCapabilityRequestOptions): Promise<RegionCapabilityResult>;
|
|
39
45
|
export declare function requestPresentationCapability(request: PresentationRequest, capabilityRequest: PresentationCapabilityRequest, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
40
46
|
export declare class WidgetClient {
|
|
41
47
|
readonly network: WidgetNetworkClient;
|
|
@@ -66,6 +72,8 @@ export declare class WidgetClient {
|
|
|
66
72
|
present(surface: PresentationSurface, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
67
73
|
closePresentation(options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
68
74
|
changePresentationSurface(surface: PresentationSurface, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
75
|
+
acquireRegion(region: RegionName, options?: WidgetCapabilityRequestOptions): Promise<RegionCapabilityResult>;
|
|
76
|
+
releaseRegion(options?: WidgetCapabilityRequestOptions): Promise<RegionCapabilityResult>;
|
|
69
77
|
focusPresentationBoundary(direction: PresentationFocusDirection, options?: WidgetCapabilityRequestOptions): Promise<PresentationCapabilityResult>;
|
|
70
78
|
dispose(): void;
|
|
71
79
|
private finishDispose;
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
export {
|
|
3
|
-
export
|
|
4
|
-
export {
|
|
1
|
+
export type { RegionCapabilityResult } from "@dp-bohrium/widget-contracts";
|
|
2
|
+
export type { CreateWidgetClientOptions, WidgetClientFactoryOptions, WidgetDisposeEvent, WidgetHostConnectMessage, WidgetLiveEventContext, WidgetLiveEventHandler, WidgetLiveEventName, WidgetRuntimeWindow, WidgetSize, } from "./bootstrap.js";
|
|
3
|
+
export { createWidgetClient, isWidgetHostConnectMessage, WIDGET_BOOTSTRAP_READY, WIDGET_HOST_CONNECT, WIDGET_SDK_VERSION, WidgetRuntimeClient, } from "./bootstrap.js";
|
|
4
|
+
export type { PresentationFocusDirection, PresentationSurface, RegionName, WidgetCapabilityRequestOptions, WidgetClientEvents, WidgetClientOptions, WidgetClientState, } from "./client.js";
|
|
5
|
+
export { PRESENTATION_CONFIRMATION_TIMEOUT_MS, REGION_CONFIRMATION_TIMEOUT_MS, WidgetClient, } from "./client.js";
|
|
5
6
|
export type { SubscribeWidgetEventsOptions, WidgetEventBatchContext, WidgetEventSubscription, WidgetToolHooks, } from "./events.js";
|
|
6
7
|
export type { WidgetNetworkClient, WidgetNetworkFetchResult, } from "./network.js";
|
|
8
|
+
export type { HostUserEmail, HostUserEmailResult, HostUserProfile, HostUserProfileResult, WidgetHostUserClient, WidgetServiceClient, WidgetServiceInvokeInput, WidgetServiceInvokeResult, } from "./service.js";
|
|
7
9
|
export type { WidgetMessagePort, WidgetTransport } from "./transport.js";
|
|
8
10
|
export { isWidgetProtocolMessage, MessagePortTransport, } from "./transport.js";
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as isWidgetHostConnectMessage, i as createWidgetClient, n as WIDGET_HOST_CONNECT, o as PRESENTATION_CONFIRMATION_TIMEOUT_MS, r as WidgetRuntimeClient, s as
|
|
1
|
+
import { a as isWidgetHostConnectMessage, c as WidgetClient, i as createWidgetClient, l as WIDGET_SDK_VERSION, n as WIDGET_HOST_CONNECT, o as PRESENTATION_CONFIRMATION_TIMEOUT_MS, r as WidgetRuntimeClient, s as REGION_CONFIRMATION_TIMEOUT_MS, t as WIDGET_BOOTSTRAP_READY } from "../runtime-Dute9ozh.js";
|
|
2
2
|
import { i as isWidgetProtocolMessage, r as MessagePortTransport } from "../protocol-endpoint-I78q3jVT.js";
|
|
3
|
-
export { MessagePortTransport, PRESENTATION_CONFIRMATION_TIMEOUT_MS, WIDGET_BOOTSTRAP_READY, WIDGET_HOST_CONNECT, WidgetClient, WidgetRuntimeClient, createWidgetClient, isWidgetHostConnectMessage, isWidgetProtocolMessage };
|
|
3
|
+
export { MessagePortTransport, PRESENTATION_CONFIRMATION_TIMEOUT_MS, REGION_CONFIRMATION_TIMEOUT_MS, WIDGET_BOOTSTRAP_READY, WIDGET_HOST_CONNECT, WIDGET_SDK_VERSION, WidgetClient, WidgetRuntimeClient, createWidgetClient, isWidgetHostConnectMessage, isWidgetProtocolMessage };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { CapabilityRequest, CapabilityResult, JsonValue } from "@dp-bohrium/widget-contracts";
|
|
2
|
+
import type { WidgetCapabilityRequestOptions, WidgetClientState } from "./client.js";
|
|
3
|
+
export type WidgetServiceInvokeInput = Extract<CapabilityRequest, {
|
|
4
|
+
operation: "service.invoke";
|
|
5
|
+
}>["input"];
|
|
6
|
+
export type WidgetServiceInvokeResult = Readonly<{
|
|
7
|
+
ok: true;
|
|
8
|
+
data: JsonValue;
|
|
9
|
+
}> | Extract<CapabilityResult, {
|
|
10
|
+
ok: false;
|
|
11
|
+
}>;
|
|
12
|
+
export interface WidgetServiceClient {
|
|
13
|
+
invoke(input: WidgetServiceInvokeInput, options?: WidgetCapabilityRequestOptions): Promise<WidgetServiceInvokeResult>;
|
|
14
|
+
}
|
|
15
|
+
export interface HostUserProfile {
|
|
16
|
+
readonly userId: string;
|
|
17
|
+
readonly displayName: string;
|
|
18
|
+
}
|
|
19
|
+
export interface HostUserEmail {
|
|
20
|
+
readonly email: string | null;
|
|
21
|
+
}
|
|
22
|
+
export type HostUserProfileResult = Readonly<{
|
|
23
|
+
ok: true;
|
|
24
|
+
data: HostUserProfile;
|
|
25
|
+
}> | Extract<CapabilityResult, {
|
|
26
|
+
ok: false;
|
|
27
|
+
}>;
|
|
28
|
+
export type HostUserEmailResult = Readonly<{
|
|
29
|
+
ok: true;
|
|
30
|
+
data: HostUserEmail;
|
|
31
|
+
}> | Extract<CapabilityResult, {
|
|
32
|
+
ok: false;
|
|
33
|
+
}>;
|
|
34
|
+
export interface WidgetHostUserClient {
|
|
35
|
+
readProfile(options?: WidgetCapabilityRequestOptions): Promise<HostUserProfileResult>;
|
|
36
|
+
readEmail(options?: WidgetCapabilityRequestOptions): Promise<HostUserEmailResult>;
|
|
37
|
+
}
|
|
38
|
+
interface Dependencies {
|
|
39
|
+
readonly state: () => WidgetClientState;
|
|
40
|
+
readonly grant: () => Extract<import("@dp-bohrium/widget-contracts").GrantedCapability, {
|
|
41
|
+
name: "service.invoke";
|
|
42
|
+
}> | undefined;
|
|
43
|
+
readonly request: (request: CapabilityRequest, options?: WidgetCapabilityRequestOptions) => Promise<CapabilityResult>;
|
|
44
|
+
}
|
|
45
|
+
export declare function createWidgetServiceClient(dependencies: Dependencies): WidgetServiceClient;
|
|
46
|
+
export declare function createWidgetHostUserClient(services: WidgetServiceClient): WidgetHostUserClient;
|
|
47
|
+
export {};
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { r as MessagePortTransport, t as ProtocolEndpoint } from "./protocol-endpoint-I78q3jVT.js";
|
|
2
|
+
//#endregion
|
|
3
|
+
//#region src/runtime/version.ts
|
|
4
|
+
/** 从当前安装的 SDK package.json 读取版本,插件作者不需要重复填写。 */
|
|
5
|
+
const WIDGET_SDK_VERSION = "0.2.0";
|
|
6
|
+
//#endregion
|
|
2
7
|
//#region src/runtime/network.ts
|
|
3
8
|
const failureReasons = /* @__PURE__ */ new Set([
|
|
4
9
|
"unsupported",
|
|
@@ -77,6 +82,7 @@ function invalidResult() {
|
|
|
77
82
|
//#endregion
|
|
78
83
|
//#region src/runtime/client.ts
|
|
79
84
|
const PRESENTATION_CONFIRMATION_TIMEOUT_MS = 6e4;
|
|
85
|
+
const REGION_CONFIRMATION_TIMEOUT_MS = 6e4;
|
|
80
86
|
const presentationSurfaces = /* @__PURE__ */ new Set([
|
|
81
87
|
"workspace",
|
|
82
88
|
"floating",
|
|
@@ -226,6 +232,41 @@ function assertPresentationResult(input, result) {
|
|
|
226
232
|
}
|
|
227
233
|
if (!valid) throw new Error(`presentation protocol error: invalid success result for ${action}`);
|
|
228
234
|
}
|
|
235
|
+
function assertRegionResult(input, result) {
|
|
236
|
+
if (!isRecord$1(result) || !Object.hasOwn(result, "ok")) throw new Error(`region protocol error: invalid result for ${input.action}`);
|
|
237
|
+
if (property$1(result, "ok") === false) {
|
|
238
|
+
const message = property$1(result, "message");
|
|
239
|
+
if (hasExactKeys$1(result, [
|
|
240
|
+
"ok",
|
|
241
|
+
"reason",
|
|
242
|
+
"message",
|
|
243
|
+
"retryable"
|
|
244
|
+
]) && isCapabilityFailureReason(property$1(result, "reason")) && typeof message === "string" && message.length > 0 && typeof property$1(result, "retryable") === "boolean") return;
|
|
245
|
+
throw new Error(`region protocol error: invalid result for ${input.action}`);
|
|
246
|
+
}
|
|
247
|
+
if (!hasExactKeys$1(result, ["ok", "data"])) throw new Error(`region protocol error: invalid success result for ${input.action}`);
|
|
248
|
+
const data = property$1(result, "data");
|
|
249
|
+
const leaseId = isRecord$1(data) ? property$1(data, "leaseId") : void 0;
|
|
250
|
+
if (!(isRecord$1(data) && hasExactKeys$1(data, input.action === "acquire" ? [
|
|
251
|
+
"action",
|
|
252
|
+
"region",
|
|
253
|
+
"mode",
|
|
254
|
+
"leaseId"
|
|
255
|
+
] : [
|
|
256
|
+
"action",
|
|
257
|
+
"region",
|
|
258
|
+
"mode"
|
|
259
|
+
]) && property$1(data, "action") === input.action && property$1(data, "region") === "session.rightRail" && property$1(data, "mode") === "replace" && (input.action !== "acquire" || typeof leaseId === "string" && leaseId.length > 0))) throw new Error(`region protocol error: invalid success result for ${input.action}`);
|
|
260
|
+
}
|
|
261
|
+
function requestRegionCapability(request, capabilityRequest, options) {
|
|
262
|
+
return request(capabilityRequest, {
|
|
263
|
+
...options,
|
|
264
|
+
timeoutMs: options?.timeoutMs ?? 6e4
|
|
265
|
+
}).then((result) => {
|
|
266
|
+
assertRegionResult(capabilityRequest.input, result);
|
|
267
|
+
return result;
|
|
268
|
+
});
|
|
269
|
+
}
|
|
229
270
|
function requestPresentationCapability(request, capabilityRequest, options) {
|
|
230
271
|
return request(capabilityRequest, {
|
|
231
272
|
...options,
|
|
@@ -393,6 +434,21 @@ var WidgetClient = class {
|
|
|
393
434
|
}
|
|
394
435
|
}, options);
|
|
395
436
|
}
|
|
437
|
+
acquireRegion(region, options) {
|
|
438
|
+
return requestRegionCapability((request, requestOptions) => this.requestCapability(request, requestOptions), {
|
|
439
|
+
operation: "ui.region",
|
|
440
|
+
input: {
|
|
441
|
+
action: "acquire",
|
|
442
|
+
region
|
|
443
|
+
}
|
|
444
|
+
}, options);
|
|
445
|
+
}
|
|
446
|
+
releaseRegion(options) {
|
|
447
|
+
return requestRegionCapability((request, requestOptions) => this.requestCapability(request, requestOptions), {
|
|
448
|
+
operation: "ui.region",
|
|
449
|
+
input: { action: "release" }
|
|
450
|
+
}, options);
|
|
451
|
+
}
|
|
396
452
|
focusPresentationBoundary(direction, options) {
|
|
397
453
|
if (!this.overlayPresentationGranted) return Promise.reject(/* @__PURE__ */ new Error("Overlay presentation is not granted for focus cooperation"));
|
|
398
454
|
return requestPresentationCapability((request, requestOptions) => this.requestCapability(request, requestOptions), {
|
|
@@ -790,6 +846,63 @@ function createPresentationKeyboardAdapter(options) {
|
|
|
790
846
|
} };
|
|
791
847
|
}
|
|
792
848
|
//#endregion
|
|
849
|
+
//#region src/runtime/service.ts
|
|
850
|
+
function createWidgetServiceClient(dependencies) {
|
|
851
|
+
return Object.freeze({ invoke(input, options) {
|
|
852
|
+
const state = dependencies.state();
|
|
853
|
+
if (state === "disposed") return Promise.reject(/* @__PURE__ */ new Error("client is disposed"));
|
|
854
|
+
if (state !== "ready") return Promise.reject(/* @__PURE__ */ new Error("Widget service is not ready"));
|
|
855
|
+
if (!(dependencies.grant()?.services.find((entry) => entry.service === input.service))?.actions.includes(input.action)) return Promise.reject(/* @__PURE__ */ new Error("Widget service is not granted"));
|
|
856
|
+
return dependencies.request({
|
|
857
|
+
operation: "service.invoke",
|
|
858
|
+
input
|
|
859
|
+
}, options).then(validateServiceResult);
|
|
860
|
+
} });
|
|
861
|
+
}
|
|
862
|
+
function createWidgetHostUserClient(services) {
|
|
863
|
+
return Object.freeze({
|
|
864
|
+
readProfile(options) {
|
|
865
|
+
return services.invoke({
|
|
866
|
+
service: "host.user",
|
|
867
|
+
action: "profile.read",
|
|
868
|
+
payload: null
|
|
869
|
+
}, options).then((result) => validateHostUserResult(result, isHostUserProfile));
|
|
870
|
+
},
|
|
871
|
+
readEmail(options) {
|
|
872
|
+
return services.invoke({
|
|
873
|
+
service: "host.user",
|
|
874
|
+
action: "email.read",
|
|
875
|
+
payload: null
|
|
876
|
+
}, options).then((result) => validateHostUserResult(result, isHostUserEmail));
|
|
877
|
+
}
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
function validateHostUserResult(result, validate) {
|
|
881
|
+
if (result.ok === false) return result;
|
|
882
|
+
if (!validate(result.data)) throw new Error("service protocol error: invalid Host user result");
|
|
883
|
+
return {
|
|
884
|
+
ok: true,
|
|
885
|
+
data: result.data
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
function isHostUserProfile(value) {
|
|
889
|
+
return isExactRecord(value, ["userId", "displayName"]) && typeof value["userId"] === "string" && typeof value["displayName"] === "string";
|
|
890
|
+
}
|
|
891
|
+
function isHostUserEmail(value) {
|
|
892
|
+
return isExactRecord(value, ["email"]) && (typeof value["email"] === "string" || value["email"] === null);
|
|
893
|
+
}
|
|
894
|
+
function isExactRecord(value, keys) {
|
|
895
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
896
|
+
const actualKeys = Object.keys(value);
|
|
897
|
+
return actualKeys.length === keys.length && keys.every((key) => actualKeys.includes(key));
|
|
898
|
+
}
|
|
899
|
+
function validateServiceResult(result) {
|
|
900
|
+
if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("service protocol error: invalid result");
|
|
901
|
+
if (result.ok === false) return result;
|
|
902
|
+
if (result.ok !== true || !("data" in result)) throw new Error("service protocol error: invalid result");
|
|
903
|
+
return result;
|
|
904
|
+
}
|
|
905
|
+
//#endregion
|
|
793
906
|
//#region src/runtime/bootstrap.ts
|
|
794
907
|
const WIDGET_BOOTSTRAP_READY = "widget-bootstrap-ready";
|
|
795
908
|
const WIDGET_HOST_CONNECT = "widget-host-connect";
|
|
@@ -889,6 +1002,8 @@ function cloneGrantedCapabilities(capabilities) {
|
|
|
889
1002
|
*/
|
|
890
1003
|
var WidgetRuntimeClient = class {
|
|
891
1004
|
network;
|
|
1005
|
+
services;
|
|
1006
|
+
hostUser;
|
|
892
1007
|
runtimeWindow;
|
|
893
1008
|
options;
|
|
894
1009
|
events;
|
|
@@ -939,6 +1054,12 @@ var WidgetRuntimeClient = class {
|
|
|
939
1054
|
return this.requireClient().network.fetch(input, requestOptions);
|
|
940
1055
|
} };
|
|
941
1056
|
this.network = Object.freeze(network);
|
|
1057
|
+
this.services = createWidgetServiceClient({
|
|
1058
|
+
state: () => this.currentState,
|
|
1059
|
+
grant: () => this.capabilities.find((capability) => capability.name === "service.invoke"),
|
|
1060
|
+
request: (request, requestOptions) => this.requestCapability(request, requestOptions)
|
|
1061
|
+
});
|
|
1062
|
+
this.hostUser = createWidgetHostUserClient(this.services);
|
|
942
1063
|
this.readyPromise = new Promise((resolve, reject) => {
|
|
943
1064
|
this.resolveReady = resolve;
|
|
944
1065
|
this.rejectReady = reject;
|
|
@@ -1005,6 +1126,21 @@ var WidgetRuntimeClient = class {
|
|
|
1005
1126
|
}
|
|
1006
1127
|
}, options);
|
|
1007
1128
|
}
|
|
1129
|
+
acquireRegion(region, options) {
|
|
1130
|
+
return requestRegionCapability((request, requestOptions) => this.requestCapability(request, requestOptions), {
|
|
1131
|
+
operation: "ui.region",
|
|
1132
|
+
input: {
|
|
1133
|
+
action: "acquire",
|
|
1134
|
+
region
|
|
1135
|
+
}
|
|
1136
|
+
}, options);
|
|
1137
|
+
}
|
|
1138
|
+
releaseRegion(options) {
|
|
1139
|
+
return requestRegionCapability((request, requestOptions) => this.requestCapability(request, requestOptions), {
|
|
1140
|
+
operation: "ui.region",
|
|
1141
|
+
input: { action: "release" }
|
|
1142
|
+
}, options);
|
|
1143
|
+
}
|
|
1008
1144
|
focusPresentationBoundary(direction, options) {
|
|
1009
1145
|
return this.readyPromise.then(() => this.requireClient().focusPresentationBoundary(direction, options));
|
|
1010
1146
|
}
|
|
@@ -1101,7 +1237,7 @@ var WidgetRuntimeClient = class {
|
|
|
1101
1237
|
const clientOptions = {
|
|
1102
1238
|
transport: new MessagePortTransport(port),
|
|
1103
1239
|
channelId: event.data.channelId,
|
|
1104
|
-
widgetSdkVersion: this.options.widgetSdkVersion,
|
|
1240
|
+
widgetSdkVersion: this.options.widgetSdkVersion ?? WIDGET_SDK_VERSION,
|
|
1105
1241
|
initialPayload: event.data.initPayload,
|
|
1106
1242
|
...this.options.hostApiVersion === void 0 ? {} : { hostApiVersion: this.options.hostApiVersion },
|
|
1107
1243
|
...this.options.capabilityTimeoutMs === void 0 ? {} : { capabilityTimeoutMs: this.options.capabilityTimeoutMs },
|
|
@@ -1157,4 +1293,4 @@ function createWidgetClient(options) {
|
|
|
1157
1293
|
return new WidgetRuntimeClient(options);
|
|
1158
1294
|
}
|
|
1159
1295
|
//#endregion
|
|
1160
|
-
export { isWidgetHostConnectMessage as a, createWidgetClient as i, WIDGET_HOST_CONNECT as n, PRESENTATION_CONFIRMATION_TIMEOUT_MS as o, WidgetRuntimeClient as r,
|
|
1296
|
+
export { isWidgetHostConnectMessage as a, WidgetClient as c, createWidgetClient as i, WIDGET_SDK_VERSION as l, WIDGET_HOST_CONNECT as n, PRESENTATION_CONFIRMATION_TIMEOUT_MS as o, WidgetRuntimeClient as r, REGION_CONFIRMATION_TIMEOUT_MS as s, WIDGET_BOOTSTRAP_READY as t };
|
package/dist/widget.d.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type { CapabilityRequest, CapabilityResult, FileDownloadResult, FileReference, GrantedCapability, RegionCapabilityResult, RenderRequest, TaskObservationBatch, Theme, UiStateResult, UiStateWriteResult, WidgetEventName, WidgetLiveEvent } from "@dp-bohrium/widget-contracts";
|
|
2
|
+
import { type CreateWidgetClientOptions, type RegionName, type WidgetClientFactoryOptions, type WidgetClientState, type WidgetLiveEventContext, type WidgetLiveEventHandler } from "./runtime/index.js";
|
|
3
|
+
import type { WidgetNetworkClient } from "./runtime/network.js";
|
|
4
|
+
import type { WidgetHostUserClient, WidgetServiceClient } from "./runtime/service.js";
|
|
5
|
+
export interface WidgetDisposable {
|
|
6
|
+
dispose(): void | Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export type WidgetDisposeRegistration = WidgetDisposable | (() => void | Promise<void>);
|
|
9
|
+
export interface WidgetRenderContext {
|
|
10
|
+
readonly phase: "initial" | "update";
|
|
11
|
+
readonly signal: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
export type WidgetRenderHandler = (request: RenderRequest, context: WidgetRenderContext) => void | PromiseLike<void>;
|
|
14
|
+
export interface WidgetEventApi {
|
|
15
|
+
on(handler: WidgetLiveEventHandler): WidgetDisposable;
|
|
16
|
+
on<T extends WidgetEventName>(eventName: T, handler: (event: WidgetLiveEvent & {
|
|
17
|
+
readonly type: T;
|
|
18
|
+
}, context: WidgetLiveEventContext) => void | Promise<void>): WidgetDisposable;
|
|
19
|
+
}
|
|
20
|
+
export interface WidgetCapabilityApi {
|
|
21
|
+
readonly granted: readonly GrantedCapability[];
|
|
22
|
+
request(request: CapabilityRequest, options?: {
|
|
23
|
+
readonly timeoutMs?: number;
|
|
24
|
+
readonly signal?: AbortSignal;
|
|
25
|
+
}): Promise<CapabilityResult>;
|
|
26
|
+
}
|
|
27
|
+
export interface WidgetFileApi {
|
|
28
|
+
/** 请求 Host 在用户确认后通过宿主 Download Adapter 保存文件。 */
|
|
29
|
+
download(input: {
|
|
30
|
+
readonly file: FileReference;
|
|
31
|
+
readonly suggestedName: string;
|
|
32
|
+
}, options?: {
|
|
33
|
+
readonly timeoutMs?: number;
|
|
34
|
+
readonly signal?: AbortSignal;
|
|
35
|
+
}): Promise<FileDownloadCapabilityResult>;
|
|
36
|
+
}
|
|
37
|
+
export type FileDownloadCapabilityResult = {
|
|
38
|
+
readonly ok: true;
|
|
39
|
+
readonly data: FileDownloadResult;
|
|
40
|
+
} | Extract<CapabilityResult, {
|
|
41
|
+
readonly ok: false;
|
|
42
|
+
}>;
|
|
43
|
+
export interface WidgetTaskApi {
|
|
44
|
+
/**
|
|
45
|
+
* 读取一次受 Host 限制的任务快照和事件页。调用方使用返回的 cursor
|
|
46
|
+
* 继续轮询;此 API 不创建、调度或取消任务。
|
|
47
|
+
*/
|
|
48
|
+
watch(input: {
|
|
49
|
+
readonly taskId: string;
|
|
50
|
+
readonly cursor?: string;
|
|
51
|
+
readonly limit?: number;
|
|
52
|
+
}, options?: {
|
|
53
|
+
readonly timeoutMs?: number;
|
|
54
|
+
readonly signal?: AbortSignal;
|
|
55
|
+
}): Promise<TaskWatchCapabilityResult>;
|
|
56
|
+
}
|
|
57
|
+
export type TaskWatchCapabilityResult = {
|
|
58
|
+
readonly ok: true;
|
|
59
|
+
readonly data: TaskObservationBatch;
|
|
60
|
+
} | Extract<CapabilityResult, {
|
|
61
|
+
readonly ok: false;
|
|
62
|
+
}>;
|
|
63
|
+
export interface WidgetUiStateApi {
|
|
64
|
+
read(key: string, options?: {
|
|
65
|
+
readonly timeoutMs?: number;
|
|
66
|
+
readonly signal?: AbortSignal;
|
|
67
|
+
}): Promise<UiStateReadCapabilityResult>;
|
|
68
|
+
write(key: string, value: import("@dp-bohrium/widget-contracts").JsonValue, options?: {
|
|
69
|
+
readonly timeoutMs?: number;
|
|
70
|
+
readonly signal?: AbortSignal;
|
|
71
|
+
}): Promise<UiStateWriteCapabilityResult>;
|
|
72
|
+
}
|
|
73
|
+
export type UiStateReadCapabilityResult = {
|
|
74
|
+
readonly ok: true;
|
|
75
|
+
readonly data: UiStateResult;
|
|
76
|
+
} | Extract<CapabilityResult, {
|
|
77
|
+
readonly ok: false;
|
|
78
|
+
}>;
|
|
79
|
+
export type UiStateWriteCapabilityResult = {
|
|
80
|
+
readonly ok: true;
|
|
81
|
+
readonly data: UiStateWriteResult;
|
|
82
|
+
} | Extract<CapabilityResult, {
|
|
83
|
+
readonly ok: false;
|
|
84
|
+
}>;
|
|
85
|
+
export interface WidgetUiRegionApi {
|
|
86
|
+
acquire(region: RegionName, options?: {
|
|
87
|
+
readonly timeoutMs?: number;
|
|
88
|
+
readonly signal?: AbortSignal;
|
|
89
|
+
}): Promise<RegionCapabilityResult>;
|
|
90
|
+
release(options?: {
|
|
91
|
+
readonly timeoutMs?: number;
|
|
92
|
+
readonly signal?: AbortSignal;
|
|
93
|
+
}): Promise<RegionCapabilityResult>;
|
|
94
|
+
}
|
|
95
|
+
export interface WidgetUiApi {
|
|
96
|
+
readonly state: WidgetUiStateApi;
|
|
97
|
+
readonly region: WidgetUiRegionApi;
|
|
98
|
+
present(surface: "workspace" | "floating" | "overlay", options?: {
|
|
99
|
+
readonly timeoutMs?: number;
|
|
100
|
+
readonly signal?: AbortSignal;
|
|
101
|
+
}): Promise<CapabilityResult>;
|
|
102
|
+
close(options?: {
|
|
103
|
+
readonly timeoutMs?: number;
|
|
104
|
+
readonly signal?: AbortSignal;
|
|
105
|
+
}): Promise<CapabilityResult>;
|
|
106
|
+
changeSurface(surface: "workspace" | "floating" | "overlay", options?: {
|
|
107
|
+
readonly timeoutMs?: number;
|
|
108
|
+
readonly signal?: AbortSignal;
|
|
109
|
+
}): Promise<CapabilityResult>;
|
|
110
|
+
}
|
|
111
|
+
export interface WidgetContext {
|
|
112
|
+
readonly instanceId: string;
|
|
113
|
+
readonly locale: string;
|
|
114
|
+
readonly theme: Theme;
|
|
115
|
+
/** Widget Host 的生命周期信号;Host 停用或 Bridge 断开时会 abort。 */
|
|
116
|
+
readonly signal: AbortSignal;
|
|
117
|
+
readonly capabilities: WidgetCapabilityApi;
|
|
118
|
+
readonly files: WidgetFileApi;
|
|
119
|
+
readonly tasks: WidgetTaskApi;
|
|
120
|
+
readonly network: WidgetNetworkClient;
|
|
121
|
+
/** 低层 service.invoke 入口;保留给自定义 Host service。 */
|
|
122
|
+
readonly services: WidgetServiceClient;
|
|
123
|
+
/** 经过 Host 独立授权的公共用户资料入口。 */
|
|
124
|
+
readonly hostUser: WidgetHostUserClient;
|
|
125
|
+
readonly ui: WidgetUiApi;
|
|
126
|
+
readonly events: WidgetEventApi;
|
|
127
|
+
readonly subscriptions: {
|
|
128
|
+
add(registration: WidgetDisposeRegistration): void;
|
|
129
|
+
};
|
|
130
|
+
render(handler: WidgetRenderHandler): WidgetDisposable;
|
|
131
|
+
resize(width: number, height: number): void;
|
|
132
|
+
}
|
|
133
|
+
export type WidgetActivation = (context: WidgetContext) => void | WidgetDisposeRegistration | PromiseLike<WidgetDisposeRegistration | void>;
|
|
134
|
+
export interface WidgetHostOptions extends Omit<CreateWidgetClientOptions, "widgetSdkVersion" | "events" | "onInit" | "onRender" | "onUpdate" | "onEvent" | "onDispose"> {
|
|
135
|
+
readonly events?: Pick<NonNullable<WidgetClientFactoryOptions["events"]>, "onError">;
|
|
136
|
+
/** Widget Host 启动失败时的统一处理入口。 */
|
|
137
|
+
readonly onStartupError?: (error: Error) => void;
|
|
138
|
+
/** 停用或资源释放错误,诊断失败不会影响其它资源释放。 */
|
|
139
|
+
readonly onCleanupError?: (error: Error) => void;
|
|
140
|
+
}
|
|
141
|
+
export interface WidgetModule {
|
|
142
|
+
activate: WidgetActivation;
|
|
143
|
+
deactivate?: () => void | PromiseLike<void>;
|
|
144
|
+
}
|
|
145
|
+
export interface WidgetHandle {
|
|
146
|
+
/** 供测试、开发工具和 Host 编排等待激活完成。 */
|
|
147
|
+
readonly whenReady: Promise<void>;
|
|
148
|
+
/** Host 释放 Guest 后完成;包含已完成激活插件的异步 deactivate 清理。 */
|
|
149
|
+
readonly whenDisposed: Promise<void>;
|
|
150
|
+
readonly state: () => WidgetClientState;
|
|
151
|
+
dispose(): void;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Generated Widget Host 的唯一运行入口。Widget 作者只导出 activate/deactivate,
|
|
155
|
+
* 不直接调用此函数;CLI 生成的 widget-host.ts 负责调用它。
|
|
156
|
+
*/
|
|
157
|
+
export declare function runWidgetHost(widget: WidgetModule | WidgetActivation, options?: WidgetHostOptions): WidgetHandle;
|
package/llms.txt
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# @dp-bohrium/widget-sdk
|
|
2
|
+
|
|
3
|
+
> Agent 读取索引:本包提供 Widget 的 `activate(context)` 运行时、Bridge 生命周期、能力
|
|
4
|
+
> API、测试 Host 和低层 Runtime 入口。
|
|
5
|
+
|
|
6
|
+
## 先读
|
|
7
|
+
|
|
8
|
+
- [AGENTS.md](./AGENTS.md):安装、入口选择、错误恢复和安全边界。
|
|
9
|
+
- [README.md](./README.md):快速开始、Manifest、能力和生命周期说明。
|
|
10
|
+
- [package.json](./package.json):精确版本、exports 和 Node 要求。
|
|
11
|
+
|
|
12
|
+
## 选择入口
|
|
13
|
+
|
|
14
|
+
- 生产 Widget:`@dp-bohrium/widget-sdk`
|
|
15
|
+
- 单元测试:`@dp-bohrium/widget-sdk/testing`
|
|
16
|
+
- 协议级集成:`@dp-bohrium/widget-sdk/runtime`
|
|
17
|
+
- 配套类型和 Schema:`@dp-bohrium/widget-contracts`
|
|
18
|
+
|
|
19
|
+
## 使用原则
|
|
20
|
+
|
|
21
|
+
- 先在 Manifest 声明 capability,再等待 Host grant。
|
|
22
|
+
- 用 `WidgetError` 的 `code/phase/retryable/correlationId` 诊断启动、渲染和能力失败。
|
|
23
|
+
- `ok=false` 的能力结果是可处理状态,不要直接重试或绕过 Host。
|
|
24
|
+
- SDK 本地通过不等于 iframe 已真实渲染、Bundle 已发布或 Agent 已绑定。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dp-bohrium/widget-sdk",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Bohrium Widget 开发者 SDK:在 Widget Bundle 内与 Host 建立 Bridge,并暴露生命周期与能力协议。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -38,6 +38,9 @@
|
|
|
38
38
|
"files": [
|
|
39
39
|
"dist",
|
|
40
40
|
"README.md",
|
|
41
|
+
"AGENTS.md",
|
|
42
|
+
"llms.txt",
|
|
43
|
+
"CHANGELOG.md",
|
|
41
44
|
"LICENSE"
|
|
42
45
|
],
|
|
43
46
|
"sideEffects": false,
|
|
@@ -45,7 +48,7 @@
|
|
|
45
48
|
"access": "public"
|
|
46
49
|
},
|
|
47
50
|
"dependencies": {
|
|
48
|
-
"@dp-bohrium/widget-contracts": "0.0
|
|
51
|
+
"@dp-bohrium/widget-contracts": "0.2.0"
|
|
49
52
|
},
|
|
50
53
|
"devDependencies": {
|
|
51
54
|
"@biomejs/biome": "^2.2.0",
|