@zhin.js/console-contract 1.1.2 → 1.1.4

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/src/page.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export interface PageMetadata {
2
2
  readonly title?: string;
3
+ /** Explicit display titles; missing locales retain title. */
4
+ readonly titleI18n?: Readonly<Partial<Record<'zh-CN' | 'en', string>>>;
3
5
  readonly icon?: string;
4
6
  readonly order?: number;
5
7
  readonly hideInNav?: boolean;
@@ -9,6 +11,7 @@ export interface PageMetadata {
9
11
 
10
12
  export interface NormalizedPageMetadata {
11
13
  readonly title: string;
14
+ readonly titleI18n?: Readonly<Partial<Record<'zh-CN' | 'en', string>>>;
12
15
  readonly icon?: string;
13
16
  readonly order: number;
14
17
  readonly hideInNav: boolean;
@@ -20,6 +23,7 @@ export interface ClientModuleArtifact {
20
23
  readonly module: string;
21
24
  readonly hash: string;
22
25
  readonly metadata?: unknown;
26
+ readonly blueprint?: ConsolePageBlueprint | ConsoleAdapterPageBlueprint;
23
27
  }
24
28
 
25
29
  export function normalizeClientModuleArtifact(
@@ -30,7 +34,21 @@ export function normalizeClientModuleArtifact(
30
34
  const module = optionalString(input.module, `${label} module`);
31
35
  const hash = optionalString(input.hash, `${label} hash`);
32
36
  if (!module || !hash) throw new TypeError(`${label} must include module and hash`);
33
- return Object.freeze({ module, hash, metadata: input.metadata });
37
+ const blueprint = isConsoleBlueprint(input.blueprint) ? input.blueprint : undefined;
38
+ return Object.freeze({
39
+ module,
40
+ hash,
41
+ metadata: input.metadata,
42
+ ...(blueprint !== undefined ? { blueprint } : {}),
43
+ });
44
+ }
45
+
46
+ export function isConsoleBlueprint(
47
+ value: unknown,
48
+ ): value is ConsolePageBlueprint | ConsoleAdapterPageBlueprint {
49
+ if (!value || typeof value !== 'object') return false;
50
+ const kind = (value as { readonly kind?: unknown }).kind;
51
+ return kind === 'zhin.console.page-blueprint' || kind === 'zhin.console.adapter-page';
34
52
  }
35
53
 
36
54
  export interface PageManifest extends NormalizedPageMetadata {
@@ -41,6 +59,7 @@ export interface PageManifest extends NormalizedPageMetadata {
41
59
  readonly module: string;
42
60
  readonly hash: string;
43
61
  readonly route: string;
62
+ readonly blueprint?: ConsolePageBlueprint | ConsoleAdapterPageBlueprint;
44
63
  }
45
64
 
46
65
  export function definePage(metadata: PageMetadata = {}): Readonly<PageMetadata> {
@@ -55,11 +74,13 @@ export function normalizePageMetadata(
55
74
  const input = metadata === undefined ? {} : requireRecord(metadata, 'Page metadata');
56
75
  assertKnownMetadataKeys(input);
57
76
  const title = optionalString(input.title, 'Page title') ?? titleFromName(localName);
77
+ const titleI18n = pageTitleTranslations(input.titleI18n);
58
78
  const icon = optionalString(input.icon, 'Page icon');
59
79
  const order = optionalNumber(input.order, 'Page order') ?? 100;
60
80
  const hideInNav = optionalBoolean(input.hideInNav, 'Page hideInNav') ?? false;
61
81
  return Object.freeze({
62
82
  title,
83
+ ...(titleI18n === undefined ? {} : { titleI18n }),
63
84
  icon,
64
85
  order,
65
86
  hideInNav,
@@ -71,6 +92,7 @@ export function normalizePageMetadata(
71
92
  function assertKnownMetadataKeys(input: Record<string, unknown>): void {
72
93
  const known = new Set([
73
94
  'title',
95
+ 'titleI18n',
74
96
  'icon',
75
97
  'order',
76
98
  'hideInNav',
@@ -105,6 +127,7 @@ function normalizePageInput(metadata: PageMetadata): Readonly<PageMetadata> {
105
127
  const normalized = normalizePageMetadata('page', metadata);
106
128
  return Object.freeze({
107
129
  title: metadata.title === undefined ? undefined : normalized.title,
130
+ ...(normalized.titleI18n === undefined ? {} : { titleI18n: normalized.titleI18n }),
108
131
  icon: normalized.icon,
109
132
  order: metadata.order === undefined ? undefined : normalized.order,
110
133
  hideInNav: metadata.hideInNav === undefined ? undefined : normalized.hideInNav,
@@ -151,3 +174,1157 @@ function stringList(value: unknown, label: string): readonly string[] {
151
174
  });
152
175
  return Object.freeze([...new Set(result)].sort());
153
176
  }
177
+
178
+ function pageTitleTranslations(value: unknown): NormalizedPageMetadata['titleI18n'] {
179
+ if (value === undefined) return undefined;
180
+ const input = requireRecord(value, 'Page titleI18n');
181
+ const output: Partial<Record<'zh-CN' | 'en', string>> = {};
182
+ for (const [locale, title] of Object.entries(input)) {
183
+ if (locale !== 'zh-CN' && locale !== 'en') throw new TypeError(`Unsupported Page titleI18n locale: ${locale}`);
184
+ const text = optionalString(title, `Page titleI18n.${locale}`);
185
+ if (text === undefined) throw new TypeError(`Page titleI18n.${locale} must be a non-empty string`);
186
+ output[locale] = text;
187
+ }
188
+ return Object.freeze(output);
189
+ }
190
+
191
+ // ── Server-Driven Page Blueprint & Declarative Page Contracts ──────────────
192
+
193
+ export type DeclarativeI18nText =
194
+ | string
195
+ | { readonly zh: string; readonly en?: string; readonly 'zh-CN'?: string };
196
+
197
+ export type DeclarativeBadgeTone = 'neutral' | 'info' | 'success' | 'warning' | 'danger';
198
+ export type DeclarativeButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
199
+ export type DeclarativeUiLocale = 'zh-CN' | 'en';
200
+ /** Framework-agnostic renderable value (string, number, boolean, null, undefined, or JSX/ReactNode in browser). */
201
+ export type DeclarativeRenderable = unknown;
202
+
203
+ export interface DeclarativePageContext<TData = Record<string, unknown>> {
204
+ readonly pluginId: string;
205
+ readonly locale: DeclarativeUiLocale;
206
+ readonly t: (key: string, ...values: readonly (string | number)[]) => string;
207
+ readonly resource: {
208
+ readonly state: 'loading' | 'ready' | 'empty' | 'error' | 'stale';
209
+ readonly data: TData | undefined;
210
+ readonly error: Error | undefined;
211
+ readonly lastSuccessAt: number | undefined;
212
+ readonly refreshing: boolean;
213
+ readonly refresh: () => Promise<boolean>;
214
+ readonly mutate: (updater: TData | ((previous: TData | undefined) => TData | undefined)) => void;
215
+ };
216
+ readonly call: <TResult = unknown>(
217
+ method: string,
218
+ params?: Readonly<Record<string, unknown>>,
219
+ ) => Promise<TResult>;
220
+ readonly refresh: () => Promise<boolean>;
221
+ readonly notify: (tone: 'info' | 'success' | 'warning' | 'danger', message: string) => void;
222
+ }
223
+
224
+ export interface DeclarativeBadgeSpec<TData = Record<string, unknown>> {
225
+ readonly key?: string;
226
+ readonly label:
227
+ | DeclarativeI18nText
228
+ | ((data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable);
229
+ readonly tone?: DeclarativeBadgeTone | ((data: TData) => DeclarativeBadgeTone);
230
+ }
231
+
232
+ export interface DeclarativeStatSpec<TData = Record<string, unknown>> {
233
+ readonly key?: string;
234
+ readonly label: DeclarativeI18nText;
235
+ readonly value:
236
+ | (keyof TData & string)
237
+ | ((data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable);
238
+ readonly hint?: DeclarativeI18nText | ((data: TData) => DeclarativeRenderable);
239
+ readonly badge?: {
240
+ readonly label: DeclarativeI18nText | ((data: TData) => DeclarativeRenderable);
241
+ readonly tone?: DeclarativeBadgeTone | ((data: TData) => DeclarativeBadgeTone);
242
+ };
243
+ }
244
+
245
+ export interface DeclarativeActionFieldSpec {
246
+ readonly key: string;
247
+ readonly label: DeclarativeI18nText;
248
+ readonly placeholder?: string;
249
+ readonly required?: boolean;
250
+ readonly defaultValue?: string;
251
+ readonly secret?: boolean;
252
+ }
253
+
254
+ export interface DeclarativeActionSpec<TData = Record<string, unknown>> {
255
+ /** RPC action method name (`plugin.<pluginId>.<name>`). */
256
+ readonly name: string;
257
+ readonly label: DeclarativeI18nText;
258
+ readonly description?: DeclarativeI18nText;
259
+ readonly variant?: DeclarativeButtonVariant;
260
+ readonly confirm?: DeclarativeI18nText;
261
+ readonly confirmLabel?: DeclarativeI18nText;
262
+ readonly fields?: readonly DeclarativeActionFieldSpec[];
263
+ readonly params?:
264
+ | Readonly<Record<string, unknown>>
265
+ | ((
266
+ data: TData | undefined,
267
+ values: Readonly<Record<string, string>>,
268
+ ) => Readonly<Record<string, unknown>>);
269
+ readonly disabled?: boolean | ((data: TData | undefined) => boolean);
270
+ readonly successMessage?: DeclarativeI18nText;
271
+ }
272
+
273
+ export interface DeclarativeColumnSpec<
274
+ TRow = Record<string, unknown>,
275
+ TData = Record<string, unknown>,
276
+ > {
277
+ readonly key: keyof TRow & string;
278
+ readonly label: DeclarativeI18nText;
279
+ readonly render?: (
280
+ value: unknown,
281
+ row: TRow,
282
+ ctx: DeclarativePageContext<TData>,
283
+ ) => DeclarativeRenderable;
284
+ }
285
+
286
+ export interface DeclarativeSectionSpec<
287
+ TData = Record<string, unknown>,
288
+ TRow = Record<string, unknown>,
289
+ > {
290
+ readonly id?: string;
291
+ readonly title?: DeclarativeI18nText;
292
+ readonly description?: DeclarativeI18nText;
293
+ readonly emptyText?: DeclarativeI18nText;
294
+ /** Extract rows for a declarative table or list. */
295
+ readonly items?: (keyof TData & string) | ((data: TData) => readonly TRow[]);
296
+ /** Columns for a declarative table/card list when `items` is provided. */
297
+ readonly columns?: readonly DeclarativeColumnSpec<TRow, TData>[];
298
+ /** Custom row renderer when `items` is provided. */
299
+ readonly renderItem?: (
300
+ item: TRow,
301
+ index: number,
302
+ ctx: DeclarativePageContext<TData>,
303
+ ) => DeclarativeRenderable;
304
+ /** Key-value description list extractor (`<dl className="zk-dl">`). */
305
+ readonly entries?: (
306
+ data: TData,
307
+ ctx: DeclarativePageContext<TData>,
308
+ ) =>
309
+ | Readonly<Record<string, DeclarativeRenderable>>
310
+ | readonly { readonly label: DeclarativeRenderable; readonly value: DeclarativeRenderable }[];
311
+ /** Custom section body renderer. */
312
+ readonly render?: (data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable;
313
+ }
314
+
315
+ export interface DeclarativePageSpec<TData = Record<string, unknown>> {
316
+ /** Explicit plugin ID (`root/<name>`); auto-resolved from page props or route when omitted. */
317
+ readonly pluginId?: string;
318
+ readonly title: DeclarativeI18nText;
319
+ readonly description?: DeclarativeI18nText;
320
+ readonly mark?: DeclarativeRenderable;
321
+ /** Status RPC method name; defaults to `'status'`. */
322
+ readonly statusMethod?: string;
323
+ /** Optional polling interval in ms; defaults to 10_000. Pass `0` to disable polling. */
324
+ readonly pollMs?: number;
325
+ readonly dictionary?: Readonly<Record<string, string>>;
326
+ readonly isEmpty?: (data: TData) => boolean;
327
+ readonly emptyTitle?: DeclarativeI18nText;
328
+ readonly emptyDescription?: DeclarativeI18nText;
329
+ readonly badges?:
330
+ | readonly DeclarativeBadgeSpec<TData>[]
331
+ | ((
332
+ data: TData,
333
+ ctx: DeclarativePageContext<TData>,
334
+ ) => readonly DeclarativeBadgeSpec<TData>[]);
335
+ readonly stats?:
336
+ | readonly DeclarativeStatSpec<TData>[]
337
+ | ((
338
+ data: TData,
339
+ ctx: DeclarativePageContext<TData>,
340
+ ) => readonly DeclarativeStatSpec<TData>[]);
341
+ readonly actions?: readonly DeclarativeActionSpec<TData>[];
342
+ readonly sections?: readonly DeclarativeSectionSpec<TData, any>[];
343
+ readonly render?: (data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable;
344
+ readonly footnote?: DeclarativeI18nText;
345
+ }
346
+
347
+ export interface DeclarativePageComponentProps {
348
+ readonly pluginId?: string;
349
+ readonly owner?: string;
350
+ readonly localName?: string;
351
+ readonly route?: string;
352
+ readonly title?: string;
353
+ readonly [key: string]: unknown;
354
+ }
355
+
356
+ export type ConsolePageBlueprintSection =
357
+ | {
358
+ readonly type: 'stats';
359
+ readonly id: string;
360
+ readonly title: string;
361
+ readonly items: readonly {
362
+ readonly key: string;
363
+ readonly label: string;
364
+ readonly value?: unknown;
365
+ readonly suffix?: string;
366
+ readonly dataKey?: string;
367
+ }[];
368
+ }
369
+ | {
370
+ readonly type: 'table';
371
+ readonly id: string;
372
+ readonly title: string;
373
+ readonly dataKey?: string;
374
+ readonly rowKey: string;
375
+ readonly columns: readonly { readonly key: string; readonly label: string }[];
376
+ }
377
+ | {
378
+ readonly type: 'entries';
379
+ readonly id: string;
380
+ readonly title: string;
381
+ }
382
+ | {
383
+ readonly type: 'actions';
384
+ readonly id: string;
385
+ readonly title: string;
386
+ readonly items: readonly {
387
+ readonly label: string;
388
+ readonly action: string;
389
+ readonly name?: string;
390
+ readonly description?: string;
391
+ readonly variant?: DeclarativeButtonVariant;
392
+ }[];
393
+ }
394
+ | {
395
+ readonly type: 'markdown';
396
+ readonly id: string;
397
+ readonly title?: string;
398
+ readonly content: string;
399
+ }
400
+ | {
401
+ readonly type: 'custom';
402
+ readonly id: string;
403
+ readonly title?: string;
404
+ };
405
+
406
+ export interface ConsolePageBlueprint<TData = Record<string, unknown>> {
407
+ readonly kind: 'zhin.console.page-blueprint';
408
+ readonly version: 1;
409
+ readonly title: string;
410
+ readonly titleI18n?: Readonly<Partial<Record<'zh-CN' | 'en', string>>>;
411
+ readonly description?: string;
412
+ readonly dataSource: {
413
+ readonly action: string;
414
+ };
415
+ readonly sections: readonly ConsolePageBlueprintSection[];
416
+ readonly spec?: DeclarativePageSpec<TData>;
417
+ readonly reviewSpec?: CommentReviewBlueprintSpec<any, any>;
418
+ }
419
+
420
+ export interface CommentReviewDraftBase {
421
+ readonly id: string;
422
+ readonly url: string;
423
+ readonly message: string;
424
+ readonly status: 'pending' | 'sending';
425
+ readonly interrupted: boolean;
426
+ readonly createdAt: number;
427
+ readonly updatedAt?: number;
428
+ readonly author?: string;
429
+ readonly original?: string;
430
+ }
431
+
432
+ export interface CommentReviewEndpointBase<D extends CommentReviewDraftBase = CommentReviewDraftBase> {
433
+ readonly id: string;
434
+ readonly sendMode: 'review' | 'off';
435
+ readonly persistent: boolean;
436
+ readonly circuit: { readonly code: number } | null;
437
+ readonly login: { readonly state: 'none' | 'ok' | 'expired' };
438
+ readonly pendingCount: number;
439
+ readonly drafts: readonly D[];
440
+ }
441
+
442
+ export interface CommentReviewBlueprintSpec<
443
+ E extends CommentReviewEndpointBase<any> = CommentReviewEndpointBase<CommentReviewDraftBase>,
444
+ D extends CommentReviewDraftBase = CommentReviewDraftBase,
445
+ > {
446
+ readonly adapter: string;
447
+ readonly platform: { readonly zh: string; readonly en: string };
448
+ readonly mark: string;
449
+ readonly resource: { readonly zh: string; readonly en: string };
450
+ readonly dictionary?: Readonly<Record<string, string>>;
451
+ readonly openLabel?: string;
452
+ readonly account?: (endpoint: E) => { readonly id?: string; readonly name?: string };
453
+ readonly draftResource?: (
454
+ draft: D,
455
+ t: (key: string, ...values: readonly (string | number)[]) => string,
456
+ ) => string;
457
+ readonly loginHint?: (
458
+ endpoint: E,
459
+ t: (key: string, ...values: readonly (string | number)[]) => string,
460
+ ) => string | undefined;
461
+ readonly isLoginPending?: (endpoint: E) => boolean;
462
+ readonly loginMode?: 'qr' | 'cookie-check';
463
+ readonly resourcesKey?: string;
464
+ readonly pollMs?: number;
465
+ readonly pendingPollMs?: number;
466
+ }
467
+
468
+ export interface ConsoleAdapterPageBlueprint {
469
+ readonly kind: 'zhin.console.adapter-page';
470
+ readonly version: 1;
471
+ readonly adapterKey: string;
472
+ readonly dataSource: {
473
+ readonly action: 'status';
474
+ };
475
+ }
476
+
477
+ export type BlueprintPageComponent<TData = Record<string, unknown>> = ((
478
+ props?: DeclarativePageComponentProps,
479
+ ) => ConsolePageBlueprint<TData>) &
480
+ Readonly<ConsolePageBlueprint<TData>>;
481
+
482
+ export type AdapterPageComponent = ((
483
+ props?: DeclarativePageComponentProps,
484
+ ) => ConsoleAdapterPageBlueprint) &
485
+ Readonly<ConsoleAdapterPageBlueprint>;
486
+
487
+ export function resolveDeclarativeText(
488
+ text: DeclarativeI18nText | undefined,
489
+ preferredLocale: 'en' | 'zh-CN' = 'en',
490
+ ): string {
491
+ if (!text) return '';
492
+ if (typeof text === 'string') return text;
493
+ if (preferredLocale === 'en') {
494
+ return text.en ?? text['zh-CN'] ?? text.zh;
495
+ }
496
+ return text['zh-CN'] ?? text.zh ?? text.en ?? '';
497
+ }
498
+
499
+ export function buildBlueprintFromSpec<TData = Record<string, unknown>>(
500
+ input: DeclarativePageSpec<TData> | ConsolePageBlueprint<TData>,
501
+ ): Readonly<ConsolePageBlueprint<TData>> {
502
+ if ((input as ConsolePageBlueprint<TData>)?.kind === 'zhin.console.page-blueprint') {
503
+ const bp = input as ConsolePageBlueprint<TData>;
504
+ return Object.freeze({
505
+ kind: 'zhin.console.page-blueprint' as const,
506
+ version: 1 as const,
507
+ title: bp.title,
508
+ ...(bp.titleI18n ? { titleI18n: Object.freeze({ ...bp.titleI18n }) } : {}),
509
+ ...(bp.description !== undefined ? { description: bp.description } : {}),
510
+ dataSource: Object.freeze({ action: bp.dataSource?.action ?? 'status' }),
511
+ sections: Object.freeze([...(bp.sections ?? [])]),
512
+ ...(bp.spec !== undefined ? { spec: bp.spec } : {}),
513
+ });
514
+ }
515
+
516
+ const spec = input as DeclarativePageSpec<TData>;
517
+ const title = resolveDeclarativeText(spec.title, 'en');
518
+ const titleI18n =
519
+ typeof spec.title === 'object' && spec.title !== null
520
+ ? {
521
+ 'zh-CN': spec.title['zh-CN'] ?? spec.title.zh,
522
+ ...(spec.title.en ? { en: spec.title.en } : {}),
523
+ }
524
+ : undefined;
525
+ const description = spec.description ? resolveDeclarativeText(spec.description, 'en') : undefined;
526
+ const dataSource = Object.freeze({ action: spec.statusMethod ?? 'status' });
527
+ const sections: ConsolePageBlueprintSection[] = [];
528
+
529
+ if (Array.isArray(spec.stats) && spec.stats.length > 0) {
530
+ sections.push(
531
+ Object.freeze({
532
+ type: 'stats',
533
+ id: 'runtime-stats',
534
+ title: 'Runtime Stats',
535
+ items: Object.freeze(
536
+ spec.stats.map((stat, idx) =>
537
+ Object.freeze({
538
+ key: stat.key ?? (typeof stat.value === 'string' ? stat.value : `stat-${idx}`),
539
+ label: resolveDeclarativeText(stat.label, 'en'),
540
+ ...(typeof stat.value === 'string' ? { dataKey: stat.value } : {}),
541
+ }),
542
+ ),
543
+ ),
544
+ }),
545
+ );
546
+ }
547
+
548
+ for (const [idx, sec] of (spec.sections ?? []).entries()) {
549
+ const id = sec.id ?? `section-${idx}`;
550
+ const secTitle = resolveDeclarativeText(sec.title, 'en');
551
+ if (sec.columns !== undefined || sec.items !== undefined) {
552
+ sections.push(
553
+ Object.freeze({
554
+ type: 'table',
555
+ id,
556
+ title: secTitle,
557
+ ...(typeof sec.items === 'string' ? { dataKey: sec.items } : {}),
558
+ rowKey: sec.columns?.[0]?.key ?? 'id',
559
+ columns: Object.freeze(
560
+ (sec.columns ?? []).map((col) =>
561
+ Object.freeze({
562
+ key: col.key,
563
+ label: resolveDeclarativeText(col.label, 'en'),
564
+ }),
565
+ ),
566
+ ),
567
+ }),
568
+ );
569
+ } else if (sec.entries !== undefined) {
570
+ sections.push(
571
+ Object.freeze({
572
+ type: 'entries',
573
+ id,
574
+ title: secTitle,
575
+ }),
576
+ );
577
+ } else {
578
+ sections.push(
579
+ Object.freeze({
580
+ type: 'custom',
581
+ id,
582
+ ...(secTitle ? { title: secTitle } : {}),
583
+ }),
584
+ );
585
+ }
586
+ }
587
+
588
+ if (Array.isArray(spec.actions) && spec.actions.length > 0) {
589
+ sections.push(
590
+ Object.freeze({
591
+ type: 'actions',
592
+ id: 'actions',
593
+ title: 'Actions',
594
+ items: Object.freeze(
595
+ spec.actions.map((act) =>
596
+ Object.freeze({
597
+ label: resolveDeclarativeText(act.label, 'en'),
598
+ action: act.name,
599
+ name: act.name,
600
+ ...(act.description
601
+ ? { description: resolveDeclarativeText(act.description, 'en') }
602
+ : {}),
603
+ ...(act.variant ? { variant: act.variant } : {}),
604
+ }),
605
+ ),
606
+ ),
607
+ }),
608
+ );
609
+ }
610
+
611
+ return Object.freeze({
612
+ kind: 'zhin.console.page-blueprint',
613
+ version: 1,
614
+ title,
615
+ ...(titleI18n ? { titleI18n: Object.freeze(titleI18n) } : {}),
616
+ ...(description !== undefined ? { description } : {}),
617
+ dataSource,
618
+ sections: Object.freeze(sections),
619
+ spec,
620
+ });
621
+ }
622
+
623
+ export function definePageBlueprint<TData = Record<string, unknown>>(
624
+ spec: DeclarativePageSpec<TData> | ConsolePageBlueprint<TData>,
625
+ ): BlueprintPageComponent<TData> {
626
+ const blueprint = buildBlueprintFromSpec(spec);
627
+ function BlueprintPage(_props?: DeclarativePageComponentProps): ConsolePageBlueprint<TData> {
628
+ return blueprint;
629
+ }
630
+ return Object.freeze(Object.assign(BlueprintPage, blueprint));
631
+ }
632
+
633
+ export const createDeclarativePage = definePageBlueprint;
634
+
635
+ export function defineAdapterPage(adapterKey: string): AdapterPageComponent {
636
+ const validKey = optionalString(adapterKey, 'Adapter page adapterKey');
637
+ if (!validKey) throw new TypeError('Adapter page adapterKey must be a non-empty string');
638
+ const blueprint: ConsoleAdapterPageBlueprint = Object.freeze({
639
+ kind: 'zhin.console.adapter-page',
640
+ version: 1,
641
+ adapterKey: validKey,
642
+ dataSource: Object.freeze({ action: 'status' as const }),
643
+ });
644
+ function AdapterConsoleRoute(_props?: DeclarativePageComponentProps): ConsoleAdapterPageBlueprint {
645
+ return blueprint;
646
+ }
647
+ return Object.freeze(Object.assign(AdapterConsoleRoute, blueprint));
648
+ }
649
+
650
+ export const createAdapterConsolePage = defineAdapterPage;
651
+
652
+ export function defineCommentReviewPage<
653
+ E extends CommentReviewEndpointBase<any> = CommentReviewEndpointBase<CommentReviewDraftBase>,
654
+ D extends CommentReviewDraftBase = CommentReviewDraftBase,
655
+ >(
656
+ reviewSpec: CommentReviewBlueprintSpec<E, D>,
657
+ ): BlueprintPageComponent<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }> {
658
+ const zhTitle = `${reviewSpec.platform.zh}评论审批`;
659
+ const enTitle = `${reviewSpec.platform.en} comment review`;
660
+ const loginActions: DeclarativeActionSpec<any>[] =
661
+ reviewSpec.loginMode === 'cookie-check'
662
+ ? [{ name: 'login-check', label: { zh: '重新检查登录', en: 'Check login again' } }]
663
+ : [
664
+ { name: 'login', label: { zh: '扫码登录', en: 'Sign in with QR code' }, variant: 'primary' },
665
+ { name: 'login-cancel', label: { zh: '取消扫码', en: 'Cancel QR login' }, variant: 'ghost' },
666
+ { name: 'logout', label: { zh: '退出登录', en: 'Sign out' }, variant: 'secondary' },
667
+ ];
668
+ const blueprint = buildBlueprintFromSpec<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }>({
669
+ pluginId: reviewSpec.adapter,
670
+ title: { zh: zhTitle, 'zh-CN': zhTitle, en: enTitle },
671
+ mark: reviewSpec.mark,
672
+ statusMethod: 'status',
673
+ pollMs: reviewSpec.pollMs ?? 10_000,
674
+ ...(reviewSpec.dictionary ? { dictionary: reviewSpec.dictionary } : {}),
675
+ stats: [
676
+ {
677
+ key: 'endpoints',
678
+ label: { zh: '账号数', en: 'Accounts' },
679
+ value: (data) => (Array.isArray(data?.endpoints) ? data.endpoints.length : 0),
680
+ },
681
+ {
682
+ key: 'pendingDrafts',
683
+ label: { zh: '待审草稿', en: 'Pending drafts' },
684
+ value: (data) =>
685
+ (data?.endpoints ?? []).reduce(
686
+ (sum, ep) => sum + (typeof ep?.pendingCount === 'number' ? ep.pendingCount : (ep?.drafts?.length ?? 0)),
687
+ 0,
688
+ ),
689
+ },
690
+ ],
691
+ sections: [
692
+ {
693
+ id: 'endpoints',
694
+ title: { zh: '评论账号与待审草稿', en: 'Accounts & Pending Drafts' },
695
+ items: 'endpoints',
696
+ columns: [
697
+ { key: 'id', label: { zh: '账号', en: 'Account' } },
698
+ { key: 'sendMode', label: { zh: '发送模式', en: 'Send Mode' } },
699
+ { key: 'pendingCount', label: { zh: '待审数', en: 'Pending' } },
700
+ ],
701
+ },
702
+ ],
703
+ actions: [
704
+ ...loginActions,
705
+ {
706
+ name: 'edit',
707
+ label: { zh: '修改草稿', en: 'Edit draft' },
708
+ fields: [
709
+ { key: 'id', label: { zh: '草稿 ID', en: 'Draft ID' }, required: true },
710
+ { key: 'message', label: { zh: '回复内容', en: 'Reply content' }, required: true },
711
+ ],
712
+ },
713
+ {
714
+ name: 'send',
715
+ label: { zh: '发送草稿', en: 'Send draft' },
716
+ variant: 'primary',
717
+ fields: [{ key: 'id', label: { zh: '草稿 ID', en: 'Draft ID' }, required: true }],
718
+ },
719
+ {
720
+ name: 'drop',
721
+ label: { zh: '丢弃草稿', en: 'Discard draft' },
722
+ variant: 'danger',
723
+ confirm: { zh: '确认丢弃该草稿?', en: 'Discard this draft?' },
724
+ fields: [{ key: 'id', label: { zh: '草稿 ID', en: 'Draft ID' }, required: true }],
725
+ },
726
+ ],
727
+ });
728
+ const enriched: ConsolePageBlueprint<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }> =
729
+ Object.freeze({
730
+ ...blueprint,
731
+ reviewSpec,
732
+ });
733
+ function CommentReviewBlueprintPage(
734
+ _props?: DeclarativePageComponentProps,
735
+ ): ConsolePageBlueprint<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }> {
736
+ return enriched;
737
+ }
738
+ return Object.freeze(Object.assign(CommentReviewBlueprintPage, enriched));
739
+ }
740
+
741
+ export const createCommentReviewPage = defineCommentReviewPage;
742
+
743
+ // ── Multi-Surface Blueprint Projection (IM Card & CLI TUI) ─────────────────
744
+
745
+ export interface BlueprintProjectionOptions {
746
+ readonly locale?: DeclarativeUiLocale;
747
+ readonly pluginId?: string;
748
+ readonly maxRows?: number;
749
+ }
750
+
751
+ export interface BlueprintImStatItem {
752
+ readonly key: string;
753
+ readonly label: string;
754
+ readonly value: string;
755
+ readonly hint?: string;
756
+ readonly badge?: string;
757
+ }
758
+
759
+ export interface BlueprintImTableSection {
760
+ readonly id: string;
761
+ readonly title: string;
762
+ readonly columns: readonly { readonly key: string; readonly label: string }[];
763
+ readonly rows: readonly (readonly string[])[];
764
+ readonly totalRows: number;
765
+ readonly emptyText?: string;
766
+ }
767
+
768
+ export interface BlueprintImEntriesSection {
769
+ readonly id: string;
770
+ readonly title: string;
771
+ readonly items: readonly { readonly label: string; readonly value: string }[];
772
+ }
773
+
774
+ export interface BlueprintImActionItem {
775
+ readonly name: string;
776
+ readonly label: string;
777
+ readonly rpcMethod: string;
778
+ readonly description?: string;
779
+ readonly variant: DeclarativeButtonVariant;
780
+ readonly disabled: boolean;
781
+ }
782
+
783
+ export interface BlueprintImSegment {
784
+ readonly type: 'card' | 'markdown' | 'button' | 'text';
785
+ readonly data: Readonly<Record<string, unknown>>;
786
+ }
787
+
788
+ export interface BlueprintImCardProjection {
789
+ readonly kind: 'zhin.im.blueprint-card';
790
+ readonly pluginId: string;
791
+ readonly title: string;
792
+ readonly description?: string;
793
+ readonly stats: readonly BlueprintImStatItem[];
794
+ readonly tables: readonly BlueprintImTableSection[];
795
+ readonly entries: readonly BlueprintImEntriesSection[];
796
+ readonly actions: readonly BlueprintImActionItem[];
797
+ readonly markdown: string;
798
+ readonly segments: readonly BlueprintImSegment[];
799
+ }
800
+
801
+ function createProjectionContext<TData = Record<string, unknown>>(
802
+ data: TData | undefined,
803
+ locale: DeclarativeUiLocale,
804
+ pluginId: string,
805
+ dictionary?: Readonly<Record<string, string>>,
806
+ ): DeclarativePageContext<TData> {
807
+ const t = (key: string, ...values: readonly (string | number)[]): string => {
808
+ const template = locale === 'en' && dictionary?.[key] ? dictionary[key] : key;
809
+ return template.replace(/\{(\d+)\}/gu, (_m, idx) => String(values[Number(idx)] ?? ''));
810
+ };
811
+ return {
812
+ pluginId,
813
+ locale,
814
+ t,
815
+ resource: {
816
+ state: data === undefined ? 'empty' : 'ready',
817
+ data,
818
+ error: undefined,
819
+ lastSuccessAt: Date.now(),
820
+ refreshing: false,
821
+ refresh: async () => true,
822
+ mutate: () => undefined,
823
+ },
824
+ call: async () => undefined as never,
825
+ refresh: async () => true,
826
+ notify: () => undefined,
827
+ };
828
+ }
829
+
830
+ function formatRenderableValue(value: unknown): string {
831
+ if (value === null || value === undefined) return '—';
832
+ if (typeof value === 'string') return value || '—';
833
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
834
+ if (Array.isArray(value)) return value.map((item) => formatRenderableValue(item)).join(', ');
835
+ if (typeof value === 'object') {
836
+ const record = value as Record<string, unknown>;
837
+ if (typeof record.label === 'string') return record.label;
838
+ if (typeof record.text === 'string') return record.text;
839
+ try {
840
+ return JSON.stringify(value);
841
+ } catch {
842
+ return String(value);
843
+ }
844
+ }
845
+ return String(value);
846
+ }
847
+
848
+ /**
849
+ * Projects any Server-Driven Console Blueprint (`definePageBlueprint`, `defineAdapterPage`,
850
+ * `defineCommentReviewPage`, or `DeclarativePageSpec`) + runtime status payload into a
851
+ * structured IM Card / Markdown / Segment payload ready for `Message.$reply` or `Adapter.sendMessage`.
852
+ */
853
+ export function projectBlueprintToImCard<TData = Record<string, unknown>>(
854
+ input:
855
+ | ConsolePageBlueprint<TData>
856
+ | ConsoleAdapterPageBlueprint
857
+ | DeclarativePageSpec<TData>,
858
+ data?: TData,
859
+ options: BlueprintProjectionOptions = {},
860
+ ): Readonly<BlueprintImCardProjection> {
861
+ const locale: DeclarativeUiLocale = options.locale ?? 'zh-CN';
862
+ const maxRows = Math.max(1, options.maxRows ?? 10);
863
+ const recordData = (data && typeof data === 'object' ? data : {}) as Record<string, unknown>;
864
+
865
+ if ((input as ConsoleAdapterPageBlueprint)?.kind === 'zhin.console.adapter-page') {
866
+ const adapterBp = input as ConsoleAdapterPageBlueprint;
867
+ const pluginId = options.pluginId ?? adapterBp.adapterKey;
868
+ const title =
869
+ locale === 'zh-CN'
870
+ ? `${adapterBp.adapterKey} 适配器状态`
871
+ : `${adapterBp.adapterKey} Adapter Status`;
872
+ const bots = Array.isArray(recordData.bots)
873
+ ? recordData.bots
874
+ : Array.isArray(recordData.endpoints)
875
+ ? recordData.endpoints
876
+ : [];
877
+ const onlineCount = bots.filter(
878
+ (b: any) => b?.online === true || b?.connected === true || b?.status === 'online',
879
+ ).length;
880
+ const stats: BlueprintImStatItem[] = [
881
+ {
882
+ key: 'adapter',
883
+ label: locale === 'zh-CN' ? '适配器' : 'Adapter',
884
+ value: adapterBp.adapterKey,
885
+ },
886
+ {
887
+ key: 'endpoints',
888
+ label: locale === 'zh-CN' ? '实例数' : 'Instances',
889
+ value: String(bots.length),
890
+ },
891
+ {
892
+ key: 'online',
893
+ label: locale === 'zh-CN' ? '在线数' : 'Online',
894
+ value: String(onlineCount),
895
+ },
896
+ ];
897
+ const columns = [
898
+ { key: 'id', label: locale === 'zh-CN' ? '账号/端点' : 'Endpoint' },
899
+ { key: 'status', label: locale === 'zh-CN' ? '状态' : 'Status' },
900
+ ];
901
+ const rows = bots.slice(0, maxRows).map((b: any, i: number) => [
902
+ String(b?.id ?? b?.selfId ?? b?.name ?? `#${i + 1}`),
903
+ String(
904
+ b?.status ??
905
+ (b?.online === true || b?.connected === true
906
+ ? locale === 'zh-CN'
907
+ ? '在线'
908
+ : 'online'
909
+ : locale === 'zh-CN'
910
+ ? '离线'
911
+ : 'offline'),
912
+ ),
913
+ ]);
914
+ const tables: BlueprintImTableSection[] =
915
+ bots.length > 0
916
+ ? [
917
+ {
918
+ id: 'endpoints',
919
+ title: locale === 'zh-CN' ? '端点列表' : 'Endpoints',
920
+ columns,
921
+ rows,
922
+ totalRows: bots.length,
923
+ },
924
+ ]
925
+ : [];
926
+ const mdLines = [
927
+ `### ${title}`,
928
+ stats.map((s) => `- **${s.label}**: ${s.value}`).join('\n'),
929
+ ];
930
+ if (tables.length > 0) {
931
+ for (const tbl of tables) {
932
+ mdLines.push(`\n#### ${tbl.title}`);
933
+ mdLines.push(`| ${tbl.columns.map((c) => c.label).join(' | ')} |`);
934
+ mdLines.push(`| ${tbl.columns.map(() => '---').join(' | ')} |`);
935
+ for (const r of tbl.rows) {
936
+ mdLines.push(`| ${r.join(' | ')} |`);
937
+ }
938
+ }
939
+ }
940
+ const markdown = mdLines.filter(Boolean).join('\n');
941
+ const segments: BlueprintImSegment[] = [
942
+ {
943
+ type: 'card',
944
+ data: {
945
+ title,
946
+ pluginId,
947
+ stats,
948
+ tables,
949
+ },
950
+ },
951
+ {
952
+ type: 'markdown',
953
+ data: { content: markdown },
954
+ },
955
+ ];
956
+ return Object.freeze({
957
+ kind: 'zhin.im.blueprint-card',
958
+ pluginId,
959
+ title,
960
+ stats: Object.freeze(stats),
961
+ tables: Object.freeze(tables),
962
+ entries: Object.freeze([]),
963
+ actions: Object.freeze([]),
964
+ markdown,
965
+ segments: Object.freeze(segments),
966
+ });
967
+ }
968
+
969
+ const bp =
970
+ (input as ConsolePageBlueprint<TData>)?.kind === 'zhin.console.page-blueprint'
971
+ ? (input as ConsolePageBlueprint<TData>)
972
+ : buildBlueprintFromSpec(input as DeclarativePageSpec<TData>);
973
+ const spec = bp.spec;
974
+ const pluginId = options.pluginId ?? spec?.pluginId ?? 'plugin';
975
+ const ctx = createProjectionContext(data, locale, pluginId, spec?.dictionary);
976
+ const title =
977
+ (locale === 'zh-CN' ? bp.titleI18n?.['zh-CN'] : bp.titleI18n?.en) ??
978
+ (spec?.title ? resolveDeclarativeText(spec.title, locale) : bp.title);
979
+ const description = spec?.description
980
+ ? resolveDeclarativeText(spec.description, locale)
981
+ : bp.description;
982
+
983
+ const stats: BlueprintImStatItem[] = [];
984
+ const rawStats =
985
+ typeof spec?.stats === 'function'
986
+ ? spec.stats((data ?? ({} as TData)), ctx)
987
+ : Array.isArray(spec?.stats)
988
+ ? spec.stats
989
+ : undefined;
990
+ if (rawStats) {
991
+ for (const [idx, s] of rawStats.entries()) {
992
+ const val =
993
+ typeof s.value === 'function'
994
+ ? s.value((data ?? ({} as TData)), ctx)
995
+ : recordData[s.value];
996
+ const hint =
997
+ typeof s.hint === 'function'
998
+ ? formatRenderableValue(s.hint((data ?? ({} as TData))))
999
+ : s.hint
1000
+ ? resolveDeclarativeText(s.hint, locale)
1001
+ : undefined;
1002
+ const badge = s.badge
1003
+ ? typeof s.badge.label === 'function'
1004
+ ? formatRenderableValue(s.badge.label((data ?? ({} as TData))))
1005
+ : resolveDeclarativeText(s.badge.label, locale)
1006
+ : undefined;
1007
+ stats.push(
1008
+ Object.freeze({
1009
+ key: s.key ?? `stat-${idx}`,
1010
+ label: resolveDeclarativeText(s.label, locale),
1011
+ value: formatRenderableValue(val),
1012
+ ...(hint ? { hint } : {}),
1013
+ ...(badge ? { badge } : {}),
1014
+ }),
1015
+ );
1016
+ }
1017
+ } else {
1018
+ for (const sec of bp.sections) {
1019
+ if (sec.type === 'stats') {
1020
+ for (const item of sec.items) {
1021
+ const val = item.dataKey ? recordData[item.dataKey] : item.value;
1022
+ stats.push(
1023
+ Object.freeze({
1024
+ key: item.key,
1025
+ label: item.label,
1026
+ value: `${formatRenderableValue(val)}${item.suffix ?? ''}`,
1027
+ }),
1028
+ );
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ const tables: BlueprintImTableSection[] = [];
1035
+ const entries: BlueprintImEntriesSection[] = [];
1036
+
1037
+ if (Array.isArray(spec?.sections)) {
1038
+ for (const [idx, sec] of spec.sections.entries()) {
1039
+ const id = sec.id ?? `section-${idx}`;
1040
+ const secTitle = resolveDeclarativeText(sec.title, locale) || id;
1041
+ if (sec.items !== undefined) {
1042
+ const rawItems =
1043
+ typeof sec.items === 'function'
1044
+ ? sec.items((data ?? ({} as TData)))
1045
+ : (recordData[sec.items] as readonly Record<string, unknown>[] | undefined);
1046
+ const list = Array.isArray(rawItems) ? rawItems : [];
1047
+ const cols: readonly {
1048
+ readonly key: string;
1049
+ readonly label: string;
1050
+ readonly render?: (
1051
+ value: unknown,
1052
+ row: unknown,
1053
+ ctx: DeclarativePageContext<TData>,
1054
+ ) => DeclarativeRenderable;
1055
+ }[] =
1056
+ sec.columns && sec.columns.length > 0
1057
+ ? sec.columns.map((c: DeclarativeColumnSpec<any, TData>) => ({
1058
+ key: c.key,
1059
+ label: resolveDeclarativeText(c.label, locale),
1060
+ render: c.render,
1061
+ }))
1062
+ : list[0] && typeof list[0] === 'object'
1063
+ ? Object.keys(list[0] as Record<string, unknown>)
1064
+ .slice(0, 5)
1065
+ .map((k) => ({ key: k, label: k, render: undefined }))
1066
+ : [{ key: 'value', label: locale === 'zh-CN' ? '内容' : 'Value', render: undefined }];
1067
+ const rows = list.slice(0, maxRows).map((row, rowIdx) => {
1068
+ if (sec.renderItem && (!sec.columns || sec.columns.length === 0)) {
1069
+ return [formatRenderableValue(sec.renderItem(row, rowIdx, ctx))];
1070
+ }
1071
+ const rec = (row && typeof row === 'object' ? row : { value: row }) as Record<string, unknown>;
1072
+ return cols.map((c) =>
1073
+ c.render
1074
+ ? formatRenderableValue(c.render(rec[c.key], row, ctx))
1075
+ : formatRenderableValue(rec[c.key]),
1076
+ );
1077
+ });
1078
+ const emptyText = sec.emptyText ? resolveDeclarativeText(sec.emptyText, locale) : undefined;
1079
+ tables.push(
1080
+ Object.freeze({
1081
+ id,
1082
+ title: secTitle,
1083
+ columns: Object.freeze(cols.map(({ key, label }) => Object.freeze({ key, label }))),
1084
+ rows: Object.freeze(rows.map((r) => Object.freeze(r))),
1085
+ totalRows: list.length,
1086
+ ...(emptyText ? { emptyText } : {}),
1087
+ }),
1088
+ );
1089
+ } else if (sec.entries !== undefined) {
1090
+ const rawEntries = sec.entries((data ?? ({} as TData)), ctx);
1091
+ const items = Array.isArray(rawEntries)
1092
+ ? rawEntries.map((entry) =>
1093
+ Object.freeze({
1094
+ label: formatRenderableValue(entry.label),
1095
+ value: formatRenderableValue(entry.value),
1096
+ }),
1097
+ )
1098
+ : Object.entries(rawEntries ?? {}).map(([k, v]) =>
1099
+ Object.freeze({
1100
+ label: k,
1101
+ value: formatRenderableValue(v),
1102
+ }),
1103
+ );
1104
+ entries.push(
1105
+ Object.freeze({
1106
+ id,
1107
+ title: secTitle,
1108
+ items: Object.freeze(items),
1109
+ }),
1110
+ );
1111
+ }
1112
+ }
1113
+ } else {
1114
+ for (const sec of bp.sections) {
1115
+ if (sec.type === 'table') {
1116
+ const rawItems = sec.dataKey ? recordData[sec.dataKey] : undefined;
1117
+ const list = Array.isArray(rawItems) ? rawItems : [];
1118
+ const rows = list.slice(0, maxRows).map((row) => {
1119
+ const rec = (row && typeof row === 'object' ? row : {}) as Record<string, unknown>;
1120
+ return sec.columns.map((c) => formatRenderableValue(rec[c.key]));
1121
+ });
1122
+ tables.push(
1123
+ Object.freeze({
1124
+ id: sec.id,
1125
+ title: sec.title,
1126
+ columns: sec.columns,
1127
+ rows: Object.freeze(rows.map((r) => Object.freeze(r))),
1128
+ totalRows: list.length,
1129
+ }),
1130
+ );
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ const actions: BlueprintImActionItem[] = [];
1136
+ if (Array.isArray(spec?.actions)) {
1137
+ for (const act of spec.actions) {
1138
+ const disabled =
1139
+ typeof act.disabled === 'function' ? act.disabled(data) : Boolean(act.disabled);
1140
+ const desc = act.description ? resolveDeclarativeText(act.description, locale) : undefined;
1141
+ actions.push(
1142
+ Object.freeze({
1143
+ name: act.name,
1144
+ label: resolveDeclarativeText(act.label, locale),
1145
+ rpcMethod: `plugin.${pluginId}.${act.name}`,
1146
+ ...(desc ? { description: desc } : {}),
1147
+ variant: act.variant ?? 'secondary',
1148
+ disabled,
1149
+ }),
1150
+ );
1151
+ }
1152
+ } else {
1153
+ for (const sec of bp.sections) {
1154
+ if (sec.type === 'actions') {
1155
+ for (const item of sec.items) {
1156
+ actions.push(
1157
+ Object.freeze({
1158
+ name: item.name ?? item.action,
1159
+ label: item.label,
1160
+ rpcMethod: `plugin.${pluginId}.${item.action}`,
1161
+ ...(item.description ? { description: item.description } : {}),
1162
+ variant: item.variant ?? 'secondary',
1163
+ disabled: false,
1164
+ }),
1165
+ );
1166
+ }
1167
+ }
1168
+ }
1169
+ }
1170
+
1171
+ const mdLines: string[] = [`### ${title}`];
1172
+ if (description) mdLines.push(description);
1173
+ if (stats.length > 0) {
1174
+ mdLines.push('');
1175
+ for (const s of stats) {
1176
+ const badgeSuffix = s.badge ? ` [${s.badge}]` : '';
1177
+ const hintSuffix = s.hint ? ` (${s.hint})` : '';
1178
+ mdLines.push(`- **${s.label}**: ${s.value}${badgeSuffix}${hintSuffix}`);
1179
+ }
1180
+ }
1181
+ for (const entrySec of entries) {
1182
+ mdLines.push(`\n#### ${entrySec.title}`);
1183
+ for (const item of entrySec.items) {
1184
+ mdLines.push(`- **${item.label}**: ${item.value}`);
1185
+ }
1186
+ }
1187
+ for (const tbl of tables) {
1188
+ mdLines.push(`\n#### ${tbl.title} (${tbl.totalRows})`);
1189
+ if (tbl.rows.length === 0) {
1190
+ mdLines.push(`_${tbl.emptyText ?? (locale === 'zh-CN' ? '暂无数据' : 'No data')}_`);
1191
+ } else {
1192
+ mdLines.push(`| ${tbl.columns.map((c) => c.label).join(' | ')} |`);
1193
+ mdLines.push(`| ${tbl.columns.map(() => '---').join(' | ')} |`);
1194
+ for (const r of tbl.rows) {
1195
+ mdLines.push(`| ${r.join(' | ')} |`);
1196
+ }
1197
+ }
1198
+ }
1199
+ if (actions.length > 0) {
1200
+ mdLines.push(
1201
+ `\n> ${locale === 'zh-CN' ? '可执行操作' : 'Available Actions'}: ${actions
1202
+ .map((a) => `\`${a.label}\` (${a.name})`)
1203
+ .join(' · ')}`,
1204
+ );
1205
+ }
1206
+ const markdown = mdLines.join('\n');
1207
+
1208
+ const segments: BlueprintImSegment[] = [
1209
+ {
1210
+ type: 'card',
1211
+ data: {
1212
+ title,
1213
+ ...(description ? { description } : {}),
1214
+ pluginId,
1215
+ stats,
1216
+ tables,
1217
+ entries,
1218
+ actions,
1219
+ },
1220
+ },
1221
+ {
1222
+ type: 'markdown',
1223
+ data: { content: markdown },
1224
+ },
1225
+ ...actions
1226
+ .filter((a) => !a.disabled)
1227
+ .map(
1228
+ (a): BlueprintImSegment => ({
1229
+ type: 'button',
1230
+ data: {
1231
+ id: a.rpcMethod,
1232
+ label: a.label,
1233
+ action: a.name,
1234
+ variant: a.variant,
1235
+ },
1236
+ }),
1237
+ ),
1238
+ ];
1239
+
1240
+ return Object.freeze({
1241
+ kind: 'zhin.im.blueprint-card',
1242
+ pluginId,
1243
+ title,
1244
+ ...(description ? { description } : {}),
1245
+ stats: Object.freeze(stats),
1246
+ tables: Object.freeze(tables),
1247
+ entries: Object.freeze(entries),
1248
+ actions: Object.freeze(actions),
1249
+ markdown,
1250
+ segments: Object.freeze(segments),
1251
+ });
1252
+ }
1253
+
1254
+ export interface BlueprintCliPanelOptions extends BlueprintProjectionOptions {
1255
+ readonly width?: number;
1256
+ }
1257
+
1258
+ /**
1259
+ * Projects any Server-Driven Console Blueprint (`definePageBlueprint`, `defineAdapterPage`,
1260
+ * `defineCommentReviewPage`, or `DeclarativePageSpec`) + runtime status payload into a
1261
+ * formatted CLI TUI panel string.
1262
+ */
1263
+ export function projectBlueprintToCliPanel<TData = Record<string, unknown>>(
1264
+ input:
1265
+ | ConsolePageBlueprint<TData>
1266
+ | ConsoleAdapterPageBlueprint
1267
+ | DeclarativePageSpec<TData>,
1268
+ data?: TData,
1269
+ options: BlueprintCliPanelOptions = {},
1270
+ ): string {
1271
+ const card = projectBlueprintToImCard(input, data, options);
1272
+ const width = Math.max(44, options.width ?? 72);
1273
+ const innerWidth = width - 4;
1274
+ const hr = '─'.repeat(width - 2);
1275
+ const padLine = (text: string): string => {
1276
+ const clean = text.replace(/\r?\n/gu, ' ').slice(0, innerWidth);
1277
+ const pad = Math.max(0, innerWidth - clean.length);
1278
+ return `│ ${clean}${' '.repeat(pad)} │`;
1279
+ };
1280
+
1281
+ const lines: string[] = [`┌${hr}┐`, padLine(`[${card.pluginId}] ${card.title}`)];
1282
+ if (card.description) {
1283
+ lines.push(padLine(card.description));
1284
+ }
1285
+ lines.push(`├${hr}┤`);
1286
+
1287
+ if (card.stats.length > 0) {
1288
+ const statSummary = card.stats
1289
+ .map((s) => `${s.label}: ${s.value}${s.badge ? ` [${s.badge}]` : ''}`)
1290
+ .join(' │ ');
1291
+ lines.push(padLine(statSummary));
1292
+ lines.push(`├${hr}┤`);
1293
+ }
1294
+
1295
+ for (const entrySec of card.entries) {
1296
+ lines.push(padLine(`■ ${entrySec.title}`));
1297
+ for (const item of entrySec.items) {
1298
+ lines.push(padLine(` ${item.label}: ${item.value}`));
1299
+ }
1300
+ lines.push(`├${hr}┤`);
1301
+ }
1302
+
1303
+ for (const tbl of card.tables) {
1304
+ lines.push(padLine(`■ ${tbl.title} (${tbl.totalRows})`));
1305
+ if (tbl.rows.length === 0) {
1306
+ lines.push(padLine(` (${tbl.emptyText ?? 'empty'})`));
1307
+ } else {
1308
+ lines.push(padLine(` ${tbl.columns.map((c) => c.label).join(' | ')}`));
1309
+ for (const row of tbl.rows) {
1310
+ lines.push(padLine(` ${row.join(' | ')}`));
1311
+ }
1312
+ }
1313
+ lines.push(`├${hr}┤`);
1314
+ }
1315
+
1316
+ if (card.actions.length > 0) {
1317
+ const actionBar = card.actions
1318
+ .map((a) => (a.disabled ? `(${a.label})` : `[${a.label} -> ${a.name}]`))
1319
+ .join(' ');
1320
+ lines.push(padLine(`Actions: ${actionBar}`));
1321
+ } else {
1322
+ // Remove trailing separator if no actions
1323
+ if (lines[lines.length - 1] === `├${hr}┤`) {
1324
+ lines.pop();
1325
+ }
1326
+ }
1327
+
1328
+ lines.push(`└${hr}┘`);
1329
+ return lines.join('\n');
1330
+ }