@zhin.js/core 1.1.55 → 1.1.57

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 (64) hide show
  1. package/lib/built/generic-segment-mapper.js +2 -0
  2. package/lib/built/html-to-text.js +2 -2
  3. package/lib/built/rich-segments/markdown-to-text.js +19 -0
  4. package/lib/built/segment-contract/validate.d.ts +1442 -300
  5. package/lib/built/user-interaction.js +3 -1
  6. package/lib/index.d.ts +4 -0
  7. package/lib/index.js +3 -0
  8. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +1 -1
  9. package/lib/plugin-runtime/im/command-menu-navigation.js +2 -1
  10. package/lib/plugin-runtime/im/contracts.d.ts +8 -1
  11. package/lib/plugin-runtime/im/contracts.js +20 -1
  12. package/lib/plugin-runtime/im/conversation-runtime.d.ts +2 -2
  13. package/lib/plugin-runtime/im/conversation-runtime.js +6 -4
  14. package/lib/plugin-runtime/im/im-runtime.js +8 -1
  15. package/lib/plugin-runtime/im/inbound-dedup.d.ts +1 -0
  16. package/lib/plugin-runtime/im/inbound-dedup.js +1 -0
  17. package/lib/plugin-runtime/im/inbound-origin.d.ts +27 -0
  18. package/lib/plugin-runtime/im/inbound-runtime.d.ts +8 -1
  19. package/lib/plugin-runtime/im/inbound-runtime.js +79 -2
  20. package/lib/plugin-runtime/im/index.d.ts +2 -0
  21. package/lib/plugin-runtime/im/index.js +2 -0
  22. package/lib/plugin-runtime/im/interaction-runtime.d.ts +7 -6
  23. package/lib/plugin-runtime/im/interaction-runtime.js +85 -24
  24. package/lib/plugin-runtime/im/interactive-router.d.ts +28 -8
  25. package/lib/plugin-runtime/im/interactive-router.js +112 -35
  26. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +16 -2
  27. package/lib/plugin-runtime/im/jsx-button-registry.js +56 -19
  28. package/lib/plugin-runtime/im/message-dispatcher.js +59 -6
  29. package/lib/plugin-runtime/im/operation-resources.d.ts +15 -0
  30. package/lib/plugin-runtime/im/operation-resources.js +2 -0
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +5 -4
  32. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +71 -21
  33. package/lib/plugin-runtime/im/outbound-segments.d.ts +1 -1
  34. package/lib/plugin-runtime/im/outbound-segments.js +2 -20
  35. package/lib/runtime.d.ts +2 -0
  36. package/lib/runtime.js +2 -0
  37. package/lib/side-event/index.d.ts +0 -1
  38. package/lib/side-event/index.js +0 -1
  39. package/lib/side-event/normalize.d.ts +0 -28
  40. package/lib/side-event/normalize.js +0 -100
  41. package/lib/side-event/scene-events.js +1 -1
  42. package/lib/side-event/types.d.ts +0 -6
  43. package/lib/side-event/types.js +1 -57
  44. package/lib/venue/contracts.d.ts +21 -0
  45. package/lib/venue/contracts.js +3 -0
  46. package/lib/venue/floor-controller.d.ts +11 -0
  47. package/lib/venue/floor-controller.js +63 -0
  48. package/lib/venue/index.d.ts +13 -0
  49. package/lib/venue/index.js +11 -0
  50. package/lib/venue/membership-port.d.ts +23 -0
  51. package/lib/venue/membership-port.js +141 -0
  52. package/lib/venue/projector.d.ts +38 -0
  53. package/lib/venue/projector.js +45 -0
  54. package/lib/venue/registry.d.ts +16 -0
  55. package/lib/venue/registry.js +63 -0
  56. package/lib/venue/router.d.ts +19 -0
  57. package/lib/venue/router.js +101 -0
  58. package/lib/venue/send-limiter.d.ts +17 -0
  59. package/lib/venue/send-limiter.js +73 -0
  60. package/lib/venue/validator.d.ts +6 -0
  61. package/lib/venue/validator.js +160 -0
  62. package/package.json +16 -16
  63. package/lib/side-event/dispatch.d.ts +0 -15
  64. package/lib/side-event/dispatch.js +0 -168
