@mbws/plugin-sdk 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/caps.d.ts CHANGED
@@ -6,8 +6,9 @@
6
6
  * 驱动附件(任意 args),字节不过协议通道(输入 localize 进沙箱、产物宿主代传)。
7
7
  *
8
8
  * 命名空间固定两个(附件种类开放,不按附件分命名空间):
9
- * - caps.exec —— 附件 ensure/状态 + 输入本地化 + spawn 长任务 + 产物登记 + 媒体预览(有 attachments 声明才授予)
10
- * - caps.uploads —— 上传队列状态查询(桌面宿主恒授)
9
+ * - caps.exec —— 附件 ensure/状态 + 输入本地化 + spawn 长任务 + 产物登记 + 媒体预览
10
+ * + 通用文件/文件夹选择(有 attachments 声明才授予)
11
+ * - caps.uploads —— 上传队列事实查询(status/list 批量快照)+ 事件订阅 onUpload(桌面宿主恒授)
11
12
  */
12
13
  /** 附件状态机(宿主侧 attachment-store 的投影)。 */
13
14
  export interface AttachmentState {
@@ -52,26 +53,71 @@ export interface CapsAttachmentEvent {
52
53
  totalBytes?: number;
53
54
  message?: string;
54
55
  }
55
- export type CapsEvent = CapsJobEvent | CapsAttachmentEvent;
56
+ /** `mbws:event { event: "upload" }` 的 payload 形状(placeholder 是插件侧唯一句柄)。 */
57
+ export interface CapsUploadEvent {
58
+ /** 宿主侧路由键(broker 按它圈定下发对象;SDK 本地合成的事件不带,插件不应依赖) */
59
+ pluginId?: string;
60
+ placeholder: string;
61
+ /** registered=已登记未入队 / pending=已入队待传 / uploading / done / failed(终态必发不节流) */
62
+ phase: "registered" | "pending" | "uploading" | "done" | "failed";
63
+ /** 已传字节(uploading 时有值)——ratio 插件自算(对齐附件事件的字节级口径) */
64
+ receivedBytes?: number;
65
+ /** 总字节 */
66
+ totalBytes?: number;
67
+ /** done 时下发(local: → OSS key 换轨可追溯) */
68
+ objectKey?: string;
69
+ /** failed 时 */
70
+ error?: string;
71
+ }
72
+ export type CapsEvent = CapsJobEvent | CapsAttachmentEvent | CapsUploadEvent;
56
73
  /**
57
74
  * 附件事件并入状态镜像(client 端口客户端 / dev-mock 共用的纯函数):
58
75
  * phase → status、receivedBytes/totalBytes → ratio 派生;终态清进度字段。
59
76
  * 镜像由 init 快照种入、事件增量维护——attachmentStatus 本地读零往返。
60
77
  */
61
78
  export declare function mergeAttachmentEvent(states: Map<string, AttachmentState>, event: CapsAttachmentEvent): AttachmentState;
62
- /** caps.uploads.status 返回的占位值上传状态(pending-uploads 状态机投影)。 */
79
+ /** caps.uploads.status / caps.uploads.list 返回的占位值上传事实(pending-uploads 状态机投影)。 */
63
80
  export interface UploadStatusPayload {
81
+ /** 唯一句柄(list() 多条时插件按它对齐自己的产物映射) */
82
+ placeholder: string;
64
83
  status: "registered" | "pending" | "uploading" | "done" | "failed" | "missing";
65
84
  /** uploading 时 0..1 */
66
85
  progress?: number;
86
+ /** registerOutput 登记名 */
87
+ filename: string;
88
+ /** 文件总字节 */
89
+ totalBytes: number;
90
+ contentType?: string;
91
+ /** 追溯到产出任务(registerOutput 时插件传入的 jobId) */
92
+ jobId?: string;
67
93
  /** done 时的 OSS objectKey */
68
94
  objectKey?: string | null;
95
+ /** failed 时的错误摘要 */
96
+ error?: string;
97
+ /** 登记时间(ISO) */
98
+ createdAt?: string;
99
+ /** 事件并入镜像时派生的已传字节(uploading 时有值;status()/list() 宿主投影不含) */
100
+ receivedBytes?: number;
69
101
  }
102
+ /**
103
+ * 上传事件并入状态镜像(client 端口客户端 / dev-mock 共用的纯函数,对称 mergeAttachmentEvent):
104
+ * phase → status、receivedBytes/totalBytes → progress 派生;非 uploading 清进度字段、
105
+ * done 带 objectKey、failed 记 error。镜像由事件增量维护——status 本地读零往返。
106
+ */
107
+ export declare function mergeUploadEvent(states: Map<string, UploadStatusPayload>, event: CapsUploadEvent): UploadStatusPayload;
70
108
  /** caps.exec.localize 返回:job 沙箱相对路径(cwd 相对,args 直接引用)。 */
71
109
  export interface LocalizedInput {
72
110
  path: string;
73
111
  size: number;
74
112
  }
113
+ /** caps.exec.pickFile 请求:插件可限制可选文件类型(宿主系统选择器的过滤形状)。 */
114
+ export interface CapsPickFileRequest {
115
+ /** 扩展名过滤(如 [{ name: "视频", extensions: ["mp4", "mov"] }];缺省不限类型) */
116
+ filters?: {
117
+ name: string;
118
+ extensions: string[];
119
+ }[];
120
+ }
75
121
  /** caps.exec.registerOutput 返回:`local:` 占位值(apply 回写用,宿主代传)。 */
76
122
  export interface RegisteredOutput {
77
123
  placeholder: string;
@@ -105,7 +151,7 @@ export interface ExecJob {
105
151
  read(path: string, maxBytes?: number): Promise<string | null>;
106
152
  }
107
153
  /** caps.exec 方法白名单(宿主 broker 路由 + 参数校验依据,防调到桥内部方法)。 */
108
- export declare const CAPS_EXEC_METHODS: readonly ["ensureAttachment", "attachmentStatus", "localize", "spawn", "jobResult", "cancelJob", "readFile", "registerOutput", "mediaUrl"];
109
- export declare const CAPS_UPLOADS_METHODS: readonly ["status"];
154
+ export declare const CAPS_EXEC_METHODS: readonly ["ensureAttachment", "attachmentStatus", "localize", "spawn", "jobResult", "cancelJob", "readFile", "registerOutput", "mediaUrl", "pickDirectory", "pickFile"];
155
+ export declare const CAPS_UPLOADS_METHODS: readonly ["status", "list"];
110
156
  export type CapsExecMethod = (typeof CAPS_EXEC_METHODS)[number];
111
157
  export type CapsUploadsMethod = (typeof CAPS_UPLOADS_METHODS)[number];
package/dist/caps.js CHANGED
@@ -6,8 +6,9 @@
6
6
  * 驱动附件(任意 args),字节不过协议通道(输入 localize 进沙箱、产物宿主代传)。
7
7
  *
8
8
  * 命名空间固定两个(附件种类开放,不按附件分命名空间):
9
- * - caps.exec —— 附件 ensure/状态 + 输入本地化 + spawn 长任务 + 产物登记 + 媒体预览(有 attachments 声明才授予)
10
- * - caps.uploads —— 上传队列状态查询(桌面宿主恒授)
9
+ * - caps.exec —— 附件 ensure/状态 + 输入本地化 + spawn 长任务 + 产物登记 + 媒体预览
10
+ * + 通用文件/文件夹选择(有 attachments 声明才授予)
11
+ * - caps.uploads —— 上传队列事实查询(status/list 批量快照)+ 事件订阅 onUpload(桌面宿主恒授)
11
12
  */
12
13
  /**
13
14
  * 附件事件并入状态镜像(client 端口客户端 / dev-mock 共用的纯函数):
@@ -35,6 +36,42 @@ export function mergeAttachmentEvent(states, event) {
35
36
  states.set(event.name, next);
36
37
  return next;
37
38
  }
39
+ /**
40
+ * 上传事件并入状态镜像(client 端口客户端 / dev-mock 共用的纯函数,对称 mergeAttachmentEvent):
41
+ * phase → status、receivedBytes/totalBytes → progress 派生;非 uploading 清进度字段、
42
+ * done 带 objectKey、failed 记 error。镜像由事件增量维护——status 本地读零往返。
43
+ */
44
+ export function mergeUploadEvent(states, event) {
45
+ const prev = states.get(event.placeholder);
46
+ const next = {
47
+ ...(prev ?? {}),
48
+ // 必填事实兜底:事件不携带时沿用镜像旧值(无旧值用空值——事件面只保证 phase/字节)
49
+ filename: prev?.filename ?? "",
50
+ totalBytes: prev?.totalBytes ?? 0,
51
+ placeholder: event.placeholder,
52
+ status: event.phase,
53
+ ...(event.receivedBytes !== undefined ? { receivedBytes: event.receivedBytes } : {}),
54
+ ...(event.totalBytes !== undefined ? { totalBytes: event.totalBytes } : {}),
55
+ ...(event.objectKey !== undefined ? { objectKey: event.objectKey } : {}),
56
+ ...(event.error !== undefined ? { error: event.error } : {}),
57
+ };
58
+ // progress 从合并后的字节派生(事件只带 receivedBytes 时用镜像旧 totalBytes 补算);
59
+ // 非 uploading 一律清进度(done 后镜像旧字节不再回算 progress)
60
+ if (event.phase === "uploading" && next.receivedBytes !== undefined && next.totalBytes > 0) {
61
+ next.progress = Math.min(1, next.receivedBytes / next.totalBytes);
62
+ }
63
+ else if (event.phase !== "uploading") {
64
+ delete next.progress;
65
+ delete next.receivedBytes;
66
+ }
67
+ if (event.phase !== "failed")
68
+ delete next.error;
69
+ // done 才保留 objectKey(占位值重登记等极端态清残留)
70
+ if (event.phase !== "done" && event.objectKey === undefined)
71
+ delete next.objectKey;
72
+ states.set(event.placeholder, next);
73
+ return next;
74
+ }
38
75
  /** caps.exec 方法白名单(宿主 broker 路由 + 参数校验依据,防调到桥内部方法)。 */
39
76
  export const CAPS_EXEC_METHODS = [
40
77
  "ensureAttachment",
@@ -46,5 +83,7 @@ export const CAPS_EXEC_METHODS = [
46
83
  "readFile",
47
84
  "registerOutput",
48
85
  "mediaUrl",
86
+ "pickDirectory",
87
+ "pickFile",
49
88
  ];
50
- export const CAPS_UPLOADS_METHODS = ["status"];
89
+ export const CAPS_UPLOADS_METHODS = ["status", "list"];
package/dist/client.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * 安全定位:客户端只是包装不是防线——插件绕过客户端手发消息伪造调用,
14
14
  * broker 对每条进入的消息仍按 manifest 独立校验(防线在宿主侧)。
15
15
  */
16
- import type { AttachmentState, CapsAttachmentEvent, ExecJob, LocalizedInput, RegisteredOutput, UploadStatusPayload } from "./caps.js";
16
+ import type { AttachmentState, CapsAttachmentEvent, CapsPickFileRequest, CapsUploadEvent, ExecJob, LocalizedInput, RegisteredOutput, UploadStatusPayload } from "./caps.js";
17
17
  import { type FetchContractOptions, type PluginContract } from "./contract.js";
18
18
  import { type MbwsErrorCode } from "./errors.js";
19
19
  import type { MbwsErrorPayload } from "./protocol.js";
@@ -115,7 +115,12 @@ export interface MbwsClient<C extends MbwsContractTypes = MbwsContractTypes> {
115
115
  args: string[];
116
116
  timeoutMs?: number;
117
117
  }): Promise<ExecJob>;
118
- /** 产物登记:job 沙箱内相对路径 → local: 占位值(宿主 move 进上传队列代传) */
118
+ /**
119
+ * 产物登记 → local: 占位值(apply 回写用,宿主代传)。path 两种形态:
120
+ * - job 沙箱内相对路径:宿主 move 进上传队列托管目录;
121
+ * - 本会话 pickDirectory/pickFile 选中范围内的绝对路径:reference 登记、
122
+ * 文件原地不动(产物已由 spawn 直接写进用户所选文件夹),定稿从原路径直传。
123
+ */
119
124
  registerOutput(req: {
120
125
  jobId: string;
121
126
  path: string;
@@ -127,12 +132,34 @@ export interface MbwsClient<C extends MbwsContractTypes = MbwsContractTypes> {
127
132
  url: string;
128
133
  mime?: string;
129
134
  }>;
135
+ /** 选文件夹(宿主弹系统选择器)。返回所选目录绝对路径;取消返回 null */
136
+ pickDirectory(): Promise<string | null>;
137
+ /** 选文件(filters 可限制可选类型)。返回所选文件绝对路径;取消返回 null */
138
+ pickFile(req?: CapsPickFileRequest): Promise<string | null>;
130
139
  /** 附件下载进度/状态事件订阅(返回退订函数) */
131
140
  onAttachment(cb: (e: CapsAttachmentEvent) => void): () => void;
132
141
  };
133
142
  uploads: {
134
- /** 占位值上传状态查询(面板展示「待上传/上传中 42%/已上传」) */
143
+ /**
144
+ * 占位值上传事实查询(面板展示「待上传/上传中 42%/已上传」)。
145
+ * 本地镜像(事件维护)优先,未知名落宿主查询。
146
+ */
135
147
  status(placeholder: string): Promise<UploadStatusPayload>;
148
+ /**
149
+ * 本插件名下全部占位的批量快照(含已 done)——面板重开首屏一条调用
150
+ * 渲染「上次产出 + 上传中」区块;与事件同源(同一状态机投影),先后调用不丢事件
151
+ * (onUpload 订阅即对非终态条目补发当前状态)。
152
+ */
153
+ list(): Promise<UploadStatusPayload[]>;
154
+ /**
155
+ * 上传进度/状态事件订阅(返回退订函数)——进度推进的主通道,status/list 只是
156
+ * 快照与兜底。订阅即补发:对当前非终态占位各喂一条当前状态,免去先 list 再订阅。
157
+ *
158
+ * 预留命名(本期未实现,防后续签名破坏性变更):
159
+ * - retry(placeholder): Promise<void> —— 宿主自动退避重试穷尽后的手动重试
160
+ * - cancel(placeholder): Promise<void> —— 放弃上传,占位转 failed
161
+ */
162
+ onUpload(cb: (e: CapsUploadEvent) => void): () => void;
136
163
  };
137
164
  };
138
165
  /**
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { mergeAttachmentEvent } from "./caps.js";
1
+ import { mergeAttachmentEvent, mergeUploadEvent } from "./caps.js";
2
2
  import { fetchContract } from "./contract.js";
3
3
  import { createDevMockMbws } from "./dev-mock.js";
4
4
  import { MBWS_ERROR_CODES } from "./errors.js";
@@ -62,6 +62,10 @@ export function connectMbwsPort(port, init, opts = {}) {
62
62
  const applyAttachmentEvent = (e) => {
63
63
  mergeAttachmentEvent(attachmentStates, e);
64
64
  };
65
+ // 上传状态本地镜像 + 订阅(对称附件镜像):事件增量维护——status 本地读零往返;
66
+ // list() 结果按「缺才种入」并入(事件更新的条目比 list 响应新,不回退)
67
+ const uploadStates = new Map();
68
+ const uploadCbs = new Set();
65
69
  const jobSessionOf = (jobId) => {
66
70
  let session = jobSessions.get(jobId);
67
71
  if (!session) {
@@ -106,6 +110,11 @@ export function connectMbwsPort(port, init, opts = {}) {
106
110
  session.waiters = [];
107
111
  }
108
112
  }
113
+ else if ("placeholder" in e) {
114
+ mergeUploadEvent(uploadStates, e);
115
+ for (const cb of uploadCbs)
116
+ cb(e);
117
+ }
109
118
  else if ("name" in e) {
110
119
  applyAttachmentEvent(e);
111
120
  for (const cb of attachmentCbs)
@@ -163,10 +172,12 @@ export function connectMbwsPort(port, init, opts = {}) {
163
172
  break;
164
173
  }
165
174
  case "mbws:event": {
166
- // 取消事件桥到 AbortSignal;job/attachment 事件路由进 caps 会话
175
+ // 取消事件桥到 AbortSignal;job/attachment/upload 事件路由进 caps 会话
167
176
  if (message.event === "cancel")
168
177
  abortController.abort();
169
- else if (message.event === "job" || message.event === "attachment") {
178
+ else if (message.event === "job" ||
179
+ message.event === "attachment" ||
180
+ message.event === "upload") {
170
181
  handleCapsEvent(message.payload);
171
182
  }
172
183
  break;
@@ -241,13 +252,67 @@ export function connectMbwsPort(port, init, opts = {}) {
241
252
  },
242
253
  registerOutput: (req) => invoke("caps.exec", "registerOutput", req),
243
254
  mediaUrl: (ref) => invoke("caps.exec", "mediaUrl", { ref }),
255
+ pickDirectory: () => invoke("caps.exec", "pickDirectory", {}),
256
+ pickFile: (req) => invoke("caps.exec", "pickFile", req ?? {}),
244
257
  onAttachment: (cb) => {
245
258
  attachmentCbs.add(cb);
246
259
  return () => attachmentCbs.delete(cb);
247
260
  },
248
261
  },
249
262
  uploads: {
250
- status: (placeholder) => invoke("caps.uploads", "status", { placeholder }),
263
+ status: (placeholder) => {
264
+ // 本地镜像优先(事件维护 + list 种入);未知名落宿主查询
265
+ const local = uploadStates.get(placeholder);
266
+ if (local)
267
+ return Promise.resolve({ ...local });
268
+ return invoke("caps.uploads", "status", {
269
+ placeholder,
270
+ });
271
+ },
272
+ list: async () => {
273
+ const items = (await invoke("caps.uploads", "list"));
274
+ for (const item of items) {
275
+ if (item?.placeholder && !uploadStates.has(item.placeholder)) {
276
+ uploadStates.set(item.placeholder, item);
277
+ }
278
+ }
279
+ return items;
280
+ },
281
+ onUpload: (cb) => {
282
+ uploadCbs.add(cb);
283
+ // 订阅即补发:对当前非终态占位各喂一条当前状态(快照在订阅前调用也不丢
284
+ // 事件)。只喂 cb 不并入镜像——镜像可能已被更新的真实事件推进
285
+ void invoke("caps.uploads", "list")
286
+ .then((items) => {
287
+ if (!uploadCbs.has(cb))
288
+ return; // 已退订,不再补发
289
+ for (const item of items ?? []) {
290
+ if (!item?.placeholder)
291
+ continue;
292
+ if (item.status === "done" ||
293
+ item.status === "failed" ||
294
+ item.status === "missing")
295
+ continue;
296
+ cb({
297
+ placeholder: item.placeholder,
298
+ phase: item.status,
299
+ ...(item.receivedBytes !== undefined || item.progress !== undefined
300
+ ? {
301
+ receivedBytes: item.receivedBytes ??
302
+ (item.progress !== undefined && item.totalBytes
303
+ ? Math.round(item.progress * item.totalBytes)
304
+ : undefined),
305
+ totalBytes: item.totalBytes,
306
+ }
307
+ : {}),
308
+ });
309
+ }
310
+ })
311
+ .catch(() => {
312
+ // 补发是尽力而为:宿主不可达(旧宿主无 list)时静默,事件通道照常
313
+ });
314
+ return () => uploadCbs.delete(cb);
315
+ },
251
316
  },
252
317
  },
253
318
  }
package/dist/dev-mock.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * 宿主两端通用,不自己解析 stderr。快照从 `/__mbws__/dev/attachments` 种入
15
15
  * (.mbws/attachments/ 缓存命中 = ready,否则 missing),attachmentStatus 本地读。
16
16
  */
17
- import { mergeAttachmentEvent, } from "./caps.js";
17
+ import { mergeAttachmentEvent, mergeUploadEvent, } from "./caps.js";
18
18
  import { MbwsInvokeError } from "./client.js";
19
19
  import { fetchContract } from "./contract.js";
20
20
  import { MBWS_ERROR_CODES } from "./errors.js";
@@ -26,6 +26,57 @@ function emitDevAttachment(e) {
26
26
  for (const cb of devAttachmentCbs)
27
27
  cb(e);
28
28
  }
29
+ // ===== 上传事件通道(dev 会话级):registerOutput 假登记 + 模拟 uploading→done 时序 =====
30
+ // dev 无真上传队列——registerOutput 登记后按固定时序推进(500ms 后转 uploading,
31
+ // 每 500ms +20% 字节,终至 done 带假 objectKey),onUpload 收到与宿主同形的事件序列,
32
+ // 插件进度 UI 在浏览器 dev 即可联调。
33
+ const devUploadStates = new Map();
34
+ const devUploadCbs = new Set();
35
+ function emitDevUpload(e) {
36
+ mergeUploadEvent(devUploadStates, e);
37
+ for (const cb of devUploadCbs)
38
+ cb(e);
39
+ }
40
+ /** dev 模拟上传的假体量(24MB)与时序参数 */
41
+ const DEV_UPLOAD_TOTAL_BYTES = 24 * 1024 * 1024;
42
+ const DEV_UPLOAD_TICK_MS = 500;
43
+ const DEV_UPLOAD_STEP_RATIO = 0.2;
44
+ function simulateDevUpload(placeholder) {
45
+ setTimeout(() => {
46
+ emitDevUpload({
47
+ placeholder,
48
+ phase: "uploading",
49
+ receivedBytes: 0,
50
+ totalBytes: DEV_UPLOAD_TOTAL_BYTES,
51
+ });
52
+ let ratio = DEV_UPLOAD_STEP_RATIO;
53
+ const tick = () => {
54
+ if (ratio >= 1 || !devUploadStates.has(placeholder))
55
+ return;
56
+ emitDevUpload({
57
+ placeholder,
58
+ phase: "uploading",
59
+ receivedBytes: Math.round(ratio * DEV_UPLOAD_TOTAL_BYTES),
60
+ totalBytes: DEV_UPLOAD_TOTAL_BYTES,
61
+ });
62
+ ratio += DEV_UPLOAD_STEP_RATIO;
63
+ if (ratio <= 1)
64
+ setTimeout(tick, DEV_UPLOAD_TICK_MS);
65
+ };
66
+ setTimeout(tick, DEV_UPLOAD_TICK_MS);
67
+ // 5 拍后 done(0.2 × 5 = 1.0)
68
+ setTimeout(() => {
69
+ if (!devUploadStates.has(placeholder))
70
+ return;
71
+ emitDevUpload({
72
+ placeholder,
73
+ phase: "done",
74
+ totalBytes: DEV_UPLOAD_TOTAL_BYTES,
75
+ objectKey: `union-dev/dev-uploads/${placeholder.split(":").pop() ?? "out"}`,
76
+ });
77
+ }, DEV_UPLOAD_TICK_MS * 6);
78
+ }, DEV_UPLOAD_TICK_MS);
79
+ }
29
80
  /** dev 快照种子(会话内一次):非 dev server / 端点缺席静默跳过,attachmentStatus 回 missing */
30
81
  let devSnapshotPromise = null;
31
82
  function seedDevAttachmentSnapshot() {
@@ -329,8 +380,20 @@ export function createDevMockMbws() {
329
380
  },
330
381
  spawn: (req) => spawnDevJob(req),
331
382
  registerOutput: async (req) => {
332
- console.info(`[mbws:dev] registerOutput(${req.filename})——假占位不入库`);
333
- return { placeholder: `devlocal:${encodeURIComponent(req.filename)}` };
383
+ console.info(`[mbws:dev] registerOutput(${req.filename})——假占位 + 模拟上传时序`);
384
+ const placeholder = `devlocal:${encodeURIComponent(req.filename)}`;
385
+ emitDevUpload({ placeholder, phase: "registered", totalBytes: DEV_UPLOAD_TOTAL_BYTES });
386
+ const seeded = devUploadStates.get(placeholder);
387
+ if (seeded) {
388
+ seeded.filename = req.filename;
389
+ if (req.contentType)
390
+ seeded.contentType = req.contentType;
391
+ if (req.jobId)
392
+ seeded.jobId = req.jobId;
393
+ seeded.createdAt = new Date().toISOString();
394
+ }
395
+ simulateDevUpload(placeholder);
396
+ return { placeholder };
334
397
  },
335
398
  mediaUrl: async (ref) => {
336
399
  try {
@@ -345,15 +408,63 @@ export function createDevMockMbws() {
345
408
  }
346
409
  return { url: `dev://samples/${ref}` };
347
410
  },
411
+ // dev 无系统选择器:pick 固定指向工程内目录(中间件创建并返回绝对路径),
412
+ // spawn(cwd=工程根)对相对兜底值同样可用;取消语义 dev 下不存在(恒有返回)
413
+ pickDirectory: async () => {
414
+ try {
415
+ const response = await fetch("/__mbws__/dev/pick-directory", { method: "POST" });
416
+ if (response.ok)
417
+ return (await response.json()).path;
418
+ }
419
+ catch {
420
+ // 非 dev server 场景,走兜底
421
+ }
422
+ return ".mbws/dev-outputs";
423
+ },
424
+ pickFile: async (req) => {
425
+ try {
426
+ const response = await fetch("/__mbws__/dev/pick-file", {
427
+ method: "POST",
428
+ headers: { "content-type": "application/json" },
429
+ body: JSON.stringify({ filters: req?.filters ?? [] }),
430
+ });
431
+ if (response.ok)
432
+ return (await response.json()).path;
433
+ }
434
+ catch {
435
+ // 非 dev server 场景,走兜底
436
+ }
437
+ return "samples";
438
+ },
348
439
  onAttachment: (cb) => {
349
440
  devAttachmentCbs.add(cb);
350
441
  return () => devAttachmentCbs.delete(cb);
351
442
  },
352
443
  },
353
444
  uploads: {
445
+ // 与宿主端口客户端同语义:本地镜像(事件维护)优先,未知名回 missing
354
446
  status: async (placeholder) => {
355
- console.info(`[mbws:dev] uploads.status(${placeholder})`);
356
- return { status: "registered" };
447
+ const local = devUploadStates.get(placeholder);
448
+ if (local)
449
+ return { ...local };
450
+ return { placeholder, status: "missing", filename: "", totalBytes: 0 };
451
+ },
452
+ list: async () => [...devUploadStates.values()].map((s) => ({ ...s })),
453
+ onUpload: (cb) => {
454
+ devUploadCbs.add(cb);
455
+ // 订阅即补发:对当前非终态占位各喂一条当前状态(与宿主客户端的 list 补发同语义)
456
+ for (const s of devUploadStates.values()) {
457
+ if (s.status === "done" || s.status === "failed" || s.status === "missing")
458
+ continue;
459
+ cb({
460
+ placeholder: s.placeholder,
461
+ phase: s.status,
462
+ ...(s.progress !== undefined
463
+ ? { receivedBytes: Math.round(s.progress * s.totalBytes), totalBytes: s.totalBytes }
464
+ : { totalBytes: s.totalBytes }),
465
+ });
466
+ }
467
+ return () => devUploadCbs.delete(cb);
357
468
  },
358
469
  },
359
470
  },
@@ -18,9 +18,10 @@ import { type MbwsErrorCode } from "./errors.js";
18
18
  export declare const MBWS_NAMESPACES: readonly ["data", "runtime", "storage", "ui"];
19
19
  /**
20
20
  * 宿主 → 插件事件种类(设计稿 §6.6:progress / log / cancel / theme + caps 长任务两族)。
21
- * `job`:附件子进程行流/退出;`attachment`:附件下载进度/状态。payload 形状见 caps.ts。
21
+ * `job`:附件子进程行流/退出;`attachment`:附件下载进度/状态;`upload`:产物上传进度/状态。
22
+ * payload 形状见 caps.ts。
22
23
  */
23
- export declare const MBWS_EVENT_KINDS: readonly ["progress", "log", "cancel", "theme", "job", "attachment"];
24
+ export declare const MBWS_EVENT_KINDS: readonly ["progress", "log", "cancel", "theme", "job", "attachment", "upload"];
24
25
  export declare const MbwsMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
25
26
  v: z.ZodLiteral<1>;
26
27
  type: z.ZodLiteral<"mbws:invoke">;
@@ -78,6 +79,7 @@ export declare const MbwsMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
78
79
  theme: "theme";
79
80
  job: "job";
80
81
  attachment: "attachment";
82
+ upload: "upload";
81
83
  }>;
82
84
  payload: z.ZodOptional<z.ZodUnknown>;
83
85
  }, z.core.$strip>, z.ZodObject<{
package/dist/protocol.js CHANGED
@@ -21,7 +21,8 @@ const NS_RE = /^(data|runtime|storage|ui|caps(\.[a-z0-9-]+)?)$/;
21
21
  const nsField = z.string().regex(NS_RE);
22
22
  /**
23
23
  * 宿主 → 插件事件种类(设计稿 §6.6:progress / log / cancel / theme + caps 长任务两族)。
24
- * `job`:附件子进程行流/退出;`attachment`:附件下载进度/状态。payload 形状见 caps.ts。
24
+ * `job`:附件子进程行流/退出;`attachment`:附件下载进度/状态;`upload`:产物上传进度/状态。
25
+ * payload 形状见 caps.ts。
25
26
  */
26
27
  export const MBWS_EVENT_KINDS = [
27
28
  "progress",
@@ -30,6 +31,7 @@ export const MBWS_EVENT_KINDS = [
30
31
  "theme",
31
32
  "job",
32
33
  "attachment",
34
+ "upload",
33
35
  ];
34
36
  const InvokeMessage = z.object({
35
37
  v: z.literal(PROTOCOL_VERSION),
package/dist/version.d.ts CHANGED
@@ -12,4 +12,4 @@ export declare const PROTOCOL_VERSION: 1;
12
12
  * SDK 自身版本(与 package.json version 保持一致)。
13
13
  * init-ack 上报给宿主做审计,与 manifest.sdk(build 写入)交叉核对。
14
14
  */
15
- export declare const SDK_VERSION = "0.3.5";
15
+ export declare const SDK_VERSION = "0.3.7";
package/dist/version.js CHANGED
@@ -12,4 +12,4 @@ export const PROTOCOL_VERSION = 1;
12
12
  * SDK 自身版本(与 package.json version 保持一致)。
13
13
  * init-ack 上报给宿主做审计,与 manifest.sdk(build 写入)交叉核对。
14
14
  */
15
- export const SDK_VERSION = "0.3.5";
15
+ export const SDK_VERSION = "0.3.7";
package/dist/vite.js CHANGED
@@ -172,6 +172,24 @@ export function mbwsVitePlugin(opts) {
172
172
  // 附件状态快照:面板首屏提示(missing/ready + 尽力而为的 totalBytes)
173
173
  return handleDevAttachmentsSnapshot(config, projectRoot, res).catch(next);
174
174
  }
175
+ if (pathname === "/__mbws__/dev/pick-directory") {
176
+ if (req.method !== "POST") {
177
+ res.statusCode = 405;
178
+ res.end();
179
+ return;
180
+ }
181
+ // dev 无系统选择器:pickDirectory 固定指 .mbws/dev-outputs(绝对路径,目录即建)
182
+ return handleDevPickDirectory(projectRoot, res).catch(next);
183
+ }
184
+ if (pathname === "/__mbws__/dev/pick-file") {
185
+ if (req.method !== "POST") {
186
+ res.statusCode = 405;
187
+ res.end();
188
+ return;
189
+ }
190
+ // dev 无选择器:pickFile 取 samples/ 下第一个文件(filters 仅回显,不真正过滤)
191
+ return handleDevPickFile(projectRoot, req, res).catch(next);
192
+ }
175
193
  if (pathname === "/__mbws__/dev/localize") {
176
194
  const ref = new URL(req.url ?? "/", "http://dev").searchParams.get("ref") ?? "";
177
195
  if (!ref) {
@@ -634,6 +652,44 @@ async function handleDevAttachmentsSnapshot(config, root, res) {
634
652
  res.setHeader("cache-control", "no-store");
635
653
  res.end(JSON.stringify(items));
636
654
  }
655
+ /**
656
+ * POST /__mbws__/dev/pick-directory:dev 无系统选择器——固定指 `.mbws/dev-outputs/`
657
+ * (绝对路径,目录即建)。插件拿路径拼产物输出位置,spawn(cwd=工程根)直接写绝对路径。
658
+ */
659
+ async function handleDevPickDirectory(root, res) {
660
+ const dir = path.join(root, ".mbws", "dev-outputs");
661
+ await fs.promises.mkdir(dir, { recursive: true });
662
+ res.setHeader("content-type", "application/json");
663
+ res.setHeader("cache-control", "no-store");
664
+ res.end(JSON.stringify({ path: dir }));
665
+ }
666
+ /**
667
+ * POST /__mbws__/dev/pick-file:dev 无选择器——取 `samples/` 下第一个文件
668
+ * (无文件则返回目录本身,目录即建);body 的 filters 仅回显日志,dev 不真正过滤。
669
+ */
670
+ async function handleDevPickFile(root, req, res) {
671
+ let filters;
672
+ try {
673
+ const body = JSON.parse((await readRequestBody(req)).toString("utf8"));
674
+ filters = body.filters;
675
+ }
676
+ catch {
677
+ // 空体容忍(dev-mock 恒发 JSON,手 curl 可能空体)
678
+ }
679
+ const dir = path.join(root, "samples");
680
+ await fs.promises.mkdir(dir, { recursive: true });
681
+ let picked = dir;
682
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
683
+ const firstFile = entries.find((e) => e.isFile());
684
+ if (firstFile)
685
+ picked = path.join(dir, firstFile.name);
686
+ if (filters !== undefined) {
687
+ console.info(`[mbws:dev] pick-file filters 仅回显(dev 不真正过滤):${JSON.stringify(filters)}`);
688
+ }
689
+ res.setHeader("content-type", "application/json");
690
+ res.setHeader("cache-control", "no-store");
691
+ res.end(JSON.stringify({ path: picked }));
692
+ }
637
693
  /** GET /__mbws__/dev/localize?ref=:映射到工程内 samples/ 夹具(存在才 200) */
638
694
  async function handleDevLocalize(root, res, ref) {
639
695
  const basename = ref.split("/").pop() ?? "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mbws/plugin-sdk",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "description": "Moye 插件开发 SDK——panel/viewer 与宿主的类型定义与运行时端口适配",
5
5
  "license": "MIT",
6
6
  "type": "module",