@dsh-workbench/shared 0.2.9 → 0.2.11

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 (89) hide show
  1. package/dist/api/dsh-client.d.ts +4 -1
  2. package/dist/components/Activity.css +1 -0
  3. package/dist/components/Card.css +4 -4
  4. package/dist/components/CardAnchor.d.ts +7 -0
  5. package/dist/components/CardAnchor.js +8 -0
  6. package/dist/components/CardAnchor.module.css +3 -0
  7. package/dist/components/CardHead.css +1 -5
  8. package/dist/components/ChoiceGroup.css +11 -2
  9. package/dist/components/Field.css +4 -0
  10. package/dist/components/MockStrip.css +6 -0
  11. package/dist/components/Note.css +4 -4
  12. package/dist/components/SelectField.css +156 -0
  13. package/dist/components/SelectField.d.ts +57 -0
  14. package/dist/components/SelectField.js +236 -0
  15. package/dist/components/SettingsSection.css +2 -2
  16. package/dist/components/StateDot.d.ts +5 -0
  17. package/dist/components/StateDot.js +10 -0
  18. package/dist/components/TextField.css +5 -0
  19. package/dist/components/icons.d.ts +1 -0
  20. package/dist/components/icons.js +13 -0
  21. package/dist/host/__tests__/fakes.d.ts +41 -0
  22. package/dist/host/__tests__/fakes.js +76 -0
  23. package/dist/host/__tests__/preflight-fixtures.d.ts +19 -0
  24. package/dist/host/__tests__/preflight-fixtures.js +47 -0
  25. package/dist/host/context-inject.d.ts +24 -0
  26. package/dist/host/context-inject.js +74 -0
  27. package/dist/host/events.d.ts +9 -0
  28. package/dist/host/events.js +70 -0
  29. package/dist/host/mount-units.d.ts +52 -0
  30. package/dist/host/mount-units.js +186 -0
  31. package/dist/host/preflight.d.ts +58 -0
  32. package/dist/host/preflight.js +233 -0
  33. package/dist/host/probe-cache.d.ts +6 -0
  34. package/dist/host/probe-cache.js +19 -0
  35. package/dist/host/probe-libs.d.ts +45 -0
  36. package/dist/host/probe-libs.js +61 -0
  37. package/dist/host/probe-units.d.ts +17 -0
  38. package/dist/host/probe-units.js +102 -0
  39. package/dist/host/probe-verdict.d.ts +7 -0
  40. package/dist/host/probe-verdict.js +143 -0
  41. package/dist/host/tool-approval.d.ts +3 -1
  42. package/dist/host/tool-approval.js +3 -3
  43. package/dist/host/tool-kit.js +2 -2
  44. package/dist/host/tool-scope.d.ts +32 -0
  45. package/dist/host/tool-scope.js +84 -0
  46. package/dist/host/unit-readiness.d.ts +7 -0
  47. package/dist/host/unit-readiness.js +5 -0
  48. package/dist/host/unit-registry.d.ts +9 -0
  49. package/dist/host/unit-registry.js +33 -0
  50. package/dist/host/version-range.d.ts +2 -0
  51. package/dist/host/version-range.js +73 -0
  52. package/dist/host.d.ts +1 -0
  53. package/dist/host.js +1 -0
  54. package/dist/i18n/en.js +1 -1
  55. package/dist/i18n/index.d.ts +1 -1
  56. package/dist/i18n/zh.d.ts +1 -1
  57. package/dist/i18n/zh.js +1 -1
  58. package/dist/index.d.ts +2 -0
  59. package/dist/index.js +2 -0
  60. package/dist/lib/react.d.ts +2 -0
  61. package/dist/lib/react.js +2 -0
  62. package/package.json +1 -1
  63. package/src/api/dsh-client.ts +5 -1
  64. package/src/components/Activity.css +1 -0
  65. package/src/components/Card.css +4 -4
  66. package/src/components/Card.test.tsx +46 -0
  67. package/src/components/CardAnchor.module.css +3 -0
  68. package/src/components/CardAnchor.test.tsx +36 -0
  69. package/src/components/CardAnchor.tsx +20 -0
  70. package/src/components/CardHead.css +1 -5
  71. package/src/components/ChoiceGroup.css +11 -2
  72. package/src/components/Field.css +4 -0
  73. package/src/components/MockStrip.css +6 -0
  74. package/src/components/Note.css +4 -4
  75. package/src/components/SelectField.css +156 -0
  76. package/src/components/SelectField.test.tsx +238 -0
  77. package/src/components/SelectField.tsx +486 -0
  78. package/src/components/SettingsSection.css +2 -2
  79. package/src/components/TextField.css +5 -0
  80. package/src/components/icons.tsx +19 -0
  81. package/src/host/tool-approval.ts +4 -3
  82. package/src/host/tool-kit.ts +2 -2
  83. package/src/host.ts +1 -0
  84. package/src/i18n/en.ts +1 -1
  85. package/src/i18n/zh.ts +1 -1
  86. package/src/index.ts +2 -0
  87. package/src/lib/react.ts +3 -0
  88. package/dist/lib/lint-probe.d.ts +0 -1
  89. package/dist/lib/lint-probe.js +0 -6
