@zhin.js/console-contract 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/page.ts CHANGED
@@ -23,6 +23,7 @@ export interface ClientModuleArtifact {
23
23
  readonly module: string;
24
24
  readonly hash: string;
25
25
  readonly metadata?: unknown;
26
+ readonly blueprint?: ConsolePageBlueprint | ConsoleAdapterPageBlueprint;
26
27
  }
27
28
 
28
29
  export function normalizeClientModuleArtifact(
@@ -33,7 +34,21 @@ export function normalizeClientModuleArtifact(
33
34
  const module = optionalString(input.module, `${label} module`);
34
35
  const hash = optionalString(input.hash, `${label} hash`);
35
36
  if (!module || !hash) throw new TypeError(`${label} must include module and hash`);
36
- 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' && typeof value !== 'function')) return false;
50
+ const kind = (value as { readonly kind?: unknown }).kind;
51
+ return kind === 'zhin.console.page-blueprint' || kind === 'zhin.console.adapter-page';
37
52
  }
38
53
 
39
54
  export interface PageManifest extends NormalizedPageMetadata {
@@ -44,6 +59,7 @@ export interface PageManifest extends NormalizedPageMetadata {
44
59
  readonly module: string;
45
60
  readonly hash: string;
46
61
  readonly route: string;
62
+ readonly blueprint?: ConsolePageBlueprint | ConsoleAdapterPageBlueprint;
47
63
  }
48
64
 
49
65
  export function definePage(metadata: PageMetadata = {}): Readonly<PageMetadata> {
@@ -171,3 +187,1518 @@ function pageTitleTranslations(value: unknown): NormalizedPageMetadata['titleI18
171
187
  }
172
188
  return Object.freeze(output);
173
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
+ /**
204
+ * Pure JSON-serializable expression descriptor for zero-closure Server-Driven Blueprints.
205
+ * Can be evaluated identically in Web Console, IM Card projection, and CLI TUI panels.
206
+ */
207
+ export type DeclarativeValueExpr =
208
+ | { readonly $path: string; readonly fallback?: string | number | boolean }
209
+ | { readonly $count: string }
210
+ | { readonly $sum: { readonly path: string; readonly field: string } }
211
+ | { readonly $format: DeclarativeI18nText; readonly args: readonly string[] }
212
+ | {
213
+ readonly $map: {
214
+ readonly path: string;
215
+ readonly cases: Readonly<Record<string, DeclarativeI18nText>>;
216
+ readonly default?: DeclarativeI18nText;
217
+ };
218
+ }
219
+ | {
220
+ readonly $join: {
221
+ readonly path: string;
222
+ readonly sep?: string;
223
+ readonly empty?: DeclarativeI18nText;
224
+ };
225
+ }
226
+ | { readonly $coalesce: readonly string[]; readonly fallback?: string | number | boolean };
227
+
228
+ export function isDeclarativeValueExpr(value: unknown): value is DeclarativeValueExpr {
229
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
230
+ const rec = value as Record<string, unknown>;
231
+ return (
232
+ typeof rec.$path === 'string' ||
233
+ typeof rec.$count === 'string' ||
234
+ (rec.$sum !== null && typeof rec.$sum === 'object') ||
235
+ (rec.$format !== undefined && Array.isArray(rec.$args ?? rec.args)) ||
236
+ (rec.$map !== null && typeof rec.$map === 'object') ||
237
+ (rec.$join !== null && typeof rec.$join === 'object') ||
238
+ Array.isArray(rec.$coalesce)
239
+ );
240
+ }
241
+
242
+ export function resolveDataPath(data: unknown, path: string): unknown {
243
+ if (!data || typeof data !== 'object' || !path) return undefined;
244
+ const record = data as Record<string, unknown>;
245
+ if (Object.prototype.hasOwnProperty.call(record, path)) return record[path];
246
+ const segments = path.split('.').filter(Boolean);
247
+ let cursor: unknown = data;
248
+ for (const seg of segments) {
249
+ if (cursor === null || cursor === undefined) return undefined;
250
+ if (Array.isArray(cursor) && seg === 'length') return cursor.length;
251
+ if (typeof cursor !== 'object') return undefined;
252
+ cursor = Object.prototype.hasOwnProperty.call(cursor, seg)
253
+ ? (cursor as Record<string, unknown>)[seg]
254
+ : undefined;
255
+ }
256
+ return cursor;
257
+ }
258
+
259
+ export function evaluateDeclarativeValue(
260
+ exprOrKey: unknown,
261
+ data: unknown,
262
+ locale: DeclarativeUiLocale = 'en',
263
+ ): unknown {
264
+ if (exprOrKey === null || exprOrKey === undefined) return undefined;
265
+ if (typeof exprOrKey === 'string') {
266
+ return resolveDataPath(data, exprOrKey);
267
+ }
268
+ if (!isDeclarativeValueExpr(exprOrKey)) {
269
+ return exprOrKey;
270
+ }
271
+ const rec = exprOrKey as Record<string, unknown>;
272
+ if (typeof rec.$path === 'string') {
273
+ const val = resolveDataPath(data, rec.$path);
274
+ return val !== undefined && val !== null && val !== '' ? val : rec.fallback;
275
+ }
276
+ if (typeof rec.$count === 'string') {
277
+ const target = resolveDataPath(data, rec.$count);
278
+ if (Array.isArray(target)) return target.length;
279
+ if (target && typeof target === 'object') return Object.keys(target).length;
280
+ return typeof target === 'number' ? target : 0;
281
+ }
282
+ if (rec.$sum && typeof rec.$sum === 'object') {
283
+ const sumSpec = rec.$sum as { readonly path?: string; readonly field?: string };
284
+ const list = sumSpec.path ? resolveDataPath(data, sumSpec.path) : undefined;
285
+ if (!Array.isArray(list) || !sumSpec.field) return 0;
286
+ return list.reduce((acc: number, item: unknown) => {
287
+ let raw = resolveDataPath(item, sumSpec.field!);
288
+ if (raw === undefined && sumSpec.field === 'pendingCount') {
289
+ raw = resolveDataPath(item, 'drafts.length');
290
+ }
291
+ const n = Number(raw);
292
+ return acc + (Number.isFinite(n) ? n : 0);
293
+ }, 0);
294
+ }
295
+ const formatArgs = Array.isArray(rec.args)
296
+ ? rec.args
297
+ : Array.isArray(rec.$args)
298
+ ? rec.$args
299
+ : undefined;
300
+ if (rec.$format !== undefined && formatArgs) {
301
+ const template = resolveDeclarativeText(rec.$format as DeclarativeI18nText, locale);
302
+ const args = (formatArgs as readonly string[]).map((p) => resolveDataPath(data, p));
303
+ if (args.length > 0 && args.every((v) => v === undefined || v === null || v === '')) {
304
+ return undefined;
305
+ }
306
+ return template.replace(/\{(\d+)\}/gu, (_m, idx) => {
307
+ const v = args[Number(idx)];
308
+ return v === undefined || v === null ? '' : String(v);
309
+ });
310
+ }
311
+ if (rec.$map && typeof rec.$map === 'object') {
312
+ const mapSpec = rec.$map as {
313
+ readonly path?: string;
314
+ readonly cases?: Readonly<Record<string, DeclarativeI18nText>>;
315
+ readonly default?: DeclarativeI18nText;
316
+ };
317
+ const rawVal = mapSpec.path ? resolveDataPath(data, mapSpec.path) : undefined;
318
+ if (rawVal !== undefined && rawVal !== null && mapSpec.cases) {
319
+ const key = String(rawVal);
320
+ if (Object.prototype.hasOwnProperty.call(mapSpec.cases, key)) {
321
+ return resolveDeclarativeText(mapSpec.cases[key]!, locale);
322
+ }
323
+ }
324
+ if (mapSpec.default !== undefined) return resolveDeclarativeText(mapSpec.default, locale);
325
+ return rawVal;
326
+ }
327
+ if (rec.$join && typeof rec.$join === 'object') {
328
+ const joinSpec = rec.$join as {
329
+ readonly path?: string;
330
+ readonly sep?: string;
331
+ readonly empty?: DeclarativeI18nText;
332
+ };
333
+ const list = joinSpec.path ? resolveDataPath(data, joinSpec.path) : undefined;
334
+ if (!Array.isArray(list) || list.length === 0) {
335
+ return joinSpec.empty !== undefined ? resolveDeclarativeText(joinSpec.empty, locale) : '—';
336
+ }
337
+ return list.map((item) => String(item ?? '')).join(joinSpec.sep ?? ', ');
338
+ }
339
+ if (Array.isArray(rec.$coalesce)) {
340
+ for (const candidate of rec.$coalesce as readonly string[]) {
341
+ const val = resolveDataPath(data, candidate);
342
+ if (val !== undefined && val !== null && val !== '') return val;
343
+ }
344
+ return rec.fallback;
345
+ }
346
+ return undefined;
347
+ }
348
+
349
+ export interface DeclarativePageContext<TData = Record<string, unknown>> {
350
+ readonly pluginId: string;
351
+ readonly locale: DeclarativeUiLocale;
352
+ readonly t: (key: string, ...values: readonly (string | number)[]) => string;
353
+ readonly resource: {
354
+ readonly state: 'loading' | 'ready' | 'empty' | 'error' | 'stale';
355
+ readonly data: TData | undefined;
356
+ readonly error: Error | undefined;
357
+ readonly lastSuccessAt: number | undefined;
358
+ readonly refreshing: boolean;
359
+ readonly refresh: () => Promise<boolean>;
360
+ readonly mutate: (updater: TData | ((previous: TData | undefined) => TData | undefined)) => void;
361
+ };
362
+ readonly call: <TResult = unknown>(
363
+ method: string,
364
+ params?: Readonly<Record<string, unknown>>,
365
+ ) => Promise<TResult>;
366
+ readonly refresh: () => Promise<boolean>;
367
+ readonly notify: (tone: 'info' | 'success' | 'warning' | 'danger', message: string) => void;
368
+ }
369
+
370
+ export interface DeclarativeBadgeSpec<TData = Record<string, unknown>> {
371
+ readonly key?: string;
372
+ readonly label:
373
+ | DeclarativeI18nText
374
+ | DeclarativeValueExpr
375
+ | ((data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable);
376
+ readonly tone?:
377
+ | DeclarativeBadgeTone
378
+ | DeclarativeValueExpr
379
+ | ((data: TData) => DeclarativeBadgeTone);
380
+ }
381
+
382
+ export interface DeclarativeStatSpec<TData = Record<string, unknown>> {
383
+ readonly key?: string;
384
+ readonly label: DeclarativeI18nText;
385
+ readonly value:
386
+ | (keyof TData & string)
387
+ | string
388
+ | DeclarativeValueExpr
389
+ | ((data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable);
390
+ readonly unit?: DeclarativeI18nText;
391
+ readonly icon?: DeclarativeRenderable;
392
+ readonly image?: string;
393
+ readonly watermark?: DeclarativeRenderable | string;
394
+ readonly tone?: DeclarativeBadgeTone | 'primary';
395
+ readonly progress?: number | string | DeclarativeValueExpr;
396
+ readonly sparkline?: string;
397
+ readonly trend?: {
398
+ readonly value: DeclarativeI18nText | DeclarativeValueExpr;
399
+ readonly direction?: 'up' | 'down' | 'flat';
400
+ };
401
+ readonly hint?:
402
+ | DeclarativeI18nText
403
+ | DeclarativeValueExpr
404
+ | ((data: TData) => DeclarativeRenderable);
405
+ readonly badge?: {
406
+ readonly label:
407
+ | DeclarativeI18nText
408
+ | DeclarativeValueExpr
409
+ | ((data: TData) => DeclarativeRenderable);
410
+ readonly tone?:
411
+ | DeclarativeBadgeTone
412
+ | DeclarativeValueExpr
413
+ | ((data: TData) => DeclarativeBadgeTone);
414
+ };
415
+ }
416
+
417
+ export interface DeclarativeActionFieldSpec {
418
+ readonly key: string;
419
+ readonly label: DeclarativeI18nText;
420
+ readonly type?: 'text' | 'password' | 'number' | 'textarea' | 'select' | 'switch' | 'radio' | 'checkbox-group' | 'segmented';
421
+ readonly options?: readonly {
422
+ readonly value: string;
423
+ readonly label: DeclarativeI18nText;
424
+ readonly description?: DeclarativeI18nText;
425
+ readonly icon?: DeclarativeRenderable;
426
+ readonly badge?: DeclarativeRenderable;
427
+ readonly disabled?: boolean;
428
+ }[];
429
+ readonly variant?: 'default' | 'card' | 'button';
430
+ readonly direction?: 'column' | 'row' | 'grid';
431
+ readonly hint?: DeclarativeI18nText;
432
+ readonly rows?: number;
433
+ readonly placeholder?: string;
434
+ readonly required?: boolean;
435
+ readonly defaultValue?: string;
436
+ readonly secret?: boolean;
437
+ }
438
+
439
+ export interface DeclarativeActionSpec<TData = Record<string, unknown>> {
440
+ /** RPC action method name (`plugin.<pluginId>.<name>`). */
441
+ readonly name: string;
442
+ readonly label: DeclarativeI18nText;
443
+ readonly description?: DeclarativeI18nText;
444
+ readonly icon?: DeclarativeRenderable;
445
+ readonly variant?: DeclarativeButtonVariant;
446
+ readonly confirm?: DeclarativeI18nText;
447
+ readonly confirmLabel?: DeclarativeI18nText;
448
+ readonly fields?: readonly DeclarativeActionFieldSpec[];
449
+ readonly params?:
450
+ | Readonly<Record<string, unknown>>
451
+ | ((
452
+ data: TData | undefined,
453
+ values: Readonly<Record<string, string>>,
454
+ ) => Readonly<Record<string, unknown>>);
455
+ readonly disabled?: boolean | ((data: TData | undefined) => boolean);
456
+ readonly successMessage?: DeclarativeI18nText;
457
+ }
458
+
459
+ export type DeclarativeColumnType =
460
+ | 'auto'
461
+ | 'text'
462
+ | 'code'
463
+ | 'badge'
464
+ | 'boolean'
465
+ | 'link'
466
+ | 'datetime'
467
+ | 'number'
468
+ | 'progress'
469
+ | 'tags'
470
+ | 'json';
471
+
472
+ export interface DeclarativeColumnSpec<
473
+ TRow = Record<string, unknown>,
474
+ TData = Record<string, unknown>,
475
+ > {
476
+ readonly key: keyof TRow & string;
477
+ readonly label: DeclarativeI18nText;
478
+ readonly icon?: DeclarativeRenderable;
479
+ readonly type?: DeclarativeColumnType;
480
+ readonly align?: 'left' | 'center' | 'right';
481
+ readonly fixed?: 'left' | 'right';
482
+ readonly sortable?: boolean;
483
+ readonly copyable?: boolean;
484
+ readonly width?: string | number;
485
+ readonly toneMap?: Readonly<Record<string, DeclarativeBadgeTone>>;
486
+ readonly render?: (
487
+ value: unknown,
488
+ row: TRow,
489
+ ctx: DeclarativePageContext<TData>,
490
+ ) => DeclarativeRenderable;
491
+ }
492
+
493
+ export interface DeclarativeBatchActionSpec<
494
+ TRow = Record<string, unknown>,
495
+ TData = Record<string, unknown>,
496
+ > {
497
+ readonly name: string;
498
+ readonly label: DeclarativeI18nText;
499
+ readonly icon?: DeclarativeRenderable;
500
+ readonly variant?: DeclarativeButtonVariant;
501
+ readonly confirm?: DeclarativeI18nText;
502
+ readonly confirmLabel?: DeclarativeI18nText;
503
+ readonly idsParamKey?: string;
504
+ readonly params?: (
505
+ selectedRows: readonly TRow[],
506
+ selectedKeys: readonly string[],
507
+ data: TData | undefined,
508
+ ) => Readonly<Record<string, unknown>>;
509
+ readonly onExecute?: (
510
+ selectedRows: readonly TRow[],
511
+ selectedKeys: readonly string[],
512
+ ctx: DeclarativePageContext<TData>,
513
+ ) => unknown;
514
+ readonly successMessage?: DeclarativeI18nText;
515
+ }
516
+
517
+ export interface DeclarativeRowActionSpec<
518
+ TRow = Record<string, unknown>,
519
+ TData = Record<string, unknown>,
520
+ > {
521
+ readonly name: string;
522
+ readonly label: DeclarativeI18nText;
523
+ readonly icon?: DeclarativeRenderable;
524
+ readonly variant?: DeclarativeButtonVariant;
525
+ readonly confirm?: DeclarativeI18nText;
526
+ readonly confirmLabel?: DeclarativeI18nText;
527
+ readonly idParamKey?: string;
528
+ readonly params?: (
529
+ row: TRow,
530
+ rowKey: string,
531
+ data: TData | undefined,
532
+ ) => Readonly<Record<string, unknown>>;
533
+ readonly onExecute?: (
534
+ row: TRow,
535
+ rowKey: string,
536
+ ctx: DeclarativePageContext<TData>,
537
+ ) => unknown;
538
+ readonly disabled?: boolean | ((row: TRow) => boolean);
539
+ readonly successMessage?: DeclarativeI18nText;
540
+ }
541
+
542
+ export interface DeclarativeSectionSpec<
543
+ TData = Record<string, unknown>,
544
+ TRow = Record<string, unknown>,
545
+ > {
546
+ readonly id?: string;
547
+ readonly title?: DeclarativeI18nText;
548
+ readonly description?: DeclarativeI18nText;
549
+ readonly tab?: DeclarativeI18nText;
550
+ readonly layout?: 'table' | 'cards' | 'kv' | 'timeline' | 'json';
551
+ readonly columnsCount?: 1 | 2 | 3;
552
+ readonly collapsible?: boolean;
553
+ readonly defaultCollapsed?: boolean;
554
+ readonly emptyText?: DeclarativeI18nText;
555
+ readonly rowKey?: keyof TRow & string;
556
+ readonly selectable?: boolean;
557
+ readonly batchActions?: readonly DeclarativeBatchActionSpec<TRow, TData>[];
558
+ readonly rowActions?: readonly DeclarativeRowActionSpec<TRow, TData>[];
559
+ readonly renderExpandedRow?: (
560
+ row: TRow,
561
+ index: number,
562
+ ctx: DeclarativePageContext<TData>,
563
+ ) => DeclarativeRenderable;
564
+ readonly responsiveStack?: boolean;
565
+ /** Extract rows for a declarative table or list. */
566
+ readonly items?: (keyof TData & string) | ((data: TData) => readonly TRow[]);
567
+ /** Columns for a declarative table/card list when `items` is provided. */
568
+ readonly columns?: readonly DeclarativeColumnSpec<TRow, TData>[];
569
+ /** Custom row renderer when `items` is provided. */
570
+ readonly renderItem?: (
571
+ item: TRow,
572
+ index: number,
573
+ ctx: DeclarativePageContext<TData>,
574
+ ) => DeclarativeRenderable;
575
+ /** Key-value description list extractor (`<dl className="zk-dl">`). */
576
+ readonly entries?:
577
+ | readonly {
578
+ readonly label: DeclarativeI18nText;
579
+ readonly value?: DeclarativeRenderable | DeclarativeValueExpr;
580
+ readonly dataKey?: string;
581
+ }[]
582
+ | ((
583
+ data: TData,
584
+ ctx: DeclarativePageContext<TData>,
585
+ ) =>
586
+ | Readonly<Record<string, DeclarativeRenderable>>
587
+ | readonly { readonly label: DeclarativeRenderable; readonly value: DeclarativeRenderable }[]);
588
+ /** Custom section body renderer. */
589
+ readonly render?: (data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable;
590
+ }
591
+
592
+ export interface DeclarativePageSpec<TData = Record<string, unknown>> {
593
+ /** Explicit plugin ID (`root/<name>`); auto-resolved from page props or route when omitted. */
594
+ readonly pluginId?: string;
595
+ readonly title: DeclarativeI18nText;
596
+ readonly description?: DeclarativeI18nText;
597
+ readonly mark?: DeclarativeRenderable;
598
+ /** Status RPC method name; defaults to `'status'`. */
599
+ readonly statusMethod?: string;
600
+ /** Optional polling interval in ms; defaults to 10_000. Pass `0` to disable polling. */
601
+ readonly pollMs?: number;
602
+ readonly dictionary?: Readonly<Record<string, string>>;
603
+ readonly isEmpty?: (data: TData) => boolean;
604
+ readonly emptyTitle?: DeclarativeI18nText;
605
+ readonly emptyDescription?: DeclarativeI18nText;
606
+ readonly badges?:
607
+ | readonly DeclarativeBadgeSpec<TData>[]
608
+ | ((
609
+ data: TData,
610
+ ctx: DeclarativePageContext<TData>,
611
+ ) => readonly DeclarativeBadgeSpec<TData>[]);
612
+ readonly stats?:
613
+ | readonly DeclarativeStatSpec<TData>[]
614
+ | ((
615
+ data: TData,
616
+ ctx: DeclarativePageContext<TData>,
617
+ ) => readonly DeclarativeStatSpec<TData>[]);
618
+ readonly actions?: readonly DeclarativeActionSpec<TData>[];
619
+ readonly sections?: readonly DeclarativeSectionSpec<TData, any>[];
620
+ readonly render?: (data: TData, ctx: DeclarativePageContext<TData>) => DeclarativeRenderable;
621
+ readonly footnote?: DeclarativeI18nText;
622
+ }
623
+
624
+ export interface DeclarativePageComponentProps {
625
+ readonly pluginId?: string;
626
+ readonly owner?: string;
627
+ readonly localName?: string;
628
+ readonly route?: string;
629
+ readonly title?: string;
630
+ readonly [key: string]: unknown;
631
+ }
632
+
633
+ export type ConsolePageBlueprintSection =
634
+ | {
635
+ readonly type: 'stats';
636
+ readonly id: string;
637
+ readonly title: string;
638
+ readonly items: readonly {
639
+ readonly key: string;
640
+ readonly label: string;
641
+ readonly value?: unknown;
642
+ readonly suffix?: string;
643
+ readonly dataKey?: string;
644
+ readonly expr?: DeclarativeValueExpr;
645
+ }[];
646
+ }
647
+ | {
648
+ readonly type: 'table';
649
+ readonly id: string;
650
+ readonly title: string;
651
+ readonly dataKey?: string;
652
+ readonly rowKey: string;
653
+ readonly columns: readonly { readonly key: string; readonly label: string }[];
654
+ }
655
+ | {
656
+ readonly type: 'entries';
657
+ readonly id: string;
658
+ readonly title: string;
659
+ readonly entries?: readonly {
660
+ readonly label: string;
661
+ readonly value: string;
662
+ readonly dataKey?: string;
663
+ readonly expr?: DeclarativeValueExpr;
664
+ }[];
665
+ }
666
+ | {
667
+ readonly type: 'actions';
668
+ readonly id: string;
669
+ readonly title: string;
670
+ readonly items: readonly {
671
+ readonly label: string;
672
+ readonly action: string;
673
+ readonly name?: string;
674
+ readonly description?: string;
675
+ readonly variant?: DeclarativeButtonVariant;
676
+ readonly confirm?: DeclarativeI18nText;
677
+ readonly confirmLabel?: DeclarativeI18nText;
678
+ readonly fields?: readonly DeclarativeActionFieldSpec[];
679
+ readonly params?: DeclarativeActionSpec<any>['params'];
680
+ readonly disabled?: DeclarativeActionSpec<any>['disabled'];
681
+ readonly successMessage?: DeclarativeI18nText;
682
+ }[];
683
+ }
684
+ | {
685
+ readonly type: 'markdown';
686
+ readonly id: string;
687
+ readonly title?: string;
688
+ readonly content: string;
689
+ }
690
+ | {
691
+ readonly type: 'custom';
692
+ readonly id: string;
693
+ readonly title?: string;
694
+ };
695
+
696
+ export interface ConsolePageBlueprint<TData = Record<string, unknown>> {
697
+ readonly kind: 'zhin.console.page-blueprint';
698
+ readonly version: 1;
699
+ readonly title: string;
700
+ readonly titleI18n?: Readonly<Partial<Record<'zh-CN' | 'en', string>>>;
701
+ readonly description?: string;
702
+ readonly dataSource: {
703
+ readonly action: string;
704
+ };
705
+ readonly sections: readonly ConsolePageBlueprintSection[];
706
+ readonly spec?: DeclarativePageSpec<TData>;
707
+ readonly reviewSpec?: CommentReviewBlueprintSpec<any, any>;
708
+ }
709
+
710
+ export interface CommentReviewDraftBase {
711
+ readonly id: string;
712
+ readonly url: string;
713
+ readonly message: string;
714
+ readonly status: 'pending' | 'sending';
715
+ readonly interrupted: boolean;
716
+ readonly createdAt: number;
717
+ readonly updatedAt?: number;
718
+ readonly author?: string;
719
+ readonly original?: string;
720
+ }
721
+
722
+ export interface CommentReviewEndpointBase<D extends CommentReviewDraftBase = CommentReviewDraftBase> {
723
+ readonly id: string;
724
+ readonly sendMode: 'review' | 'off';
725
+ readonly persistent: boolean;
726
+ readonly circuit: { readonly code: number } | null;
727
+ readonly login: { readonly state: 'none' | 'ok' | 'expired' };
728
+ readonly pendingCount: number;
729
+ readonly drafts: readonly D[];
730
+ }
731
+
732
+ export interface CommentReviewBlueprintSpec<
733
+ E extends CommentReviewEndpointBase<any> = CommentReviewEndpointBase<CommentReviewDraftBase>,
734
+ D extends CommentReviewDraftBase = CommentReviewDraftBase,
735
+ > {
736
+ readonly adapter: string;
737
+ readonly platform: { readonly zh: string; readonly en: string };
738
+ readonly mark: string;
739
+ readonly resource: { readonly zh: string; readonly en: string };
740
+ readonly dictionary?: Readonly<Record<string, string>>;
741
+ readonly openLabel?: string;
742
+ readonly account?: (endpoint: E) => { readonly id?: string; readonly name?: string };
743
+ readonly draftResource?: (
744
+ draft: D,
745
+ t: (key: string, ...values: readonly (string | number)[]) => string,
746
+ ) => string;
747
+ readonly loginHint?: (
748
+ endpoint: E,
749
+ t: (key: string, ...values: readonly (string | number)[]) => string,
750
+ ) => string | undefined;
751
+ readonly isLoginPending?: (endpoint: E) => boolean;
752
+ readonly loginMode?: 'qr' | 'cookie-check';
753
+ readonly resourcesKey?: string;
754
+ readonly pollMs?: number;
755
+ readonly pendingPollMs?: number;
756
+ }
757
+
758
+ export interface ConsoleAdapterPageBlueprint {
759
+ readonly kind: 'zhin.console.adapter-page';
760
+ readonly version: 1;
761
+ readonly adapterKey: string;
762
+ readonly dataSource: {
763
+ readonly action: 'status';
764
+ };
765
+ }
766
+
767
+ export type BlueprintPageComponent<TData = Record<string, unknown>> = ((
768
+ props?: DeclarativePageComponentProps,
769
+ ) => ConsolePageBlueprint<TData>) &
770
+ Readonly<ConsolePageBlueprint<TData>>;
771
+
772
+ export type AdapterPageComponent = ((
773
+ props?: DeclarativePageComponentProps,
774
+ ) => ConsoleAdapterPageBlueprint) &
775
+ Readonly<ConsoleAdapterPageBlueprint>;
776
+
777
+ export function resolveDeclarativeText(
778
+ text: DeclarativeI18nText | undefined,
779
+ preferredLocale: 'en' | 'zh-CN' = 'en',
780
+ ): string {
781
+ if (!text) return '';
782
+ if (typeof text === 'string') return text;
783
+ if (preferredLocale === 'en') {
784
+ return text.en ?? text['zh-CN'] ?? text.zh;
785
+ }
786
+ return text['zh-CN'] ?? text.zh ?? text.en ?? '';
787
+ }
788
+
789
+ export function buildBlueprintFromSpec<TData = Record<string, unknown>>(
790
+ input: DeclarativePageSpec<TData> | ConsolePageBlueprint<TData>,
791
+ ): Readonly<ConsolePageBlueprint<TData>> {
792
+ if ((input as ConsolePageBlueprint<TData>)?.kind === 'zhin.console.page-blueprint') {
793
+ const bp = input as ConsolePageBlueprint<TData>;
794
+ return Object.freeze({
795
+ kind: 'zhin.console.page-blueprint' as const,
796
+ version: 1 as const,
797
+ title: bp.title,
798
+ ...(bp.titleI18n ? { titleI18n: Object.freeze({ ...bp.titleI18n }) } : {}),
799
+ ...(bp.description !== undefined ? { description: bp.description } : {}),
800
+ dataSource: Object.freeze({ action: bp.dataSource?.action ?? 'status' }),
801
+ sections: Object.freeze([...(bp.sections ?? [])]),
802
+ ...(bp.spec !== undefined ? { spec: bp.spec } : {}),
803
+ ...(bp.reviewSpec !== undefined ? { reviewSpec: bp.reviewSpec } : {}),
804
+ });
805
+ }
806
+
807
+ const spec = input as DeclarativePageSpec<TData>;
808
+ const title = resolveDeclarativeText(spec.title, 'en');
809
+ const titleI18n =
810
+ typeof spec.title === 'object' && spec.title !== null
811
+ ? {
812
+ 'zh-CN': spec.title['zh-CN'] ?? spec.title.zh,
813
+ ...(spec.title.en ? { en: spec.title.en } : {}),
814
+ }
815
+ : undefined;
816
+ const description = spec.description ? resolveDeclarativeText(spec.description, 'en') : undefined;
817
+ const dataSource = Object.freeze({ action: spec.statusMethod ?? 'status' });
818
+ const sections: ConsolePageBlueprintSection[] = [];
819
+
820
+ if (Array.isArray(spec.stats) && spec.stats.length > 0) {
821
+ sections.push(
822
+ Object.freeze({
823
+ type: 'stats',
824
+ id: 'runtime-stats',
825
+ title: 'Runtime Stats',
826
+ items: Object.freeze(
827
+ spec.stats.map((stat, idx) =>
828
+ Object.freeze({
829
+ key: stat.key ?? (typeof stat.value === 'string' ? stat.value : `stat-${idx}`),
830
+ label: resolveDeclarativeText(stat.label, 'en'),
831
+ ...(typeof stat.value === 'string' ? { dataKey: stat.value } : {}),
832
+ ...(isDeclarativeValueExpr(stat.value) ? { expr: stat.value } : {}),
833
+ }),
834
+ ),
835
+ ),
836
+ }),
837
+ );
838
+ }
839
+
840
+ for (const [idx, sec] of (spec.sections ?? []).entries()) {
841
+ const id = sec.id ?? `section-${idx}`;
842
+ const secTitle = resolveDeclarativeText(sec.title, 'en');
843
+ if (sec.columns !== undefined || sec.items !== undefined) {
844
+ const preferredRowKey = sec.columns?.find(
845
+ (c) => c.key === 'id' || c.key === 'key' || c.key === 'ownerKey',
846
+ )?.key ?? 'id';
847
+ sections.push(
848
+ Object.freeze({
849
+ type: 'table',
850
+ id,
851
+ title: secTitle,
852
+ ...(typeof sec.items === 'string' ? { dataKey: sec.items } : {}),
853
+ rowKey: preferredRowKey,
854
+ columns: Object.freeze(
855
+ (sec.columns ?? []).map((col) =>
856
+ Object.freeze({
857
+ key: col.key,
858
+ label: resolveDeclarativeText(col.label, 'en'),
859
+ }),
860
+ ),
861
+ ),
862
+ }),
863
+ );
864
+ } else if (sec.entries !== undefined) {
865
+ sections.push(
866
+ Object.freeze({
867
+ type: 'entries',
868
+ id,
869
+ title: secTitle,
870
+ ...(Array.isArray(sec.entries)
871
+ ? {
872
+ entries: Object.freeze(
873
+ sec.entries.map((e) => {
874
+ const inferredDataKey =
875
+ e.dataKey ??
876
+ (isDeclarativeValueExpr(e.value) &&
877
+ typeof (e.value as { $path?: unknown }).$path === 'string'
878
+ ? (e.value as { $path: string }).$path
879
+ : undefined);
880
+ return Object.freeze({
881
+ label: resolveDeclarativeText(e.label, 'en'),
882
+ value: isDeclarativeValueExpr(e.value) ? '' : String(e.value ?? ''),
883
+ ...(inferredDataKey ? { dataKey: inferredDataKey } : {}),
884
+ ...(isDeclarativeValueExpr(e.value) ? { expr: e.value } : {}),
885
+ });
886
+ }),
887
+ ),
888
+ }
889
+ : {}),
890
+ }),
891
+ );
892
+ } else {
893
+ sections.push(
894
+ Object.freeze({
895
+ type: 'custom',
896
+ id,
897
+ ...(secTitle ? { title: secTitle } : {}),
898
+ }),
899
+ );
900
+ }
901
+ }
902
+
903
+ if (Array.isArray(spec.actions) && spec.actions.length > 0) {
904
+ sections.push(
905
+ Object.freeze({
906
+ type: 'actions',
907
+ id: 'actions',
908
+ title: 'Actions',
909
+ items: Object.freeze(
910
+ spec.actions.map((act) =>
911
+ Object.freeze({
912
+ label: resolveDeclarativeText(act.label, 'en'),
913
+ action: act.name,
914
+ name: act.name,
915
+ ...(act.description
916
+ ? { description: resolveDeclarativeText(act.description, 'en') }
917
+ : {}),
918
+ ...(act.variant ? { variant: act.variant } : {}),
919
+ ...(act.confirm !== undefined ? { confirm: act.confirm } : {}),
920
+ ...(act.confirmLabel !== undefined ? { confirmLabel: act.confirmLabel } : {}),
921
+ ...(act.fields !== undefined ? { fields: act.fields } : {}),
922
+ ...(act.params !== undefined ? { params: act.params } : {}),
923
+ ...(act.disabled !== undefined ? { disabled: act.disabled } : {}),
924
+ ...(act.successMessage !== undefined ? { successMessage: act.successMessage } : {}),
925
+ }),
926
+ ),
927
+ ),
928
+ }),
929
+ );
930
+ }
931
+
932
+ const rawReviewSpec = (spec as unknown as { readonly reviewSpec?: CommentReviewBlueprintSpec<any, any> }).reviewSpec;
933
+
934
+ return Object.freeze({
935
+ kind: 'zhin.console.page-blueprint',
936
+ version: 1,
937
+ title,
938
+ ...(titleI18n ? { titleI18n: Object.freeze(titleI18n) } : {}),
939
+ ...(description !== undefined ? { description } : {}),
940
+ dataSource,
941
+ sections: Object.freeze(sections),
942
+ spec,
943
+ ...(rawReviewSpec !== undefined ? { reviewSpec: rawReviewSpec } : {}),
944
+ });
945
+ }
946
+
947
+ export function definePageBlueprint<TData = Record<string, unknown>>(
948
+ spec: DeclarativePageSpec<TData> | ConsolePageBlueprint<TData>,
949
+ ): BlueprintPageComponent<TData> {
950
+ const blueprint = buildBlueprintFromSpec(spec);
951
+ function BlueprintPage(_props?: DeclarativePageComponentProps): ConsolePageBlueprint<TData> {
952
+ return blueprint;
953
+ }
954
+ return Object.freeze(Object.assign(BlueprintPage, blueprint));
955
+ }
956
+
957
+ export const createDeclarativePage = definePageBlueprint;
958
+
959
+ export function defineAdapterPage(adapterKey: string): AdapterPageComponent {
960
+ const validKey = optionalString(adapterKey, 'Adapter page adapterKey');
961
+ if (!validKey) throw new TypeError('Adapter page adapterKey must be a non-empty string');
962
+ const blueprint: ConsoleAdapterPageBlueprint = Object.freeze({
963
+ kind: 'zhin.console.adapter-page',
964
+ version: 1,
965
+ adapterKey: validKey,
966
+ dataSource: Object.freeze({ action: 'status' as const }),
967
+ });
968
+ function AdapterConsoleRoute(_props?: DeclarativePageComponentProps): ConsoleAdapterPageBlueprint {
969
+ return blueprint;
970
+ }
971
+ return Object.freeze(Object.assign(AdapterConsoleRoute, blueprint));
972
+ }
973
+
974
+ export const createAdapterConsolePage = defineAdapterPage;
975
+
976
+ export function defineCommentReviewPage<
977
+ E extends CommentReviewEndpointBase<any> = CommentReviewEndpointBase<CommentReviewDraftBase>,
978
+ D extends CommentReviewDraftBase = CommentReviewDraftBase,
979
+ >(
980
+ reviewSpec: CommentReviewBlueprintSpec<E, D>,
981
+ ): BlueprintPageComponent<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }> {
982
+ const zhTitle = `${reviewSpec.platform.zh}评论审批`;
983
+ const enTitle = `${reviewSpec.platform.en} comment review`;
984
+ const loginActions: DeclarativeActionSpec<any>[] =
985
+ reviewSpec.loginMode === 'cookie-check'
986
+ ? [{ name: 'login-check', label: { zh: '重新检查登录', en: 'Check login again' } }]
987
+ : [
988
+ { name: 'login', label: { zh: '扫码登录', en: 'Sign in with QR code' }, variant: 'primary' },
989
+ { name: 'login-cancel', label: { zh: '取消扫码', en: 'Cancel QR login' }, variant: 'ghost' },
990
+ { name: 'logout', label: { zh: '退出登录', en: 'Sign out' }, variant: 'secondary' },
991
+ ];
992
+ const blueprint = buildBlueprintFromSpec<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }>({
993
+ pluginId: reviewSpec.adapter,
994
+ title: { zh: zhTitle, 'zh-CN': zhTitle, en: enTitle },
995
+ mark: reviewSpec.mark,
996
+ statusMethod: 'status',
997
+ pollMs: reviewSpec.pollMs ?? 10_000,
998
+ ...(reviewSpec.dictionary ? { dictionary: reviewSpec.dictionary } : {}),
999
+ stats: [
1000
+ {
1001
+ key: 'endpoints',
1002
+ label: { zh: '账号数', en: 'Accounts' },
1003
+ value: { $count: 'endpoints' },
1004
+ },
1005
+ {
1006
+ key: 'pendingDrafts',
1007
+ label: { zh: '待审草稿', en: 'Pending drafts' },
1008
+ value: { $sum: { path: 'endpoints', field: 'pendingCount' } },
1009
+ },
1010
+ ],
1011
+ sections: [
1012
+ {
1013
+ id: 'endpoints',
1014
+ title: { zh: '评论账号与待审草稿', en: 'Accounts & Pending Drafts' },
1015
+ items: 'endpoints',
1016
+ columns: [
1017
+ { key: 'id', label: { zh: '账号', en: 'Account' } },
1018
+ { key: 'sendMode', label: { zh: '发送模式', en: 'Send Mode' } },
1019
+ { key: 'pendingCount', label: { zh: '待审数', en: 'Pending' } },
1020
+ ],
1021
+ },
1022
+ ],
1023
+ actions: [
1024
+ ...loginActions,
1025
+ {
1026
+ name: 'edit',
1027
+ label: { zh: '修改草稿', en: 'Edit draft' },
1028
+ fields: [
1029
+ { key: 'id', label: { zh: '草稿 ID', en: 'Draft ID' }, required: true },
1030
+ { key: 'message', label: { zh: '回复内容', en: 'Reply content' }, required: true },
1031
+ ],
1032
+ },
1033
+ {
1034
+ name: 'send',
1035
+ label: { zh: '发送草稿', en: 'Send draft' },
1036
+ variant: 'primary',
1037
+ fields: [{ key: 'id', label: { zh: '草稿 ID', en: 'Draft ID' }, required: true }],
1038
+ },
1039
+ {
1040
+ name: 'drop',
1041
+ label: { zh: '丢弃草稿', en: 'Discard draft' },
1042
+ variant: 'danger',
1043
+ confirm: { zh: '确认丢弃该草稿?', en: 'Discard this draft?' },
1044
+ fields: [{ key: 'id', label: { zh: '草稿 ID', en: 'Draft ID' }, required: true }],
1045
+ },
1046
+ ],
1047
+ });
1048
+ const enriched: ConsolePageBlueprint<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }> =
1049
+ Object.freeze({
1050
+ ...blueprint,
1051
+ reviewSpec,
1052
+ });
1053
+ function CommentReviewBlueprintPage(
1054
+ _props?: DeclarativePageComponentProps,
1055
+ ): ConsolePageBlueprint<{ readonly endpoints?: readonly E[]; readonly updatedAt?: number }> {
1056
+ return enriched;
1057
+ }
1058
+ return Object.freeze(Object.assign(CommentReviewBlueprintPage, enriched));
1059
+ }
1060
+
1061
+ export const createCommentReviewPage = defineCommentReviewPage;
1062
+
1063
+ // ── Multi-Surface Blueprint Projection (IM Card & CLI TUI) ─────────────────
1064
+
1065
+ export interface BlueprintProjectionOptions {
1066
+ readonly locale?: DeclarativeUiLocale;
1067
+ readonly pluginId?: string;
1068
+ readonly maxRows?: number;
1069
+ }
1070
+
1071
+ export interface BlueprintImStatItem {
1072
+ readonly key: string;
1073
+ readonly label: string;
1074
+ readonly value: string;
1075
+ readonly hint?: string;
1076
+ readonly badge?: string;
1077
+ }
1078
+
1079
+ export interface BlueprintImTableSection {
1080
+ readonly id: string;
1081
+ readonly title: string;
1082
+ readonly columns: readonly { readonly key: string; readonly label: string }[];
1083
+ readonly rows: readonly (readonly string[])[];
1084
+ readonly totalRows: number;
1085
+ readonly emptyText?: string;
1086
+ }
1087
+
1088
+ export interface BlueprintImEntriesSection {
1089
+ readonly id: string;
1090
+ readonly title: string;
1091
+ readonly items: readonly { readonly label: string; readonly value: string }[];
1092
+ }
1093
+
1094
+ export interface BlueprintImActionItem {
1095
+ readonly name: string;
1096
+ readonly label: string;
1097
+ readonly rpcMethod: string;
1098
+ readonly description?: string;
1099
+ readonly variant: DeclarativeButtonVariant;
1100
+ readonly disabled: boolean;
1101
+ }
1102
+
1103
+ export interface BlueprintImSegment {
1104
+ readonly type: 'card' | 'markdown' | 'button' | 'text';
1105
+ readonly data: Readonly<Record<string, unknown>>;
1106
+ }
1107
+
1108
+ export interface BlueprintImCardProjection {
1109
+ readonly kind: 'zhin.im.blueprint-card';
1110
+ readonly pluginId: string;
1111
+ readonly title: string;
1112
+ readonly description?: string;
1113
+ readonly stats: readonly BlueprintImStatItem[];
1114
+ readonly tables: readonly BlueprintImTableSection[];
1115
+ readonly entries: readonly BlueprintImEntriesSection[];
1116
+ readonly actions: readonly BlueprintImActionItem[];
1117
+ readonly markdown: string;
1118
+ readonly segments: readonly BlueprintImSegment[];
1119
+ }
1120
+
1121
+ function createProjectionContext<TData = Record<string, unknown>>(
1122
+ data: TData | undefined,
1123
+ locale: DeclarativeUiLocale,
1124
+ pluginId: string,
1125
+ dictionary?: Readonly<Record<string, string>>,
1126
+ ): DeclarativePageContext<TData> {
1127
+ const t = (key: string, ...values: readonly (string | number)[]): string => {
1128
+ const template = locale === 'en' && dictionary?.[key] ? dictionary[key] : key;
1129
+ return template.replace(/\{(\d+)\}/gu, (_m, idx) => String(values[Number(idx)] ?? ''));
1130
+ };
1131
+ return {
1132
+ pluginId,
1133
+ locale,
1134
+ t,
1135
+ resource: {
1136
+ state: data === undefined ? 'empty' : 'ready',
1137
+ data,
1138
+ error: undefined,
1139
+ lastSuccessAt: Date.now(),
1140
+ refreshing: false,
1141
+ refresh: async () => true,
1142
+ mutate: () => undefined,
1143
+ },
1144
+ call: async () => undefined as never,
1145
+ refresh: async () => true,
1146
+ notify: () => undefined,
1147
+ };
1148
+ }
1149
+
1150
+ function formatRenderableValue(value: unknown): string {
1151
+ if (value === null || value === undefined) return '—';
1152
+ if (typeof value === 'string') return value || '—';
1153
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
1154
+ if (Array.isArray(value)) return value.map((item) => formatRenderableValue(item)).join(', ');
1155
+ if (typeof value === 'object') {
1156
+ const record = value as Record<string, unknown>;
1157
+ if (typeof record.label === 'string') return record.label;
1158
+ if (typeof record.text === 'string') return record.text;
1159
+ try {
1160
+ return JSON.stringify(value);
1161
+ } catch {
1162
+ return String(value);
1163
+ }
1164
+ }
1165
+ return String(value);
1166
+ }
1167
+
1168
+ /**
1169
+ * Projects any Server-Driven Console Blueprint (`definePageBlueprint`, `defineAdapterPage`,
1170
+ * `defineCommentReviewPage`, or `DeclarativePageSpec`) + runtime status payload into a
1171
+ * structured IM Card / Markdown / Segment payload ready for `Message.$reply` or `Adapter.sendMessage`.
1172
+ */
1173
+ export function projectBlueprintToImCard<TData = Record<string, unknown>>(
1174
+ input:
1175
+ | ConsolePageBlueprint<TData>
1176
+ | ConsoleAdapterPageBlueprint
1177
+ | DeclarativePageSpec<TData>,
1178
+ data?: TData,
1179
+ options: BlueprintProjectionOptions = {},
1180
+ ): Readonly<BlueprintImCardProjection> {
1181
+ const locale: DeclarativeUiLocale = options.locale ?? 'zh-CN';
1182
+ const maxRows = Math.max(1, options.maxRows ?? 10);
1183
+ const recordData = (data && typeof data === 'object' ? data : {}) as Record<string, unknown>;
1184
+
1185
+ if ((input as ConsoleAdapterPageBlueprint)?.kind === 'zhin.console.adapter-page') {
1186
+ const adapterBp = input as ConsoleAdapterPageBlueprint;
1187
+ const pluginId = options.pluginId ?? adapterBp.adapterKey;
1188
+ const title =
1189
+ locale === 'zh-CN'
1190
+ ? `${adapterBp.adapterKey} 适配器状态`
1191
+ : `${adapterBp.adapterKey} Adapter Status`;
1192
+ const bots = Array.isArray(recordData.bots)
1193
+ ? recordData.bots
1194
+ : Array.isArray(recordData.endpoints)
1195
+ ? recordData.endpoints
1196
+ : [];
1197
+ const onlineCount = bots.filter(
1198
+ (b: any) => b?.online === true || b?.connected === true || b?.status === 'online',
1199
+ ).length;
1200
+ const stats: BlueprintImStatItem[] = [
1201
+ {
1202
+ key: 'adapter',
1203
+ label: locale === 'zh-CN' ? '适配器' : 'Adapter',
1204
+ value: adapterBp.adapterKey,
1205
+ },
1206
+ {
1207
+ key: 'endpoints',
1208
+ label: locale === 'zh-CN' ? '实例数' : 'Instances',
1209
+ value: String(bots.length),
1210
+ },
1211
+ {
1212
+ key: 'online',
1213
+ label: locale === 'zh-CN' ? '在线数' : 'Online',
1214
+ value: String(onlineCount),
1215
+ },
1216
+ ];
1217
+ const columns = [
1218
+ { key: 'id', label: locale === 'zh-CN' ? '账号/端点' : 'Endpoint' },
1219
+ { key: 'status', label: locale === 'zh-CN' ? '状态' : 'Status' },
1220
+ ];
1221
+ const rows = bots.slice(0, maxRows).map((b: any, i: number) => [
1222
+ String(b?.id ?? b?.selfId ?? b?.name ?? `#${i + 1}`),
1223
+ String(
1224
+ b?.status ??
1225
+ (b?.online === true || b?.connected === true
1226
+ ? locale === 'zh-CN'
1227
+ ? '在线'
1228
+ : 'online'
1229
+ : locale === 'zh-CN'
1230
+ ? '离线'
1231
+ : 'offline'),
1232
+ ),
1233
+ ]);
1234
+ const tables: BlueprintImTableSection[] =
1235
+ bots.length > 0
1236
+ ? [
1237
+ {
1238
+ id: 'endpoints',
1239
+ title: locale === 'zh-CN' ? '端点列表' : 'Endpoints',
1240
+ columns,
1241
+ rows,
1242
+ totalRows: bots.length,
1243
+ },
1244
+ ]
1245
+ : [];
1246
+ const mdLines = [
1247
+ `### ${title}`,
1248
+ stats.map((s) => `- **${s.label}**: ${s.value}`).join('\n'),
1249
+ ];
1250
+ if (tables.length > 0) {
1251
+ for (const tbl of tables) {
1252
+ mdLines.push(`\n#### ${tbl.title}`);
1253
+ mdLines.push(`| ${tbl.columns.map((c) => c.label).join(' | ')} |`);
1254
+ mdLines.push(`| ${tbl.columns.map(() => '---').join(' | ')} |`);
1255
+ for (const r of tbl.rows) {
1256
+ mdLines.push(`| ${r.join(' | ')} |`);
1257
+ }
1258
+ }
1259
+ }
1260
+ const markdown = mdLines.filter(Boolean).join('\n');
1261
+ const segments: BlueprintImSegment[] = [
1262
+ {
1263
+ type: 'card',
1264
+ data: {
1265
+ title,
1266
+ pluginId,
1267
+ stats,
1268
+ tables,
1269
+ },
1270
+ },
1271
+ {
1272
+ type: 'markdown',
1273
+ data: { content: markdown },
1274
+ },
1275
+ ];
1276
+ return Object.freeze({
1277
+ kind: 'zhin.im.blueprint-card',
1278
+ pluginId,
1279
+ title,
1280
+ stats: Object.freeze(stats),
1281
+ tables: Object.freeze(tables),
1282
+ entries: Object.freeze([]),
1283
+ actions: Object.freeze([]),
1284
+ markdown,
1285
+ segments: Object.freeze(segments),
1286
+ });
1287
+ }
1288
+
1289
+ const bp =
1290
+ (input as ConsolePageBlueprint<TData>)?.kind === 'zhin.console.page-blueprint'
1291
+ ? (input as ConsolePageBlueprint<TData>)
1292
+ : buildBlueprintFromSpec(input as DeclarativePageSpec<TData>);
1293
+ const spec = bp.spec;
1294
+ const pluginId = options.pluginId ?? spec?.pluginId ?? 'plugin';
1295
+ const ctx = createProjectionContext(data, locale, pluginId, spec?.dictionary);
1296
+ const title =
1297
+ (locale === 'zh-CN' ? bp.titleI18n?.['zh-CN'] : bp.titleI18n?.en) ??
1298
+ (spec?.title ? resolveDeclarativeText(spec.title, locale) : bp.title);
1299
+ const description = spec?.description
1300
+ ? resolveDeclarativeText(spec.description, locale)
1301
+ : bp.description;
1302
+
1303
+ const stats: BlueprintImStatItem[] = [];
1304
+ const rawStats =
1305
+ typeof spec?.stats === 'function'
1306
+ ? spec.stats((data ?? ({} as TData)), ctx)
1307
+ : Array.isArray(spec?.stats)
1308
+ ? spec.stats
1309
+ : undefined;
1310
+ if (rawStats) {
1311
+ for (const [idx, s] of rawStats.entries()) {
1312
+ const val =
1313
+ typeof s.value === 'function'
1314
+ ? s.value((data ?? ({} as TData)), ctx)
1315
+ : evaluateDeclarativeValue(s.value, recordData, locale);
1316
+ const hint =
1317
+ typeof s.hint === 'function'
1318
+ ? formatRenderableValue(s.hint((data ?? ({} as TData))))
1319
+ : isDeclarativeValueExpr(s.hint)
1320
+ ? formatRenderableValue(evaluateDeclarativeValue(s.hint, recordData, locale))
1321
+ : s.hint
1322
+ ? resolveDeclarativeText(s.hint, locale)
1323
+ : undefined;
1324
+ const badge = s.badge
1325
+ ? typeof s.badge.label === 'function'
1326
+ ? formatRenderableValue(s.badge.label((data ?? ({} as TData))))
1327
+ : isDeclarativeValueExpr(s.badge.label)
1328
+ ? formatRenderableValue(evaluateDeclarativeValue(s.badge.label, recordData, locale))
1329
+ : resolveDeclarativeText(s.badge.label, locale)
1330
+ : undefined;
1331
+ stats.push(
1332
+ Object.freeze({
1333
+ key: s.key ?? `stat-${idx}`,
1334
+ label: resolveDeclarativeText(s.label, locale),
1335
+ value: formatRenderableValue(val),
1336
+ ...(hint ? { hint } : {}),
1337
+ ...(badge ? { badge } : {}),
1338
+ }),
1339
+ );
1340
+ }
1341
+ } else {
1342
+ for (const sec of bp.sections) {
1343
+ if (sec.type === 'stats') {
1344
+ for (const item of sec.items) {
1345
+ const val = item.expr
1346
+ ? evaluateDeclarativeValue(item.expr, recordData, locale)
1347
+ : item.dataKey
1348
+ ? resolveDataPath(recordData, item.dataKey)
1349
+ : item.value;
1350
+ stats.push(
1351
+ Object.freeze({
1352
+ key: item.key,
1353
+ label: item.label,
1354
+ value: `${formatRenderableValue(val)}${item.suffix ?? ''}`,
1355
+ }),
1356
+ );
1357
+ }
1358
+ }
1359
+ }
1360
+ }
1361
+
1362
+ const tables: BlueprintImTableSection[] = [];
1363
+ const entries: BlueprintImEntriesSection[] = [];
1364
+
1365
+ if (Array.isArray(spec?.sections)) {
1366
+ for (const [idx, sec] of spec.sections.entries()) {
1367
+ const id = sec.id ?? `section-${idx}`;
1368
+ const secTitle = resolveDeclarativeText(sec.title, locale) || id;
1369
+ if (sec.items !== undefined) {
1370
+ const rawItems =
1371
+ typeof sec.items === 'function'
1372
+ ? sec.items((data ?? ({} as TData)))
1373
+ : (resolveDataPath(recordData, sec.items) as readonly Record<string, unknown>[] | undefined);
1374
+ const list = Array.isArray(rawItems) ? rawItems : [];
1375
+ const cols: readonly {
1376
+ readonly key: string;
1377
+ readonly label: string;
1378
+ readonly render?: (
1379
+ value: unknown,
1380
+ row: unknown,
1381
+ ctx: DeclarativePageContext<TData>,
1382
+ ) => DeclarativeRenderable;
1383
+ }[] =
1384
+ sec.columns && sec.columns.length > 0
1385
+ ? sec.columns.map((c: DeclarativeColumnSpec<any, TData>) => ({
1386
+ key: c.key,
1387
+ label: resolveDeclarativeText(c.label, locale),
1388
+ render: c.render,
1389
+ }))
1390
+ : list[0] && typeof list[0] === 'object'
1391
+ ? Object.keys(list[0] as Record<string, unknown>)
1392
+ .slice(0, 5)
1393
+ .map((k) => ({ key: k, label: k, render: undefined }))
1394
+ : [{ key: 'value', label: locale === 'zh-CN' ? '内容' : 'Value', render: undefined }];
1395
+ const rows = list.slice(0, maxRows).map((row, rowIdx) => {
1396
+ if (sec.renderItem && (!sec.columns || sec.columns.length === 0)) {
1397
+ return [formatRenderableValue(sec.renderItem(row, rowIdx, ctx))];
1398
+ }
1399
+ const rec = (row && typeof row === 'object' ? row : { value: row }) as Record<string, unknown>;
1400
+ return cols.map((c) => {
1401
+ const cellVal = resolveDataPath(rec, c.key);
1402
+ return c.render
1403
+ ? formatRenderableValue(c.render(cellVal, row, ctx))
1404
+ : formatRenderableValue(cellVal);
1405
+ });
1406
+ });
1407
+ const emptyText = sec.emptyText ? resolveDeclarativeText(sec.emptyText, locale) : undefined;
1408
+ tables.push(
1409
+ Object.freeze({
1410
+ id,
1411
+ title: secTitle,
1412
+ columns: Object.freeze(cols.map(({ key, label }) => Object.freeze({ key, label }))),
1413
+ rows: Object.freeze(rows.map((r) => Object.freeze(r))),
1414
+ totalRows: list.length,
1415
+ ...(emptyText ? { emptyText } : {}),
1416
+ }),
1417
+ );
1418
+ } else if (sec.entries !== undefined) {
1419
+ const rawEntries =
1420
+ typeof sec.entries === 'function'
1421
+ ? sec.entries((data ?? ({} as TData)), ctx)
1422
+ : sec.entries;
1423
+ const items = Array.isArray(rawEntries)
1424
+ ? rawEntries.map((entry) => {
1425
+ const entryRecord = entry as {
1426
+ readonly label: unknown;
1427
+ readonly value: unknown;
1428
+ readonly dataKey?: string;
1429
+ readonly expr?: DeclarativeValueExpr;
1430
+ };
1431
+ const resolvedValue = isDeclarativeValueExpr(entryRecord.expr)
1432
+ ? evaluateDeclarativeValue(entryRecord.expr, recordData, locale)
1433
+ : isDeclarativeValueExpr(entryRecord.value)
1434
+ ? evaluateDeclarativeValue(entryRecord.value, recordData, locale)
1435
+ : entryRecord.dataKey
1436
+ ? resolveDataPath(recordData, entryRecord.dataKey)
1437
+ : entryRecord.value;
1438
+ return Object.freeze({
1439
+ label:
1440
+ typeof entryRecord.label === 'object' &&
1441
+ entryRecord.label !== null &&
1442
+ ('zh' in entryRecord.label || 'en' in entryRecord.label || 'zh-CN' in entryRecord.label)
1443
+ ? resolveDeclarativeText(entryRecord.label as DeclarativeI18nText, locale)
1444
+ : formatRenderableValue(entryRecord.label),
1445
+ value: formatRenderableValue(resolvedValue),
1446
+ });
1447
+ })
1448
+ : Object.entries(rawEntries ?? {}).map(([k, v]) =>
1449
+ Object.freeze({
1450
+ label: k,
1451
+ value: formatRenderableValue(
1452
+ isDeclarativeValueExpr(v) ? evaluateDeclarativeValue(v, recordData, locale) : v,
1453
+ ),
1454
+ }),
1455
+ );
1456
+ entries.push(
1457
+ Object.freeze({
1458
+ id,
1459
+ title: secTitle,
1460
+ items: Object.freeze(items),
1461
+ }),
1462
+ );
1463
+ }
1464
+ }
1465
+ } else {
1466
+ for (const sec of bp.sections) {
1467
+ if (sec.type === 'table') {
1468
+ const rawItems = sec.dataKey ? resolveDataPath(recordData, sec.dataKey) : undefined;
1469
+ const list = Array.isArray(rawItems) ? rawItems : [];
1470
+ const rows = list.slice(0, maxRows).map((row) => {
1471
+ const rec = (row && typeof row === 'object' ? row : {}) as Record<string, unknown>;
1472
+ return sec.columns.map((c) => formatRenderableValue(resolveDataPath(rec, c.key)));
1473
+ });
1474
+ tables.push(
1475
+ Object.freeze({
1476
+ id: sec.id,
1477
+ title: sec.title,
1478
+ columns: sec.columns,
1479
+ rows: Object.freeze(rows.map((r) => Object.freeze(r))),
1480
+ totalRows: list.length,
1481
+ }),
1482
+ );
1483
+ } else if (sec.type === 'entries' && Array.isArray(sec.entries)) {
1484
+ entries.push(
1485
+ Object.freeze({
1486
+ id: sec.id,
1487
+ title: sec.title,
1488
+ items: Object.freeze(
1489
+ sec.entries.map((entry) => {
1490
+ const resolvedValue = entry.expr
1491
+ ? evaluateDeclarativeValue(entry.expr, recordData, locale)
1492
+ : isDeclarativeValueExpr(entry.value)
1493
+ ? evaluateDeclarativeValue(entry.value, recordData, locale)
1494
+ : entry.dataKey
1495
+ ? resolveDataPath(recordData, entry.dataKey)
1496
+ : entry.value;
1497
+ return Object.freeze({
1498
+ label: formatRenderableValue(entry.label),
1499
+ value: formatRenderableValue(resolvedValue),
1500
+ });
1501
+ }),
1502
+ ),
1503
+ }),
1504
+ );
1505
+ }
1506
+ }
1507
+ }
1508
+
1509
+ const actions: BlueprintImActionItem[] = [];
1510
+ if (Array.isArray(spec?.actions)) {
1511
+ for (const act of spec.actions) {
1512
+ const disabled =
1513
+ typeof act.disabled === 'function' ? act.disabled(data) : Boolean(act.disabled);
1514
+ const desc = act.description ? resolveDeclarativeText(act.description, locale) : undefined;
1515
+ actions.push(
1516
+ Object.freeze({
1517
+ name: act.name,
1518
+ label: resolveDeclarativeText(act.label, locale),
1519
+ rpcMethod: `plugin.${pluginId}.${act.name}`,
1520
+ ...(desc ? { description: desc } : {}),
1521
+ variant: act.variant ?? 'secondary',
1522
+ disabled,
1523
+ }),
1524
+ );
1525
+ }
1526
+ } else {
1527
+ for (const sec of bp.sections) {
1528
+ if (sec.type === 'actions') {
1529
+ for (const item of sec.items) {
1530
+ actions.push(
1531
+ Object.freeze({
1532
+ name: item.name ?? item.action,
1533
+ label: item.label,
1534
+ rpcMethod: `plugin.${pluginId}.${item.action}`,
1535
+ ...(item.description ? { description: item.description } : {}),
1536
+ variant: item.variant ?? 'secondary',
1537
+ disabled: false,
1538
+ }),
1539
+ );
1540
+ }
1541
+ }
1542
+ }
1543
+ }
1544
+
1545
+ const mdLines: string[] = [`### ${title}`];
1546
+ if (description) mdLines.push(description);
1547
+ if (stats.length > 0) {
1548
+ mdLines.push('');
1549
+ for (const s of stats) {
1550
+ const badgeSuffix = s.badge ? ` [${s.badge}]` : '';
1551
+ const hintSuffix = s.hint ? ` (${s.hint})` : '';
1552
+ mdLines.push(`- **${s.label}**: ${s.value}${badgeSuffix}${hintSuffix}`);
1553
+ }
1554
+ }
1555
+ for (const entrySec of entries) {
1556
+ mdLines.push(`\n#### ${entrySec.title}`);
1557
+ for (const item of entrySec.items) {
1558
+ mdLines.push(`- **${item.label}**: ${item.value}`);
1559
+ }
1560
+ }
1561
+ for (const tbl of tables) {
1562
+ mdLines.push(`\n#### ${tbl.title} (${tbl.totalRows})`);
1563
+ if (tbl.rows.length === 0) {
1564
+ mdLines.push(`_${tbl.emptyText ?? (locale === 'zh-CN' ? '暂无数据' : 'No data')}_`);
1565
+ } else {
1566
+ mdLines.push(`| ${tbl.columns.map((c) => c.label).join(' | ')} |`);
1567
+ mdLines.push(`| ${tbl.columns.map(() => '---').join(' | ')} |`);
1568
+ for (const r of tbl.rows) {
1569
+ mdLines.push(`| ${r.join(' | ')} |`);
1570
+ }
1571
+ }
1572
+ }
1573
+ if (actions.length > 0) {
1574
+ mdLines.push(
1575
+ `\n> ${locale === 'zh-CN' ? '可执行操作' : 'Available Actions'}: ${actions
1576
+ .map((a) => `\`${a.label}\` (${a.name})`)
1577
+ .join(' · ')}`,
1578
+ );
1579
+ }
1580
+ const markdown = mdLines.join('\n');
1581
+
1582
+ const segments: BlueprintImSegment[] = [
1583
+ {
1584
+ type: 'card',
1585
+ data: {
1586
+ title,
1587
+ ...(description ? { description } : {}),
1588
+ pluginId,
1589
+ stats,
1590
+ tables,
1591
+ entries,
1592
+ actions,
1593
+ },
1594
+ },
1595
+ {
1596
+ type: 'markdown',
1597
+ data: { content: markdown },
1598
+ },
1599
+ ...actions
1600
+ .filter((a) => !a.disabled)
1601
+ .map(
1602
+ (a): BlueprintImSegment => ({
1603
+ type: 'button',
1604
+ data: {
1605
+ id: a.rpcMethod,
1606
+ label: a.label,
1607
+ action: a.name,
1608
+ variant: a.variant,
1609
+ },
1610
+ }),
1611
+ ),
1612
+ ];
1613
+
1614
+ return Object.freeze({
1615
+ kind: 'zhin.im.blueprint-card',
1616
+ pluginId,
1617
+ title,
1618
+ ...(description ? { description } : {}),
1619
+ stats: Object.freeze(stats),
1620
+ tables: Object.freeze(tables),
1621
+ entries: Object.freeze(entries),
1622
+ actions: Object.freeze(actions),
1623
+ markdown,
1624
+ segments: Object.freeze(segments),
1625
+ });
1626
+ }
1627
+
1628
+ export interface BlueprintCliPanelOptions extends BlueprintProjectionOptions {
1629
+ readonly width?: number;
1630
+ }
1631
+
1632
+ /**
1633
+ * Projects any Server-Driven Console Blueprint (`definePageBlueprint`, `defineAdapterPage`,
1634
+ * `defineCommentReviewPage`, or `DeclarativePageSpec`) + runtime status payload into a
1635
+ * formatted CLI TUI panel string.
1636
+ */
1637
+ export function projectBlueprintToCliPanel<TData = Record<string, unknown>>(
1638
+ input:
1639
+ | ConsolePageBlueprint<TData>
1640
+ | ConsoleAdapterPageBlueprint
1641
+ | DeclarativePageSpec<TData>,
1642
+ data?: TData,
1643
+ options: BlueprintCliPanelOptions = {},
1644
+ ): string {
1645
+ const card = projectBlueprintToImCard(input, data, options);
1646
+ const width = Math.max(44, options.width ?? 72);
1647
+ const innerWidth = width - 4;
1648
+ const hr = '─'.repeat(width - 2);
1649
+ const padLine = (text: string): string => {
1650
+ const clean = text.replace(/\r?\n/gu, ' ').slice(0, innerWidth);
1651
+ const pad = Math.max(0, innerWidth - clean.length);
1652
+ return `│ ${clean}${' '.repeat(pad)} │`;
1653
+ };
1654
+
1655
+ const lines: string[] = [`┌${hr}┐`, padLine(`[${card.pluginId}] ${card.title}`)];
1656
+ if (card.description) {
1657
+ lines.push(padLine(card.description));
1658
+ }
1659
+ lines.push(`├${hr}┤`);
1660
+
1661
+ if (card.stats.length > 0) {
1662
+ const statSummary = card.stats
1663
+ .map((s) => `${s.label}: ${s.value}${s.badge ? ` [${s.badge}]` : ''}`)
1664
+ .join(' │ ');
1665
+ lines.push(padLine(statSummary));
1666
+ lines.push(`├${hr}┤`);
1667
+ }
1668
+
1669
+ for (const entrySec of card.entries) {
1670
+ lines.push(padLine(`■ ${entrySec.title}`));
1671
+ for (const item of entrySec.items) {
1672
+ lines.push(padLine(` ${item.label}: ${item.value}`));
1673
+ }
1674
+ lines.push(`├${hr}┤`);
1675
+ }
1676
+
1677
+ for (const tbl of card.tables) {
1678
+ lines.push(padLine(`■ ${tbl.title} (${tbl.totalRows})`));
1679
+ if (tbl.rows.length === 0) {
1680
+ lines.push(padLine(` (${tbl.emptyText ?? 'empty'})`));
1681
+ } else {
1682
+ lines.push(padLine(` ${tbl.columns.map((c) => c.label).join(' | ')}`));
1683
+ for (const row of tbl.rows) {
1684
+ lines.push(padLine(` ${row.join(' | ')}`));
1685
+ }
1686
+ }
1687
+ lines.push(`├${hr}┤`);
1688
+ }
1689
+
1690
+ if (card.actions.length > 0) {
1691
+ const actionBar = card.actions
1692
+ .map((a) => (a.disabled ? `(${a.label})` : `[${a.label} -> ${a.name}]`))
1693
+ .join(' ');
1694
+ lines.push(padLine(`Actions: ${actionBar}`));
1695
+ } else {
1696
+ // Remove trailing separator if no actions
1697
+ if (lines[lines.length - 1] === `├${hr}┤`) {
1698
+ lines.pop();
1699
+ }
1700
+ }
1701
+
1702
+ lines.push(`└${hr}┘`);
1703
+ return lines.join('\n');
1704
+ }