dsh-plugin-core-demo 0.42.5 → 0.43.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.
Files changed (3) hide show
  1. package/dist/client.js +2678 -4328
  2. package/dist/index.js +299 -50
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -26,10 +26,10 @@ function filterKeys(object, filter) {
26
26
  function mapValues(object, transform) {
27
27
  return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
28
28
  }
29
- function pick(source, keys, forced) {
30
- if (!keys) return { ...source };
29
+ function pick(source2, keys, forced) {
30
+ if (!keys) return { ...source2 };
31
31
  const result = {};
32
- for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
32
+ for (const key of keys) if (forced || source2[key] !== void 0) result[key] = source2[key];
33
33
  return result;
34
34
  }
35
35
  function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
@@ -67,26 +67,26 @@ function isArrayBufferLike(value) {
67
67
  function isArrayBufferSource(value) {
68
68
  return isArrayBufferLike(value) || ArrayBuffer.isView(value);
69
69
  }
70
- function clone(source, refs = /* @__PURE__ */ new Map()) {
71
- if (!source || typeof source !== "object") return source;
72
- if (is("Date", source)) return new Date(source.valueOf());
73
- if (is("RegExp", source)) return new RegExp(source.source, source.flags);
74
- if (isArrayBufferLike(source)) return source.slice(0);
75
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
76
- const cached = refs.get(source);
70
+ function clone(source2, refs = /* @__PURE__ */ new Map()) {
71
+ if (!source2 || typeof source2 !== "object") return source2;
72
+ if (is("Date", source2)) return new Date(source2.valueOf());
73
+ if (is("RegExp", source2)) return new RegExp(source2.source, source2.flags);
74
+ if (isArrayBufferLike(source2)) return source2.slice(0);
75
+ if (ArrayBuffer.isView(source2)) return source2.buffer.slice(source2.byteOffset, source2.byteOffset + source2.byteLength);
76
+ const cached = refs.get(source2);
77
77
  if (cached) return cached;
78
- if (Array.isArray(source)) {
78
+ if (Array.isArray(source2)) {
79
79
  const result2 = [];
80
- refs.set(source, result2);
81
- source.forEach((value, index) => {
80
+ refs.set(source2, result2);
81
+ source2.forEach((value, index) => {
82
82
  result2[index] = Reflect.apply(clone, null, [value, refs]);
83
83
  });
84
84
  return result2;
85
85
  }
86
- const result = Object.create(Object.getPrototypeOf(source));
87
- refs.set(source, result);
88
- for (const key of Reflect.ownKeys(source)) {
89
- const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
86
+ const result = Object.create(Object.getPrototypeOf(source2));
87
+ refs.set(source2, result);
88
+ for (const key of Reflect.ownKeys(source2)) {
89
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source2, key) };
90
90
  if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
91
91
  Reflect.defineProperty(result, key, descriptor);
92
92
  }
@@ -132,34 +132,34 @@ var init_lib = __esm({
132
132
  (function(Binary2) {
133
133
  Binary2.is = isArrayBufferLike;
134
134
  Binary2.isSource = isArrayBufferSource;
135
- function fromSource(source) {
136
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
137
- else return source;
135
+ function fromSource(source2) {
136
+ if (ArrayBuffer.isView(source2)) return source2.buffer.slice(source2.byteOffset, source2.byteOffset + source2.byteLength);
137
+ else return source2;
138
138
  }
139
139
  Binary2.fromSource = fromSource;
140
- function toBase64(source) {
141
- source = fromSource(source);
142
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
140
+ function toBase64(source2) {
141
+ source2 = fromSource(source2);
142
+ if (typeof Buffer !== "undefined") return Buffer.from(source2).toString("base64");
143
143
  let binary = "";
144
- const bytes = new Uint8Array(source);
144
+ const bytes = new Uint8Array(source2);
145
145
  for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
146
146
  return btoa(binary);
147
147
  }
148
148
  Binary2.toBase64 = toBase64;
149
- function fromBase64(source) {
150
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
151
- return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
149
+ function fromBase64(source2) {
150
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source2, "base64"));
151
+ return Uint8Array.from(atob(source2), (c) => c.charCodeAt(0));
152
152
  }
153
153
  Binary2.fromBase64 = fromBase64;
154
- function toHex(source) {
155
- source = fromSource(source);
156
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
157
- return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
154
+ function toHex(source2) {
155
+ source2 = fromSource(source2);
156
+ if (typeof Buffer !== "undefined") return Buffer.from(source2).toString("hex");
157
+ return Array.from(new Uint8Array(source2), (byte) => byte.toString(16).padStart(2, "0")).join("");
158
158
  }
159
159
  Binary2.toHex = toHex;
160
- function fromHex(source) {
161
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
162
- const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
160
+ function fromHex(source2) {
161
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source2, "hex"));
162
+ const hex = source2.length % 2 === 0 ? source2 : source2.slice(0, source2.length - 1);
163
163
  const buffer = [];
164
164
  for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
165
165
  return Uint8Array.from(buffer).buffer;
@@ -206,8 +206,8 @@ var init_lib = __esm({
206
206
  "m(?:in(?:ute)?(?:s)?)?",
207
207
  "s(?:ec(?:ond)?(?:s)?)?"
208
208
  ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
209
- function parseTime(source) {
210
- const capture = timeRegExp.exec(source);
209
+ function parseTime(source2) {
210
+ const capture = timeRegExp.exec(source2);
211
211
  if (!capture) return 0;
212
212
  return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
213
213
  }
@@ -229,8 +229,8 @@ var init_lib = __esm({
229
229
  return ms + "ms";
230
230
  }
231
231
  Time2.format = format;
232
- function toDigits(source, length = 2) {
233
- return source.toString().padStart(length, "0");
232
+ function toDigits(source2, length = 2) {
233
+ return source2.toString().padStart(length, "0");
234
234
  }
235
235
  Time2.toDigits = toDigits;
236
236
  function template(template2, time = /* @__PURE__ */ new Date()) {
@@ -635,15 +635,15 @@ var init_lib2 = __esm({
635
635
  return [schema.meta.default];
636
636
  }
637
637
  };
638
- Schema.from = function from(source) {
639
- if (isNullable(source)) return Schema.any();
638
+ Schema.from = function from(source2) {
639
+ if (isNullable(source2)) return Schema.any();
640
640
  else if ([
641
641
  "string",
642
642
  "number",
643
643
  "boolean"
644
- ].includes(typeof source)) return Schema.const(source).required();
645
- else if (source[kSchema]) return source;
646
- else if (typeof source === "function") switch (source) {
644
+ ].includes(typeof source2)) return Schema.const(source2).required();
645
+ else if (source2[kSchema]) return source2;
646
+ else if (typeof source2 === "function") switch (source2) {
647
647
  case String:
648
648
  return Schema.string().required();
649
649
  case Number:
@@ -653,9 +653,9 @@ var init_lib2 = __esm({
653
653
  case Function:
654
654
  return Schema.function().required();
655
655
  default:
656
- return Schema.is(source).required();
656
+ return Schema.is(source2).required();
657
657
  }
658
- else throw new TypeError(`cannot infer schema from ${source}`);
658
+ else throw new TypeError(`cannot infer schema from ${source2}`);
659
659
  };
660
660
  Schema.lazy = function lazy(builder) {
661
661
  const toJSON2 = () => {
@@ -892,6 +892,156 @@ var init_lib2 = __esm({
892
892
  }
893
893
  });
894
894
 
895
+ // dist/host/task-stream.js
896
+ function json(res, status, body) {
897
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
898
+ res.end(JSON.stringify(body));
899
+ }
900
+ var KEEP_ALIVE = ": keep-alive\n\n";
901
+ function serveTaskStream(ctx, options) {
902
+ if (typeof options.authorize !== "function") {
903
+ throw new Error("serveTaskStream requires authorize: host provides no server-wide auth");
904
+ }
905
+ const base = options.basePath.replace(/\/$/, "");
906
+ const keepAliveMs = options.keepAliveMs ?? 25e3;
907
+ const connections = /* @__PURE__ */ new Set();
908
+ ctx.inject(["webServer"], (services) => {
909
+ const web = services.webServer;
910
+ if (web === void 0)
911
+ return;
912
+ web.register({
913
+ kind: "exact",
914
+ path: `${base}/stream`,
915
+ handler: (req, rawRes) => {
916
+ const res = rawRes;
917
+ Promise.resolve().then(() => options.authorize(req)).then((viewer) => {
918
+ if (viewer === null || viewer === "") {
919
+ json(res, 401, { error: "unauthorized" });
920
+ return;
921
+ }
922
+ const buffered = [];
923
+ let streaming = false;
924
+ const push2 = (event, payload) => {
925
+ const frame = `event: ${event}
926
+ data: ${JSON.stringify(payload)}
927
+
928
+ `;
929
+ if (streaming)
930
+ res.write(frame);
931
+ else
932
+ buffered.push(frame);
933
+ };
934
+ const sendTask = (task) => {
935
+ push2("task", task);
936
+ };
937
+ const sendNotice = (notice) => {
938
+ push2("task-notice", notice);
939
+ };
940
+ const offTask = options.source.subscribe(sendTask, viewer);
941
+ const offNotice = options.source.subscribeNotices?.(sendNotice, viewer);
942
+ const timer = setInterval(() => {
943
+ res.write(KEEP_ALIVE);
944
+ }, keepAliveMs);
945
+ timer.unref?.();
946
+ const conn = {
947
+ cleanup() {
948
+ clearInterval(timer);
949
+ offTask();
950
+ offNotice?.();
951
+ connections.delete(conn);
952
+ }
953
+ };
954
+ connections.add(conn);
955
+ res.on?.("close", () => {
956
+ conn.cleanup();
957
+ });
958
+ void Promise.resolve(options.source.snapshot(viewer)).then((baseline) => {
959
+ res.writeHead(200, {
960
+ "content-type": "text/event-stream; charset=utf-8",
961
+ "cache-control": "no-cache, no-transform",
962
+ connection: "keep-alive",
963
+ "x-accel-buffering": "no"
964
+ });
965
+ for (const task of baseline)
966
+ res.write(`event: task-snapshot
967
+ data: ${JSON.stringify(task)}
968
+
969
+ `);
970
+ streaming = true;
971
+ for (const frame of buffered)
972
+ res.write(frame);
973
+ buffered.length = 0;
974
+ }).catch((error) => {
975
+ console.error("dsh-plugin-core: task stream baseline failed", error);
976
+ conn.cleanup();
977
+ res.end();
978
+ });
979
+ }).catch(() => {
980
+ json(res, 401, { error: "unauthorized" });
981
+ });
982
+ }
983
+ });
984
+ });
985
+ return () => {
986
+ for (const conn of [...connections])
987
+ conn.cleanup();
988
+ connections.clear();
989
+ };
990
+ }
991
+
992
+ // dist/host/task-submit.js
993
+ var JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
994
+ function readBody(req) {
995
+ return new Promise((resolve2, reject) => {
996
+ if (req.on === void 0 || req.once === void 0) {
997
+ reject(new Error("request body stream unavailable"));
998
+ return;
999
+ }
1000
+ const chunks = [];
1001
+ req.on("data", (chunk) => {
1002
+ chunks.push(chunk);
1003
+ });
1004
+ req.once("end", () => {
1005
+ resolve2(Buffer.concat(chunks).toString("utf8"));
1006
+ });
1007
+ req.once("error", reject);
1008
+ });
1009
+ }
1010
+ function serveTaskSubmit(ctx, options) {
1011
+ let off;
1012
+ ctx.inject(["webServer"], (services) => {
1013
+ const webServer = services.webServer;
1014
+ if (webServer === void 0)
1015
+ return;
1016
+ webServer.register({
1017
+ kind: "exact",
1018
+ path: options.path,
1019
+ handler: async (req, res) => {
1020
+ if (!await options.authorize(req)) {
1021
+ res.writeHead(403, JSON_HEADERS);
1022
+ res.end(JSON.stringify({ error: "forbidden" }));
1023
+ return;
1024
+ }
1025
+ try {
1026
+ const raw = await readBody(req);
1027
+ const payload = JSON.parse(raw);
1028
+ const id = await options.onSubmit(payload);
1029
+ res.writeHead(200, JSON_HEADERS);
1030
+ res.end(JSON.stringify({ ok: true, id }));
1031
+ } catch (error) {
1032
+ res.writeHead(400, JSON_HEADERS);
1033
+ res.end(JSON.stringify({ ok: false, error: String(error) }));
1034
+ }
1035
+ }
1036
+ });
1037
+ off = () => {
1038
+ };
1039
+ });
1040
+ return () => {
1041
+ off?.();
1042
+ };
1043
+ }
1044
+
895
1045
  // dist/host/fs-route.js
896
1046
  import { access, open, readdir, stat } from "node:fs/promises";
897
1047
  import { isAbsolute, join, normalize, sep } from "node:path";
@@ -1107,7 +1257,7 @@ async function buildModelRoutes(llm) {
1107
1257
  routes.sort((left, right) => left.displayName.localeCompare(right.displayName));
1108
1258
  return routes;
1109
1259
  }
1110
- var JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
1260
+ var JSON_HEADERS2 = { "content-type": "application/json; charset=utf-8" };
1111
1261
  function resolveLlm(ctx, options) {
1112
1262
  const fromHook = options.getLlm?.();
1113
1263
  if (fromHook !== void 0)
@@ -1128,22 +1278,22 @@ function serveModelCatalog(ctx, options) {
1128
1278
  path: options.path,
1129
1279
  handler: async (req, res) => {
1130
1280
  if (options.authorize !== void 0 && !await options.authorize(req)) {
1131
- res.writeHead(403, JSON_HEADERS);
1281
+ res.writeHead(403, JSON_HEADERS2);
1132
1282
  res.end(JSON.stringify({ error: "forbidden" }));
1133
1283
  return;
1134
1284
  }
1135
1285
  const llm = resolveLlm(ctx, options);
1136
1286
  if (llm === void 0) {
1137
- res.writeHead(503, JSON_HEADERS);
1287
+ res.writeHead(503, JSON_HEADERS2);
1138
1288
  res.end(JSON.stringify({ routes: [], error: "llm-unavailable" }));
1139
1289
  return;
1140
1290
  }
1141
1291
  try {
1142
1292
  const routes = await buildModelRoutes(llm);
1143
- res.writeHead(200, JSON_HEADERS);
1293
+ res.writeHead(200, JSON_HEADERS2);
1144
1294
  res.end(JSON.stringify({ routes }));
1145
1295
  } catch (error) {
1146
- res.writeHead(500, JSON_HEADERS);
1296
+ res.writeHead(500, JSON_HEADERS2);
1147
1297
  res.end(JSON.stringify({ routes: [], error: String(error) }));
1148
1298
  }
1149
1299
  }
@@ -1154,6 +1304,104 @@ function serveModelCatalog(ctx, options) {
1154
1304
  // packages/demo/src/paths.ts
1155
1305
  var MODELS_PATH = "/api/dsh-plugin-core-demo/models";
1156
1306
  var FS_PATH = "/api/dsh-plugin-core-demo/fs";
1307
+ var TASK_PATH = "/api/dsh-plugin-core-demo/tasks";
1308
+
1309
+ // packages/demo/src/host-tasks.ts
1310
+ var VIEWER = "demo-viewer";
1311
+ var tasks = /* @__PURE__ */ new Map();
1312
+ var listeners = /* @__PURE__ */ new Set();
1313
+ var notices = [];
1314
+ var noticeListeners = /* @__PURE__ */ new Set();
1315
+ var NOTICE_LIMIT = 200;
1316
+ function emit(task) {
1317
+ tasks.set(task.id, task);
1318
+ for (const listener of listeners) listener(task);
1319
+ }
1320
+ function emitNotice(task) {
1321
+ const notice = { id: `${task.id}@${String(task.settledAt ?? Date.now())}`, task };
1322
+ notices.push(notice);
1323
+ if (notices.length > NOTICE_LIMIT) notices.splice(0, notices.length - NOTICE_LIMIT);
1324
+ for (const listener of noticeListeners) listener(notice);
1325
+ }
1326
+ function execute(id, seconds, steps, fail2, label, base) {
1327
+ const total = steps > 0 ? steps : 10;
1328
+ const tick = seconds * 1e3 / total;
1329
+ let i = 0;
1330
+ const step = () => {
1331
+ if (tasks.get(id) === void 0) return;
1332
+ i += 1;
1333
+ if (steps > 0) {
1334
+ emit({ ...base, progress: {
1335
+ message: `${label} \xB7 \u6267\u884C\u5230 ${i}/${total}\uFF08${Math.round(i * 100 / total)}%\uFF09`,
1336
+ current: i,
1337
+ total,
1338
+ updatedAt: Date.now()
1339
+ } });
1340
+ }
1341
+ if (i < total) {
1342
+ setTimeout(step, tick);
1343
+ return;
1344
+ }
1345
+ const terminal = {
1346
+ ...base,
1347
+ state: fail2 ? "failed" : "done",
1348
+ reason: fail2 ? "\u6F14\u793A\u5931\u8D25" : void 0,
1349
+ settledAt: Date.now()
1350
+ };
1351
+ emit(terminal);
1352
+ emitNotice(terminal);
1353
+ };
1354
+ setTimeout(step, tick);
1355
+ }
1356
+ var source = {
1357
+ snapshot: () => [...tasks.values()],
1358
+ subscribe: (listener) => {
1359
+ listeners.add(listener);
1360
+ return () => {
1361
+ listeners.delete(listener);
1362
+ };
1363
+ },
1364
+ subscribeNotices: (listener) => {
1365
+ for (const notice of notices) listener(notice);
1366
+ noticeListeners.add(listener);
1367
+ return () => {
1368
+ noticeListeners.delete(listener);
1369
+ };
1370
+ }
1371
+ };
1372
+ function serveDemoTasks(ctx) {
1373
+ serveTaskSubmit(ctx, {
1374
+ path: `${TASK_PATH}/submit`,
1375
+ authorize: () => true,
1376
+ onSubmit: (payload) => {
1377
+ const id = `task:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 7)}`;
1378
+ const args = typeof payload.args === "object" && payload.args !== null ? payload.args : {};
1379
+ const seconds = Number(args.seconds) || 10;
1380
+ const steps = Number(args.steps) || 0;
1381
+ const fail2 = args.fail === true;
1382
+ const base = {
1383
+ id,
1384
+ project: String(payload.project ?? "dsh-plugin-core-demo"),
1385
+ group: String(payload.group ?? "demo-jobs"),
1386
+ title: String(payload.title ?? "\u540E\u53F0\u4EFB\u52A1"),
1387
+ state: "running",
1388
+ startedAt: Date.now(),
1389
+ ...typeof payload.toast === "object" && payload.toast !== null ? { toast: payload.toast } : {},
1390
+ ...typeof payload.notify === "object" && payload.notify !== null ? { notify: payload.notify } : {},
1391
+ ...typeof payload.rowButtons === "object" && payload.rowButtons !== null ? { rowButtons: payload.rowButtons } : {}
1392
+ };
1393
+ emit(base);
1394
+ execute(id, seconds, steps, fail2, String(args.label ?? ""), base);
1395
+ return id;
1396
+ }
1397
+ });
1398
+ serveTaskStream(ctx, {
1399
+ basePath: TASK_PATH,
1400
+ authorize: () => VIEWER,
1401
+ source,
1402
+ keepAliveMs: 25e3
1403
+ });
1404
+ }
1157
1405
 
1158
1406
  // packages/demo/src/index.ts
1159
1407
  var name = "dsh-plugin-core-demo";
@@ -1173,6 +1421,7 @@ var Config = z === void 0 ? void 0 : z.object({
1173
1421
  function apply(ctx) {
1174
1422
  serveModelCatalog(ctx, { path: MODELS_PATH });
1175
1423
  serveFsRoute(ctx, { path: FS_PATH });
1424
+ serveDemoTasks(ctx);
1176
1425
  }
1177
1426
  export {
1178
1427
  Config,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-core-demo",
3
- "version": "0.42.5",
3
+ "version": "0.43.0",
4
4
  "description": "The shared UI foundation for DSH plugins, with a live component preview: design tokens, common controls, workspace browsing and notifications maintained in one place — install it to preview every component in a real host.",
5
5
  "icon": "./assets/icon-components.svg",
6
6
  "keywords": [