@lingda-ai/dsh-plugin-ledger 0.1.4 → 0.1.5

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.
@@ -0,0 +1,248 @@
1
+ /**
2
+ * @lingda-ai/ledger —— 浏览器半(右侧栏 tab)**源码**
3
+ *
4
+ * 注意:本文件不是发布产物。发布入口是 `lib/client.js`,由
5
+ * `node scripts/build-client.mjs` 从本文件 + panel-view.js + panel-path.js +
6
+ * tool-size.js 打包成宿主要求的 loader 形态(`window.__ModuleLoader__.load`)。
7
+ * 手工改 `lib/client.js` 会在下次构建时被覆盖。
8
+ *
9
+ * 为什么必须有这一步(真机崩溃换来的):
10
+ * dsh-client-modules 的 Node 半侧把每个包的 `client.js` **原样拼接**成一个
11
+ * combo 脚本(`/plugins/??a/client.js,b/client.js&rev=…`),浏览器按 classic
12
+ * script 解析。所以客户端入口里不能出现任何 `import` / `export` 语句,
13
+ * 否则整页抛 `SyntaxError: Cannot use import statement outside a module`,
14
+ * 连宿主一起带崩。0.1.4 就是直接发布了 ESM 源码,一重启就崩。
15
+ *
16
+ * 已核实的契约(源码逐条对过,勿凭记忆改):
17
+ *
18
+ * 1) 类型登记 @ dsh-client-ui-sidebar-right
19
+ * ctx.sidebarRightTabs.register(definition) → disposer
20
+ * definition: { id, kind, title(address), priority?, patterns?, canOpen?, guide?, multiple?, keepMounted? }
21
+ * guide entry: { id, order, title(), description?(), icon?, commandId? }
22
+ *
23
+ * 2) 正文/标题 seat @ 同一包(keyed,session scope,key = type.id)
24
+ * - 'sidebar.right.pane.tab'
25
+ * - 'sidebar.right.pane.tab.title'
26
+ * 宿主自带的注册形态(sidebar-right 自己的 guide 就是这么写的):
27
+ * ctx.slots.inject('<seat>', () => ctx.slots.register({ name: '<seat>', key: ID }, Component))
28
+ *
29
+ * 3) React 来自宿主模块表(`require("react")`)。本文件在 Node 侧(单测、脚本)
30
+ * 走动态 import('react');打进 client.js 后由构建产物通过 __setReactLoader
31
+ * 注入 factory 拿到的 require。两条路都失败时退回"只登记类型、不挂正文"。
32
+ *
33
+ * 取数通道(已接,细节见 docs/spikes.md C-3):
34
+ * 数据在 Host 的 ctx.ledger 上,浏览器进程拿不到;Host 把只读快照写成
35
+ * 工作区里的 JSON,这里用 `ctx.remote.workspaceFiles` 的 stat/read 读回。
36
+ * 接入点集中在 createFetchView() 一处。
37
+ *
38
+ * 约定(dsh-client-modules):客户端模块是 lazy factory,副作用只能发生在 apply() 内。
39
+ */
40
+
41
+ /** 本实现的身份,也是两个 keyed seat 的 key。 */
42
+ const LEDGER_ID = '@lingda-ai/ledger'
43
+ /** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
44
+ const LEDGER_KIND = 'ledger.cost'
45
+
46
+ /** 面板用到的 seat 名,抽出来避免字符串散落。 */
47
+ const SEAT_BODY = 'sidebar.right.pane.tab'
48
+ const SEAT_TITLE = 'sidebar.right.pane.tab.title'
49
+
50
+ /**
51
+ * React 取用方式:默认走动态 import(Node 侧单测/脚本)。
52
+ * 构建成 client.js 后,产物在 factory 里用宿主模块表的 `require('react')` 覆盖它——
53
+ * 浏览器里没有裸 `import('react')` 能解析的相对路径,动态 import 必然失败。
54
+ * @type {() => Promise<any>}
55
+ */
56
+ // #region react-loader-default
57
+ let reactLoader = async () => {
58
+ const mod = await import('react')
59
+ return mod.default ?? mod ?? null
60
+ }
61
+ // #endregion react-loader-default
62
+
63
+ /** 只给构建产物用:把 React 换成宿主模块表给的 require。 */
64
+ export function __setReactLoader(fn) {
65
+ if (typeof fn === 'function') reactLoader = fn
66
+ }
67
+
68
+ import { panelRelativePath } from './panel-path.js'
69
+ import {
70
+ makeLedgerBody,
71
+ makeLedgerTitle,
72
+ renderPayload,
73
+ formatAmount,
74
+ formatTokens,
75
+ formatShare,
76
+ formatClock,
77
+ shortId,
78
+ sourceLabel,
79
+ } from './panel-view.js'
80
+
81
+
82
+ /** 会话 id 太长时截断成 chip 能放下的样子。 */
83
+
84
+ /**
85
+ * 面板取数的唯一注入点:读 Host 落在工作区里的只读快照。
86
+ *
87
+ * 通道已核实(@deepseek-ai/dsh-api-workspace-files 的生成 remote 声明):
88
+ * list(scopeId, path, signal?) → RemoteResult<WorkspaceDirectoryListing>
89
+ * stat(scopeId, path, signal?) → RemoteResult<WorkspaceFileStat>(带 absolutePath)
90
+ * read(scopeId, absolutePath, range, signal?) → RemoteResult<WorkspaceFileText>
91
+ * 相对路径以 Session 的 cwd 为基准,所以客户端**不需要知道**工作区绝对路径:
92
+ * 先用相对路径 stat 换出 absolutePath,再 read。
93
+ *
94
+ * 返回形状:
95
+ * null → 还没有快照(Host 未开启或尚未落盘)
96
+ * { error: '...' } → 通道/解析失败,面板显示原因
97
+ * payload → Host 写的 JSON(version / totals / topSources / sources)
98
+ *
99
+ * @param {any} ctx - 浏览器侧 cordis 上下文
100
+ * @returns {(sessionId: string, opts?: { signal?: AbortSignal }) => Promise<any>}
101
+ */
102
+ export function createFetchView(ctx) {
103
+ return async function fetchView(sessionId, opts = {}) {
104
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return null
105
+ const files = ctx?.remote?.workspaceFiles
106
+ if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
107
+ return { error: '宿主未提供 workspaceFiles 通道' }
108
+ }
109
+ const relative = panelRelativePath(sessionId)
110
+
111
+ let stat
112
+ try {
113
+ stat = await files.stat(sessionId, relative, opts.signal)
114
+ } catch (error) {
115
+ return { error: stringifyError(error) }
116
+ }
117
+ if (!stat?.ok) return null // 文件不存在=尚未落盘,不是错误
118
+ const absolutePath = stat.value?.absolutePath
119
+ if (typeof absolutePath !== 'string') return null
120
+ // 快照可能被写坏/过大:超过上限直接拒绝,避免把整份文件拖进内存
121
+ const bytes = stat.value?.bytes
122
+ if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
123
+
124
+ let page
125
+ try {
126
+ page = await files.read(sessionId, absolutePath, { offset: 0, limit: 400 }, opts.signal)
127
+ } catch (error) {
128
+ return { error: stringifyError(error) }
129
+ }
130
+ if (!page?.ok) return { error: '读取快照失败' }
131
+ const text = page.value?.text
132
+ if (typeof text !== 'string') return { error: '快照内容为空' }
133
+ if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
134
+
135
+ try {
136
+ const parsed = JSON.parse(text)
137
+ return parsed && typeof parsed === 'object' ? parsed : { error: '快照格式无法识别' }
138
+ } catch {
139
+ return { error: '快照不是合法 JSON(可能正写到一半)' }
140
+ }
141
+ }
142
+ }
143
+
144
+ /** 把任意抛出物变成一句话。 */
145
+ function stringifyError(error) {
146
+ if (error instanceof Error) return error.message
147
+ if (typeof error === 'string') return error
148
+ return '未知错误'
149
+ }
150
+
151
+ /** CNY 用 ¥,其它币种保留原符号 + 代码。 */
152
+
153
+ /**
154
+ * 正文组件。用 createElement 而不引 JSX,避免给独立仓库引入构建链。
155
+ * @param {any} React - 宿主的 React
156
+ * @param {(sid: string, opts?: object) => Promise<any>} fetchView
157
+ */
158
+
159
+ /**
160
+ * 渲染已取到的快照。
161
+ *
162
+ * 从组件里抽出来是为了可测:SSR 不跑 effect,组件首帧永远是"读取中",
163
+ * 只有把渲染当纯函数,才能在测试里断言四档金额、明细、预算条真的画出来了。
164
+ * @param {any} React
165
+ * @param {any} view - 快照 payload
166
+ * @param {string|null} sessionId
167
+ * @param {any} head - 已在组件侧建好的头部(含刷新按钮)
168
+ */
169
+
170
+ /** 一行 label / value,两个渲染入口共用。 */
171
+
172
+ /** 标题组件:chip 上的实时文案(不做金额,避免每次事件都改布局)。 */
173
+
174
+ /** @param {import('@deepseek-ai/cordis').Context} ctx */
175
+ export async function apply(ctx) {
176
+ const tabs = ctx.sidebarRightTabs
177
+ if (!tabs || typeof tabs.register !== 'function') return
178
+
179
+ const definition = {
180
+ id: LEDGER_ID,
181
+ kind: LEDGER_KIND,
182
+ title: () => '账本',
183
+ priority: 'extension',
184
+ guide: [
185
+ {
186
+ id: 'ledger.cost',
187
+ order: 10,
188
+ title: () => '账本',
189
+ description: () => '本会话的 token 用量与成本归因',
190
+ },
191
+ ],
192
+ // 切会话不重建面板体:成本是常驻读数,重建会丢滚动位置
193
+ keepMounted: true,
194
+ }
195
+
196
+ const disposeTab = tabs.register(definition)
197
+ const disposeClose =
198
+ typeof ctx.sidebarRight?.registerCloseHandler === 'function'
199
+ ? ctx.sidebarRight.registerCloseHandler(LEDGER_KIND, () => {})
200
+ : null
201
+
202
+ // 正文与标题:宿主把 seat 声明在 sidebar-right 里,先 inject 再 register
203
+ let disposeBody = null
204
+ let disposeTitle = null
205
+ const slots = ctx.slots
206
+ if (typeof slots?.inject === 'function' && typeof slots.register === 'function') {
207
+ let React = null
208
+ try {
209
+ React = await reactLoader()
210
+ } catch {
211
+ React = null // 宿主没给 React:保持无正文的降级态
212
+ }
213
+ if (React !== null) {
214
+ const fetchView = createFetchView(ctx)
215
+ disposeBody = slots.inject(SEAT_BODY, () =>
216
+ slots.register({ name: SEAT_BODY, key: LEDGER_ID }, makeLedgerBody(React, fetchView)),
217
+ )
218
+ disposeTitle = slots.inject(SEAT_TITLE, () =>
219
+ slots.register({ name: SEAT_TITLE, key: LEDGER_ID }, makeLedgerTitle(React)),
220
+ )
221
+ }
222
+ }
223
+
224
+ const cleanup = () => {
225
+ disposeTitle?.()
226
+ disposeBody?.()
227
+ disposeClose?.()
228
+ disposeTab()
229
+ }
230
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
231
+ else ctx.on('dispose', cleanup)
232
+ }
233
+
234
+ /**
235
+ * 测试可见的内部件。实现都在 panel-view.js(纯展示),
236
+ * 这里重导出,是为了让断言只认 `client.js` 一个入口。
237
+ */
238
+ export const __internal = {
239
+ makeLedgerBody,
240
+ makeLedgerTitle,
241
+ renderPayload,
242
+ formatAmount,
243
+ formatTokens,
244
+ formatShare,
245
+ formatClock,
246
+ shortId,
247
+ sourceLabel,
248
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingda-ai/dsh-plugin-ledger",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "DSH 插件搜索入口:运行时账本(成本/用量观测)。自包含单包,不依赖其他 npm 包,便于从镜像源安装。",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -46,4 +46,4 @@
46
46
  "engines": {
47
47
  "node": ">=18"
48
48
  }
49
- }
49
+ }