@zhin.js/core 1.1.41 → 1.1.42
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/lib/built/interactive-segments/action.js +1 -1
- package/lib/built/segment-contract/assert.js +1 -1
- package/lib/built/segment-contract/json-schema.js +1 -1
- package/lib/jsx/intrinsic-elements.d.ts +83 -0
- package/lib/jsx/intrinsic-elements.js +1 -0
- package/lib/jsx/message-renderer.d.ts +13 -0
- package/lib/jsx/message-renderer.js +128 -0
- package/lib/jsx/message-tags.d.ts +126 -0
- package/lib/jsx/message-tags.js +47 -0
- package/lib/jsx-dev-runtime.d.ts +2 -1
- package/lib/jsx-dev-runtime.js +1 -1
- package/lib/jsx-runtime.d.ts +2 -1
- package/lib/jsx-runtime.js +1 -1
- package/lib/jsx.d.ts +5 -0
- package/lib/jsx.js +2 -0
- package/lib/plugin-runtime/im/im-runtime.js +1 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +3 -3
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +6 -3
- package/lib/plugin-runtime/im/interaction-runtime.js +14 -3
- package/lib/plugin-runtime/im/interactive-router.d.ts +1 -1
- package/lib/plugin-runtime/im/interactive-router.js +19 -16
- package/lib/plugin-runtime/im/jsx-button-registry.d.ts +17 -0
- package/lib/plugin-runtime/im/jsx-button-registry.js +93 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +3 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +16 -3
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +3 -1
- package/lib/plugin-runtime/im/outbound-renderer.js +33 -12
- package/lib/plugin-runtime/im/outbound-segments.d.ts +1 -1
- package/lib/plugin-runtime/im/outbound-segments.js +3 -2
- package/package.json +3 -3
|
@@ -44,7 +44,7 @@ export function resolveTextFallbackPayload(raw, map) {
|
|
|
44
44
|
const trimmed = raw.trim();
|
|
45
45
|
if (map[trimmed])
|
|
46
46
|
return map[trimmed];
|
|
47
|
-
const match = trimmed.match(/^(?:ttt\s+)?(\d)$/i);
|
|
47
|
+
const match = trimmed.match(/^(?:ttt\s+)?(\d+)$/i);
|
|
48
48
|
if (match && map[match[1]])
|
|
49
49
|
return map[match[1]];
|
|
50
50
|
return undefined;
|
|
@@ -8,7 +8,7 @@ const STRICT_CANONICAL_TYPES = new Set([
|
|
|
8
8
|
// their gradual contracts isolated here; third-party extensions must be
|
|
9
9
|
// namespaced so a future canonical type cannot silently collide with them.
|
|
10
10
|
const CORE_EXTENSION_TYPES = new Set([
|
|
11
|
-
'action', 'html', 'keyboard', 'link', 'markdown', 'qrcode', 'record', 'tts', 'voice',
|
|
11
|
+
'action', 'card', 'html', 'keyboard', 'link', 'markdown', 'qrcode', 'record', 'tts', 'voice',
|
|
12
12
|
]);
|
|
13
13
|
const extensionTypePattern = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)+$/u;
|
|
14
14
|
function isPlainObject(value) {
|
|
@@ -66,7 +66,7 @@ const looseBranch = {
|
|
|
66
66
|
properties: {
|
|
67
67
|
type: {
|
|
68
68
|
type: 'string',
|
|
69
|
-
enum: ['voice', 'record', 'link', 'markdown', 'html'],
|
|
69
|
+
enum: ['voice', 'record', 'link', 'markdown', 'html', 'card'],
|
|
70
70
|
},
|
|
71
71
|
data: { type: 'object' },
|
|
72
72
|
platform: platformJsonSchema,
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { JSX as BaseJSX, JSXAttributes, HtmlProps } from '@zhin.js/jsx';
|
|
2
|
+
import type { MediaRef, ForwardSegment, ShareSegment } from '@zhin.js/im-contract';
|
|
3
|
+
import type { ButtonProps, ImageProps, MentionProps, FaceProps, TextProps, MarkdownProps } from './message-tags.js';
|
|
4
|
+
import type { AudioSegment, VideoSegment, FileSegment } from '../built/segment-contract/types.js';
|
|
5
|
+
import type { KeyboardSegmentData, ActionSegmentData } from '../built/interactive-segments/types.js';
|
|
6
|
+
type MediaProps = {
|
|
7
|
+
readonly media: MediaRef;
|
|
8
|
+
readonly duration?: number;
|
|
9
|
+
readonly alt?: string;
|
|
10
|
+
readonly name?: string;
|
|
11
|
+
};
|
|
12
|
+
type HtmlInputProps = Omit<HtmlProps, 'children'> & ({
|
|
13
|
+
readonly html: string;
|
|
14
|
+
readonly children?: never;
|
|
15
|
+
} | {
|
|
16
|
+
readonly children?: HtmlProps['children'];
|
|
17
|
+
readonly html?: never;
|
|
18
|
+
});
|
|
19
|
+
/** Lowercase tags mirror Segment.type and its data fields, with typed creation helpers. */
|
|
20
|
+
export interface MessageTagProps {
|
|
21
|
+
text: TextProps;
|
|
22
|
+
image: ImageProps | {
|
|
23
|
+
readonly media: MediaRef;
|
|
24
|
+
readonly alt?: string;
|
|
25
|
+
};
|
|
26
|
+
mention: MentionProps;
|
|
27
|
+
face: FaceProps;
|
|
28
|
+
audio: AudioSegment['data'];
|
|
29
|
+
video: VideoSegment['data'];
|
|
30
|
+
file: FileSegment['data'];
|
|
31
|
+
record: MediaProps;
|
|
32
|
+
voice: MediaProps;
|
|
33
|
+
reply: {
|
|
34
|
+
readonly message_id: string;
|
|
35
|
+
};
|
|
36
|
+
forward: ForwardSegment['data'];
|
|
37
|
+
share: ShareSegment['data'];
|
|
38
|
+
dice: {
|
|
39
|
+
readonly result?: number;
|
|
40
|
+
};
|
|
41
|
+
rps: {
|
|
42
|
+
readonly result?: number;
|
|
43
|
+
};
|
|
44
|
+
card: Readonly<Record<string, unknown>> & {
|
|
45
|
+
readonly children?: never;
|
|
46
|
+
};
|
|
47
|
+
button: ButtonProps;
|
|
48
|
+
keyboard: KeyboardSegmentData;
|
|
49
|
+
action: ActionSegmentData;
|
|
50
|
+
html: HtmlInputProps;
|
|
51
|
+
markdown: MarkdownProps;
|
|
52
|
+
link: {
|
|
53
|
+
readonly url: string;
|
|
54
|
+
readonly text?: string;
|
|
55
|
+
};
|
|
56
|
+
qrcode: {
|
|
57
|
+
readonly text: string;
|
|
58
|
+
readonly width?: number;
|
|
59
|
+
readonly margin?: number;
|
|
60
|
+
readonly errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H';
|
|
61
|
+
readonly small?: boolean;
|
|
62
|
+
};
|
|
63
|
+
tts: {
|
|
64
|
+
readonly text: string;
|
|
65
|
+
readonly voice?: string;
|
|
66
|
+
readonly provider?: string;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** Compiler namespace shared by both production and development runtime entrypoints. */
|
|
70
|
+
export declare namespace JSX {
|
|
71
|
+
type Element = BaseJSX.Element;
|
|
72
|
+
type ElementType = BaseJSX.ElementType;
|
|
73
|
+
interface ElementChildrenAttribute {
|
|
74
|
+
children: {};
|
|
75
|
+
}
|
|
76
|
+
interface IntrinsicAttributes {
|
|
77
|
+
key?: string | number;
|
|
78
|
+
}
|
|
79
|
+
interface IntrinsicElements extends MessageTagProps {
|
|
80
|
+
[name: string]: JSXAttributes | MessageTagProps[keyof MessageTagProps];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type JSXRenderable, type JSXProps } from '@zhin.js/jsx';
|
|
2
|
+
import type { Segment } from '@zhin.js/im-contract';
|
|
3
|
+
import { type ButtonProps } from './message-tags.js';
|
|
4
|
+
/** Native and namespaced extension tags do not use ComponentIndex. */
|
|
5
|
+
export declare function isNativeMessageTag(type: string): boolean;
|
|
6
|
+
export interface MessageRenderOptions {
|
|
7
|
+
readonly maxDepth?: number;
|
|
8
|
+
readonly signal?: AbortSignal;
|
|
9
|
+
readonly bindButton?: (props: ButtonProps) => Segment;
|
|
10
|
+
readonly renderComponent?: (name: string, props: JSXProps) => Promise<JSXRenderable>;
|
|
11
|
+
}
|
|
12
|
+
/** Default JSX lays out ordered message segments. Only Html changes to HTML semantics. */
|
|
13
|
+
export declare function renderToSegments(node: JSXRenderable, options?: MessageRenderOptions): Promise<readonly Segment[]>;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { Fragment, Html, isJsxElement, renderToHtml } from '@zhin.js/jsx';
|
|
2
|
+
import { segment } from '../utils.js';
|
|
3
|
+
import { isSegmentContent } from '../plugin-runtime/im/contracts.js';
|
|
4
|
+
import { Image } from './message-tags.js';
|
|
5
|
+
import { isKeyboardSegment } from '../built/interactive-segments/types.js';
|
|
6
|
+
const MESSAGE_TAGS = new Set([
|
|
7
|
+
'text', 'mention', 'image', 'audio', 'video', 'file', 'reply', 'forward', 'face',
|
|
8
|
+
'dice', 'rps', 'share', 'card', 'action', 'html', 'keyboard', 'link', 'markdown',
|
|
9
|
+
'qrcode', 'record', 'tts', 'voice',
|
|
10
|
+
]);
|
|
11
|
+
/** Native and namespaced extension tags do not use ComponentIndex. */
|
|
12
|
+
export function isNativeMessageTag(type) {
|
|
13
|
+
return type === 'button' || MESSAGE_TAGS.has(type) || /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)+$/.test(type);
|
|
14
|
+
}
|
|
15
|
+
/** Default JSX lays out ordered message segments. Only Html changes to HTML semantics. */
|
|
16
|
+
export async function renderToSegments(node, options = {}) {
|
|
17
|
+
const maxDepth = options.maxDepth ?? 100;
|
|
18
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth < 1)
|
|
19
|
+
throw new RangeError('JSX maxDepth must be a positive integer');
|
|
20
|
+
const ancestors = new WeakSet();
|
|
21
|
+
const output = [];
|
|
22
|
+
let lastButtonIndex = -1;
|
|
23
|
+
const render = async (value, depth) => {
|
|
24
|
+
options.signal?.throwIfAborted();
|
|
25
|
+
if (depth > maxDepth)
|
|
26
|
+
throw new RangeError(`JSX exceeds maximum render depth ${maxDepth}`);
|
|
27
|
+
if (value == null || typeof value === 'boolean')
|
|
28
|
+
return;
|
|
29
|
+
if (typeof value === 'string' || typeof value === 'number') {
|
|
30
|
+
if (value !== '')
|
|
31
|
+
output.push(segment.text(String(value)));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (typeof value !== 'object')
|
|
35
|
+
throw new TypeError('Unsupported JSX child');
|
|
36
|
+
if (ancestors.has(value))
|
|
37
|
+
throw new TypeError('Circular JSX tree');
|
|
38
|
+
ancestors.add(value);
|
|
39
|
+
try {
|
|
40
|
+
if (Array.isArray(value)) {
|
|
41
|
+
for (const child of value)
|
|
42
|
+
await render(child, depth + 1);
|
|
43
|
+
}
|
|
44
|
+
else if ('then' in value && typeof value.then === 'function') {
|
|
45
|
+
const then = value.then;
|
|
46
|
+
const resolved = await new Promise((resolve, reject) => {
|
|
47
|
+
then.call(value, (child) => resolve({ node: child }), reject);
|
|
48
|
+
});
|
|
49
|
+
await render(resolved.node, depth + 1);
|
|
50
|
+
}
|
|
51
|
+
else if (isJsxElement(value)) {
|
|
52
|
+
const { type, props } = value;
|
|
53
|
+
if (type === Fragment)
|
|
54
|
+
await render(props.children, depth + 1);
|
|
55
|
+
else if (type === Html || type === 'html') {
|
|
56
|
+
if (props.html !== undefined && props.children !== undefined)
|
|
57
|
+
throw new TypeError('Html accepts html or children, not both');
|
|
58
|
+
if (props.html !== undefined && typeof props.html !== 'string')
|
|
59
|
+
throw new TypeError('Html html must be a string');
|
|
60
|
+
const html = typeof props.html === 'string' ? props.html
|
|
61
|
+
: await renderToHtml(props.children, { maxDepth: Math.max(1, maxDepth - depth) });
|
|
62
|
+
const { width, backgroundColor, fileName, text } = props;
|
|
63
|
+
if (html || text)
|
|
64
|
+
output.push(segment.html({ html,
|
|
65
|
+
...(width === undefined ? {} : { width }),
|
|
66
|
+
...(backgroundColor === undefined ? {} : { backgroundColor }),
|
|
67
|
+
...(fileName === undefined ? {} : { fileName }),
|
|
68
|
+
...(text === undefined ? {} : { text }),
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
else if (typeof type === 'function')
|
|
72
|
+
await render(type(props), depth + 1);
|
|
73
|
+
else if (type === 'image' && 'src' in props)
|
|
74
|
+
await render(Image(props), depth + 1);
|
|
75
|
+
else if (type === 'button') {
|
|
76
|
+
if (!options.bindButton)
|
|
77
|
+
throw new TypeError('Button requires an active IM runtime');
|
|
78
|
+
const button = options.bindButton(props);
|
|
79
|
+
const previous = output[lastButtonIndex];
|
|
80
|
+
if (lastButtonIndex === output.length - 1 && isKeyboardSegment(previous) && isKeyboardSegment(button)) {
|
|
81
|
+
output[lastButtonIndex] = { type: 'keyboard', data: { rows: [[...previous.data.rows.flat(), ...button.data.rows.flat()]] } };
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
output.push(button);
|
|
85
|
+
lastButtonIndex = output.length - 1;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
else if (typeof type === 'string' && isNativeMessageTag(type)) {
|
|
89
|
+
const { children, ...data } = props;
|
|
90
|
+
if ((type === 'text' || type === 'markdown') && children !== undefined) {
|
|
91
|
+
const field = type === 'text' ? 'text' : 'content';
|
|
92
|
+
if (data[field] !== undefined)
|
|
93
|
+
throw new TypeError(`${type} accepts ${field} or children, not both`);
|
|
94
|
+
const start = output.length;
|
|
95
|
+
await render(children, depth + 1);
|
|
96
|
+
const parts = output.splice(start);
|
|
97
|
+
if (!parts.every((part) => part.type === 'text' && 'text' in part.data && typeof part.data.text === 'string')) {
|
|
98
|
+
throw new TypeError(`${type} children must produce text segments`);
|
|
99
|
+
}
|
|
100
|
+
const text = parts.map(part => part.data.text).join('');
|
|
101
|
+
if (text)
|
|
102
|
+
output.push(segment(type, { ...data, [field]: text }));
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
if (children !== undefined)
|
|
106
|
+
throw new TypeError(`Message tag ${type} stores content in its data props, not children`);
|
|
107
|
+
output.push(segment(type, data));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (typeof type === 'string' && options.renderComponent) {
|
|
111
|
+
await render(await options.renderComponent(type, props), depth + 1);
|
|
112
|
+
}
|
|
113
|
+
else
|
|
114
|
+
throw new TypeError(`Unknown message tag ${String(type)}; register a component or wrap HTML in <html>`);
|
|
115
|
+
}
|
|
116
|
+
else if (isSegmentContent(value))
|
|
117
|
+
output.push(value);
|
|
118
|
+
else
|
|
119
|
+
throw new TypeError('Unsupported JSX child: expected a JSX element or Segment');
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
ancestors.delete(value);
|
|
123
|
+
}
|
|
124
|
+
options.signal?.throwIfAborted();
|
|
125
|
+
};
|
|
126
|
+
await render(node, 0);
|
|
127
|
+
return output;
|
|
128
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type JSXElement, type JSXRenderable } from '@zhin.js/jsx';
|
|
2
|
+
import type { MediaRef, Segment } from '@zhin.js/im-contract';
|
|
3
|
+
import type { Message, SendContent } from '../plugin-runtime/im/contracts.js';
|
|
4
|
+
import type { ButtonData } from '../built/interactive-segments/types.js';
|
|
5
|
+
export type TextProps = {
|
|
6
|
+
readonly text: string;
|
|
7
|
+
readonly children?: never;
|
|
8
|
+
} | {
|
|
9
|
+
readonly children: JSXRenderable;
|
|
10
|
+
readonly text?: never;
|
|
11
|
+
};
|
|
12
|
+
export declare function Text(props: TextProps): JSXElement;
|
|
13
|
+
export interface ImageProps {
|
|
14
|
+
readonly src: string | MediaRef;
|
|
15
|
+
readonly alt?: string;
|
|
16
|
+
}
|
|
17
|
+
/** URLs and local paths are convenient sources; opaque platform IDs use MediaRef. */
|
|
18
|
+
export declare function Image({ src, alt }: ImageProps): JSXElement;
|
|
19
|
+
export interface MentionProps {
|
|
20
|
+
readonly target: string;
|
|
21
|
+
readonly name?: string;
|
|
22
|
+
}
|
|
23
|
+
export declare function Mention(props: MentionProps): JSXElement;
|
|
24
|
+
export interface FaceProps {
|
|
25
|
+
readonly id: string | number;
|
|
26
|
+
readonly name?: string;
|
|
27
|
+
}
|
|
28
|
+
export declare function Face(props: FaceProps): JSXElement;
|
|
29
|
+
export type MarkdownProps = ({
|
|
30
|
+
readonly content: string;
|
|
31
|
+
readonly children?: never;
|
|
32
|
+
} | {
|
|
33
|
+
readonly children: JSXRenderable;
|
|
34
|
+
readonly content?: never;
|
|
35
|
+
}) & {
|
|
36
|
+
readonly width?: number;
|
|
37
|
+
readonly backgroundColor?: string;
|
|
38
|
+
readonly fileName?: string;
|
|
39
|
+
};
|
|
40
|
+
export declare function Markdown(props: MarkdownProps): JSXElement;
|
|
41
|
+
/** Platform-native payload; no HTML serialization or cross-platform card schema. */
|
|
42
|
+
export interface CardProps {
|
|
43
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
44
|
+
}
|
|
45
|
+
export declare function Card({ data }: CardProps): Segment;
|
|
46
|
+
export type ButtonClickResult = SendContent | number | boolean | null | void;
|
|
47
|
+
export type ButtonClickHandler = (message: Message) => ButtonClickResult | Promise<ButtonClickResult>;
|
|
48
|
+
export type ButtonProps = Omit<ButtonData, 'id' | 'label' | 'payload'> & {
|
|
49
|
+
readonly id?: string;
|
|
50
|
+
} & ({
|
|
51
|
+
readonly label: string;
|
|
52
|
+
readonly children?: never;
|
|
53
|
+
} | {
|
|
54
|
+
readonly children: string;
|
|
55
|
+
readonly label?: never;
|
|
56
|
+
}) & ({
|
|
57
|
+
readonly onClick: ButtonClickHandler;
|
|
58
|
+
readonly payload?: never;
|
|
59
|
+
} | {
|
|
60
|
+
readonly payload: string;
|
|
61
|
+
readonly onClick?: never;
|
|
62
|
+
});
|
|
63
|
+
/** Event handlers are bound by the active IM operation, never serialized onto the wire. */
|
|
64
|
+
export declare function Button(props: ButtonProps): JSXElement;
|
|
65
|
+
export declare const Audio: (props: {
|
|
66
|
+
media: MediaRef;
|
|
67
|
+
duration?: number;
|
|
68
|
+
}) => JSXElement;
|
|
69
|
+
export declare const Video: (props: {
|
|
70
|
+
media: MediaRef;
|
|
71
|
+
duration?: number;
|
|
72
|
+
alt?: string;
|
|
73
|
+
}) => JSXElement;
|
|
74
|
+
export declare const File: (props: {
|
|
75
|
+
media: MediaRef;
|
|
76
|
+
name?: string;
|
|
77
|
+
}) => JSXElement;
|
|
78
|
+
export declare const Reply: (props: {
|
|
79
|
+
readonly message_id: string;
|
|
80
|
+
}) => JSXElement;
|
|
81
|
+
export declare const Forward: (props: Readonly<{
|
|
82
|
+
forward_id: string;
|
|
83
|
+
title?: string;
|
|
84
|
+
entries?: readonly import("@zhin.js/im-contract").ForwardEntry[];
|
|
85
|
+
}>) => JSXElement;
|
|
86
|
+
export declare const Share: (props: Readonly<{
|
|
87
|
+
url: string;
|
|
88
|
+
title: string;
|
|
89
|
+
description?: string;
|
|
90
|
+
image?: string;
|
|
91
|
+
audio?: string;
|
|
92
|
+
content?: string;
|
|
93
|
+
artist?: string;
|
|
94
|
+
duration?: number;
|
|
95
|
+
config?: Readonly<{
|
|
96
|
+
appid: number;
|
|
97
|
+
package?: string;
|
|
98
|
+
sign?: string;
|
|
99
|
+
icon?: string;
|
|
100
|
+
version?: string;
|
|
101
|
+
}>;
|
|
102
|
+
}>) => JSXElement;
|
|
103
|
+
export declare const Dice: (props: {
|
|
104
|
+
readonly result?: number;
|
|
105
|
+
}) => JSXElement;
|
|
106
|
+
export declare const Rps: (props: {
|
|
107
|
+
readonly result?: number;
|
|
108
|
+
}) => JSXElement;
|
|
109
|
+
export declare const Keyboard: (props: import("../index.js").KeyboardSegmentData) => JSXElement;
|
|
110
|
+
export declare const Action: (props: import("../index.js").ActionSegmentData) => JSXElement;
|
|
111
|
+
export declare const Link: (props: {
|
|
112
|
+
readonly url: string;
|
|
113
|
+
readonly text?: string;
|
|
114
|
+
}) => JSXElement;
|
|
115
|
+
export declare const Qrcode: (props: {
|
|
116
|
+
readonly text: string;
|
|
117
|
+
readonly width?: number;
|
|
118
|
+
readonly margin?: number;
|
|
119
|
+
readonly errorCorrectionLevel?: "L" | "M" | "Q" | "H";
|
|
120
|
+
readonly small?: boolean;
|
|
121
|
+
}) => JSXElement;
|
|
122
|
+
export declare const Tts: (props: {
|
|
123
|
+
readonly text: string;
|
|
124
|
+
readonly voice?: string;
|
|
125
|
+
readonly provider?: string;
|
|
126
|
+
}) => JSXElement;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { jsx } from '@zhin.js/jsx';
|
|
2
|
+
export function Text(props) {
|
|
3
|
+
return jsx('text', { ...props });
|
|
4
|
+
}
|
|
5
|
+
/** URLs and local paths are convenient sources; opaque platform IDs use MediaRef. */
|
|
6
|
+
export function Image({ src, alt }) {
|
|
7
|
+
let media;
|
|
8
|
+
if (typeof src !== 'string')
|
|
9
|
+
media = src;
|
|
10
|
+
else if (/^https?:\/\//i.test(src))
|
|
11
|
+
media = { kind: 'url', value: src };
|
|
12
|
+
else if (src.startsWith('base64://'))
|
|
13
|
+
media = { kind: 'base64', value: src.slice(9) };
|
|
14
|
+
else if (src.startsWith('data:')) {
|
|
15
|
+
const match = /^data:([^;,]+)(?:;[^;,]*)*;base64,([\s\S]+)$/i.exec(src);
|
|
16
|
+
if (!match)
|
|
17
|
+
throw new TypeError('Image data URI must contain base64 media');
|
|
18
|
+
media = { kind: 'base64', value: match[2], mime_type: match[1] };
|
|
19
|
+
}
|
|
20
|
+
else
|
|
21
|
+
media = { kind: 'path', value: src };
|
|
22
|
+
return jsx('image', { media, ...(alt === undefined ? {} : { alt }) });
|
|
23
|
+
}
|
|
24
|
+
export function Mention(props) { return jsx('mention', { ...props }); }
|
|
25
|
+
export function Face(props) { return jsx('face', { ...props }); }
|
|
26
|
+
export function Markdown(props) {
|
|
27
|
+
return jsx('markdown', { ...props });
|
|
28
|
+
}
|
|
29
|
+
export function Card({ data }) { return { type: 'card', data }; }
|
|
30
|
+
/** Event handlers are bound by the active IM operation, never serialized onto the wire. */
|
|
31
|
+
export function Button(props) { return jsx('button', { ...props }); }
|
|
32
|
+
function nativeTag(type) {
|
|
33
|
+
return (props) => jsx(type, { ...props });
|
|
34
|
+
}
|
|
35
|
+
export const Audio = nativeTag('audio');
|
|
36
|
+
export const Video = nativeTag('video');
|
|
37
|
+
export const File = nativeTag('file');
|
|
38
|
+
export const Reply = nativeTag('reply');
|
|
39
|
+
export const Forward = nativeTag('forward');
|
|
40
|
+
export const Share = nativeTag('share');
|
|
41
|
+
export const Dice = nativeTag('dice');
|
|
42
|
+
export const Rps = nativeTag('rps');
|
|
43
|
+
export const Keyboard = nativeTag('keyboard');
|
|
44
|
+
export const Action = nativeTag('action');
|
|
45
|
+
export const Link = nativeTag('link');
|
|
46
|
+
export const Qrcode = nativeTag('qrcode');
|
|
47
|
+
export const Tts = nativeTag('tts');
|
package/lib/jsx-dev-runtime.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { Fragment, jsxDEV } from '@zhin.js/jsx/jsx-dev-runtime';
|
|
2
|
+
export type { JSX } from './jsx/intrinsic-elements.js';
|
package/lib/jsx-dev-runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { Fragment, jsxDEV } from '@zhin.js/jsx/jsx-dev-runtime';
|
package/lib/jsx-runtime.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { Fragment, jsx, jsxs } from '@zhin.js/jsx/jsx-runtime';
|
|
2
|
+
export type { JSX } from './jsx/intrinsic-elements.js';
|
package/lib/jsx-runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { Fragment, jsx, jsxs } from '@zhin.js/jsx/jsx-runtime';
|
package/lib/jsx.d.ts
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
1
|
export * from '@zhin.js/jsx';
|
|
2
|
+
export { Image, Mention, Card, Button, Markdown, Face, Text, Audio, Video, File, Reply, Forward, Share, Dice, Rps, Keyboard, Action, Link, Qrcode, Tts } from './jsx/message-tags.js';
|
|
3
|
+
export type { ImageProps, MentionProps, CardProps, ButtonProps, ButtonClickHandler, ButtonClickResult, MarkdownProps, FaceProps, TextProps } from './jsx/message-tags.js';
|
|
4
|
+
export { renderToSegments } from './jsx/message-renderer.js';
|
|
5
|
+
export type { MessageRenderOptions } from './jsx/message-renderer.js';
|
|
6
|
+
export type { JSX, MessageTagProps } from './jsx/intrinsic-elements.js';
|
package/lib/jsx.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
1
|
export * from '@zhin.js/jsx';
|
|
2
|
+
export { Image, Mention, Card, Button, Markdown, Face, Text, Audio, Video, File, Reply, Forward, Share, Dice, Rps, Keyboard, Action, Link, Qrcode, Tts } from './jsx/message-tags.js';
|
|
3
|
+
export { renderToSegments } from './jsx/message-renderer.js';
|
|
@@ -31,6 +31,7 @@ export class ImRuntime {
|
|
|
31
31
|
record: (request, receipt) => this.#conversations.recordOutbound(request, receipt),
|
|
32
32
|
rememberFallback: (conversation, generation, map) => this.#interactions.rememberFallback(conversation, generation, map),
|
|
33
33
|
publish: (event) => this.#messageEventStream.publish(event),
|
|
34
|
+
prepareButtons: (request, snapshot) => this.#interactions.prepareButtons(request, snapshot),
|
|
34
35
|
}, options.renderer);
|
|
35
36
|
this.#inbound = new InboundRuntime({
|
|
36
37
|
interactions: this.#interactions,
|
|
@@ -110,7 +110,7 @@ export class InboundRuntime {
|
|
|
110
110
|
await this.#runHandlers(lease.value, 'message.receive', [
|
|
111
111
|
withEndpointEventPayload(source, message),
|
|
112
112
|
]);
|
|
113
|
-
result = await this.#dispatchInteractive(message, requester, admission)
|
|
113
|
+
result = await this.#dispatchInteractive(message, requester, admission, lease.value)
|
|
114
114
|
?? await this.#dispatcher.dispatch(message, lease.value, interactionFactory);
|
|
115
115
|
if (!result.matched && ingressRoute) {
|
|
116
116
|
logger.debug(formatCompact({
|
|
@@ -258,8 +258,8 @@ export class InboundRuntime {
|
|
|
258
258
|
});
|
|
259
259
|
return this.context.interactions.create(source);
|
|
260
260
|
}
|
|
261
|
-
async #dispatchInteractive(message, requester, admission) {
|
|
262
|
-
const handled = await this.context.interactions.dispatch(message, admission);
|
|
261
|
+
async #dispatchInteractive(message, requester, admission, snapshot) {
|
|
262
|
+
const handled = await this.context.interactions.dispatch(message, admission, snapshot);
|
|
263
263
|
return handled
|
|
264
264
|
? Object.freeze({ matched: true, command: 'interactive', owner: requester })
|
|
265
265
|
: undefined;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract';
|
|
2
2
|
import type { UserInteraction } from '@zhin.js/interaction';
|
|
3
|
-
import type {
|
|
3
|
+
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
4
|
+
import type { Message, MessageSenderRef, SendContent, SendRequest } from './contracts.js';
|
|
4
5
|
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
6
|
+
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
5
7
|
export interface UserInteractionSource {
|
|
6
8
|
readonly conversation: ConversationRef;
|
|
7
9
|
readonly sender?: MessageSenderRef;
|
|
@@ -12,8 +14,9 @@ export declare class RuntimeInteractionCoordinator<Admission = never> {
|
|
|
12
14
|
#private;
|
|
13
15
|
constructor(router?: RuntimeInteractiveRouter<Admission>);
|
|
14
16
|
register(prefix: string, handler: (message: Message) => Promise<boolean> | boolean, admission?: Admission): () => void;
|
|
15
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>):
|
|
16
|
-
dispatch(message: Message, admission?: Admission): Promise<boolean>;
|
|
17
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string>;
|
|
18
|
+
dispatch(message: Message, admission?: Admission, snapshot?: RuntimeSnapshot): Promise<boolean>;
|
|
19
|
+
prepareButtons(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
17
20
|
resolveClaim(message: Message): boolean;
|
|
18
21
|
createForMessage(message: Message, bind?: {
|
|
19
22
|
readonly subjectId: string;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
2
2
|
import { assertUserInteractionRequest, parseUserInteractionAnswer, projectUserInteraction, renderUserInteraction, } from '../../built/user-interaction.js';
|
|
3
3
|
import { RuntimeInteractiveRouter } from './interactive-router.js';
|
|
4
|
+
import { isJsxButtonPayload, JsxButtonRegistry } from './jsx-button-registry.js';
|
|
4
5
|
class UserInteractionTimeoutError extends Error {
|
|
5
6
|
constructor(message) {
|
|
6
7
|
super(message);
|
|
@@ -23,6 +24,7 @@ class UserInteractionDeliveryError extends Error {
|
|
|
23
24
|
export class RuntimeInteractionCoordinator {
|
|
24
25
|
#router;
|
|
25
26
|
#claims = new Map();
|
|
27
|
+
#buttons = new JsxButtonRegistry();
|
|
26
28
|
constructor(router = new RuntimeInteractiveRouter()) {
|
|
27
29
|
this.#router = router;
|
|
28
30
|
}
|
|
@@ -30,16 +32,25 @@ export class RuntimeInteractionCoordinator {
|
|
|
30
32
|
return this.#router.register(prefix, handler, admission);
|
|
31
33
|
}
|
|
32
34
|
rememberFallback(conversation, generation, map) {
|
|
33
|
-
this.#router.rememberFallback(conversation, generation, map);
|
|
35
|
+
return this.#router.rememberFallback(conversation, generation, map);
|
|
34
36
|
}
|
|
35
|
-
dispatch(message, admission) {
|
|
37
|
+
async dispatch(message, admission, snapshot) {
|
|
38
|
+
const payload = this.#router.resolvePayload(message);
|
|
39
|
+
if (payload && snapshot && await this.#buttons.dispatch(message, payload, snapshot))
|
|
40
|
+
return true;
|
|
36
41
|
return this.#router.dispatch(message, admission);
|
|
37
42
|
}
|
|
43
|
+
prepareButtons(request, snapshot) {
|
|
44
|
+
return this.#buttons.prepare(request, snapshot);
|
|
45
|
+
}
|
|
38
46
|
resolveClaim(message) {
|
|
47
|
+
const payload = this.#router.resolvePayload(message);
|
|
48
|
+
if (isJsxButtonPayload(payload))
|
|
49
|
+
return false;
|
|
39
50
|
const claim = this.#claims.get(this.#conversationKey(message));
|
|
40
51
|
if (!claim)
|
|
41
52
|
return false;
|
|
42
|
-
claim.resolve(
|
|
53
|
+
claim.resolve(payload ?? message.content);
|
|
43
54
|
return true;
|
|
44
55
|
}
|
|
45
56
|
createForMessage(message, bind) {
|
|
@@ -10,7 +10,7 @@ export declare class RuntimeInteractiveRouter<Admission = never> {
|
|
|
10
10
|
private readonly fallbackTtlMs;
|
|
11
11
|
constructor(fallbackTtlMs?: number);
|
|
12
12
|
register(prefix: string, handler: RuntimeInteractiveHandler, admission?: Admission): () => void;
|
|
13
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number):
|
|
13
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>, ttlMs?: number): Record<string, string>;
|
|
14
14
|
resolvePayload(message: Message): string | undefined;
|
|
15
15
|
dispatch(message: Message, admission?: Admission): Promise<boolean>;
|
|
16
16
|
}
|
|
@@ -16,6 +16,7 @@ export class RuntimeInteractiveRouter {
|
|
|
16
16
|
fallbackTtlMs;
|
|
17
17
|
#handlers = [];
|
|
18
18
|
#fallbacks = new Map();
|
|
19
|
+
#nextNumber = 1;
|
|
19
20
|
constructor(fallbackTtlMs = DEFAULT_FALLBACK_TTL_MS) {
|
|
20
21
|
this.fallbackTtlMs = fallbackTtlMs;
|
|
21
22
|
}
|
|
@@ -35,13 +36,17 @@ export class RuntimeInteractiveRouter {
|
|
|
35
36
|
};
|
|
36
37
|
}
|
|
37
38
|
rememberFallback(conversation, generation, map, ttlMs = this.fallbackTtlMs) {
|
|
38
|
-
if (Object.keys(map).length === 0)
|
|
39
|
-
return;
|
|
40
39
|
this.#pruneFallbacks();
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
40
|
+
const key = interactiveConversationKey(conversation, generation);
|
|
41
|
+
const allocated = {};
|
|
42
|
+
for (const [label, payload] of Object.entries(map)) {
|
|
43
|
+
allocated[/^\d+$/.test(label) ? String(this.#nextNumber++) : label] = payload;
|
|
44
|
+
}
|
|
45
|
+
// One runtime counter survives expiry/generation changes without retaining conversation IDs.
|
|
46
|
+
const entries = this.#fallbacks.get(key) ?? [];
|
|
47
|
+
entries.push(Object.freeze({ map: Object.freeze({ ...allocated }), expiresAt: Date.now() + ttlMs }));
|
|
48
|
+
this.#fallbacks.set(key, entries);
|
|
49
|
+
return allocated;
|
|
45
50
|
}
|
|
46
51
|
resolvePayload(message) {
|
|
47
52
|
const fromSegments = actionPayloadFromSegments(message.segments);
|
|
@@ -69,19 +74,17 @@ export class RuntimeInteractiveRouter {
|
|
|
69
74
|
}
|
|
70
75
|
#fallbackMap(conversation, generation) {
|
|
71
76
|
const key = interactiveConversationKey(conversation, generation);
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
if (entry.expiresAt < Date.now()) {
|
|
76
|
-
this.#fallbacks.delete(key);
|
|
77
|
-
return undefined;
|
|
78
|
-
}
|
|
79
|
-
return entry.map;
|
|
77
|
+
this.#pruneFallbacks();
|
|
78
|
+
const entries = this.#fallbacks.get(key);
|
|
79
|
+
return entries ? Object.assign({}, ...entries.map(entry => entry.map)) : undefined;
|
|
80
80
|
}
|
|
81
81
|
#pruneFallbacks() {
|
|
82
82
|
const now = Date.now();
|
|
83
|
-
for (const [key,
|
|
84
|
-
|
|
83
|
+
for (const [key, entries] of this.#fallbacks) {
|
|
84
|
+
const active = entries.filter(entry => entry.expiresAt >= now);
|
|
85
|
+
if (active.length)
|
|
86
|
+
this.#fallbacks.set(key, active);
|
|
87
|
+
else
|
|
85
88
|
this.#fallbacks.delete(key);
|
|
86
89
|
}
|
|
87
90
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Segment } from '@zhin.js/im-contract';
|
|
2
|
+
import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
+
import type { ButtonProps } from '../../jsx/message-tags.js';
|
|
4
|
+
import type { Message, SendRequest } from './contracts.js';
|
|
5
|
+
export declare function isJsxButtonPayload(payload: string | undefined): boolean;
|
|
6
|
+
export interface JsxButtonBatch {
|
|
7
|
+
bind(props: ButtonProps): Segment;
|
|
8
|
+
/** Publish callbacks immediately before transport; revoke them on definitive non-delivery. */
|
|
9
|
+
activate(payloads: ReadonlySet<string>): () => void;
|
|
10
|
+
}
|
|
11
|
+
/** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
|
|
12
|
+
export declare class JsxButtonRegistry {
|
|
13
|
+
#private;
|
|
14
|
+
prepare(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
15
|
+
dispatch(message: Message, payload: string, snapshot: RuntimeSnapshot): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
export declare function collectButtonPayloads(payload: unknown): Set<string>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { jsx } from '@zhin.js/jsx';
|
|
3
|
+
import { conversationRefKey } from '@zhin.js/im-contract';
|
|
4
|
+
import { bindOperationInput } from '@zhin.js/feature-kit';
|
|
5
|
+
import { isKeyboardSegment } from '../../built/interactive-segments/types.js';
|
|
6
|
+
const PREFIX = 'zhin:jsx:';
|
|
7
|
+
const BUTTON_TTL_MS = 60 * 60 * 1000;
|
|
8
|
+
export function isJsxButtonPayload(payload) {
|
|
9
|
+
return payload?.startsWith(PREFIX) === true;
|
|
10
|
+
}
|
|
11
|
+
/** Snapshot-owned callbacks: retired generations are unreachable and can be collected. */
|
|
12
|
+
export class JsxButtonRegistry {
|
|
13
|
+
#bindings = new WeakMap();
|
|
14
|
+
prepare(request, snapshot) {
|
|
15
|
+
const pending = new Map();
|
|
16
|
+
return {
|
|
17
|
+
bind: (props) => {
|
|
18
|
+
const { onClick, payload: manualPayload, children, label, id, ...options } = props;
|
|
19
|
+
if (onClick !== undefined && typeof onClick !== 'function')
|
|
20
|
+
throw new TypeError('Button onClick must be a function');
|
|
21
|
+
if (onClick && manualPayload !== undefined)
|
|
22
|
+
throw new TypeError('Button accepts onClick or payload, not both');
|
|
23
|
+
if (!onClick && typeof manualPayload !== 'string')
|
|
24
|
+
throw new TypeError('Button requires onClick or payload');
|
|
25
|
+
const payload = onClick ? `${PREFIX}${randomUUID()}` : manualPayload;
|
|
26
|
+
if (onClick && !props.disabled)
|
|
27
|
+
pending.set(payload, {
|
|
28
|
+
onClick, requester: request.requester, conversationKey: conversationRefKey(request.conversation),
|
|
29
|
+
expiresAt: 0,
|
|
30
|
+
});
|
|
31
|
+
return { type: 'keyboard', data: { rows: [[{
|
|
32
|
+
...options,
|
|
33
|
+
id: id ?? randomUUID(),
|
|
34
|
+
label: label ?? children,
|
|
35
|
+
payload,
|
|
36
|
+
...(onClick ? { mode: 'callback' } : {}),
|
|
37
|
+
}]] } };
|
|
38
|
+
},
|
|
39
|
+
activate: (payloads) => {
|
|
40
|
+
let active = this.#bindings.get(snapshot);
|
|
41
|
+
const activated = [];
|
|
42
|
+
if (active)
|
|
43
|
+
this.#prune(active);
|
|
44
|
+
for (const [payload, binding] of pending) {
|
|
45
|
+
if (!payloads.has(payload))
|
|
46
|
+
continue;
|
|
47
|
+
if (!active)
|
|
48
|
+
this.#bindings.set(snapshot, active = new Map());
|
|
49
|
+
active.set(payload, { ...binding, expiresAt: Date.now() + BUTTON_TTL_MS });
|
|
50
|
+
activated.push(payload);
|
|
51
|
+
}
|
|
52
|
+
pending.clear();
|
|
53
|
+
return () => { for (const payload of activated)
|
|
54
|
+
active?.delete(payload); };
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async dispatch(message, payload, snapshot) {
|
|
59
|
+
if (!isJsxButtonPayload(payload))
|
|
60
|
+
return false;
|
|
61
|
+
const active = this.#bindings.get(snapshot);
|
|
62
|
+
if (active)
|
|
63
|
+
this.#prune(active);
|
|
64
|
+
const binding = active?.get(payload);
|
|
65
|
+
// Consume stale, unknown and cross-conversation callbacks without invoking user code.
|
|
66
|
+
if (!binding || binding.conversationKey !== conversationRefKey(message.conversation))
|
|
67
|
+
return true;
|
|
68
|
+
const bound = bindOperationInput(message, binding.requester, snapshot);
|
|
69
|
+
const content = await binding.onClick(bound);
|
|
70
|
+
if (typeof content === 'number')
|
|
71
|
+
await bound.$reply(jsx('text', { text: String(content) }));
|
|
72
|
+
else if (content != null && typeof content !== 'boolean')
|
|
73
|
+
await bound.$reply(content);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
#prune(bindings) {
|
|
77
|
+
const now = Date.now();
|
|
78
|
+
for (const [payload, binding] of bindings)
|
|
79
|
+
if (binding.expiresAt <= now)
|
|
80
|
+
bindings.delete(payload);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function collectButtonPayloads(payload) {
|
|
84
|
+
const result = new Set();
|
|
85
|
+
for (const item of Array.isArray(payload) ? payload : [payload]) {
|
|
86
|
+
if (isKeyboardSegment(item)) {
|
|
87
|
+
for (const row of item.data.rows)
|
|
88
|
+
for (const button of row)
|
|
89
|
+
result.add(button.payload);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
@@ -3,9 +3,11 @@ import { type ConversationRef, type DeliveryReceipt } from '@zhin.js/im-contract
|
|
|
3
3
|
import { type SendRequest } from './contracts.js';
|
|
4
4
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
5
5
|
import { type RuntimeMessageEvent } from './message-events.js';
|
|
6
|
+
import { type JsxButtonBatch } from './jsx-button-registry.js';
|
|
6
7
|
interface OutboundDeliveryContext {
|
|
8
|
+
prepareButtons?(request: SendRequest, snapshot: RuntimeSnapshot): JsxButtonBatch;
|
|
7
9
|
record(request: SendRequest, receipt: DeliveryReceipt): Promise<void>;
|
|
8
|
-
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): void;
|
|
10
|
+
rememberFallback(conversation: ConversationRef, generation: number, map: Record<string, string>): Record<string, string> | void;
|
|
9
11
|
publish(event: RuntimeMessageEvent): void;
|
|
10
12
|
}
|
|
11
13
|
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
@@ -10,6 +10,7 @@ import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
|
10
10
|
import { requireAdapters } from './endpoint-runtime.js';
|
|
11
11
|
import { formatConversationLog, previewMessageContent } from './message-events.js';
|
|
12
12
|
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
13
|
+
import { collectButtonPayloads } from './jsx-button-registry.js';
|
|
13
14
|
const logger = getLogger('im.outbound');
|
|
14
15
|
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
15
16
|
export class OutboundDeliveryRuntime {
|
|
@@ -22,9 +23,11 @@ export class OutboundDeliveryRuntime {
|
|
|
22
23
|
async deliver(request, snapshot) {
|
|
23
24
|
const adapter = request.conversation.endpoint.id;
|
|
24
25
|
const jsxCache = new WeakMap();
|
|
26
|
+
const buttons = this.context.prepareButtons?.(request, snapshot);
|
|
27
|
+
const renderOptions = { jsxCache, bindButton: buttons?.bind };
|
|
25
28
|
let initialPayload;
|
|
26
29
|
try {
|
|
27
|
-
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming,
|
|
30
|
+
const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, renderOptions);
|
|
28
31
|
initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
|
|
29
32
|
}
|
|
30
33
|
catch (error) {
|
|
@@ -51,13 +54,20 @@ export class OutboundDeliveryRuntime {
|
|
|
51
54
|
await runRuntimeMiddleware(snapshot, envelope, async () => {
|
|
52
55
|
terminalEntered = true;
|
|
53
56
|
let payload;
|
|
57
|
+
const buttonPayloads = new Set();
|
|
54
58
|
try {
|
|
55
59
|
// Native payload replacements remain possible; only authoring values need evaluation.
|
|
56
60
|
const replacement = envelope.payload;
|
|
57
61
|
const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
|
|
58
|
-
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming,
|
|
62
|
+
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
|
|
59
63
|
: replacement;
|
|
60
|
-
payload = await prepareOutboundPayload(replaced, request.conversation, snapshot, (map) =>
|
|
64
|
+
payload = await prepareOutboundPayload(replaced, request.conversation, snapshot, (map) => {
|
|
65
|
+
for (const value of Object.values(map))
|
|
66
|
+
buttonPayloads.add(value);
|
|
67
|
+
return this.context.rememberFallback(request.conversation, snapshot.generation, map);
|
|
68
|
+
});
|
|
69
|
+
for (const value of collectButtonPayloads(payload))
|
|
70
|
+
buttonPayloads.add(value);
|
|
61
71
|
}
|
|
62
72
|
catch (error) {
|
|
63
73
|
receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
|
|
@@ -68,6 +78,7 @@ export class OutboundDeliveryRuntime {
|
|
|
68
78
|
receipt = suppressedDeliveryReceipt();
|
|
69
79
|
return;
|
|
70
80
|
}
|
|
81
|
+
const revokeButtons = buttons?.activate(buttonPayloads);
|
|
71
82
|
try {
|
|
72
83
|
const result = await requireAdapters(snapshot).send(adapter, {
|
|
73
84
|
conversation: request.conversation,
|
|
@@ -78,6 +89,8 @@ export class OutboundDeliveryRuntime {
|
|
|
78
89
|
catch (error) {
|
|
79
90
|
receipt = receiptFromEndpointError(error);
|
|
80
91
|
}
|
|
92
|
+
if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown)
|
|
93
|
+
revokeButtons?.();
|
|
81
94
|
if (receipt.status === 'sent') {
|
|
82
95
|
await this.context.record(request, receipt);
|
|
83
96
|
this.context.publish({
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
3
|
import { type JSXElement } from '@zhin.js/jsx';
|
|
4
|
+
import { type MessageRenderOptions } from '../../jsx/message-renderer.js';
|
|
4
5
|
import { type IncomingContext, type SendContent } from './contracts.js';
|
|
5
6
|
export interface OutboundRenderOptions {
|
|
6
|
-
readonly jsxCache?: WeakMap<JSXElement, Promise<
|
|
7
|
+
readonly jsxCache?: WeakMap<JSXElement, Promise<unknown>>;
|
|
8
|
+
readonly bindButton?: MessageRenderOptions['bindButton'];
|
|
7
9
|
readonly signal?: AbortSignal;
|
|
8
10
|
}
|
|
9
11
|
export declare class OutboundRenderer {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { componentHostToken } from '@zhin.js/plugin-runtime';
|
|
2
|
-
import { isJsxElement
|
|
3
|
-
import {
|
|
2
|
+
import { isJsxElement } from '@zhin.js/jsx';
|
|
3
|
+
import { isNativeMessageTag, renderToSegments } from '../../jsx/message-renderer.js';
|
|
4
4
|
import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
|
|
5
5
|
import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
|
|
6
6
|
import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
|
|
@@ -11,11 +11,11 @@ export class OutboundRenderer {
|
|
|
11
11
|
options.signal?.throwIfAborted();
|
|
12
12
|
const host = resolveComponentHost(snapshot);
|
|
13
13
|
const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
|
|
14
|
-
const rendered = await this.#render(content, requester, snapshot, host, ctx, 0, options.jsxCache ?? new WeakMap(), options.signal, new Set());
|
|
14
|
+
const rendered = await this.#render(content, requester, snapshot, host, ctx, 0, options.jsxCache ?? new WeakMap(), options.signal, new Set(), options.bindButton);
|
|
15
15
|
options.signal?.throwIfAborted();
|
|
16
16
|
return rendered;
|
|
17
17
|
}
|
|
18
|
-
async #render(content, requester, snapshot, host, ctx, depth, jsxCache, signal, arrayAncestors) {
|
|
18
|
+
async #render(content, requester, snapshot, host, ctx, depth, jsxCache, signal, arrayAncestors, bindButton, jsxAncestors = new Set()) {
|
|
19
19
|
signal?.throwIfAborted();
|
|
20
20
|
if (depth > maxComponentDepth)
|
|
21
21
|
throw new Error('Component render depth exceeded 32');
|
|
@@ -28,19 +28,38 @@ export class OutboundRenderer {
|
|
|
28
28
|
throw new RangeError('SendContent array depth exceeded 512');
|
|
29
29
|
// Each parallel branch gets its own ancestry; repeated sibling arrays are valid.
|
|
30
30
|
const ancestors = new Set(arrayAncestors).add(content);
|
|
31
|
-
const items = await Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth, jsxCache, signal, ancestors)));
|
|
31
|
+
const items = await Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth, jsxCache, signal, ancestors, bindButton, jsxAncestors)));
|
|
32
32
|
signal?.throwIfAborted();
|
|
33
33
|
return flattenOutboundArray(items);
|
|
34
34
|
}
|
|
35
35
|
if (isJsxElement(content)) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
if (jsxAncestors.has(content))
|
|
37
|
+
throw new TypeError('Circular JSX component tree');
|
|
38
|
+
let segments = jsxCache.get(content);
|
|
39
|
+
if (!segments) {
|
|
40
|
+
const ancestors = new Set(jsxAncestors).add(content);
|
|
41
|
+
const renderNamedComponent = async (name, props) => {
|
|
42
|
+
const components = snapshot.projections.get(componentFeatureId);
|
|
43
|
+
if (!isComponentIndex(components)) {
|
|
44
|
+
throw new TypeError(`Unknown message tag ${name}; register a component or wrap HTML in <html>`);
|
|
45
|
+
}
|
|
46
|
+
const rendered = await components.render(requester, name, props, { snapshot, ...(signal ? { signal } : {}) });
|
|
47
|
+
if (rendered == null)
|
|
48
|
+
return [];
|
|
49
|
+
// Resolve every SendContent shape with the same depth and ancestry
|
|
50
|
+
// guards as ComponentCall. Root raw payloads remain opaque.
|
|
51
|
+
return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors, bindButton, ancestors);
|
|
52
|
+
};
|
|
53
|
+
segments = typeof content.type === 'string' && !isNativeMessageTag(content.type)
|
|
54
|
+
? renderNamedComponent(content.type, content.props)
|
|
55
|
+
: renderToSegments(content, { signal, bindButton,
|
|
56
|
+
renderComponent: async (name, props) => await renderNamedComponent(name, props),
|
|
57
|
+
});
|
|
58
|
+
jsxCache.set(content, segments);
|
|
40
59
|
}
|
|
41
|
-
const rendered = await
|
|
60
|
+
const rendered = await segments;
|
|
42
61
|
signal?.throwIfAborted();
|
|
43
|
-
return rendered
|
|
62
|
+
return rendered;
|
|
44
63
|
}
|
|
45
64
|
if (isRawContent(content))
|
|
46
65
|
return content.payload;
|
|
@@ -55,7 +74,9 @@ export class OutboundRenderer {
|
|
|
55
74
|
}
|
|
56
75
|
if (isComponentCall(content)) {
|
|
57
76
|
const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot, ...(signal ? { signal } : {}) });
|
|
58
|
-
|
|
77
|
+
if (rendered == null)
|
|
78
|
+
return [];
|
|
79
|
+
return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors, bindButton, jsxAncestors);
|
|
59
80
|
}
|
|
60
81
|
throw new TypeError('Unsupported SendContent');
|
|
61
82
|
}
|
|
@@ -67,7 +67,7 @@ export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'n
|
|
|
67
67
|
* keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
|
|
68
68
|
* fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
|
|
69
69
|
*/
|
|
70
|
-
export declare function applyOutboundInteractivePolicy(payload: unknown, policy: InteractivePolicy, remember?: (map: Record<string, string>) => void): unknown;
|
|
70
|
+
export declare function applyOutboundInteractivePolicy(payload: unknown, policy: InteractivePolicy, remember?: (map: Record<string, string>) => Record<string, string> | void): unknown;
|
|
71
71
|
/**
|
|
72
72
|
* Normalize a rendered outbound payload toward canonical wire segments:
|
|
73
73
|
* - segment arrays stay arrays (html segments converted per element,
|
|
@@ -124,8 +124,9 @@ export function applyOutboundInteractivePolicy(payload, policy, remember) {
|
|
|
124
124
|
if (!isKeyboardSegment(item))
|
|
125
125
|
return item;
|
|
126
126
|
const data = item.data;
|
|
127
|
-
remember?.(effectiveKeyboardFallbackMap(data));
|
|
128
|
-
|
|
127
|
+
const map = remember?.(effectiveKeyboardFallbackMap(data));
|
|
128
|
+
const projected = map ? { ...data, fallback: { hint: data.fallback?.hint ?? '请选择(回复数字):', map } } : data;
|
|
129
|
+
return { type: 'text', data: { text: renderKeyboardAsText(projected) } };
|
|
129
130
|
});
|
|
130
131
|
}
|
|
131
132
|
/** 多 endpoint 展开的 record id(`slot.id~entry`)→ slot id(entry 名禁含 `~`,见 adapter-index)。 */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/core",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.42",
|
|
4
4
|
"description": "Zhin机器人核心框架",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"@zhin.js/adapter": "1.1.17",
|
|
72
72
|
"@zhin.js/command": "1.1.5",
|
|
73
73
|
"@zhin.js/component": "1.1.4",
|
|
74
|
-
"@zhin.js/database": "1.1.
|
|
74
|
+
"@zhin.js/database": "1.1.3",
|
|
75
75
|
"@zhin.js/handler": "1.1.3",
|
|
76
76
|
"@zhin.js/im-contract": "1.1.3",
|
|
77
77
|
"@zhin.js/interaction": "1.1.0",
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
"@zhin.js/plugin-runtime": "1.1.12",
|
|
83
83
|
"@zhin.js/schedule-feature": "1.1.3",
|
|
84
84
|
"@zhin.js/schema": "1.1.1",
|
|
85
|
-
"@zhin.js/jsx": "1.1.
|
|
85
|
+
"@zhin.js/jsx": "1.1.2",
|
|
86
86
|
"@zhin.js/feature-kit": "1.1.3"
|
|
87
87
|
},
|
|
88
88
|
"devDependencies": {
|