@zhin.js/core 1.1.40 → 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/ai-trigger.js +2 -2
- package/lib/built/html-segment-fallback.d.ts +4 -2
- package/lib/built/html-segment-fallback.js +1 -1
- package/lib/built/interactive-segments/action.js +1 -1
- package/lib/built/interactive-segments/resolve.js +1 -1
- package/lib/built/interactive-segments/types.d.ts +2 -2
- package/lib/built/interactive-segments/types.js +22 -2
- package/lib/built/outbound-content-arrays.d.ts +4 -0
- package/lib/built/outbound-content-arrays.js +32 -0
- package/lib/built/outbound-media-utils.d.ts +5 -3
- package/lib/built/outbound-media-utils.js +5 -3
- package/lib/built/segment-contract/assert.js +6 -1
- package/lib/built/segment-contract/json-schema.d.ts +1 -1
- package/lib/built/segment-contract/json-schema.js +30 -2
- package/lib/feature/component.d.ts +1 -0
- package/lib/feature/component.js +1 -0
- package/lib/index.d.ts +3 -2
- package/lib/index.js +2 -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 -2
- package/lib/jsx-dev-runtime.js +1 -2
- package/lib/jsx-runtime.d.ts +2 -12
- package/lib/jsx-runtime.js +1 -10
- package/lib/jsx.d.ts +6 -30
- package/lib/jsx.js +3 -93
- package/lib/message.d.ts +0 -11
- package/lib/plugin-runtime/im/contracts.d.ts +14 -6
- package/lib/plugin-runtime/im/contracts.js +28 -6
- package/lib/plugin-runtime/im/im-runtime.js +1 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +33 -9
- 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/message-dispatcher.js +0 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +3 -1
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +50 -18
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +9 -2
- package/lib/plugin-runtime/im/outbound-renderer.js +52 -6
- package/lib/plugin-runtime/im/outbound-segments.d.ts +6 -1
- package/lib/plugin-runtime/im/outbound-segments.js +28 -8
- package/lib/types.d.ts +5 -7
- package/lib/utils.d.ts +4 -4
- package/lib/utils.js +9 -17
- package/package.json +15 -13
- package/lib/component.d.ts +0 -26
- package/lib/component.js +0 -583
|
@@ -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. */
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import { EndpointDeliveryError } from '@zhin.js/im-contract';
|
|
3
3
|
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
4
|
-
import {
|
|
4
|
+
import { isJsxElement } from '@zhin.js/jsx';
|
|
5
|
+
import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
|
|
5
6
|
import { OutboundRenderer } from './outbound-renderer.js';
|
|
6
|
-
import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
|
|
7
|
+
import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundHtmlPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
|
|
7
8
|
import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
|
|
8
|
-
import {
|
|
9
|
+
import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
10
|
+
import { requireAdapters } from './endpoint-runtime.js';
|
|
9
11
|
import { formatConversationLog, previewMessageContent } from './message-events.js';
|
|
10
12
|
import { runRuntimeMiddleware } from './runtime-middleware.js';
|
|
13
|
+
import { collectButtonPayloads } from './jsx-button-registry.js';
|
|
11
14
|
const logger = getLogger('im.outbound');
|
|
12
15
|
/** Owns rendering, policy projection, middleware, Endpoint delivery, and delivery facts. */
|
|
13
16
|
export class OutboundDeliveryRuntime {
|
|
@@ -19,9 +22,12 @@ export class OutboundDeliveryRuntime {
|
|
|
19
22
|
}
|
|
20
23
|
async deliver(request, snapshot) {
|
|
21
24
|
const adapter = request.conversation.endpoint.id;
|
|
25
|
+
const jsxCache = new WeakMap();
|
|
26
|
+
const buttons = this.context.prepareButtons?.(request, snapshot);
|
|
27
|
+
const renderOptions = { jsxCache, bindButton: buttons?.bind };
|
|
22
28
|
let initialPayload;
|
|
23
29
|
try {
|
|
24
|
-
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);
|
|
25
31
|
initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
|
|
26
32
|
}
|
|
27
33
|
catch (error) {
|
|
@@ -48,14 +54,31 @@ export class OutboundDeliveryRuntime {
|
|
|
48
54
|
await runRuntimeMiddleware(snapshot, envelope, async () => {
|
|
49
55
|
terminalEntered = true;
|
|
50
56
|
let payload;
|
|
57
|
+
const buttonPayloads = new Set();
|
|
51
58
|
try {
|
|
52
|
-
payload
|
|
59
|
+
// Native payload replacements remain possible; only authoring values need evaluation.
|
|
60
|
+
const replacement = envelope.payload;
|
|
61
|
+
const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
|
|
62
|
+
? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, renderOptions)
|
|
63
|
+
: replacement;
|
|
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);
|
|
53
71
|
}
|
|
54
72
|
catch (error) {
|
|
55
73
|
receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
|
|
56
74
|
? receiptFromEndpointError(error, false) : rejectedDeliveryReceipt('outbound_payload_rejected');
|
|
57
75
|
return;
|
|
58
76
|
}
|
|
77
|
+
if (isEmptyOutboundPayload(payload)) {
|
|
78
|
+
receipt = suppressedDeliveryReceipt();
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const revokeButtons = buttons?.activate(buttonPayloads);
|
|
59
82
|
try {
|
|
60
83
|
const result = await requireAdapters(snapshot).send(adapter, {
|
|
61
84
|
conversation: request.conversation,
|
|
@@ -66,6 +89,8 @@ export class OutboundDeliveryRuntime {
|
|
|
66
89
|
catch (error) {
|
|
67
90
|
receipt = receiptFromEndpointError(error);
|
|
68
91
|
}
|
|
92
|
+
if (receipt.status !== 'sent' && !receipt.failure?.deliveryUnknown)
|
|
93
|
+
revokeButtons?.();
|
|
69
94
|
if (receipt.status === 'sent') {
|
|
70
95
|
await this.context.record(request, receipt);
|
|
71
96
|
this.context.publish({
|
|
@@ -100,6 +125,15 @@ export class OutboundDeliveryRuntime {
|
|
|
100
125
|
return receipt ?? failedDeliveryReceipt('outbound_delivery_incomplete');
|
|
101
126
|
}
|
|
102
127
|
}
|
|
128
|
+
function isEmptyOutboundPayload(payload) {
|
|
129
|
+
if (payload === '')
|
|
130
|
+
return true;
|
|
131
|
+
return Array.isArray(payload) && payload.every(item => item?.type === 'text' && item.data?.text === '');
|
|
132
|
+
}
|
|
133
|
+
function needsAuthoringRender(value) {
|
|
134
|
+
const isAuthoring = (item) => isJsxElement(item) || isComponentCall(item) || isRawContent(item);
|
|
135
|
+
return Array.isArray(value) ? flattenOutboundArray(value).some(isAuthoring) : isAuthoring(value);
|
|
136
|
+
}
|
|
103
137
|
export function failedDeliveryReceipt(code, retryable = false) {
|
|
104
138
|
return Object.freeze({
|
|
105
139
|
status: 'failed',
|
|
@@ -112,18 +146,21 @@ export function failedDeliveryReceipt(code, retryable = false) {
|
|
|
112
146
|
}
|
|
113
147
|
async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
|
|
114
148
|
const adapter = conversation.endpoint.id;
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
:
|
|
120
|
-
|
|
121
|
-
});
|
|
149
|
+
const markdownResolved = applyOutboundMarkdownPolicy(Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
|
|
150
|
+
let payload = await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
|
|
151
|
+
mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
|
|
152
|
+
htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
|
|
153
|
+
onHtmlFallback: reason => logger.debug(formatCompact({ op: 'html_fallback', reason, generation: snapshot.generation })),
|
|
154
|
+
});
|
|
122
155
|
if (rememberInteractiveFallback) {
|
|
123
156
|
payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
|
|
124
157
|
}
|
|
125
|
-
if (
|
|
158
|
+
if (Array.isArray(payload)) {
|
|
159
|
+
// Empty text carries no wire content, including HTML's empty fallback.
|
|
160
|
+
// Remove it before canonical validation (required strings reject '').
|
|
161
|
+
payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
|
|
126
162
|
assertCanonicalSegments(payload);
|
|
163
|
+
}
|
|
127
164
|
const supported = resolveOutboundSupportedSegments(adapter, snapshot);
|
|
128
165
|
const supportedPayload = rememberInteractiveFallback ? payload : applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot));
|
|
129
166
|
if (supported && Array.isArray(supportedPayload)) {
|
|
@@ -139,11 +176,6 @@ function resolveHtmlRenderer(snapshot) {
|
|
|
139
176
|
? host
|
|
140
177
|
: undefined;
|
|
141
178
|
}
|
|
142
|
-
function isDirectHtmlConsumer(snapshot, adapter) {
|
|
143
|
-
const owner = snapshot.capabilities.get(adapter)?.owner;
|
|
144
|
-
const packageName = owner ? snapshot.tree.get(owner)?.packageName : undefined;
|
|
145
|
-
return adapterTypeName(packageName) === 'sandbox';
|
|
146
|
-
}
|
|
147
179
|
function receiptFromEndpointResult(messageId, conversation) {
|
|
148
180
|
if (typeof messageId !== 'string' || messageId.trim() === '') {
|
|
149
181
|
return unknownDeliveryReceipt('delivery_unconfirmed');
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
2
2
|
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
3
|
+
import { type JSXElement } from '@zhin.js/jsx';
|
|
4
|
+
import { type MessageRenderOptions } from '../../jsx/message-renderer.js';
|
|
3
5
|
import { type IncomingContext, type SendContent } from './contracts.js';
|
|
6
|
+
export interface OutboundRenderOptions {
|
|
7
|
+
readonly jsxCache?: WeakMap<JSXElement, Promise<unknown>>;
|
|
8
|
+
readonly bindButton?: MessageRenderOptions['bindButton'];
|
|
9
|
+
readonly signal?: AbortSignal;
|
|
10
|
+
}
|
|
4
11
|
export declare class OutboundRenderer {
|
|
5
12
|
#private;
|
|
6
|
-
render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext): Promise<unknown>;
|
|
13
|
+
render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext, options?: OutboundRenderOptions): Promise<unknown>;
|
|
7
14
|
}
|
|
@@ -1,21 +1,65 @@
|
|
|
1
1
|
import { componentHostToken } from '@zhin.js/plugin-runtime';
|
|
2
|
+
import { isJsxElement } from '@zhin.js/jsx';
|
|
3
|
+
import { isNativeMessageTag, renderToSegments } from '../../jsx/message-renderer.js';
|
|
4
|
+
import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
|
|
2
5
|
import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
|
|
3
6
|
import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
|
|
4
7
|
const maxComponentDepth = 32;
|
|
5
8
|
const TEMPLATE_MARKER = '${';
|
|
6
9
|
export class OutboundRenderer {
|
|
7
|
-
async render(content, requester, snapshot, conversation, incoming) {
|
|
10
|
+
async render(content, requester, snapshot, conversation, incoming, options = {}) {
|
|
11
|
+
options.signal?.throwIfAborted();
|
|
8
12
|
const host = resolveComponentHost(snapshot);
|
|
9
13
|
const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
|
|
10
|
-
|
|
14
|
+
const rendered = await this.#render(content, requester, snapshot, host, ctx, 0, options.jsxCache ?? new WeakMap(), options.signal, new Set(), options.bindButton);
|
|
15
|
+
options.signal?.throwIfAborted();
|
|
16
|
+
return rendered;
|
|
11
17
|
}
|
|
12
|
-
async #render(content, requester, snapshot, host, ctx, depth) {
|
|
18
|
+
async #render(content, requester, snapshot, host, ctx, depth, jsxCache, signal, arrayAncestors, bindButton, jsxAncestors = new Set()) {
|
|
19
|
+
signal?.throwIfAborted();
|
|
13
20
|
if (depth > maxComponentDepth)
|
|
14
21
|
throw new Error('Component render depth exceeded 32');
|
|
15
22
|
if (typeof content === 'string')
|
|
16
23
|
return compileText(content, host, ctx);
|
|
17
24
|
if (Array.isArray(content)) {
|
|
18
|
-
|
|
25
|
+
if (arrayAncestors.has(content))
|
|
26
|
+
throw new TypeError('Cyclic SendContent array');
|
|
27
|
+
if (arrayAncestors.size >= MAX_OUTBOUND_ARRAY_DEPTH)
|
|
28
|
+
throw new RangeError('SendContent array depth exceeded 512');
|
|
29
|
+
// Each parallel branch gets its own ancestry; repeated sibling arrays are valid.
|
|
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, bindButton, jsxAncestors)));
|
|
32
|
+
signal?.throwIfAborted();
|
|
33
|
+
return flattenOutboundArray(items);
|
|
34
|
+
}
|
|
35
|
+
if (isJsxElement(content)) {
|
|
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);
|
|
59
|
+
}
|
|
60
|
+
const rendered = await segments;
|
|
61
|
+
signal?.throwIfAborted();
|
|
62
|
+
return rendered;
|
|
19
63
|
}
|
|
20
64
|
if (isRawContent(content))
|
|
21
65
|
return content.payload;
|
|
@@ -29,8 +73,10 @@ export class OutboundRenderer {
|
|
|
29
73
|
return content;
|
|
30
74
|
}
|
|
31
75
|
if (isComponentCall(content)) {
|
|
32
|
-
const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot });
|
|
33
|
-
|
|
76
|
+
const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot, ...(signal ? { signal } : {}) });
|
|
77
|
+
if (rendered == null)
|
|
78
|
+
return [];
|
|
79
|
+
return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors, bindButton, jsxAncestors);
|
|
34
80
|
}
|
|
35
81
|
throw new TypeError('Unsupported SendContent');
|
|
36
82
|
}
|
|
@@ -36,11 +36,16 @@ export interface OutboundSegmentsPolicy {
|
|
|
36
36
|
readonly outboundMedia: readonly ('url' | 'path' | 'base64' | 'upload')[];
|
|
37
37
|
readonly interactive?: InteractivePolicy;
|
|
38
38
|
readonly markdown?: 'native' | 'text';
|
|
39
|
+
readonly html?: 'direct' | 'image' | 'text';
|
|
39
40
|
}
|
|
40
41
|
export interface NormalizeOutboundOptions {
|
|
41
42
|
/** 缺省 `url-or-text`(未声明 adapter 的保守兜底:仅 URL 媒体可达)。 */
|
|
42
43
|
readonly mediaPolicy?: OutboundMediaPolicy;
|
|
44
|
+
readonly htmlPolicy?: 'direct' | 'image' | 'text';
|
|
45
|
+
readonly onHtmlFallback?: (reason: 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported') => void;
|
|
43
46
|
}
|
|
47
|
+
/** HTML transport is an adapter capability, independent of its package name. */
|
|
48
|
+
export declare function resolveOutboundHtmlPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'direct' | 'image' | 'text';
|
|
44
49
|
/**
|
|
45
50
|
* 解析端点的出站媒体策略:读 adapter definition 声明的 `segments.outboundMedia`
|
|
46
51
|
* (多 endpoint 展开的 `slot~entry` id 回退到 slot id 查声明);
|
|
@@ -62,7 +67,7 @@ export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'n
|
|
|
62
67
|
* keyboard 段降级:'text' 端点把 keyboard 渲染为编号文本,并把有效
|
|
63
68
|
* fallback 映射交给调用方所属的 runtime;'native' 端点透传 keyboard。
|
|
64
69
|
*/
|
|
65
|
-
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;
|
|
66
71
|
/**
|
|
67
72
|
* Normalize a rendered outbound payload toward canonical wire segments:
|
|
68
73
|
* - segment arrays stay arrays (html segments converted per element,
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import { htmlToFallbackText } from '../../built/html-to-text.js';
|
|
2
|
+
import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
|
|
2
3
|
import { toCanonicalSegments } from '../../built/generic-segment-mapper.js';
|
|
3
4
|
import { effectiveKeyboardFallbackMap, renderKeyboardAsText, } from '../../built/interactive-segments/resolve.js';
|
|
4
5
|
import { DEFAULT_INTERACTIVE_POLICY, isKeyboardSegment, } from '../../built/interactive-segments/types.js';
|
|
5
6
|
import { isMediaRef } from '../../built/segment-contract/index.js';
|
|
6
7
|
import { markdownToPlainText } from '../../built/rich-segments/markdown-to-text.js';
|
|
8
|
+
/** HTML transport is an adapter capability, independent of its package name. */
|
|
9
|
+
export function resolveOutboundHtmlPolicy(adapter, snapshot) {
|
|
10
|
+
const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
|
|
11
|
+
const policy = slot?.definition?.segments?.html;
|
|
12
|
+
return policy === 'direct' || policy === 'text' ? policy : 'image';
|
|
13
|
+
}
|
|
7
14
|
const DEFAULT_CARD_WIDTH = 540;
|
|
8
15
|
const DEFAULT_CARD_FILENAME = 'card.png';
|
|
9
16
|
const DEFAULT_MEDIA_POLICY = 'url-or-text';
|
|
@@ -117,8 +124,9 @@ export function applyOutboundInteractivePolicy(payload, policy, remember) {
|
|
|
117
124
|
if (!isKeyboardSegment(item))
|
|
118
125
|
return item;
|
|
119
126
|
const data = item.data;
|
|
120
|
-
remember?.(effectiveKeyboardFallbackMap(data));
|
|
121
|
-
|
|
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) } };
|
|
122
130
|
});
|
|
123
131
|
}
|
|
124
132
|
/** 多 endpoint 展开的 record id(`slot.id~entry`)→ slot id(entry 名禁含 `~`,见 adapter-index)。 */
|
|
@@ -142,11 +150,11 @@ function adapterTypeName(packageName) {
|
|
|
142
150
|
export async function normalizeOutboundPayload(payload, renderer, options) {
|
|
143
151
|
const mediaPolicy = options?.mediaPolicy ?? DEFAULT_MEDIA_POLICY;
|
|
144
152
|
if (Array.isArray(payload)) {
|
|
145
|
-
const resolved = await Promise.all(payload.map((item) => normalizeOneSegment(item, renderer, mediaPolicy)));
|
|
153
|
+
const resolved = await Promise.all(flattenOutboundArray(payload).map((item) => normalizeOneSegment(item, renderer, mediaPolicy, options)));
|
|
146
154
|
return applyOutboundMediaPolicy(resolved, mediaPolicy);
|
|
147
155
|
}
|
|
148
156
|
if (isOutboundSegment(payload)) {
|
|
149
|
-
return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy)], mediaPolicy);
|
|
157
|
+
return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy, options)], mediaPolicy);
|
|
150
158
|
}
|
|
151
159
|
return payload;
|
|
152
160
|
}
|
|
@@ -157,16 +165,24 @@ export async function normalizeOutboundPayload(payload, renderer, options) {
|
|
|
157
165
|
* - 其余项经 `toCanonicalSegments` 归一(字符串→text、at→mention、
|
|
158
166
|
* 旧 wire 字段 `{url,file,base64}`→MediaRef)。
|
|
159
167
|
*/
|
|
160
|
-
async function normalizeOneSegment(item, renderer, mediaPolicy) {
|
|
168
|
+
async function normalizeOneSegment(item, renderer, mediaPolicy, options) {
|
|
161
169
|
if (isOutboundSegment(item) && item.type === 'html') {
|
|
162
|
-
|
|
170
|
+
if (item.data?.html === '') {
|
|
171
|
+
return { type: 'text', data: { text: htmlSegmentFallbackText(item.data, '') } };
|
|
172
|
+
}
|
|
173
|
+
if (options?.htmlPolicy === 'direct')
|
|
174
|
+
return toCanonicalSegments([item])[0];
|
|
175
|
+
return renderHtmlSegment(item, renderer, mediaPolicy, options);
|
|
163
176
|
}
|
|
164
177
|
return toCanonicalSegments([item])[0];
|
|
165
178
|
}
|
|
166
|
-
async function renderHtmlSegment(segment, renderer, mediaPolicy) {
|
|
179
|
+
async function renderHtmlSegment(segment, renderer, mediaPolicy, options) {
|
|
167
180
|
const data = segment.data ?? {};
|
|
168
181
|
const html = typeof data.html === 'string' ? data.html : '';
|
|
169
182
|
// url-or-text 端点无法投递 base64 图片(本层无上传通道),直接文本降级,跳过渲染。
|
|
183
|
+
if (options?.htmlPolicy === 'text') {
|
|
184
|
+
return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
|
|
185
|
+
}
|
|
170
186
|
if (html && renderer && mediaPolicy !== 'url-or-text') {
|
|
171
187
|
try {
|
|
172
188
|
const result = await renderer.render(html, {
|
|
@@ -190,11 +206,15 @@ async function renderHtmlSegment(segment, renderer, mediaPolicy) {
|
|
|
190
206
|
},
|
|
191
207
|
};
|
|
192
208
|
}
|
|
209
|
+
options?.onHtmlFallback?.('renderer_failed');
|
|
193
210
|
}
|
|
194
211
|
catch {
|
|
195
|
-
|
|
212
|
+
options?.onHtmlFallback?.('renderer_failed');
|
|
196
213
|
}
|
|
197
214
|
}
|
|
215
|
+
else if (html) {
|
|
216
|
+
options?.onHtmlFallback?.(mediaPolicy === 'url-or-text' ? 'media_unsupported' : 'renderer_unavailable');
|
|
217
|
+
}
|
|
198
218
|
return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
|
|
199
219
|
}
|
|
200
220
|
/**
|
package/lib/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { MessageChannel
|
|
1
|
+
import type { MessageChannel } from './message.js';
|
|
2
2
|
import type { Message } from './plugin-runtime/im/contracts.js';
|
|
3
3
|
import { SystemLog } from './models/system-log.js';
|
|
4
4
|
import { User } from './models/user.js';
|
|
@@ -16,11 +16,8 @@ export type ObjectItem<T extends object> = T[keyof T];
|
|
|
16
16
|
/**
|
|
17
17
|
* 消息段结构,支持 text/image/at/face 等类型
|
|
18
18
|
*/
|
|
19
|
-
export
|
|
20
|
-
|
|
21
|
-
data: Record<string, any>;
|
|
22
|
-
}
|
|
23
|
-
export type MessageElement = MessageSegment | MessageComponent<any>;
|
|
19
|
+
export type { Segment as MessageSegment } from './built/segment-contract/types.js';
|
|
20
|
+
export type MessageElement = import('./built/segment-contract/types.js').Segment;
|
|
24
21
|
/**
|
|
25
22
|
* 单个或数组类型
|
|
26
23
|
*/
|
|
@@ -28,7 +25,8 @@ export type MaybeArray<T> = T | T[];
|
|
|
28
25
|
/**
|
|
29
26
|
* 消息发送内容类型
|
|
30
27
|
*/
|
|
31
|
-
export type SendContent
|
|
28
|
+
export type { SendContent } from './plugin-runtime/im/contracts.js';
|
|
29
|
+
import type { SendContent } from './plugin-runtime/im/contracts.js';
|
|
32
30
|
/** 可选:编辑已发送消息(交互式棋盘更新) */
|
|
33
31
|
export interface EditMessageOptions {
|
|
34
32
|
messageId: string;
|
package/lib/utils.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* IM-specific utilities (compose, segment) remain here.
|
|
6
6
|
*/
|
|
7
7
|
export { evaluate, execute, getValueWithRuntime, compiler, remove, isEmpty, Time, supportedPluginExtensions, resolveEntry, sleep, } from '@zhin.js/kernel';
|
|
8
|
-
import {
|
|
8
|
+
import { MessageElement, MessageMiddleware } from "./types.js";
|
|
9
9
|
import type { Message } from "./plugin-runtime/im/contracts.js";
|
|
10
10
|
import { KeyboardSegment } from "./built/interactive-segments/keyboard-segment.js";
|
|
11
11
|
import { ButtonSpec, type KeyboardRowInput } from "./built/interactive-segments/button-spec.js";
|
|
@@ -126,7 +126,7 @@ export declare namespace segment {
|
|
|
126
126
|
function keyboard(rows: KeyboardRowInput[], options?: {
|
|
127
127
|
fallback?: KeyboardFallback;
|
|
128
128
|
}): KeyboardSegment;
|
|
129
|
-
function from(content:
|
|
130
|
-
function raw(content:
|
|
131
|
-
function toString(content:
|
|
129
|
+
function from(content: string | MessageElement | readonly (string | MessageElement)[]): MessageElement[];
|
|
130
|
+
function raw(content: string | MessageElement | readonly (string | MessageElement)[]): string;
|
|
131
|
+
function toString(content: string | MessageElement | readonly (string | MessageElement)[]): string;
|
|
132
132
|
}
|