@zhin.js/core 1.1.38 → 1.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/lib/built/ai-access.d.ts +2 -2
  2. package/lib/built/ai-access.js +4 -4
  3. package/lib/built/ai-outbound/types.d.ts +1 -1
  4. package/lib/built/ai-trigger.d.ts +1 -1
  5. package/lib/built/ai-trigger.js +17 -10
  6. package/lib/built/interactive-segments/action.d.ts +3 -3
  7. package/lib/built/interactive-segments/action.js +1 -1
  8. package/lib/built/message-enrich.d.ts +19 -22
  9. package/lib/built/message-enrich.js +47 -42
  10. package/lib/built/tool-access.d.ts +2 -2
  11. package/lib/built/tool-access.js +2 -2
  12. package/lib/im-scene.d.ts +4 -3
  13. package/lib/im-scene.js +9 -9
  14. package/lib/im-session-id.d.ts +20 -12
  15. package/lib/im-session-id.js +8 -8
  16. package/lib/index.d.ts +2 -1
  17. package/lib/index.js +1 -1
  18. package/lib/message.d.ts +1 -29
  19. package/lib/message.js +1 -27
  20. package/lib/notice.d.ts +34 -32
  21. package/lib/notice.js +21 -7
  22. package/lib/plugin-runtime/im/contracts.d.ts +23 -1
  23. package/lib/plugin-runtime/im/contracts.js +4 -1
  24. package/lib/plugin-runtime/im/conversation-runtime.js +22 -31
  25. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +6 -1
  26. package/lib/plugin-runtime/im/endpoint-runtime.js +27 -5
  27. package/lib/plugin-runtime/im/inbound-runtime.d.ts +2 -2
  28. package/lib/plugin-runtime/im/inbound-runtime.js +58 -29
  29. package/lib/plugin-runtime/im/index.d.ts +3 -0
  30. package/lib/plugin-runtime/im/index.js +3 -0
  31. package/lib/plugin-runtime/im/message-dispatcher.js +28 -4
  32. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +1 -1
  33. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +54 -12
  34. package/lib/plugin-runtime/im/outbound-renderer.js +1 -1
  35. package/lib/plugin-runtime/im/outbound-segments.d.ts +2 -0
  36. package/lib/plugin-runtime/im/outbound-segments.js +8 -0
  37. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  38. package/lib/plugin-runtime/im/runtime-middleware.js +1 -1
  39. package/lib/request.d.ts +27 -35
  40. package/lib/request.js +14 -6
  41. package/lib/side-event/base.d.ts +64 -43
  42. package/lib/side-event/base.js +66 -19
  43. package/lib/side-event/dispatch.js +40 -38
  44. package/lib/side-event/normalize.d.ts +9 -8
  45. package/lib/side-event/normalize.js +9 -8
  46. package/lib/side-event/types.d.ts +3 -6
  47. package/lib/side-event/types.js +0 -5
  48. package/lib/system-event.d.ts +17 -11
  49. package/lib/system-event.js +8 -6
  50. package/lib/types.d.ts +3 -2
  51. package/lib/utils.d.ts +1 -1
  52. package/package.json +10 -10
@@ -1,8 +1,9 @@
1
1
  import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
2
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
2
3
  import { formatCompact, getLogger } from '@zhin.js/logger';
3
4
  import { createOutboundEnvelope } from './contracts.js';
4
5
  import { OutboundRenderer } from './outbound-renderer.js';
5
- import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, } from './outbound-segments.js';
6
+ import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
6
7
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
7
8
  import { adapterTypeName, requireAdapters } from './endpoint-runtime.js';
8
9
  import { formatConversationLog, previewMessageContent } from './message-events.js';
@@ -23,7 +24,9 @@ export class OutboundDeliveryRuntime {
23
24
  const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
24
25
  initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
25
26
  }