@@ -32,6 +32,19 @@ export function IconModules({ size = 16 }) {
32
32
  h("rect", { x: "2.5", y: "8.9", width: "4.6", height: "4.6", rx: "1.2", stroke: "currentColor", strokeWidth: "1.2" }),
33
33
  h("rect", { x: "8.9", y: "8.9", width: "4.6", height: "4.6", rx: "1.2", stroke: "currentColor", strokeWidth: "1.2" })));
34
34
  }
35
+ export function IconModuleMark({ size = 16 }) {
36
+ return (h(Shell, { size: size, viewBox: "0 0 24 24" },
37
+ h("defs", null,
38
+ h("linearGradient", { id: "workbench-module-mark", x1: "0%", y1: "0%", x2: "100%", y2: "100%" },
39
+ h("stop", { offset: "0%", stopColor: "#3b82f6" }),
40
+ h("stop", { offset: "55%", stopColor: "#8b5cf6" }),
41
+ h("stop", { offset: "100%", stopColor: "#14b8a6" }))),
42
+ h("rect", { width: 24, height: 24, rx: 7, fill: "url(#workbench-module-mark)" }),
43
+ h("rect", { x: "4.6", y: "4.6", width: "6.2", height: "6.2", rx: "1.9", fill: "#ffffff" }),
44
+ h("rect", { x: "13.2", y: "4.6", width: "6.2", height: "6.2", rx: "1.9", fill: "#ffffff", fillOpacity: 0.78 }),
45
+ h("rect", { x: "4.6", y: "13.2", width: "6.2", height: "6.2", rx: "1.9", fill: "#ffffff", fillOpacity: 0.78 }),
46
+ h("rect", { x: "13.2", y: "13.2", width: "6.2", height: "6.2", rx: "1.9", fill: "#ffffff" })));
47
+ }
35
48
  export function IconPanelScreen({ size = 16 }) {
36
49
  return (h("svg", { width: size, height: size, viewBox: "0 0 1024 1024", fill: "currentColor", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true", style: { display: 'block', overflow: 'hidden' } },
37
50
  h("path", { d: "M939 112c17.673 0 32 14.327 32 32v554.667c0 17.673-14.327 32-32 32l-394.5-0.001v96c0 3.74-0.642 7.331-1.82 10.668H768.4c17.673 0 32 14.326 32 32 0 17.496-14.042 31.712-31.47 31.995l-0.53 0.004H256.6c-17.673 0-32-14.327-32-32 0-17.496 14.042-31.713 31.47-31.995l0.53-0.005h225.721a31.923 31.923 0 0 1-1.817-10.137l-0.004-0.53v-96H86c-17.496 0-31.713-14.041-31.996-31.47l-0.004-0.53V144c0-17.673 14.327-32 32-32z m-32 64H118v490.666h789V176zM341.9 432c17.496 0 31.713 14.042 31.996 31.47l0.004 0.53v85.333c0 17.673-14.327 32-32 32-17.496 0-31.713-14.041-31.996-31.47l-0.004-0.53V464c0-17.673 14.327-32 32-32z m170.6-85.333c17.496 0 31.713 14.041 31.996 31.47l0.004 0.53v170.666c0 17.673-14.327 32-32 32-17.496 0-31.713-14.041-31.996-31.47l-0.004-0.53V378.667c0-17.673 14.327-32 32-32z m170.6-85.334c17.496 0 31.713 14.042 31.996 31.471l0.004 0.53v256c0 17.672-14.327 32-32 32-17.496 0-31.713-14.042-31.996-31.471l-0.004-0.53v-256c0-17.673 14.327-32 32-32z" })));
@@ -0,0 +1,41 @@
1
+ import type { DshShell } from '../../api/dsh.js';
2
+ import type { Opencli } from '../../host/opencli.js';
3
+ export interface ShellCall {
4
+ command: string;
5
+ workdir?: string;
6
+ timeoutMs?: number;
7
+ onExpiry?: string;
8
+ stdoutMaxBytes?: number;
9
+ }
10
+ export interface ShellReply {
11
+ stdout?: string;
12
+ stderr?: string;
13
+ exitCode?: number | null;
14
+ timedOut?: boolean;
15
+ aborted?: boolean;
16
+ failWith?: Error;
17
+ }
18
+ export declare function createFakeShell(replies?: ShellReply[] | ((call: ShellCall, index: number) => ShellReply)): {
19
+ shell: DshShell;
20
+ calls: ShellCall[];
21
+ peak: () => number;
22
+ commands: () => string[];
23
+ };
24
+ export interface OpencliCall {
25
+ args: readonly string[];
26
+ key?: string;
27
+ workdir?: string;
28
+ refresh?: boolean;
29
+ }
30
+ export declare function createFakeOpencli(replies?: Array<unknown | Error> | ((call: OpencliCall, index: number) => unknown | Error)): {
31
+ opencli: Opencli;
32
+ calls: OpencliCall[];
33
+ keys: () => (string | undefined)[];
34
+ };
35
+ export declare function createFakeLogger(): {
36
+ logger: {
37
+ info: () => void;
38
+ warn: (message: string) => void;
39
+ };
40
+ warnings: string[];
41
+ };
@@ -0,0 +1,76 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ const tick = () => delay(0);
3
+ export function createFakeShell(replies = []) {
4
+ const calls = [];
5
+ let running = 0;
6
+ let peak = 0;
7
+ const replyAt = (index) => typeof replies === 'function' ? replies(calls[index], index) : (replies[index] ?? {});
8
+ const shell = {
9
+ resolve(request) {
10
+ calls.push(request);
11
+ return request;
12
+ },
13
+ async execute() {
14
+ const index = calls.length - 1;
15
+ const reply = replyAt(index);
16
+ if (reply.failWith !== undefined)
17
+ throw reply.failWith;
18
+ running += 1;
19
+ peak = Math.max(peak, running);
20
+ return {
21
+ async result() {
22
+ await tick();
23
+ running -= 1;
24
+ return {
25
+ exitCode: reply.exitCode ?? 0,
26
+ timedOut: reply.timedOut ?? false,
27
+ aborted: reply.aborted ?? false,
28
+ stdout: { text: reply.stdout ?? '', truncated: false },
29
+ stderr: { text: reply.stderr ?? '', truncated: false },
30
+ };
31
+ },
32
+ };
33
+ },
34
+ };
35
+ return {
36
+ shell,
37
+ calls,
38
+ peak: () => peak,
39
+ commands: () => calls.map((call) => call.command),
40
+ };
41
+ }
42
+ export function createFakeOpencli(replies = []) {
43
+ const calls = [];
44
+ const opencli = {
45
+ async json(args, options = {}) {
46
+ const call = {
47
+ args,
48
+ ...(options.key === undefined ? {} : { key: options.key }),
49
+ ...(options.workdir === undefined ? {} : { workdir: options.workdir }),
50
+ };
51
+ calls.push(call);
52
+ const index = calls.length - 1;
53
+ const reply = typeof replies === 'function' ? replies(call, index) : (replies[index] ?? []);
54
+ if (reply instanceof Error)
55
+ throw reply;
56
+ return { value: reply, at: Date.now() };
57
+ },
58
+ };
59
+ return {
60
+ opencli,
61
+ calls,
62
+ keys: () => calls.map((call) => call.key),
63
+ };
64
+ }
65
+ export function createFakeLogger() {
66
+ const warnings = [];
67
+ return {
68
+ logger: {
69
+ info: () => { },
70
+ warn: (message) => {
71
+ warnings.push(message);
72
+ },
73
+ },
74
+ warnings,
75
+ };
76
+ }
@@ -0,0 +1,19 @@
1
+ import { createFakeShell } from './fakes';
2
+ export declare const GOOD_BRIDGE_REPORT: string;
3
+ export declare const ALL_OK: {
4
+ stdout: string;
5
+ }[];
6
+ export declare const STALE_DAEMON_BRIDGE: string;
7
+ export declare const BROKEN_BRIDGE: string;
8
+ export declare function build(replies: Parameters<typeof createFakeShell>[0], install?: () => Promise<{
9
+ ok: boolean;
10
+ detail: string;
11
+ }>, warmReads?: () => readonly (readonly string[])[]): {
12
+ fake: {
13
+ shell: import("../..").DshShell;
14
+ calls: import("./fakes").ShellCall[];
15
+ peak: () => number;
16
+ commands: () => string[];
17
+ };
18
+ preflight: import("../preflight").Preflight;
19
+ };
@@ -0,0 +1,47 @@
1
+ import { createPreflight } from '../preflight';
2
+ import { createFakeShell } from './fakes';
3
+ export const GOOD_BRIDGE_REPORT = [
4
+ 'opencli v1.8.7 doctor (node v24.15.0)',
5
+ '',
6
+ '[OK] Daemon: running on port 19825 (v1.8.7)',
7
+ '[OK] Extension: connected (v1.0.24)',
8
+ '[OK] Connectivity: connected in 0.0s',
9
+ '',
10
+ 'Everything looks good!',
11
+ ].join('\n');
12
+ export const ALL_OK = [{ stdout: '1.8.8\n' }, { stdout: GOOD_BRIDGE_REPORT }];
13
+ export const STALE_DAEMON_BRIDGE = [
14
+ 'opencli v1.8.7 doctor (node v24.15.0)',
15
+ '',
16
+ '[STALE] Daemon: running on port 19825 (v1.8.8 != CLI v1.8.7)',
17
+ '[OK] Extension: connected (v1.0.24)',
18
+ '[OK] Connectivity: connected in 0.0s',
19
+ '',
20
+ 'Issues:',
21
+ ' • Stale daemon detected: daemon v1.8.8 != CLI v1.8.7.',
22
+ ' Run: opencli daemon restart',
23
+ ].join('\n');
24
+ export const BROKEN_BRIDGE = [
25
+ 'opencli v1.8.7 doctor (node v24.15.0)',
26
+ '',
27
+ '[MISSING] Daemon: not running',
28
+ '[MISSING] Extension: not connected',
29
+ '[FAIL] Connectivity: failed (daemon not reachable)',
30
+ '',
31
+ 'Issues:',
32
+ " • Daemon is not running. It should start automatically when you run an opencli browser command.",
33
+ ' • Daemon is running but the Chrome/Chromium extension is not connected.',
34
+ 'If the extension is not installed:',
35
+ ' 1. Download from https://github.com/jackwener/opencli/releases',
36
+ ' 2. Open chrome://extensions/ → Enable Developer Mode',
37
+ ' 3. Click "Load unpacked" → select the extension folder',
38
+ ].join('\n');
39
+ export function build(replies, install, warmReads) {
40
+ const fake = createFakeShell(replies);
41
+ const preflight = createPreflight({
42
+ shell: fake.shell,
43
+ ...(install === undefined ? {} : { install }),
44
+ ...(warmReads === undefined ? {} : { warmReads }),
45
+ });
46
+ return { fake, preflight };
47
+ }
@@ -0,0 +1,24 @@
1
+ import { type ContextRef } from '@dsh-workbench/shared';
2
+ import type { ContextRenderer } from './unit-face';
3
+ export declare const CONTEXT_SOURCE_KIND = "workbench";
4
+ export interface ScannableMessage {
5
+ readonly source?: {
6
+ readonly kind?: string;
7
+ };
8
+ readonly content?: readonly {
9
+ readonly type?: string;
10
+ readonly text?: string;
11
+ }[];
12
+ }
13
+ export type { ContextRenderer };
14
+ export declare function collectContextRefs(messages: readonly ScannableMessage[]): ContextRef[];
15
+ export declare function buildContextMessage(text: string, summary: string): unknown;
16
+ export interface ContextInjector {
17
+ inject(messages: readonly ScannableMessage[], agent: unknown): Promise<unknown | undefined>;
18
+ }
19
+ export declare function createContextInjector(options: {
20
+ renderers: ReadonlyMap<string, ContextRenderer>;
21
+ logger?: {
22
+ warn?(message: string): void;
23
+ } | undefined;
24
+ }): ContextInjector;
@@ -0,0 +1,74 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { encodeRef, parseMarkers } from '@dsh-workbench/shared';
3
+ export const CONTEXT_SOURCE_KIND = 'workbench';
4
+ export function collectContextRefs(messages) {
5
+ const seen = new Set();
6
+ const refs = [];
7
+ for (const message of messages) {
8
+ if (message.source?.kind !== 'user')
9
+ continue;
10
+ for (const block of message.content ?? []) {
11
+ if (block.type !== 'text' || typeof block.text !== 'string')
12
+ continue;
13
+ for (const ref of parseMarkers(block.text)) {
14
+ const key = encodeRef(ref);
15
+ if (seen.has(key))
16
+ continue;
17
+ seen.add(key);
18
+ refs.push(ref);
19
+ }
20
+ }
21
+ }
22
+ return refs;
23
+ }
24
+ export function buildContextMessage(text, summary) {
25
+ return {
26
+ role: 'user',
27
+ id: randomUUID(),
28
+ content: [{ type: 'text', text }],
29
+ source: { kind: CONTEXT_SOURCE_KIND, form: 'notice', summary },
30
+ };
31
+ }
32
+ export function createContextInjector(options) {
33
+ const done = new WeakMap();
34
+ return {
35
+ async inject(messages, agent) {
36
+ const refs = collectContextRefs(messages);
37
+ if (refs.length === 0)
38
+ return undefined;
39
+ const key = typeof agent === 'object' && agent !== null ? agent : undefined;
40
+ const seen = key === undefined ? undefined : (done.get(key) ?? new Set());
41
+ if (key !== undefined && seen !== undefined)
42
+ done.set(key, seen);
43
+ const fresh = [];
44
+ for (const ref of refs) {
45
+ const encoded = encodeRef(ref);
46
+ if (seen?.has(encoded) === true)
47
+ continue;
48
+ seen?.add(encoded);
49
+ fresh.push(ref);
50
+ }
51
+ if (fresh.length === 0)
52
+ return undefined;
53
+ const texts = [];
54
+ for (const ref of fresh) {
55
+ const render = options.renderers.get(ref.kind);
56
+ if (render === undefined)
57
+ continue;
58
+ let text;
59
+ try {
60
+ text = await render(ref);
61
+ }
62
+ catch (error) {
63
+ options.logger?.warn?.(`[dsh-workbench] 渲染对话引用失败:${String(error)}`);
64
+ text = `工作台面板引用了一条内容(${encodeRef(ref)}),但当前渲染不出来(项目未选中或数据源不可用)。`;
65
+ }
66
+ if (text !== '')
67
+ texts.push(text);
68
+ }
69
+ if (texts.length === 0)
70
+ return undefined;
71
+ return buildContextMessage(texts.join('\n\n'), `工作台引用:${fresh.length} 条`);
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,9 @@
1
+ import type { DshHostContext, DshRequest, DshResponse } from '@dsh-workbench/shared';
2
+ import type { FactLog } from './facts';
3
+ export interface FactStream {
4
+ handler(req: DshRequest, res: DshResponse): void;
5
+ closeAll(): void;
6
+ size(): number;
7
+ }
8
+ export declare function createFactStream(log: FactLog): FactStream;
9
+ export declare function registerFactStream(ctx: DshHostContext, log: FactLog): () => void;
@@ -0,0 +1,70 @@
1
+ import { EVENTS_PATH } from '@dsh-workbench/shared';
2
+ const HEARTBEAT_MS = 25_000;
3
+ function frame(payload) {
4
+ return `data: ${JSON.stringify(payload)}\n\n`;
5
+ }
6
+ export function createFactStream(log) {
7
+ const connections = new Set();
8
+ const cleanups = new Map();
9
+ const drop = (res) => {
10
+ cleanups.get(res)?.();
11
+ cleanups.delete(res);
12
+ connections.delete(res);
13
+ };
14
+ return {
15
+ size: () => connections.size,
16
+ closeAll() {
17
+ for (const res of [...connections]) {
18
+ drop(res);
19
+ res.end?.();
20
+ }
21
+ },
22
+ handler(req, res) {
23
+ if (req.method !== undefined && req.method !== 'GET') {
24
+ res.statusCode = 405;
25
+ res.end();
26
+ return;
27
+ }
28
+ const url = req.url ?? '/';
29
+ const cut = url.indexOf('?');
30
+ const since = Number(new URLSearchParams(cut === -1 ? '' : url.slice(cut + 1)).get('since') ?? 0) || 0;
31
+ const opening = log.since(since);
32
+ if (typeof res.write !== 'function') {
33
+ res.statusCode = 200;
34
+ res.setHeader('content-type', 'application/json; charset=utf-8');
35
+ res.end(JSON.stringify({ ok: true, ...opening }));
36
+ return;
37
+ }
38
+ const headers = {
39
+ 'content-type': 'text/event-stream; charset=utf-8',
40
+ 'cache-control': 'no-store, no-transform',
41
+ connection: 'keep-alive',
42
+ };
43
+ if (typeof res.writeHead === 'function')
44
+ res.writeHead(200, headers);
45
+ else {
46
+ res.statusCode = 200;
47
+ for (const [name, value] of Object.entries(headers))
48
+ res.setHeader(name, value);
49
+ }
50
+ res.write(': connected\n\n');
51
+ res.write(frame({ type: 'sync', ...opening }));
52
+ connections.add(res);
53
+ const timer = setInterval(() => res.write?.(': ping\n\n'), HEARTBEAT_MS);
54
+ const unsubscribe = log.subscribe((change) => res.write?.(frame({ type: 'bump', ...change })));
55
+ cleanups.set(res, () => {
56
+ clearInterval(timer);
57
+ unsubscribe();
58
+ });
59
+ res.on?.('close', () => drop(res));
60
+ },
61
+ };
62
+ }
63
+ export function registerFactStream(ctx, log) {
64
+ const stream = createFactStream(log);
65
+ const unregister = ctx.webServer.register({ kind: 'exact', path: EVENTS_PATH, handler: stream.handler });
66
+ return () => {
67
+ stream.closeAll();
68
+ unregister();
69
+ };
70
+ }
@@ -0,0 +1,52 @@
1
+ import type { DshHostContext } from '@dsh-workbench/shared';
2
+ import type { UnitManifest } from '@dsh-workbench/shared';
3
+ import { type RouteTable } from './http';
4
+ import type { ContextRenderer, UnitHostFace, UnitMountDeps, UnitMountResult, UnitCall } from './unit-face';
5
+ import { type UnitReadiness } from './unit-readiness';
6
+ export interface MountedUnit {
7
+ readonly face: UnitHostFace;
8
+ readonly result: UnitMountResult;
9
+ readonly readiness: UnitReadiness;
10
+ }
11
+ export interface UnitsPlan {
12
+ readonly mounted: readonly MountedUnit[];
13
+ readonly routes: RouteTable;
14
+ readonly gate: UnitMountResult['gate'];
15
+ readonly prefs: ReadonlyArray<{
16
+ readonly resource: string;
17
+ readonly unit: string;
18
+ handle(payload: unknown): unknown;
19
+ }>;
20
+ readonly actions: ReadonlyArray<{
21
+ readonly resource: string;
22
+ readonly unit: string;
23
+ handle(payload: unknown): unknown;
24
+ }>;
25
+ readonly provision: UnitMountResult['provision'];
26
+ readonly contextRenderers: ReadonlyMap<string, ContextRenderer>;
27
+ readonly owners: ReadonlyMap<string, string>;
28
+ readonly routesOfUnit: ReadonlyMap<string, readonly string[]>;
29
+ readonly factsOf: ReadonlyMap<string, (call: UnitCall) => readonly string[] | undefined>;
30
+ readonly skipped: ReadonlyArray<{
31
+ readonly id: string;
32
+ readonly missing: readonly string[];
33
+ }>;
34
+ readonly warmReads: () => readonly (readonly string[])[];
35
+ readonly disposeLongTasks: () => void;
36
+ }
37
+ export declare function mountUnits(faces: readonly UnitHostFace[], deps: {
38
+ ctx: DshHostContext;
39
+ logger?: {
40
+ info?(m: string): void;
41
+ warn?(m: string): void;
42
+ } | undefined;
43
+ manifests: () => readonly UnitManifest[];
44
+ opencliCommand?: string;
45
+ probe?: UnitMountDeps['probe'];
46
+ store?: UnitMountDeps['store'];
47
+ values?: UnitMountDeps['values'];
48
+ longTasks?: {
49
+ readonly scope: string;
50
+ readonly bump: (facts: readonly string[]) => void;
51
+ } | undefined;
52
+ }): UnitsPlan;
@@ -0,0 +1,186 @@
1
+ import { runsRouteOf } from '@dsh-workbench/shared';
2
+ import { param } from './http';
3
+ import { createLongTaskHost } from './long-task';
4
+ import { unitReadiness } from './unit-readiness';
5
+ import { createWorkspaceStore } from './workspace-store';
6
+ function withRunsRoute(result, unit) {
7
+ const runs = result.longTasks;
8
+ if (runs === undefined)
9
+ return result;
10
+ return {
11
+ ...result,
12
+ routes: {
13
+ ...result.routes,
14
+ [runsRouteOf(unit)]: (search) => {
15
+ const path = (param(search, 'path') ?? '').trim();
16
+ return { ok: true, runs: path === '' ? [] : runs.current(path) };
17
+ },
18
+ },
19
+ };
20
+ }
21
+ function collectRoutes(mounted) {
22
+ const routes = {};
23
+ const owner = new Map();
24
+ const routesOfUnit = new Map();
25
+ for (const item of mounted) {
26
+ const unit = item.face.manifest.id;
27
+ for (const [key, handler] of Object.entries(item.result.routes)) {
28
+ if (key !== unit && !key.startsWith(`${unit}/`)) {
29
+ throw new Error(`路由名要住在自己那一格的命名空间里(${unit} 或 ${unit}/…):${key} 不属于 ${unit} —— ` +
30
+ `装 / 升 / 卸时点名不到它,那个模块的数据会停在旧值`);
31
+ }
32
+ const previous = owner.get(key);
33
+ if (previous !== undefined) {
34
+ throw new Error(`路由名冲突:${key} 由套件 ${previous} 与 ${unit} 同时声明`);
35
+ }
36
+ owner.set(key, unit);
37
+ routes[key] = handler;
38
+ const own = routesOfUnit.get(unit);
39
+ if (own === undefined)
40
+ routesOfUnit.set(unit, [key]);
41
+ else
42
+ own.push(key);
43
+ }
44
+ }
45
+ return { routes, owners: owner, routesOfUnit };
46
+ }
47
+ function pickGate(mounted) {
48
+ const providers = mounted.filter((item) => item.result.gate !== undefined);
49
+ if (providers.length > 1) {
50
+ throw new Error(`启停闸门只能有一个提供者,现在是:${providers.map((item) => item.face.manifest.id).join('、')}`);
51
+ }
52
+ return providers[0]?.result.gate;
53
+ }
54
+ function pickProvision(mounted) {
55
+ const providers = mounted.filter((item) => item.result.provision !== undefined);
56
+ if (providers.length > 1) {
57
+ throw new Error(`机器供给只能有一个提供者,现在是:${providers.map((item) => item.face.manifest.id).join('、')}`);
58
+ }
59
+ return providers[0]?.result.provision;
60
+ }
61
+ function collectPrefs(mounted) {
62
+ const owner = new Map();
63
+ const prefs = [];
64
+ for (const item of mounted) {
65
+ const entry = item.result.prefs;
66
+ if (entry === undefined)
67
+ continue;
68
+ const previous = owner.get(entry.resource);
69
+ if (previous !== undefined) {
70
+ throw new Error(`偏好资源名冲突:${entry.resource} 由套件 ${previous} 与 ${item.face.manifest.id} 同时声明`);
71
+ }
72
+ owner.set(entry.resource, item.face.manifest.id);
73
+ prefs.push({ ...entry, unit: item.face.manifest.id });
74
+ }
75
+ return prefs;
76
+ }
77
+ function collectActions(mounted) {
78
+ const owner = new Map();
79
+ const actions = [];
80
+ for (const item of mounted) {
81
+ for (const entry of item.result.actions ?? []) {
82
+ const previous = owner.get(entry.resource);
83
+ if (previous !== undefined) {
84
+ throw new Error(`动作资源名冲突:${entry.resource} 由套件 ${previous} 与 ${item.face.manifest.id} 同时声明`);
85
+ }
86
+ owner.set(entry.resource, item.face.manifest.id);
87
+ actions.push({ ...entry, unit: item.face.manifest.id });
88
+ }
89
+ }
90
+ return actions;
91
+ }
92
+ function collectWarmReads(mounted) {
93
+ const declarations = mounted
94
+ .map((item) => item.result.warmReads)
95
+ .filter((declare) => declare !== undefined);
96
+ return () => {
97
+ const seen = new Set();
98
+ const reads = [];
99
+ for (const read of declarations.flatMap((declare) => declare())) {
100
+ const key = read.join(' ');
101
+ if (seen.has(key))
102
+ continue;
103
+ seen.add(key);
104
+ reads.push(read);
105
+ }
106
+ return reads;
107
+ };
108
+ }
109
+ function collectContextRenderers(mounted) {
110
+ const table = new Map();
111
+ const owner = new Map();
112
+ for (const item of mounted) {
113
+ const context = item.result.context;
114
+ if (context === undefined)
115
+ continue;
116
+ for (const kind of context.kinds) {
117
+ const previous = owner.get(kind);
118
+ if (previous !== undefined) {
119
+ throw new Error(`对话引用的 kind 冲突:${kind} 由套件 ${previous} 与 ${item.face.manifest.id} 同时认领`);
120
+ }
121
+ owner.set(kind, item.face.manifest.id);
122
+ table.set(kind, (ref) => context.render(ref));
123
+ }
124
+ }
125
+ return table;
126
+ }
127
+ export function mountUnits(faces, deps) {
128
+ const store = deps.store ?? createWorkspaceStore({ root: null });
129
+ const mounted = [];
130
+ const skipped = [];
131
+ const longTaskDisposers = [];
132
+ for (const face of faces) {
133
+ const readiness = unitReadiness(face.manifest, (dep) => deps.ctx.get(dep));
134
+ if (!readiness.canMount) {
135
+ skipped.push({ id: face.manifest.id, missing: readiness.missingHard });
136
+ continue;
137
+ }
138
+ const unit = face.manifest.id;
139
+ const longTasks = deps.longTasks === undefined
140
+ ? undefined
141
+ : createLongTaskHost({ scope: deps.longTasks.scope, unit, bump: deps.longTasks.bump });
142
+ if (longTasks !== undefined)
143
+ longTaskDisposers.push(longTasks.dispose);
144
+ const result = face.mount({
145
+ ctx: deps.ctx,
146
+ logger: deps.logger,
147
+ manifests: deps.manifests,
148
+ ...(deps.opencliCommand === undefined ? {} : { opencliCommand: deps.opencliCommand }),
149
+ ...(deps.probe === undefined ? {} : { probe: deps.probe }),
150
+ ...(deps.values === undefined ? {} : { values: deps.values }),
151
+ ...(longTasks === undefined ? {} : { longTasks: longTasks.host }),
152
+ store,
153
+ });
154
+ mounted.push({ face, readiness, result: withRunsRoute(result, unit) });
155
+ }
156
+ const collected = collectRoutes(mounted);
157
+ const prefs = collectPrefs(mounted);
158
+ const actions = collectActions(mounted);
159
+ const owners = new Map(collected.owners);
160
+ for (const entry of [...prefs, ...actions])
161
+ owners.set(entry.resource, entry.unit);
162
+ const factsOf = new Map();
163
+ for (const item of mounted) {
164
+ const declare = item.result.factsOf;
165
+ if (declare !== undefined)
166
+ factsOf.set(item.face.manifest.id, declare);
167
+ }
168
+ return {
169
+ mounted,
170
+ routes: collected.routes,
171
+ owners,
172
+ routesOfUnit: collected.routesOfUnit,
173
+ factsOf,
174
+ gate: pickGate(mounted),
175
+ prefs,
176
+ actions,
177
+ provision: pickProvision(mounted),
178
+ contextRenderers: collectContextRenderers(mounted),
179
+ skipped,
180
+ warmReads: collectWarmReads(mounted),
181
+ disposeLongTasks: () => {
182
+ for (const dispose of longTaskDisposers.splice(0))
183
+ dispose();
184
+ },
185
+ };
186
+ }