@vibedev-si/dsh-island 0.0.0-stage → 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/recent.js ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * 别的插件放到小岛上的「最近生成」(`ctx.island.contributor(名字).recent / forget`)。
3
+ *
4
+ * 一条是一个做好了的结果:标题、一句说明、是图片 / 视频 / 音频、一张小缩略图、完成时间,以及用户在小岛上
5
+ * 点了它时要做的事(`open`)。规则:
6
+ * - 只收文字、数字和 `data:image/(png|jpeg|webp);base64,…` 形式的缩略图,缩略图整串不超过 64 KB,
7
+ * 超了或者格式不对就当没有(这一条照样显示,画成图标)。小岛不去读插件给的文件路径或网址。
8
+ * - 每个插件只留最新的 8 条(按完成时间),旧的自动撤下。
9
+ * - `open` 留在宿主这边:岛上只知道这一条「可以打开」,被点了就把它的编号报回来(`contrib/open`),
10
+ * 由这里调用插件的函数。插件的函数抛错不影响别的。
11
+ * - 谁能放由 `allowed(插件名)` 决定(设置里的开关);不让放的照样记着,放开之后补发。岛屿重启后补发。
12
+ *
13
+ * 不碰宿主也不碰进程:发消息、时钟、名字和图标都由调用方给,测试里换成假的。
14
+ */
15
+
16
+ export const RECENT_LIMIT = 8
17
+ export const THUMBNAIL_MAX = 64 * 1024
18
+ export const RECENT_TITLE_MAX = 40
19
+ export const RECENT_DETAIL_MAX = 120
20
+ export const MEDIA = Object.freeze(['image', 'video', 'audio'])
21
+
22
+ const ID_PATTERN = /^[\w.-]{1,64}$/
23
+ const THUMBNAIL = /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/
24
+
25
+ const nothing = () => undefined
26
+
27
+ /** 截到 `max` 个字(末尾省略号);不是字符串或只有空白时是 undefined。 */
28
+ function cut(value, max) {
29
+ if (typeof value !== 'string') return undefined
30
+ const text = value.replace(/\s+/g, ' ').trim()
31
+ if (text === '') return undefined
32
+ const letters = Array.from(text)
33
+ return letters.length <= max ? text : `${letters.slice(0, max - 1).join('')}…`
34
+ }
35
+
36
+ /** 能用的缩略图;不能用时是 undefined。 */
37
+ export function thumbnailOf(value) {
38
+ return typeof value === 'string' && value.length <= THUMBNAIL_MAX && THUMBNAIL.test(value) ? value : undefined
39
+ }
40
+
41
+ /**
42
+ * 插件给的一条最近生成里能用的部分;标题不像样时是 undefined。
43
+ * @param {unknown} spec `{ title, subtitle?, media?, thumbnail?, at? }`
44
+ * @param {number} fallbackAt 没给完成时间时用它
45
+ */
46
+ export function recentOf(spec, fallbackAt) {
47
+ if (spec === null || typeof spec !== 'object') return undefined
48
+ const title = cut(spec.title, RECENT_TITLE_MAX)
49
+ if (title === undefined) return undefined
50
+ const detail = cut(spec.subtitle, RECENT_DETAIL_MAX)
51
+ const media = MEDIA.includes(spec.media) ? spec.media : undefined
52
+ const thumbnail = thumbnailOf(spec.thumbnail)
53
+ const at = typeof spec.at === 'number' && Number.isFinite(spec.at) && spec.at > 0 ? spec.at : fallbackAt
54
+ return { title, detail: detail ?? null, media: media ?? null, thumbnail: thumbnail ?? null, at }
55
+ }
56
+
57
+ /**
58
+ * @param {object} options
59
+ * @param {(method: string, params: object) => boolean} options.send 交给岛屿;岛屿没在运行时返回 false。
60
+ * @param {(owner: string) => { title: string, icon: string }} options.displayOf 插件在小岛上的名字和图标
61
+ * @param {(owner: string) => boolean} [options.allowed]
62
+ * @param {() => number} [options.now]
63
+ * @param {(line: string) => void} [options.log]
64
+ */
65
+ export function createRecentBook(options) {
66
+ const send = options.send
67
+ const displayOf = options.displayOf
68
+ const allowed = options.allowed ?? (() => true)
69
+ const now = options.now ?? Date.now
70
+ const log = options.log ?? nothing
71
+ /** 插件名 → (id → 条目)。 */
72
+ const owners = new Map()
73
+ /** 岛上的编号 → 条目(点了之后按它找回来)。 */
74
+ const byWire = new Map()
75
+
76
+ const everyEntry = () => Array.from(owners.values()).flatMap((entries) => Array.from(entries.values()))
77
+
78
+ const payloadOf = (entry) => {
79
+ const display = displayOf(entry.owner)
80
+ return {
81
+ id: entry.wireId,
82
+ kind: 'recent',
83
+ owner: entry.owner,
84
+ source: display.title,
85
+ icon: display.icon,
86
+ ...entry.item,
87
+ openable: entry.open !== undefined,
88
+ }
89
+ }
90
+
91
+ const flush = (entry) => {
92
+ if (!allowed(entry.owner)) return
93
+ const payload = payloadOf(entry)
94
+ const serialized = JSON.stringify(payload)
95
+ if (serialized === entry.shown) return
96
+ if (send('contrib/upsert', payload)) entry.shown = serialized
97
+ }
98
+
99
+ const withdraw = (entry) => {
100
+ if (entry.shown !== undefined) send('contrib/remove', { id: entry.wireId })
101
+ entry.shown = undefined
102
+ }
103
+
104
+ const drop = (owner, id) => {
105
+ const entries = owners.get(owner)
106
+ const entry = entries?.get(id)
107
+ if (entry === undefined) return false
108
+ withdraw(entry)
109
+ entries.delete(id)
110
+ byWire.delete(entry.wireId)
111
+ if (entries.size === 0) owners.delete(owner)
112
+ return true
113
+ }
114
+
115
+ return {
116
+ /**
117
+ * 放上或更新一条最近生成。返回收下了没有。
118
+ * @param {string} owner 插件名
119
+ * @param {string} id 插件自己的编号(字母、数字、`.`、`_`、`-`,最多 64 个)
120
+ * @param {object} spec `{ title, subtitle?, media?, thumbnail?, at?, open? }`
121
+ */
122
+ put(owner, id, spec) {
123
+ const item = typeof id === 'string' && ID_PATTERN.test(id) ? recentOf(spec, now()) : undefined
124
+ if (item === undefined) {
125
+ log(`recent: ${owner} sent a result without a usable id or title`)
126
+ return false
127
+ }
128
+ const entries = owners.get(owner) ?? new Map()
129
+ owners.set(owner, entries)
130
+ let entry = entries.get(id)
131
+ if (entry === undefined) {
132
+ entry = { owner, id, wireId: `recent:${owner}:${id}` }
133
+ entries.set(id, entry)
134
+ byWire.set(entry.wireId, entry)
135
+ }
136
+ entry.item = item
137
+ entry.open = typeof spec.open === 'function' ? spec.open : undefined
138
+ // 只留最新的几条:完成得最早的撤下。
139
+ const ordered = Array.from(entries.values()).sort((left, right) => right.item.at - left.item.at)
140
+ for (const old of ordered.slice(RECENT_LIMIT)) drop(owner, old.id)
141
+ if (entries.get(id) === entry) flush(entry)
142
+ return entries.get(id) === entry
143
+ },
144
+
145
+ /** 撤下一条。 */
146
+ forget(owner, id) {
147
+ return drop(owner, id)
148
+ },
149
+
150
+ /** 这个插件的全部撤下。 */
151
+ clear(owner) {
152
+ for (const id of Array.from(owners.get(owner)?.keys() ?? Array.of())) drop(owner, id)
153
+ },
154
+
155
+ /**
156
+ * 用户在小岛上点了这一条:调用插件给的 `open`。返回这个编号是不是这里的(是的话就算处理过了)。
157
+ * @param {string} wireId 岛上的编号
158
+ */
159
+ open(wireId) {
160
+ const entry = byWire.get(wireId)
161
+ if (entry === undefined) return false
162
+ if (entry.open === undefined) {
163
+ log(`recent: ${entry.owner} ${entry.id} has nothing to open`)
164
+ return true
165
+ }
166
+ try {
167
+ entry.open()
168
+ log(`recent: opened ${entry.owner} ${entry.id}`)
169
+ } catch (error) {
170
+ log(`recent: ${entry.owner} failed to open ${entry.id}: ${error}`)
171
+ }
172
+ return true
173
+ },
174
+
175
+ /** 开关变了或者名字、图标变了:不让上岛的撤下,能上的补发现在的样子;没变的不发。 */
176
+ refresh() {
177
+ for (const entry of everyEntry()) {
178
+ if (allowed(entry.owner)) flush(entry)
179
+ else withdraw(entry)
180
+ }
181
+ },
182
+
183
+ /** 岛屿刚起来(或重启):全部补发。 */
184
+ islandStarted() {
185
+ for (const entry of everyEntry()) {
186
+ entry.shown = undefined
187
+ flush(entry)
188
+ }
189
+ },
190
+
191
+ /** 放过最近生成的插件和各自记着几条。 */
192
+ summary: () => Array.from(owners, ([name, entries]) => ({ name, items: entries.size })),
193
+ }
194
+ }
package/requests.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 把宿主的审批、提问请求变成岛上的一句话。
3
+ *
4
+ * 纯函数,字段按官方类型(用 cordis_inspect 查到):
5
+ *
6
+ * ApprovalRequestEvent { agent: { id }, toolName, callId?, reason?, displayReason?: { en, [locale] } }
7
+ * AskUserQuestionRequestEvent { questions: [{ id, question, detail?, header?, intent? }], agent?: { id } }
8
+ *
9
+ * 岛屿只负责提醒和带路:是否放行、怎么回答,仍然在 VibeDev 里决定。
10
+ */
11
+
12
+ /** 岛上一行放不下太长的话。 */
13
+ const MAX_DETAIL = 200
14
+
15
+ function trimmed(value) {
16
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
17
+ }
18
+
19
+ /** 从 `string | { en, [locale]: string }` 里取一段文字,优先中文。 */
20
+ export function localized(text, locales = ['zh-CN', 'zh', 'en']) {
21
+ if (typeof text === 'string') return trimmed(text)
22
+ if (text === null || typeof text !== 'object') return undefined
23
+ for (const locale of locales) {
24
+ const found = trimmed(text[locale])
25
+ if (found !== undefined) return found
26
+ }
27
+ return undefined
28
+ }
29
+
30
+ function clip(text) {
31
+ return text === undefined ? undefined : text.slice(0, MAX_DETAIL)
32
+ }
33
+
34
+ /**
35
+ * `approval/request` → 岛上的一条「等你处理」(`attention/show`)。
36
+ *
37
+ * 没有 `callId` 时用会话 id 兜底:同一个会话同一时刻只会有一个待批准的调用。
38
+ */
39
+ export function describeApproval(event) {
40
+ const sessionId = trimmed(event?.agent?.id)
41
+ const toolName = trimmed(event?.toolName)
42
+ const detail = clip(localized(event?.displayReason) ?? trimmed(event?.reason))
43
+ return {
44
+ id: trimmed(event?.callId) ?? `approval-${sessionId ?? 'unknown'}`,
45
+ kind: 'approval',
46
+ title: toolName === undefined ? 'VibeDev 需要你批准一个操作' : `等你批准 · ${toolName}`,
47
+ ...(detail === undefined ? undefined : { detail }),
48
+ ...(sessionId === undefined ? undefined : { sessionId }),
49
+ }
50
+ }
51
+
52
+ /** 这个提问其实是一次审批(宿主有时把审批走提问通道)。 */
53
+ export function isApprovalQuestion(event) {
54
+ const first = Array.isArray(event?.questions) ? event.questions[0] : undefined
55
+ return first?.intent?.kind === 'approval'
56
+ }
57
+
58
+ /**
59
+ * `user-questions/request` → 岛上的一条「等你处理」(`attention/show`)。问题没回答之前一直挂着。
60
+ *
61
+ * 审批有时也走提问通道(`intent.kind === 'approval'`),那时说"等你批准"更准确。
62
+ */
63
+ export function describeQuestion(event) {
64
+ const sessionId = trimmed(event?.agent?.id)
65
+ const first = Array.isArray(event?.questions) ? event.questions[0] : undefined
66
+ const intent = first?.intent
67
+ const isApproval = intent?.kind === 'approval'
68
+ const subject = trimmed(intent?.subject?.name)
69
+ const body = clip(
70
+ (isApproval ? localized(intent?.display?.question) : undefined) ??
71
+ trimmed(first?.question) ??
72
+ trimmed(first?.header),
73
+ )
74
+ const waiting = isApproval ? '等你批准' : 'VibeDev 在等你回答'
75
+ return {
76
+ // 一条会话同一时刻只有一组问题在等;带上第一个问题的 id,前后两组不会混。
77
+ id: `question-${sessionId ?? 'unknown'}-${trimmed(first?.id) ?? '0'}`,
78
+ // 审批走提问通道时它就是一次审批:排在别的提问前面,会话页上也说"等你批准"。
79
+ kind: isApproval ? 'approval' : 'question',
80
+ title: subject === undefined ? waiting : `${waiting} · ${subject}`,
81
+ ...(body === undefined ? undefined : { detail: body }),
82
+ ...(sessionId === undefined ? undefined : { sessionId }),
83
+ }
84
+ }
package/routes.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * 插件页用的同源路由(`ctx.connection.fetch.register`)。
3
+ *
4
+ * 连接层已经做过 Host/Origin 与浏览器凭据校验,这里收到的是已认证请求,
5
+ * 所以不需要自己发令牌。客户端只用 `fetch` 调这些路径。
6
+ *
7
+ * 注意:路由表按 **路径** 唯一,同一路径只能注册一次,多种方法写进同一条的
8
+ * `methods`,再按 `request.method` 分派。
9
+ */
10
+ import { applyPatch } from './settings.js'
11
+
12
+ export const STATUS_ROUTE = '/api/dsh-island/status'
13
+ export const SETTINGS_ROUTE = '/api/dsh-island/settings'
14
+ export const CONTROL_ROUTE = '/api/dsh-island/control'
15
+ export const EVENTS_ROUTE = '/api/dsh-island/events'
16
+ export const CHANGELOG_ROUTE = '/api/dsh-island/changelog'
17
+ export const SELECTION_ROUTE = '/api/dsh-island/selection'
18
+ export const OUTBOX_ROUTE = '/api/dsh-island/outbox'
19
+ export const THEME_ROUTE = '/api/dsh-island/theme'
20
+ export const LICENSES_ROUTE = '/api/dsh-island/licenses'
21
+
22
+ /** `control` 路由接受的动作。 */
23
+ export const CONTROL_ACTIONS = [
24
+ 'start',
25
+ 'stop',
26
+ 'restart',
27
+ 'suspend',
28
+ 'qq-request-access',
29
+ 'qq-open-settings',
30
+ 'reset-settings',
31
+ 'open-logs',
32
+ 'translate-test',
33
+ 'open-translation',
34
+ 'export-diagnostics',
35
+ 'sound-test',
36
+ ]
37
+
38
+ const json = (status, body) =>
39
+ new Response(JSON.stringify(body), {
40
+ status,
41
+ headers: { 'content-type': 'application/json; charset=utf-8' },
42
+ })
43
+
44
+ /** 请求体必须是一个 JSON 对象;不是就返回 undefined,由调用方回 400。 */
45
+ async function readObject(request) {
46
+ const body = await request.json().catch(() => undefined)
47
+ return body !== null && typeof body === 'object' && !Array.isArray(body) ? body : undefined
48
+ }
49
+
50
+ /**
51
+ * @param provider.status 当前运行状态的快照
52
+ * @param provider.settings 当前设置
53
+ * @param provider.save 保存并应用设置,返回保存后的设置
54
+ * @param provider.control 执行 `CONTROL_ACTIONS` 里的一个动作
55
+ * @param provider.events 宿主 → 页面的动作通道:`waitAfter(after, signal)` 与 `acknowledge(body)`
56
+ * @param provider.changelog 版本记录(`parseChangelog` 的结果)
57
+ * @param provider.selection 页面报上来的选区;返回页面还要不要继续报
58
+ * @param provider.outbox 取走一份要发给会话的内容(`{ sessionId, text, image? }`);没有返回 undefined
59
+ * @param provider.theme 页面报上来的 VibeDev 主题深浅(`{ scheme: 'light' | 'dark' }`)
60
+ * @param provider.licenses 第三方许可的清单(`{ rust, web }`);读不到返回 undefined
61
+ * @param provider.log 记录失败,便于排查
62
+ */
63
+ export function islandRoutes({
64
+ status,
65
+ settings,
66
+ save,
67
+ control,
68
+ events,
69
+ changelog,
70
+ selection,
71
+ outbox,
72
+ theme,
73
+ licenses = () => undefined,
74
+ log = () => undefined,
75
+ }) {
76
+ return [
77
+ {
78
+ path: STATUS_ROUTE,
79
+ methods: ['GET'],
80
+ requestBody: 'buffered',
81
+ fetch: async () => json(200, { ok: true, data: status() }),
82
+ },
83
+ {
84
+ path: SETTINGS_ROUTE,
85
+ methods: ['GET', 'POST'],
86
+ requestBody: 'buffered',
87
+ fetch: async (request) => {
88
+ if (request.method === 'GET') return json(200, { ok: true, data: settings() })
89
+
90
+ const body = await readObject(request)
91
+ if (body === undefined) return json(400, { ok: false, error: 'The body must be a JSON object.' })
92
+ try {
93
+ return json(200, { ok: true, data: await save(applyPatch(settings(), body)) })
94
+ } catch (error) {
95
+ log(`saving settings failed: ${error}`)
96
+ return json(500, { ok: false, error: String(error) })
97
+ }
98
+ },
99
+ },
100
+ {
101
+ path: CONTROL_ROUTE,
102
+ methods: ['POST'],
103
+ requestBody: 'buffered',
104
+ fetch: async (request) => {
105
+ const body = await readObject(request)
106
+ const action = body?.action
107
+ if (!CONTROL_ACTIONS.includes(action)) {
108
+ return json(400, { ok: false, error: `"action" must be one of: ${CONTROL_ACTIONS.join(', ')}.` })
109
+ }
110
+ try {
111
+ await control(action, body)
112
+ return json(200, { ok: true, data: status() })
113
+ } catch (error) {
114
+ log(`island control ${action} failed: ${error}`)
115
+ return json(500, { ok: false, error: String(error) })
116
+ }
117
+ },
118
+ },
119
+ {
120
+ path: CHANGELOG_ROUTE,
121
+ methods: ['GET'],
122
+ requestBody: 'buffered',
123
+ fetch: async () => json(200, { ok: true, data: changelog() }),
124
+ },
125
+ {
126
+ // 设置页「关于 → 第三方许可」:岛屿用到的第三方组件和许可。
127
+ path: LICENSES_ROUTE,
128
+ methods: ['GET'],
129
+ requestBody: 'buffered',
130
+ fetch: async () => {
131
+ const list = licenses()
132
+ return list === undefined
133
+ ? json(404, { ok: false, error: 'The third-party list is missing.' })
134
+ : json(200, { ok: true, data: list })
135
+ },
136
+ },
137
+ {
138
+ // 页面报上来 VibeDev 现在是深色还是浅色:小岛设成「跟随 VibeDev」时照着变。
139
+ path: THEME_ROUTE,
140
+ methods: ['POST'],
141
+ requestBody: 'buffered',
142
+ fetch: async (request) => {
143
+ const body = await readObject(request)
144
+ if (body?.scheme !== 'light' && body?.scheme !== 'dark') {
145
+ return json(400, { ok: false, error: '"scheme" must be "light" or "dark".' })
146
+ }
147
+ theme(body.scheme)
148
+ return json(200, { ok: true, data: null })
149
+ },
150
+ },
151
+ {
152
+ // 页面里选中的文字(翻译用)。回答里的 wanted 为 false 时页面先别报了:设置里关掉了。
153
+ path: SELECTION_ROUTE,
154
+ methods: ['POST'],
155
+ requestBody: 'buffered',
156
+ fetch: async (request) => {
157
+ const body = await readObject(request)
158
+ if (body === undefined) return json(400, { ok: false, error: 'The body must be a JSON object.' })
159
+ return json(200, { ok: true, data: { wanted: selection(body) } })
160
+ },
161
+ },
162
+ {
163
+ // 发送到会话:页面来取岛屿要发的内容。只能取一次,开着几个窗口时不会发两遍。
164
+ path: OUTBOX_ROUTE,
165
+ methods: ['GET'],
166
+ requestBody: 'buffered',
167
+ fetch: async (request) => {
168
+ const id = new URL(request.url).searchParams.get('id')
169
+ if (id === null || id === '') return json(400, { ok: false, error: '"id" is required.' })
170
+ try {
171
+ const entry = await outbox(id)
172
+ return entry === undefined
173
+ ? json(404, { ok: false, error: 'Nothing to send under this id.' })
174
+ : json(200, { ok: true, data: entry })
175
+ } catch (error) {
176
+ log(`reading the outbox failed: ${error}`)
177
+ return json(500, { ok: false, error: String(error) })
178
+ }
179
+ },
180
+ },
181
+ {
182
+ // GET:页面的长轮询,等宿主要它做的事。POST:页面回报某个动作做没做成。
183
+ path: EVENTS_ROUTE,
184
+ methods: ['GET', 'POST'],
185
+ requestBody: 'buffered',
186
+ fetch: async (request) => {
187
+ if (request.method === 'POST') {
188
+ const body = await readObject(request)
189
+ if (body === undefined) return json(400, { ok: false, error: 'The body must be a JSON object.' })
190
+ events.acknowledge(body)
191
+ return json(200, { ok: true, data: null })
192
+ }
193
+
194
+ const raw = new URL(request.url).searchParams.get('after')
195
+ const after = raw === null ? -1 : Number(raw)
196
+ if (!Number.isFinite(after)) return json(400, { ok: false, error: '"after" must be a number.' })
197
+ return json(200, { ok: true, data: await events.waitAfter(after, request.signal) })
198
+ },
199
+ },
200
+ ]
201
+ }
package/selection.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * VibeDev 页面里选中的文字:页面报上来,宿主整理好转给岛屿(`selection/update`),
3
+ * 鼠标移到小岛上时岛屿据此给出「翻译」按钮。
4
+ *
5
+ * 选中的文字只在内存里经过:不写日志、不落盘,点了翻译才会发给翻译服务。
6
+ */
7
+
8
+ /** 一次最多转这么多个字(按 Unicode 字符数);岛屿那边也是这个上限。 */
9
+ export const MAX_SELECTION_CHARS = 20_000
10
+ /** 网页格式超过这么大就不要了,只转文字:岛屿的协议一行最多 1 MiB。 */
11
+ export const MAX_SELECTION_HTML = 400_000
12
+
13
+ /**
14
+ * 页面报上来的一份 → 转给岛屿的参数;认不出来返回 undefined。
15
+ *
16
+ * - `{ text, html?, focused? }`:页面里选中的文字;`text` 是空的表示没有选区了。
17
+ * - `{ focused }`:选区没变,只是页面得到或失去了焦点。
18
+ */
19
+ export function selectionUpdate(body) {
20
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) return undefined
21
+ const focused = typeof body.focused === 'boolean' ? body.focused : undefined
22
+ if (typeof body.text !== 'string') return focused === undefined ? undefined : { focused }
23
+ if (body.text.trim() === '') return { text: '' }
24
+ const characters = Array.from(body.text)
25
+ const text = characters.length > MAX_SELECTION_CHARS ? characters.slice(0, MAX_SELECTION_CHARS).join('') : body.text
26
+ // 文字截断之后,网页格式和它就不是同一份东西了。
27
+ const html =
28
+ text === body.text &&
29
+ typeof body.html === 'string' &&
30
+ body.html.trim() !== '' &&
31
+ body.html.length <= MAX_SELECTION_HTML
32
+ ? body.html
33
+ : undefined
34
+ return html === undefined ? { text, focused: focused ?? true } : { text, html, focused: focused ?? true }
35
+ }
36
+
37
+ /**
38
+ * 各个页面报上来的选区,留最新的那一份。
39
+ *
40
+ * 开着几个 VibeDev 窗口时每个页面都会报:谁最后选了文字就用谁的;某个页面清空选区或失去焦点,
41
+ * 只影响它自己报的那一份(页面带着一个随机的 `page` 编号)。
42
+ */
43
+ export function createSelectionRelay() {
44
+ let held
45
+
46
+ return {
47
+ /** 记下页面报上来的一份;返回要转给岛屿的参数,不用转时返回 undefined。 */
48
+ update(body) {
49
+ const update = selectionUpdate(body)
50
+ if (update === undefined) return undefined
51
+ const page = typeof body.page === 'string' ? body.page : ''
52
+ const own = held !== undefined && held.page === page
53
+ if (update.text === undefined) {
54
+ if (!own) return undefined
55
+ held = { ...held, focused: update.focused }
56
+ return update
57
+ }
58
+ if (update.text === '') {
59
+ if (!own) return undefined
60
+ held = undefined
61
+ return update
62
+ }
63
+ held = { page, ...update }
64
+ return update
65
+ },
66
+
67
+ /** 手里那一份(岛屿刚连上时再给它一次);没有返回 undefined。 */
68
+ current() {
69
+ if (held === undefined) return undefined
70
+ const { page: _page, ...update } = held
71
+ return update
72
+ },
73
+
74
+ clear() {
75
+ held = undefined
76
+ },
77
+ }
78
+ }