26
- catch {
27
+ catch (error) {
28
+ if (error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent')
29
+ return receiptFromEndpointError(error, false);
27
30
  return rejectedDeliveryReceipt('outbound_payload_rejected');
28
31
  }
29
32
  let adapters;
@@ -31,7 +34,7 @@ export class OutboundDeliveryRuntime {
31
34
  adapters = requireAdapters(snapshot);
32
35
  }
33
36
  catch (error) {
34
- return receiptFromEndpointError(error);
37
+ return receiptFromEndpointError(error, false);
35
38
  }
36
39
  const envelope = createOutboundEnvelope({
37
40
  conversation: request.conversation,
@@ -48,8 +51,9 @@ export class OutboundDeliveryRuntime {
48
51
  try {
49
52
  payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
50
53
  }
51
- catch {
52
- receipt = rejectedDeliveryReceipt('outbound_payload_rejected');
54
+ catch (error) {
55
+ receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
56
+ ? receiptFromEndpointError(error, false) : rejectedDeliveryReceipt('outbound_payload_rejected');
53
57
  return;
54
58
  }
55
59
  try {
@@ -120,6 +124,13 @@ async function prepareOutboundPayload(rendered, conversation, snapshot, remember
120
124
  }
121
125
  if (!directHtml && Array.isArray(payload))
122
126
  assertCanonicalSegments(payload);
127
+ const supported = resolveOutboundSupportedSegments(adapter, snapshot);
128
+ const supportedPayload = rememberInteractiveFallback ? payload : applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot));
129
+ if (supported && Array.isArray(supportedPayload)) {
130
+ const unsupported = supportedPayload.find(segment => segment && typeof segment === 'object' && typeof segment.type === 'string' && !supported.includes(segment.type));
131
+ if (unsupported)
132
+ throw new EndpointDeliveryError('unsupported_operation', `Adapter does not support canonical segment ${unsupported.type}`, 'not_sent');
133
+ }
123
134
  return payload;
124
135
  }
125
136
  function resolveHtmlRenderer(snapshot) {
@@ -134,19 +145,50 @@ function isDirectHtmlConsumer(snapshot, adapter) {
134
145
  return adapterTypeName(packageName) === 'sandbox';
135
146
  }
136
147
  function receiptFromEndpointResult(messageId, conversation) {
148
+ if (typeof messageId !== 'string' || messageId.trim() === '') {
149
+ return unknownDeliveryReceipt('delivery_unconfirmed');
150
+ }
137
151
  return Object.freeze({
138
152
  status: 'sent',
139
153
  message: Object.freeze({ conversation, id: messageId }),
140
154
  });
141
155
  }
142
- function receiptFromEndpointError(error) {
143
- const message = error instanceof Error ? error.message : String(error);
144
- if (/Unknown Adapter Endpoint|does not support outbound/u.test(message)) {
145
- return unsupportedDeliveryReceipt('outbound_unsupported');
156
+ function receiptFromEndpointError(error, attempted = true) {
157
+ if (error instanceof EndpointDeliveryError) {
158
+ if (error.code === 'outbound_unsupported' || error.code === 'endpoint_not_found') {
159
+ return unsupportedDeliveryReceipt('outbound_unsupported');
160
+ }
161
+ if (error.code === 'unsupported_operation' && error.disposition === 'not_sent') {
162
+ return unsupportedDeliveryReceipt(error.code);
163
+ }
164
+ if (error.disposition === 'unknown')
165
+ return unknownDeliveryReceipt(error.code);
166
+ return failedDeliveryReceipt(error.code);
167
+ }
168
+ // imhelper ProtocolError exposes stable protocol facts without a Core SDK dependency.
169
+ if (error && typeof error === 'object' && 'protocol' in error && 'kind' in error && 'response' in error
170
+ && error.protocol === 'onebot-v11' && error.kind === 'protocol') {
171
+ const response = error.response;
172
+ if (response && typeof response === 'object' && 'status' in response && response.status === 'failed') {
173
+ return failedDeliveryReceipt('platform_rejected');
174
+ }
146
175
  }
147
- if (/not active/u.test(message))
148
- return failedDeliveryReceipt('endpoint_inactive', true);
149
- return failedDeliveryReceipt('endpoint_send_failed', true);
176
+ // Before the endpoint send boundary no message can have entered a transport.
177
+ if (!attempted)
178
+ return failedDeliveryReceipt('endpoint_send_failed');
179
+ // Unknown SDK/network failures provide no evidence that replay is safe.
180
+ return unknownDeliveryReceipt('endpoint_send_failed');
181
+ }
182
+ function unknownDeliveryReceipt(code) {
183
+ return Object.freeze({
184
+ status: 'failed',
185
+ failure: Object.freeze({
186
+ code,
187
+ message: 'Message delivery is unconfirmed; resending may duplicate delivery.',
188
+ retryable: false,
189
+ deliveryUnknown: true,
190
+ }),
191
+ });
150
192
  }
151
193
  function suppressedDeliveryReceipt() {
152
194
  return Object.freeze({ status: 'suppressed' });
@@ -29,7 +29,7 @@ export class OutboundRenderer {
29
29
  return content;
30
30
  }
31
31
  if (isComponentCall(content)) {
32
- const rendered = await requireComponents(snapshot).render(requester, content.name, content.props);
32
+ const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot });
33
33
  return this.#render(rendered, requester, snapshot, host, ctx, depth + 1);
34
34
  }
35
35
  throw new TypeError('Unsupported SendContent');
@@ -53,6 +53,8 @@ export declare function isOutboundSegment(value: unknown): value is OutboundSegm
53
53
  * `segments.interactive`,否则按平台名查内置表,未知平台回退 'text'。
54
54
  */
55
55
  export declare function resolveOutboundInteractivePolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): InteractivePolicy;
56
+ /** Read declared support from this operation's snapshot without requiring live admission. */
57
+ export declare function resolveOutboundSupportedSegments(adapter: CapabilityId, snapshot: RuntimeSnapshot): readonly string[] | undefined;
56
58
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
57
59
  export declare function resolveOutboundMarkdownPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'native' | 'text';
58
60
  export declare function applyOutboundMarkdownPolicy(payload: unknown, policy: 'native' | 'text'): unknown;
@@ -64,6 +64,14 @@ export function resolveOutboundInteractivePolicy(adapter, snapshot) {
64
64
  return (adapterType ? OUTBOUND_INTERACTIVE_POLICY_BY_ADAPTER[adapterType] : undefined)
65
65
  ?? DEFAULT_INTERACTIVE_POLICY;
66
66
  }
67
+ /** Read declared support from this operation's snapshot without requiring live admission. */
68
+ export function resolveOutboundSupportedSegments(adapter, snapshot) {
69
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
70
+ if (!slot?.definition || typeof slot.definition !== 'object')
71
+ return undefined;
72
+ const segments = slot.definition.segments;
73
+ return Array.isArray(segments?.supported) && segments.supported.every(type => typeof type === 'string') ? segments.supported : undefined;
74
+ }
67
75
  /** Preserve semantic Markdown only when the endpoint explicitly declares native consumption. */
68
76
  export function resolveOutboundMarkdownPolicy(adapter, snapshot) {
69
77
  const slot = snapshot.capabilities.get(adapter)
@@ -3,4 +3,4 @@
3
3
  * @module zhin.js/core/runtime
4
4
  */
5
5
  export { outboundMessageToken } from './im-runtime.js';
6
- export { Message, type ComponentCall, type ConversationAddress, type IncomingContext, type IncomingMessage, type MessageDispatchResult, type OutboundMessageService, type MessageSenderRef, type OutboundEnvelope, type RawContent, type SendContent, type SendRequest, } from './contracts.js';
6
+ export { Message, type MessageBase, type ComponentCall, type ConversationAddress, type IncomingContext, type IncomingMessage, type MessageDispatchResult, type OutboundMessageService, type MessageSenderRef, type OutboundEnvelope, type RawContent, type SendContent, type SendRequest, } from './contracts.js';
@@ -3,7 +3,7 @@ import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
3
3
  export async function runRuntimeMiddleware(snapshot, input, terminal, target) {
4
4
  const index = middleware(snapshot);
5
5
  if (index)
6
- await index.run(input, terminal, target);
6
+ await index.run(input, terminal, target, snapshot);
7
7
  else
8
8
  await terminal();
9
9
  }
package/lib/request.d.ts CHANGED
@@ -1,40 +1,32 @@
1
- import type { MaybePromise } from './types.js';
2
- import type { RequestKind } from './side-event/types.js';
3
- import type { SideEventBase } from './side-event/base.js';
1
+ import type { MessageSenderRef } from './plugin-runtime/im/contracts.js';
2
+ import type { ComposedRequestName } from './side-event/types.js';
3
+ import { RuntimeSideEvent, type IncomingSideEvent, type SideEventBase, type EndpointEventContext } from './side-event/base.js';
4
4
  export type { RequestKind, ComposedRequestName } from './side-event/types.js';
5
- /**
6
- * 请求基础结构 — 继承 SideEventBase,附加审批方法。
7
- *
8
- * @example
9
- * ```typescript
10
- * const request = Request.from(rawEvent, {
11
- * $id: rawEvent.flag,
12
- * $adapter: 'icqq',
13
- * $endpoint: endpointKey,
14
- * $type: 'request',
15
- * $scene_id: groupId,
16
- * $scene_type: 'group',
17
- * $sub_type: 'invite',
18
- * $actor: { id: userId, name: '邀请者' },
19
- * $comment: '请求加群消息',
20
- * $timestamp: Date.now(),
21
- * $approve: async (remark?) => { await api.approve(flag, remark); },
22
- * $reject: async (reason?) => { await api.reject(flag, reason); },
23
- * });
24
- * // formatSideEventName(request) === 'request.group.invite'
25
- * this.adapter.emit('request.receive', request);
26
- * ```
27
- */
5
+ export interface IncomingRequest extends IncomingSideEvent {
6
+ readonly type: 'request';
7
+ readonly name: ComposedRequestName;
8
+ readonly actor: MessageSenderRef;
9
+ readonly comment?: string;
10
+ readonly $approve: (remark?: string) => void | Promise<void>;
11
+ readonly $reject: (reason?: string) => void | Promise<void>;
12
+ }
28
13
  export interface RequestBase extends SideEventBase {
29
- $adapter: string;
30
- $type: RequestKind;
31
- /** 主参与者(必填) */
32
- $actor: NonNullable<SideEventBase['$actor']>;
33
- $comment?: string;
34
- $approve(remark?: string): MaybePromise<void>;
35
- $reject(reason?: string): MaybePromise<void>;
14
+ readonly type: 'request';
15
+ readonly name: ComposedRequestName;
16
+ readonly actor: MessageSenderRef;
17
+ readonly comment?: string;
18
+ readonly $approve: (remark?: string) => Promise<void>;
19
+ readonly $reject: (reason?: string) => Promise<void>;
36
20
  }
37
21
  export type Request<T extends object = {}> = RequestBase & T;
38
- export declare namespace Request {
39
- function from<T extends object>(input: T, format: RequestBase): Request<T>;
22
+ /** @internal Actions are bound by the ingress operation, never retained across generations. */
23
+ export declare class RuntimeRequest extends RuntimeSideEvent implements RequestBase {
24
+ readonly type: 'request';
25
+ readonly name: ComposedRequestName;
26
+ readonly actor: MessageSenderRef;
27
+ readonly comment?: string;
28
+ readonly $approve: RequestBase['$approve'];
29
+ readonly $reject: RequestBase['$reject'];
30
+ constructor(input: IncomingRequest, context: EndpointEventContext);
40
31
  }
32
+ export declare const Request: typeof RuntimeRequest;
package/lib/request.js CHANGED
@@ -1,7 +1,15 @@
1
- export var Request;
2
- (function (Request) {
3
- function from(input, format) {
4
- return Object.assign(input, format);
1
+ import { RuntimeSideEvent } from './side-event/base.js';
2
+ /** @internal Actions are bound by the ingress operation, never retained across generations. */
3
+ export class RuntimeRequest extends RuntimeSideEvent {
4
+ comment;
5
+ $approve;
6
+ $reject;
7
+ constructor(input, context) {
8
+ super(input, context);
9
+ this.comment = input.comment;
10
+ this.$approve = async (remark) => { await input.$approve(remark); };
11
+ this.$reject = async (reason) => { await input.$reject(reason); };
12
+ Object.freeze(this);
5
13
  }
6
- Request.from = from;
7
- })(Request || (Request = {}));
14
+ }
15
+ export const Request = RuntimeRequest;
@@ -1,51 +1,72 @@
1
- import type { MessageSender } from '../types.js';
2
- /**
3
- * Side Event 共享基础结构(Notice 与 Request 共用)。
4
- * 字段统一为 `$foo_bar` 命名。
5
- *
6
- * 完整事件名:`${$type}.${$scene_type}.${$sub_type}`(见 `formatSideEventName`)。
7
- */
8
- export interface SideEventBase {
9
- /** 平台侧去重键 / flag(非 DB 行 id) */
10
- $id: string;
11
- $adapter: string;
12
- $endpoint: string;
13
- /** 命名空间:`notice` 或 `request` */
14
- $type: string;
15
- /** 平台场景 ID(群号、用户号、频道 ID 等) */
16
- $scene_id: string;
17
- /** 场景域(如 group、friend、channel、endpoint) */
18
- $scene_type?: string;
19
- /** 动作子类型(如 member_increase、add、poke) */
20
- $sub_type?: string;
21
- /** 主参与者(原 Notice.$operator / Request.$sender) */
22
- $actor?: MessageSender;
23
- /** 被操作对象 */
24
- $target?: MessageSender;
25
- /** 毫秒时间戳 */
26
- $timestamp: number;
27
- /** Canonical relation fields populated by the Adapter boundary. */
28
- $message_id?: string;
29
- $reaction?: string;
30
- $operation?: 'added' | 'removed';
31
- $duration_seconds?: number;
32
- $role?: string;
33
- $enabled?: boolean;
1
+ import type { ConversationRef, EndpointRef } from '@zhin.js/im-contract';
2
+ import type { ConversationAddress, MessageSenderRef } from '../plugin-runtime/im/contracts.js';
3
+ /** Shared Endpoint event data, with no assumption about chat or participants. */
4
+ export interface IncomingEndpointEvent {
5
+ readonly id: string;
6
+ readonly type: 'notice' | 'request' | 'system';
7
+ readonly name: string;
8
+ readonly endpointId?: string;
9
+ readonly clientAdapter?: string;
10
+ readonly timestamp: number;
11
+ readonly metadata: Readonly<Record<string, unknown>>;
34
12
  }
35
- /** 组合 Side Event 完整类型名 */
36
- export declare function composeSideEventName(type: string, sceneType: string | undefined, subType: string | undefined): string;
37
- /** 从 Side Event 字段生成完整类型名 */
38
- export declare function formatSideEventName(event: Pick<SideEventBase, '$type' | '$scene_type' | '$sub_type'>): string;
39
- /** 判断 Side Event 是否匹配完整类型名(如 `notice.group.member_increase`) */
40
- export declare function matchesSideEventName(event: Pick<SideEventBase, '$type' | '$scene_type' | '$sub_type'>, fullName: string): boolean;
41
- /** 解析完整类型名为三段 */
13
+ /** Identity and lifetime shared by all canonical Endpoint event views. */
14
+ export interface EndpointEventBase extends IncomingEndpointEvent {
15
+ readonly endpoint: EndpointRef;
16
+ readonly generation: number;
17
+ readonly $client: unknown;
18
+ }
19
+ /** Adapter-normalized Notice/Request data. System events do not inherit this contract. */
20
+ export interface IncomingSideEvent extends IncomingEndpointEvent {
21
+ readonly type: 'notice' | 'request';
22
+ readonly conversation?: ConversationAddress;
23
+ readonly actor?: MessageSenderRef;
24
+ readonly target?: MessageSenderRef;
25
+ }
26
+ export interface SideEventBase extends IncomingSideEvent, Omit<EndpointEventBase, 'type'> {
27
+ readonly conversation?: ConversationRef;
28
+ }
29
+ /** @internal Context captured by one generation-owned ingress operation. */
30
+ export interface EndpointEventContext {
31
+ readonly endpoint: EndpointRef;
32
+ readonly generation: number;
33
+ readonly client: () => unknown;
34
+ }
35
+ /** @internal Endpoint identity/lifetime only; SystemEvent has no chat fields. */
36
+ export declare class RuntimeEndpointEvent implements EndpointEventBase {
37
+ #private;
38
+ readonly id: string;
39
+ readonly type: IncomingEndpointEvent['type'];
40
+ readonly name: string;
41
+ readonly endpoint: EndpointRef;
42
+ readonly endpointId?: string;
43
+ readonly clientAdapter?: string;
44
+ readonly timestamp: number;
45
+ readonly metadata: Readonly<Record<string, unknown>>;
46
+ readonly generation: number;
47
+ constructor(input: IncomingEndpointEvent, context: EndpointEventContext);
48
+ get $client(): unknown;
49
+ }
50
+ /** @internal Shared Notice/Request data view. */
51
+ export declare class RuntimeSideEvent extends RuntimeEndpointEvent implements SideEventBase {
52
+ readonly type: IncomingSideEvent['type'];
53
+ readonly conversation?: ConversationRef;
54
+ readonly actor?: MessageSenderRef;
55
+ readonly target?: MessageSenderRef;
56
+ constructor(input: IncomingSideEvent, context: EndpointEventContext);
57
+ }
58
+ export declare function composeSideEventName(type: string, sceneType?: string, subType?: string): string;
59
+ /** The full semantic event name is the only event-name authority. */
60
+ export declare function formatSideEventName(event: Pick<IncomingEndpointEvent, 'name'>): string;
61
+ export declare function matchesSideEventName(event: Pick<IncomingEndpointEvent, 'name'>, fullName: string): boolean;
42
62
  export declare function parseSideEventName(fullName: string): {
43
63
  type: string;
44
64
  scene_type?: string;
45
65
  sub_type?: string;
46
66
  };
47
- /** 将 Side Event 场景映射为 IM 发送通道(group-suite 等消费者用) */
48
- export declare function sideEventSendChannel(event: Pick<SideEventBase, '$scene_type' | '$scene_id'>): {
67
+ /** Map known platform scene domains; non-conversation events have no send target. */
68
+ export declare function sideEventConversation(sceneType: string | undefined, id: string): ConversationAddress | undefined;
69
+ export declare function sideEventSendChannel(event: Pick<IncomingSideEvent, 'conversation'>): {
49
70
  id: string;
50
71
  type: 'group' | 'private' | 'channel';
51
- };
72
+ } | undefined;
@@ -1,30 +1,77 @@
1
- /** 组合 Side Event 完整类型名 */
1
+ /** @internal Endpoint identity/lifetime only; SystemEvent has no chat fields. */
2
+ export class RuntimeEndpointEvent {
3
+ id;
4
+ type;
5
+ name;
6
+ endpoint;
7
+ endpointId;
8
+ clientAdapter;
9
+ timestamp;
10
+ metadata;
11
+ generation;
12
+ #client;
13
+ constructor(input, context) {
14
+ if (!input.name.startsWith(`${input.type}.`)) {
15
+ throw new TypeError('Event name must belong to its event type');
16
+ }
17
+ this.id = input.id;
18
+ this.type = input.type;
19
+ this.name = input.name;
20
+ this.endpoint = Object.freeze({ ...context.endpoint });
21
+ this.endpointId = input.endpointId;
22
+ this.clientAdapter = input.clientAdapter ?? context.endpoint.adapter;
23
+ this.timestamp = input.timestamp;
24
+ this.metadata = Object.freeze({ ...input.metadata });
25
+ this.generation = context.generation;
26
+ this.#client = context.client;
27
+ }
28
+ get $client() { return this.#client(); }
29
+ }
30
+ /** @internal Shared Notice/Request data view. */
31
+ export class RuntimeSideEvent extends RuntimeEndpointEvent {
32
+ conversation;
33
+ actor;
34
+ target;
35
+ constructor(input, context) {
36
+ super(input, context);
37
+ this.conversation = input.conversation ? Object.freeze({
38
+ ...input.conversation,
39
+ ...(input.conversation.parent ? { parent: Object.freeze({ ...input.conversation.parent }) } : {}),
40
+ endpoint: this.endpoint,
41
+ }) : undefined;
42
+ this.actor = freezeSender(input.actor);
43
+ this.target = freezeSender(input.target);
44
+ }
45
+ }
46
+ function freezeSender(sender) {
47
+ return sender ? Object.freeze({
48
+ ...sender,
49
+ ...(sender.roles ? { roles: Object.freeze([...sender.roles]) } : {}),
50
+ }) : undefined;
51
+ }
2
52
  export function composeSideEventName(type, sceneType, subType) {
3
- return [type, sceneType, subType].filter((p) => !!p).join('.');
53
+ return [type, sceneType, subType].filter(Boolean).join('.');
4
54
  }
5
- /** 从 Side Event 字段生成完整类型名 */
55
+ /** The full semantic event name is the only event-name authority. */
6
56
  export function formatSideEventName(event) {
7
- return composeSideEventName(event.$type, event.$scene_type, event.$sub_type);
57
+ return event.name;
8
58
  }
9
- /** 判断 Side Event 是否匹配完整类型名(如 `notice.group.member_increase`) */
10
59
  export function matchesSideEventName(event, fullName) {
11
- return formatSideEventName(event) === fullName;
60
+ return event.name === fullName;
12
61
  }
13
- /** 解析完整类型名为三段 */
14
62
  export function parseSideEventName(fullName) {
15
63
  const parts = fullName.split('.');
16
- return {
17
- type: parts[0] ?? '',
18
- scene_type: parts[1],
19
- sub_type: parts.slice(2).join('.') || undefined,
20
- };
64
+ return { type: parts[0] ?? '', scene_type: parts[1], sub_type: parts.slice(2).join('.') || undefined };
65
+ }
66
+ /** Map known platform scene domains; non-conversation events have no send target. */
67
+ export function sideEventConversation(sceneType, id) {
68
+ if (!id)
69
+ return undefined;
70
+ const kind = sceneType === 'friend' ? 'private' : sceneType;
71
+ return kind === 'private' || kind === 'group' || kind === 'channel'
72
+ ? Object.freeze({ kind, id })
73
+ : undefined;
21
74
  }
22
- /** 将 Side Event 场景映射为 IM 发送通道(group-suite 等消费者用) */
23
75
  export function sideEventSendChannel(event) {
24
- const domain = event.$scene_type ?? 'private';
25
- if (domain === 'group')
26
- return { id: event.$scene_id, type: 'group' };
27
- if (domain === 'channel')
28
- return { id: event.$scene_id, type: 'channel' };
29
- return { id: event.$scene_id, type: 'private' };
76
+ return event.conversation ? { id: event.conversation.id, type: event.conversation.kind } : undefined;
30
77
  }
@@ -1,3 +1,4 @@
1
+ import { composeSideEventName, sideEventConversation } from './base.js';
1
2
  import { buildNotice, buildRequest, buildSystem, mapNoticeParts, mapRequestParts, resolveSideEventDedupeKey, senderFromId, } from './normalize.js';
2
3
  /**
3
4
  * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
@@ -25,26 +26,25 @@ export async function receiveOneBotLikeSideEvent(emit, input) {
25
26
  ? raw.user_id
26
27
  : undefined;
27
28
  const notice = buildNotice(raw, {
28
- $id: id,
29
- $adapter: input.adapter,
30
- $endpoint: input.endpointKey,
31
- $type: 'notice',
32
- $scene_id: String(raw.group_id ?? raw.user_id ?? input.endpointKey),
33
- $scene_type: parts.scene_type,
34
- $sub_type: parts.sub_type,
35
- $actor: senderFromId(actorId),
36
- $target: senderFromId(targetId),
37
- $timestamp: toMillis(raw.time),
38
- ...(raw.message_id != null ? { $message_id: String(raw.message_id) } : {}),
29
+ id,
30
+ clientAdapter: input.adapter,
31
+ endpointId: input.endpointKey,
32
+ type: 'notice',
33
+ conversation: oneBotConversation(parts.scene_type, raw),
34
+ name: composeSideEventName('notice', parts.scene_type, parts.sub_type),
35
+ actor: senderFromId(actorId),
36
+ target: senderFromId(targetId),
37
+ timestamp: toMillis(raw.time),
38
+ ...(raw.message_id != null ? { messageId: String(raw.message_id) } : {}),
39
39
  ...(raw.emoji_id != null || raw.code != null
40
- ? { $reaction: String(raw.emoji_id ?? raw.code) }
40
+ ? { reaction: String(raw.emoji_id ?? raw.code) }
41
41
  : {}),
42
42
  ...(parts.sub_type === 'emoji_reaction'
43
- ? { $operation: /delete|remove/i.test(String(raw.sub_type ?? noticeType)) ? 'removed' : 'added' }
43
+ ? { operation: /delete|remove/i.test(String(raw.sub_type ?? noticeType)) ? 'removed' : 'added' }
44
44
  : {}),
45
- ...(raw.duration != null ? { $duration_seconds: Math.max(0, Number(raw.duration) || 0) } : {}),
45
+ ...(raw.duration != null ? { durationSeconds: Math.max(0, Number(raw.duration) || 0) } : {}),
46
46
  ...(parts.sub_type === 'admin_change'
47
- ? { $role: 'admin', $enabled: String(raw.sub_type ?? '') === 'set' }
47
+ ? { role: 'admin', enabled: String(raw.sub_type ?? '') === 'set' }
48
48
  : {}),
49
49
  });
50
50
  await emit('notice.receive', notice);
@@ -74,16 +74,15 @@ export async function receiveOneBotLikeSideEvent(emit, input) {
74
74
  return operation;
75
75
  };
76
76
  const request = buildRequest(raw, {
77
- $id: id,
78
- $adapter: input.adapter,
79
- $endpoint: input.endpointKey,
80
- $type: 'request',
81
- $scene_id: String(raw.group_id ?? raw.user_id ?? input.endpointKey),
82
- $scene_type: parts.scene_type,
83
- $sub_type: parts.sub_type,
84
- $actor: actor,
85
- $comment: raw.comment != null ? String(raw.comment) : undefined,
86
- $timestamp: toMillis(raw.time),
77
+ id,
78
+ clientAdapter: input.adapter,
79
+ endpointId: input.endpointKey,
80
+ type: 'request',
81
+ conversation: oneBotConversation(parts.scene_type, raw),
82
+ name: composeSideEventName('request', parts.scene_type, parts.sub_type),
83
+ actor,
84
+ comment: raw.comment != null ? String(raw.comment) : undefined,
85
+ timestamp: toMillis(raw.time),
87
86
  async $approve(remark) {
88
87
  if (!approve || !flag)
89
88
  throw new Error('Request approve is not available');
@@ -112,26 +111,29 @@ export async function receiveOneBotLikeSideEvent(emit, input) {
112
111
  ?? raw.detail_type
113
112
  ?? (postType.replace(/^(meta_event|meta|system)\.?/, '') || 'unknown'));
114
113
  const subType = raw.sub_type != null ? String(raw.sub_type) : undefined;
115
- const sceneType = postType.startsWith('system.')
116
- ? (postType.split('.')[1] ?? 'system')
117
- : metaType === 'lifecycle' || metaType === 'heartbeat'
118
- ? metaType
119
- : 'meta';
114
+ const name = postType.startsWith('system.')
115
+ ? (postType.split('.').length === 2 ? composeSideEventName(postType, subType) : postType)
116
+ : composeSideEventName('system', metaType, subType);
120
117
  const system = buildSystem(raw, {
121
- $id: `system:${toMillis(raw.time)}_${metaType}_${subType ?? ''}`,
122
- $adapter: input.adapter,
123
- $endpoint: input.endpointKey,
124
- $type: 'system',
125
- $scene_id: String(raw.self_id ?? input.endpointKey),
126
- $scene_type: sceneType,
127
- $sub_type: subType ?? metaType,
128
- $timestamp: toMillis(raw.time),
118
+ id: `system:${toMillis(raw.time)}_${metaType}_${subType ?? ''}`,
119
+ clientAdapter: input.adapter,
120
+ endpointId: input.endpointKey,
121
+ type: 'system',
122
+ name,
123
+ timestamp: toMillis(raw.time),
129
124
  });
130
125
  await emit('system.receive', system);
131
126
  return 'system';
132
127
  }
133
128
  return null;
134
129
  }
130
+ function oneBotConversation(sceneType, raw) {
131
+ const id = sceneType === 'group' ? raw.group_id
132
+ : sceneType === 'channel' ? raw.channel_id
133
+ : sceneType === 'private' || sceneType === 'friend' ? raw.user_id
134
+ : undefined;
135
+ return sideEventConversation(sceneType, id == null ? '' : String(id));
136
+ }
135
137
  function toMillis(time) {
136
138
  const seconds = Number(time);
137
139
  return Number.isFinite(seconds) && seconds > 0
@@ -1,6 +1,6 @@
1
- import { Notice, type NoticeBase } from '../notice.js';
2
- import { Request, type RequestBase } from '../request.js';
3
- import { SystemEvent, type SystemEventBase } from '../system-event.js';
1
+ import type { IncomingNotice } from '../notice.js';
2
+ import type { IncomingRequest } from '../request.js';
3
+ import type { IncomingSystemEvent } from '../system-event.js';
4
4
  import { type SideEventParts } from './types.js';
5
5
  export type SideEventPlatform = 'onebot' | 'icqq' | 'napcat' | 'kook' | (string & {});
6
6
  export interface OneBotLikeRawEvent {
@@ -18,7 +18,7 @@ export interface OneBotLikeRawEvent {
18
18
  /** 去重用:notice / request 无稳定 id 时组合键 */
19
19
  export declare function resolveSideEventDedupeKey(data: OneBotLikeRawEvent, kind: 'notice' | 'request'): string;
20
20
  /**
21
- * 将平台原始 notice_type 映射为标准 `$scene_type` + `$sub_type`。
21
+ * 将平台原始 notice_type 映射为标准 `scene_type` + `sub_type`。
22
22
  */
23
23
  export declare function mapNoticeParts(platform: SideEventPlatform, raw: string, options?: {
24
24
  sub_type?: string;
@@ -26,13 +26,14 @@ export declare function mapNoticeParts(platform: SideEventPlatform, raw: string,
26
26
  notify_handler?: (subType: string | undefined, isGroup: boolean) => SideEventParts;
27
27
  }): SideEventParts;
28
28
  /**
29
- * 将平台原始 request_type 映射为标准 `$scene_type` + `$sub_type`。
29
+ * 将平台原始 request_type 映射为标准 `scene_type` + `sub_type`。
30
30
  */
31
31
  export declare function mapRequestParts(_platform: SideEventPlatform, raw: string, subType?: string): SideEventParts;
32
32
  export declare function senderFromId(id: unknown, name?: string): {
33
33
  id: string;
34
34
  name: string;
35
35
  } | undefined;
36
- export declare function buildNotice<T extends object>(input: T, format: NoticeBase): Notice<T>;
37
- export declare function buildRequest<T extends object>(input: T, format: RequestBase): Request<T>;
38
- export declare function buildSystem<T extends object>(input: T, format: SystemEventBase): SystemEvent<T>;
36
+ /** Keep native fields under metadata; never mutate or flatten the platform event. */
37
+ export declare function buildNotice<T extends object>(input: T, format: Omit<IncomingNotice, 'metadata'>): IncomingNotice;
38
+ export declare function buildRequest<T extends object>(input: T, format: Omit<IncomingRequest, 'metadata'>): IncomingRequest;
39
+ export declare function buildSystem<T extends object>(input: T, format: Omit<IncomingSystemEvent, 'metadata'>): IncomingSystemEvent;