@@ -0,0 +1,160 @@
1
+ const VALID_SCENE_TYPES = new Set(['private', 'group', 'channel']);
2
+ const VALID_VISIBILITY_MODES = new Set(['visible', 'summary', 'backstage']);
3
+ export class VenueValidationError extends Error {
4
+ issues;
5
+ constructor(issues) {
6
+ super(`Invalid venue definitions:\n${issues.map((issue) => ` - ${issue}`).join('\n')}`);
7
+ this.name = 'VenueValidationError';
8
+ this.issues = Object.freeze([...issues]);
9
+ }
10
+ }
11
+ function isNonEmptyString(value) {
12
+ return typeof value === 'string' && value.trim().length > 0;
13
+ }
14
+ export function validateVenueDefinitions(venues) {
15
+ if (!Array.isArray(venues)) {
16
+ throw new VenueValidationError(['venues must be an array']);
17
+ }
18
+ const issues = [];
19
+ const seenVenueIds = new Set();
20
+ const seenConversations = [];
21
+ for (let i = 0; i < venues.length; i++) {
22
+ const venue = venues[i];
23
+ const label = isNonEmptyString(venue?.id) ? `venue "${venue.id.trim()}"` : `venues[${i}]`;
24
+ if (!venue || typeof venue !== 'object') {
25
+ issues.push(`${label}: must be an object`);
26
+ continue;
27
+ }
28
+ if (!isNonEmptyString(venue.id)) {
29
+ issues.push(`${label}: id must be a non-empty string`);
30
+ }
31
+ else {
32
+ const id = venue.id.trim();
33
+ if (seenVenueIds.has(id)) {
34
+ issues.push(`${label}: duplicate venue id "${id}"`);
35
+ }
36
+ else {
37
+ seenVenueIds.add(id);
38
+ }
39
+ }
40
+ const conv = venue.conversation;
41
+ if (!conv || typeof conv !== 'object') {
42
+ issues.push(`${label}: conversation is required`);
43
+ }
44
+ else {
45
+ const platformOk = isNonEmptyString(conv.platform);
46
+ const sceneIdOk = isNonEmptyString(conv.sceneId);
47
+ if (!platformOk) {
48
+ issues.push(`${label}: conversation.platform must be a non-empty string`);
49
+ }
50
+ if (!sceneIdOk) {
51
+ issues.push(`${label}: conversation.sceneId must be a non-empty string`);
52
+ }
53
+ if (conv.sceneType !== undefined && !VALID_SCENE_TYPES.has(conv.sceneType)) {
54
+ issues.push(`${label}: conversation.sceneType must be one of "private", "group", "channel"`);
55
+ }
56
+ if (conv.threadId !== undefined && !isNonEmptyString(conv.threadId)) {
57
+ issues.push(`${label}: conversation.threadId must be a non-empty string when provided`);
58
+ }
59
+ if (platformOk && sceneIdOk) {
60
+ const platform = conv.platform.trim();
61
+ const sceneType = conv.sceneType;
62
+ const sceneId = conv.sceneId.trim();
63
+ const threadId = conv.threadId?.trim() ?? '';
64
+ const conflict = seenConversations.find((existing) => existing.platform === platform
65
+ && existing.sceneId === sceneId
66
+ && existing.threadId === threadId
67
+ && (existing.sceneType === undefined || sceneType === undefined || existing.sceneType === sceneType));
68
+ if (conflict) {
69
+ issues.push(`${label}: duplicate conversation (${platform}/${sceneType ?? '*'}/${sceneId}${threadId ? `/${threadId}` : ''}) already bound by venue "${conflict.venueId}"`);
70
+ }
71
+ else {
72
+ seenConversations.push({
73
+ venueId: isNonEmptyString(venue.id) ? venue.id.trim() : `venues[${i}]`,
74
+ platform,
75
+ sceneType,
76
+ sceneId,
77
+ threadId,
78
+ });
79
+ }
80
+ }
81
+ }
82
+ const memberAgents = new Set();
83
+ const memberEndpoints = new Set();
84
+ const memberNamesLower = new Set();
85
+ if (!Array.isArray(venue.members) || venue.members.length === 0) {
86
+ issues.push(`${label}: members must be a non-empty array`);
87
+ }
88
+ else {
89
+ for (let m = 0; m < venue.members.length; m++) {
90
+ const member = venue.members[m];
91
+ const memberLabel = `${label}.members[${m}]`;
92
+ if (!member || typeof member !== 'object') {
93
+ issues.push(`${memberLabel}: must be an object`);
94
+ continue;
95
+ }
96
+ if (!isNonEmptyString(member.agent)) {
97
+ issues.push(`${memberLabel}: agent must be a non-empty string`);
98
+ }
99
+ else {
100
+ const agent = member.agent.trim();
101
+ if (memberAgents.has(agent)) {
102
+ issues.push(`${memberLabel}: duplicate member agent "${agent}" in venue`);
103
+ }
104
+ else {
105
+ memberAgents.add(agent);
106
+ memberNamesLower.add(agent.toLowerCase());
107
+ }
108
+ }
109
+ if (!isNonEmptyString(member.botEndpoint)) {
110
+ issues.push(`${memberLabel}: botEndpoint must be a non-empty string`);
111
+ }
112
+ else {
113
+ const endpoint = member.botEndpoint.trim();
114
+ if (memberEndpoints.has(endpoint)) {
115
+ issues.push(`${memberLabel}: duplicate member botEndpoint "${endpoint}" in venue`);
116
+ }
117
+ else {
118
+ memberEndpoints.add(endpoint);
119
+ }
120
+ }
121
+ if (member.aliases !== undefined) {
122
+ if (!Array.isArray(member.aliases)) {
123
+ issues.push(`${memberLabel}: aliases must be an array of strings`);
124
+ }
125
+ else {
126
+ for (let a = 0; a < member.aliases.length; a++) {
127
+ const alias = member.aliases[a];
128
+ if (!isNonEmptyString(alias)) {
129
+ issues.push(`${memberLabel}.aliases[${a}]: alias must be a non-empty string`);
130
+ }
131
+ else {
132
+ const lower = alias.trim().toLowerCase();
133
+ if (memberNamesLower.has(lower)) {
134
+ issues.push(`${memberLabel}.aliases[${a}]: duplicate alias "${alias}" in venue`);
135
+ }
136
+ else {
137
+ memberNamesLower.add(lower);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ }
143
+ }
144
+ }
145
+ if (venue.entry !== undefined) {
146
+ if (!isNonEmptyString(venue.entry)) {
147
+ issues.push(`${label}: entry must be a non-empty string when specified`);
148
+ }
149
+ else if (memberAgents.size > 0 && !memberAgents.has(venue.entry.trim())) {
150
+ issues.push(`${label}: entry "${venue.entry}" does not match any member agent in venue`);
151
+ }
152
+ }
153
+ if (venue.visibility !== undefined && !VALID_VISIBILITY_MODES.has(venue.visibility)) {
154
+ issues.push(`${label}: visibility must be "visible", "summary", or "backstage"`);
155
+ }
156
+ }
157
+ if (issues.length > 0) {
158
+ throw new VenueValidationError(issues);
159
+ }
160
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.55",
3
+ "version": "1.1.57",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -57,29 +57,29 @@
57
57
  "dependencies": {
58
58
  "qrcode": "^1.5.4",
59
59
  "segment-matcher": "^1.0.5",
60
- "@zhin.js/command": "1.1.13",
61
- "@zhin.js/component": "1.1.12",
62
- "@zhin.js/database": "1.1.5",
63
- "@zhin.js/handler": "1.1.11",
64
- "@zhin.js/adapter": "1.1.27",
60
+ "@zhin.js/adapter": "1.1.29",
61
+ "@zhin.js/command": "1.1.15",
62
+ "@zhin.js/component": "1.1.14",
63
+ "@zhin.js/database": "1.1.7",
64
+ "@zhin.js/handler": "1.1.13",
65
+ "@zhin.js/im-contract": "1.1.12",
65
66
  "@zhin.js/interaction": "1.1.2",
66
- "@zhin.js/im-contract": "1.1.10",
67
+ "@zhin.js/kernel": "1.1.6",
67
68
  "@zhin.js/logger": "1.1.2",
68
- "@zhin.js/middleware": "1.1.12",
69
- "@zhin.js/permission": "1.1.11",
70
- "@zhin.js/kernel": "1.1.5",
71
- "@zhin.js/schedule-feature": "1.1.11",
72
- "@zhin.js/schema": "1.1.4",
73
- "@zhin.js/jsx": "1.1.9",
74
- "@zhin.js/feature-kit": "1.1.11",
75
- "@zhin.js/plugin-runtime": "1.1.19"
69
+ "@zhin.js/middleware": "1.1.14",
70
+ "@zhin.js/permission": "1.1.13",
71
+ "@zhin.js/plugin-runtime": "1.1.21",
72
+ "@zhin.js/schedule-feature": "1.1.13",
73
+ "@zhin.js/schema": "1.1.5",
74
+ "@zhin.js/jsx": "1.1.11",
75
+ "@zhin.js/feature-kit": "1.1.13"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@types/node": "^26.1.2",
79
79
  "@types/qrcode": "^1.5.6",
80
80
  "ajv": "8.18.0",
81
81
  "typescript": "^6.0.3",
82
- "@zhin.js/ai": "1.1.50"
82
+ "@zhin.js/ai": "1.1.52"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",
@@ -1,15 +0,0 @@
1
- import type { EndpointEventEmitter } from '@zhin.js/adapter';
2
- import { type OneBotLikeRawEvent, type SideEventPlatform } from './normalize.js';
3
- export interface OneBotLikeSideEventInput {
4
- readonly adapter: string;
5
- readonly endpointKey: string;
6
- readonly platform?: SideEventPlatform;
7
- readonly raw: OneBotLikeRawEvent;
8
- readonly approve?: (flag: string, remark?: string) => void | Promise<void>;
9
- readonly reject?: (flag: string, reason?: string) => void | Promise<void>;
10
- }
11
- /**
12
- * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
13
- * Returns which kind was dispatched, or null when the payload is not a side event.
14
- */
15
- export declare function receiveOneBotLikeSideEvent(emit: EndpointEventEmitter, input: OneBotLikeSideEventInput): Promise<'notice' | 'request' | 'system' | null>;
@@ -1,168 +0,0 @@
1
- import { composeSideEventName, sideEventConversation } from './base.js';
2
- import { buildNotice, buildRequest, buildSystem, mapNoticeParts, mapRequestParts, resolveSideEventDedupeKey, senderFromId, } from './normalize.js';
3
- /**
4
- * Normalize OneBot / icqq-style notice|request|meta payloads and feed Endpoint.emit().
5
- * Returns which kind was dispatched, or null when the payload is not a side event.
6
- */
7
- export async function receiveOneBotLikeSideEvent(emit, input) {
8
- const raw = input.raw;
9
- const platform = input.platform ?? 'onebot';
10
- const postType = String(raw.post_type ?? raw.type ?? '');
11
- if (postType === 'notice' || postType.startsWith('notice.')) {
12
- const noticeType = String(raw.notice_type ?? (postType.replace(/^notice\.?/, '') || 'unknown'));
13
- const parts = mapNoticeParts(platform, noticeType, {
14
- sub_type: raw.sub_type != null ? String(raw.sub_type) : undefined,
15
- is_group: raw.group_id != null,
16
- });
17
- const id = resolveSideEventDedupeKey(raw, 'notice');
18
- const memberEvent = ['member_increase', 'member_decrease', 'ban', 'admin_change'].includes(parts.sub_type);
19
- const actorId = raw.operator_id
20
- ?? (!memberEvent ? raw.user_id : undefined);
21
- const targetId = memberEvent
22
- ? raw.user_id
23
- : parts.sub_type === 'poke'
24
- ? raw.target_id ?? raw.self_id
25
- : raw.user_id != null && String(raw.user_id) !== String(raw.operator_id ?? '')
26
- ? raw.user_id
27
- : undefined;
28
- const notice = buildNotice(raw, {
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
- // icqq/OneBot 入群通知携带新成员昵称;无则保持缺省(不在 core 内发起网络查询)
38
- parts.sub_type === 'member_increase' && typeof raw.nickname === 'string' && raw.nickname.trim()
39
- ? raw.nickname.trim()
40
- : undefined),
41
- timestamp: toMillis(raw.time),
42
- ...(raw.message_id != null
43
- ? { messageId: String(raw.message_id) }
44
- // icqq 群表情回应只给被回应消息的 seq
45
- : parts.sub_type === 'emoji_reaction' && raw.seq != null ? { messageId: `seq:${String(raw.seq)}` } : {}),
46
- ...(raw.emoji_id != null || raw.code != null
47
- ? { reaction: String(raw.emoji_id ?? raw.code) }
48
- : parts.sub_type === 'emoji_reaction' && raw.id != null ? { reaction: String(raw.id) } : {}),
49
- ...(parts.sub_type === 'emoji_reaction'
50
- ? {
51
- operation: raw.set === false || /delete|remove/i.test(String(raw.sub_type ?? noticeType))
52
- ? 'removed'
53
- : 'added',
54
- }
55
- : {}),
56
- ...(raw.duration != null ? { durationSeconds: Math.max(0, Number(raw.duration) || 0) } : {}),
57
- ...(parts.sub_type === 'admin_change'
58
- ? { role: 'admin', enabled: typeof raw.set === 'boolean' ? raw.set : String(raw.sub_type ?? '') === 'set' }
59
- : {}),
60
- ...sideEventValue(parts.sub_type, raw),
61
- });
62
- await emit('notice.receive', notice);
63
- return 'notice';
64
- }
65
- if (postType === 'request' || postType.startsWith('request.')) {
66
- const requestType = String(raw.request_type ?? (postType.replace(/^request\.?/, '') || 'friend'));
67
- const parts = mapRequestParts(platform, requestType, raw.sub_type != null ? String(raw.sub_type) : undefined);
68
- const flag = raw.flag != null ? String(raw.flag) : '';
69
- const id = flag || resolveSideEventDedupeKey(raw, 'request');
70
- const actor = senderFromId(raw.user_id);
71
- if (!actor)
72
- return null;
73
- const approve = input.approve;
74
- const reject = input.reject;
75
- let active = true;
76
- const actions = new Set();
77
- const requireActiveAction = () => {
78
- if (!active)
79
- throw new Error('Request action port expired with its generation operation');
80
- };
81
- const runAction = (action) => {
82
- requireActiveAction();
83
- const operation = Promise.resolve().then(action);
84
- actions.add(operation);
85
- void operation.then(() => actions.delete(operation), () => actions.delete(operation));
86
- return operation;
87
- };
88
- const request = buildRequest(raw, {
89
- id,
90
- clientAdapter: input.adapter,
91
- endpointId: input.endpointKey,
92
- type: 'request',
93
- conversation: oneBotConversation(parts.scene_type, raw),
94
- name: composeSideEventName('request', parts.scene_type, parts.sub_type),
95
- actor,
96
- comment: raw.comment != null ? String(raw.comment) : undefined,
97
- timestamp: toMillis(raw.time),
98
- async $approve(remark) {
99
- if (!approve || !flag)
100
- throw new Error('Request approve is not available');
101
- await runAction(() => approve(flag, remark));
102
- },
103
- async $reject(reason) {
104
- if (!reject || !flag)
105
- throw new Error('Request reject is not available');
106
- await runAction(() => reject(flag, reason));
107
- },
108
- });
109
- try {
110
- await emit('request.receive', request);
111
- }
112
- finally {
113
- active = false;
114
- await Promise.allSettled([...actions]);
115
- }
116
- return 'request';
117
- }
118
- if (postType === 'meta_event'
119
- || postType === 'meta'
120
- || postType.startsWith('meta.')
121
- || postType.startsWith('system.')) {
122
- const metaType = String(raw.meta_event_type
123
- ?? raw.detail_type
124
- ?? (postType.replace(/^(meta_event|meta|system)\.?/, '') || 'unknown'));
125
- const subType = raw.sub_type != null ? String(raw.sub_type) : undefined;
126
- const name = postType.startsWith('system.')
127
- ? (postType.split('.').length === 2 ? composeSideEventName(postType, subType) : postType)
128
- : composeSideEventName('system', metaType, subType);
129
- const system = buildSystem(raw, {
130
- id: `system:${toMillis(raw.time)}_${metaType}_${subType ?? ''}`,
131
- clientAdapter: input.adapter,
132
- endpointId: input.endpointKey,
133
- type: 'system',
134
- name,
135
- timestamp: toMillis(raw.time),
136
- });
137
- await emit('system.receive', system);
138
- return 'system';
139
- }
140
- return null;
141
- }
142
- /** 名片/头衔/备注的新值或公告正文:只取短文本(≤40 字),不带原始结构。 */
143
- function sideEventValue(subType, raw) {
144
- const pick = (...values) => values.find((value) => typeof value === 'string');
145
- const value = subType === 'card_change' ? pick(raw.card_new, raw.card)
146
- : subType === 'title_change' ? pick(raw.title)
147
- : subType === 'remark_change' ? pick(raw.remark)
148
- : subType === 'notice_updated' ? pick(raw.content, raw.text, raw.msg)
149
- : undefined;
150
- if (typeof value !== 'string')
151
- return {};
152
- // eslint-disable-next-line no-control-regex
153
- const flat = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
154
- return { value: flat.length > 40 ? `${flat.slice(0, 39)}…` : flat };
155
- }
156
- function oneBotConversation(sceneType, raw) {
157
- const id = sceneType === 'group' ? raw.group_id
158
- : sceneType === 'channel' ? raw.channel_id
159
- : sceneType === 'private' || sceneType === 'friend' ? raw.user_id
160
- : undefined;
161
- return sideEventConversation(sceneType, id == null ? '' : String(id));
162
- }
163
- function toMillis(time) {
164
- const seconds = Number(time);
165
- return Number.isFinite(seconds) && seconds > 0
166
- ? (seconds < 1e12 ? seconds * 1000 : seconds)
167
- : Date.now();
168
- }