@zhin.js/core 1.1.40 → 1.1.41

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 (39) hide show
  1. package/lib/built/ai-trigger.js +2 -2
  2. package/lib/built/html-segment-fallback.d.ts +4 -2
  3. package/lib/built/html-segment-fallback.js +1 -1
  4. package/lib/built/interactive-segments/resolve.js +1 -1
  5. package/lib/built/interactive-segments/types.d.ts +2 -2
  6. package/lib/built/interactive-segments/types.js +22 -2
  7. package/lib/built/outbound-content-arrays.d.ts +4 -0
  8. package/lib/built/outbound-content-arrays.js +32 -0
  9. package/lib/built/outbound-media-utils.d.ts +5 -3
  10. package/lib/built/outbound-media-utils.js +5 -3
  11. package/lib/built/segment-contract/assert.js +5 -0
  12. package/lib/built/segment-contract/json-schema.d.ts +1 -1
  13. package/lib/built/segment-contract/json-schema.js +30 -2
  14. package/lib/feature/component.d.ts +1 -0
  15. package/lib/feature/component.js +1 -0
  16. package/lib/index.d.ts +3 -2
  17. package/lib/index.js +2 -1
  18. package/lib/jsx-dev-runtime.d.ts +1 -2
  19. package/lib/jsx-dev-runtime.js +1 -2
  20. package/lib/jsx-runtime.d.ts +1 -12
  21. package/lib/jsx-runtime.js +1 -10
  22. package/lib/jsx.d.ts +1 -30
  23. package/lib/jsx.js +1 -93
  24. package/lib/message.d.ts +0 -11
  25. package/lib/plugin-runtime/im/contracts.d.ts +14 -6
  26. package/lib/plugin-runtime/im/contracts.js +28 -6
  27. package/lib/plugin-runtime/im/inbound-runtime.js +30 -6
  28. package/lib/plugin-runtime/im/message-dispatcher.js +0 -1
  29. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +37 -18
  30. package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -2
  31. package/lib/plugin-runtime/im/outbound-renderer.js +31 -6
  32. package/lib/plugin-runtime/im/outbound-segments.d.ts +5 -0
  33. package/lib/plugin-runtime/im/outbound-segments.js +25 -6
  34. package/lib/types.d.ts +5 -7
  35. package/lib/utils.d.ts +4 -4
  36. package/lib/utils.js +9 -17
  37. package/package.json +14 -12
  38. package/lib/component.d.ts +0 -26
  39. package/lib/component.js +0 -583
package/lib/component.js DELETED
@@ -1,583 +0,0 @@
1
- import { getValueWithRuntime, compiler, segment } from './utils.js';
2
- import { renderJSX } from './jsx.js';
3
- // 组件匹配符号
4
- export const CapWithChild = Symbol('CapWithChild');
5
- export const CapWithClose = Symbol('CapWithClose');
6
- // 组件定义函数 - 简化版,只支持函数式组件
7
- export function defineComponent(component, name = component.name) {
8
- if (name) {
9
- // 创建一个新的函数来避免修改只读属性
10
- const namedComponent = component;
11
- Object.defineProperty(namedComponent, 'name', {
12
- value: name,
13
- writable: false,
14
- enumerable: false,
15
- configurable: true
16
- });
17
- return namedComponent;
18
- }
19
- return component;
20
- }
21
- // 组件匹配函数
22
- export function matchComponent(comp, template) {
23
- // 使用更复杂的正则表达式来正确处理大括号内的内容
24
- const selfClosingRegex = new RegExp(`<${comp.name}((?:[^>]|{[^}]*})*)?/>`);
25
- const closingRegex = new RegExp(`<${comp.name}((?:[^>]|{[^}]*})*)?>([^<]*?)</${comp.name}>`);
26
- let match = template.match(selfClosingRegex);
27
- if (!match) {
28
- match = template.match(closingRegex);
29
- }
30
- return match ? match[0] : '';
31
- }
32
- // 属性解析函数 - 支持 children
33
- export function getProps(comp, template, context) {
34
- // 1. 首先匹配组件标签,支持自闭合和闭合标签
35
- const selfClosingRegex = new RegExp(`<${comp.name}((?:[^>]|{[^}]*})*)?/>`);
36
- const closingRegex = new RegExp(`<${comp.name}((?:[^>]|{[^}]*})*)?>([^<]*?)</${comp.name}>`);
37
- let match = template.match(selfClosingRegex);
38
- let isSelfClosing = true;
39
- let children = '';
40
- if (!match) {
41
- match = template.match(closingRegex);
42
- isSelfClosing = false;
43
- if (match) {
44
- children = match[2] || '';
45
- }
46
- }
47
- if (!match) {
48
- return {};
49
- }
50
- const attributesString = match[1] || '';
51
- // 2. 解析属性,支持多种格式
52
- const props = {};
53
- // 如果有属性字符串,解析属性
54
- if (attributesString.trim()) {
55
- // 使用手动解析来处理复杂的嵌套结构
56
- let i = 0;
57
- while (i < attributesString.length) {
58
- // 跳过空白字符
59
- while (i < attributesString.length && /\s/.test(attributesString[i])) {
60
- i++;
61
- }
62
- if (i >= attributesString.length)
63
- break;
64
- // 解析属性名
65
- let key = '';
66
- while (i < attributesString.length && /[a-zA-Z0-9_$\-]/.test(attributesString[i])) {
67
- key += attributesString[i];
68
- i++;
69
- }
70
- if (!key) {
71
- i++;
72
- continue;
73
- }
74
- // 跳过空白字符
75
- while (i < attributesString.length && /\s/.test(attributesString[i])) {
76
- i++;
77
- }
78
- // 检查是否有等号
79
- if (i < attributesString.length && attributesString[i] === '=') {
80
- i++; // 跳过等号
81
- // 跳过空白字符
82
- while (i < attributesString.length && /\s/.test(attributesString[i])) {
83
- i++;
84
- }
85
- if (i >= attributesString.length) {
86
- props[key] = true;
87
- break;
88
- }
89
- // 解析属性值
90
- const value = parseAttributeValue(attributesString, i, context);
91
- props[key] = value.value;
92
- i = value.nextIndex;
93
- }
94
- else {
95
- // 没有等号,是布尔属性
96
- props[key] = true;
97
- }
98
- }
99
- }
100
- // 3. 处理 children(如果不是自闭合标签)
101
- if (!isSelfClosing && children.trim()) {
102
- props.children = children;
103
- }
104
- // 4. 处理 kebab-case 到 camelCase 的转换
105
- const camelCaseProps = {};
106
- for (const [key, value] of Object.entries(props)) {
107
- const camelKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
108
- camelCaseProps[camelKey] = value;
109
- }
110
- return camelCaseProps;
111
- }
112
- /**
113
- * 解析属性值
114
- */
115
- function parseAttributeValue(str, startIndex, context) {
116
- let i = startIndex;
117
- // 处理引号包围的字符串
118
- if (str[i] === '"' || str[i] === "'") {
119
- const quote = str[i];
120
- i++; // 跳过开始引号
121
- let value = '';
122
- while (i < str.length && str[i] !== quote) {
123
- if (str[i] === '\\' && i + 1 < str.length) {
124
- // 处理转义字符
125
- i++;
126
- value += str[i];
127
- }
128
- else {
129
- value += str[i];
130
- }
131
- i++;
132
- }
133
- if (i < str.length) {
134
- i++; // 跳过结束引号
135
- }
136
- // 检查引号内是否包含表达式(大括号)
137
- if (value.includes('{') && value.includes('}')) {
138
- // 包含表达式,进行求值
139
- const evaluatedValue = evaluateQuotedExpression(value, context);
140
- return { value: evaluatedValue, nextIndex: i };
141
- }
142
- return { value, nextIndex: i };
143
- }
144
- // 处理大括号包围的表达式
145
- if (str[i] === '{') {
146
- let braceCount = 0;
147
- let value = '';
148
- i++; // 跳过开始大括号
149
- while (i < str.length) {
150
- if (str[i] === '{') {
151
- braceCount++;
152
- }
153
- else if (str[i] === '}') {
154
- if (braceCount === 0) {
155
- i++; // 跳过结束大括号
156
- break;
157
- }
158
- braceCount--;
159
- }
160
- value += str[i];
161
- i++;
162
- }
163
- return { value: parseExpressionValue(value, context), nextIndex: i };
164
- }
165
- // 处理无引号的值
166
- let value = '';
167
- while (i < str.length && !/\s/.test(str[i]) && str[i] !== '>') {
168
- value += str[i];
169
- i++;
170
- }
171
- return { value: parseUnquotedValue(value, context), nextIndex: i };
172
- }
173
- /**
174
- * 求值引号内的表达式
175
- */
176
- function evaluateQuotedExpression(quotedValue, context) {
177
- if (!context)
178
- return quotedValue;
179
- let result = '';
180
- let cursor = 0;
181
- for (const match of readBraceExpressions(quotedValue)) {
182
- result += quotedValue.slice(cursor, match.start);
183
- try {
184
- const value = context.getValue(match.expr);
185
- if (value !== undefined && value !== match.expr) {
186
- const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
187
- result += stringValue;
188
- }
189
- else {
190
- result += quotedValue.slice(match.start, match.end);
191
- }
192
- }
193
- catch (error) {
194
- result += quotedValue.slice(match.start, match.end);
195
- }
196
- cursor = match.end;
197
- }
198
- return result + quotedValue.slice(cursor);
199
- }
200
- function readBraceExpressions(value) {
201
- const matches = [];
202
- let cursor = 0;
203
- while (cursor < value.length) {
204
- const start = value.indexOf('{', cursor);
205
- if (start < 0)
206
- break;
207
- const end = value.indexOf('}', start + 1);
208
- if (end < 0)
209
- break;
210
- matches.push({ start, end: end + 1, expr: value.slice(start + 1, end) });
211
- cursor = end + 1;
212
- }
213
- return matches;
214
- }
215
- /**
216
- * 解析表达式值
217
- */
218
- function parseExpressionValue(expr, context) {
219
- expr = expr.trim();
220
- // 处理字符串字面量
221
- if ((expr.startsWith('"') && expr.endsWith('"')) ||
222
- (expr.startsWith("'") && expr.endsWith("'"))) {
223
- return expr.slice(1, -1);
224
- }
225
- // 处理数字
226
- if (/^-?\d+(\.\d+)?$/.test(expr)) {
227
- return parseFloat(expr);
228
- }
229
- // 处理布尔值
230
- if (expr === 'true')
231
- return true;
232
- if (expr === 'false')
233
- return false;
234
- if (expr === 'null')
235
- return null;
236
- if (expr === 'undefined')
237
- return undefined;
238
- // 处理数组
239
- if (expr.startsWith('[') && expr.endsWith(']')) {
240
- try {
241
- return JSON.parse(expr);
242
- }
243
- catch {
244
- // 如果JSON解析失败,尝试手动解析简单数组
245
- const items = expr.slice(1, -1).split(',').map(item => parseExpressionValue(item.trim(), context));
246
- return items;
247
- }
248
- }
249
- // 处理对象 - 改进的嵌套大括号处理
250
- if (expr.startsWith('{') && expr.endsWith('}')) {
251
- try {
252
- return JSON.parse(expr);
253
- }
254
- catch {
255
- // 如果JSON解析失败,尝试手动解析简单对象
256
- try {
257
- return parseSimpleObject(expr);
258
- }
259
- catch {
260
- // 如果都失败,返回原始字符串
261
- return expr;
262
- }
263
- }
264
- }
265
- // 处理表达式 - 在沙盒中执行
266
- if (context) {
267
- try {
268
- const result = context.getValue(expr);
269
- // 如果结果是 undefined,说明表达式被阻止或求值失败,返回原始表达式
270
- if (result === undefined) {
271
- return expr;
272
- }
273
- return result;
274
- }
275
- catch (error) {
276
- // 如果执行失败,返回原始表达式
277
- return expr;
278
- }
279
- }
280
- // 如果没有上下文,返回原始表达式
281
- return expr;
282
- }
283
- /**
284
- * 解析简单对象(处理嵌套大括号和方括号)
285
- */
286
- function parseSimpleObject(objStr) {
287
- const result = {};
288
- let i = 1; // 跳过开始的 {
289
- let depth = 0;
290
- let bracketDepth = 0;
291
- let key = '';
292
- let value = '';
293
- let inKey = true;
294
- let inString = false;
295
- let stringChar = '';
296
- while (i < objStr.length - 1) { // 跳过结束的 }
297
- const char = objStr[i];
298
- if (!inString) {
299
- if (char === '{') {
300
- depth++;
301
- value += char;
302
- }
303
- else if (char === '}') {
304
- depth--;
305
- value += char;
306
- }
307
- else if (char === '[') {
308
- bracketDepth++;
309
- value += char;
310
- }
311
- else if (char === ']') {
312
- bracketDepth--;
313
- value += char;
314
- }
315
- else if (char === ':' && depth === 0 && bracketDepth === 0) {
316
- inKey = false;
317
- i++;
318
- continue;
319
- }
320
- else if (char === ',' && depth === 0 && bracketDepth === 0) {
321
- // 处理键值对
322
- if (key.trim() && value.trim()) {
323
- const parsedValue = parseExpressionValue(value.trim());
324
- result[key.trim()] = parsedValue;
325
- }
326
- key = '';
327
- value = '';
328
- inKey = true;
329
- i++;
330
- continue;
331
- }
332
- else if (char === '"' || char === "'") {
333
- inString = true;
334
- stringChar = char;
335
- if (inKey) {
336
- key += char;
337
- }
338
- else {
339
- value += char;
340
- }
341
- }
342
- else {
343
- if (inKey) {
344
- key += char;
345
- }
346
- else {
347
- value += char;
348
- }
349
- }
350
- }
351
- else {
352
- if (char === stringChar) {
353
- inString = false;
354
- }
355
- if (inKey) {
356
- key += char;
357
- }
358
- else {
359
- value += char;
360
- }
361
- }
362
- i++;
363
- }
364
- // 处理最后一个键值对
365
- if (key.trim() && value.trim()) {
366
- const parsedValue = parseExpressionValue(value.trim());
367
- result[key.trim()] = parsedValue;
368
- }
369
- return result;
370
- }
371
- /**
372
- * 解析无引号的值
373
- */
374
- function parseUnquotedValue(value, context) {
375
- // 检查是否是大括号表达式
376
- if (value.startsWith('{') && value.endsWith('}')) {
377
- const expr = value.slice(1, -1); // 移除大括号
378
- return parseExpressionValue(expr, context);
379
- }
380
- // 处理布尔值
381
- if (value === 'true')
382
- return true;
383
- if (value === 'false')
384
- return false;
385
- // 处理数字
386
- if (/^-?\d+(\.\d+)?$/.test(value)) {
387
- return parseFloat(value);
388
- }
389
- // 处理 null/undefined
390
- if (value === 'null')
391
- return null;
392
- if (value === 'undefined')
393
- return undefined;
394
- // 其他情况作为字符串处理
395
- return value;
396
- }
397
- // 创建组件上下文的工厂函数
398
- export function createComponentContext(props = {}, parent, root = '') {
399
- return {
400
- // 基础渲染能力
401
- render: async (template, context) => {
402
- // 这里需要实现渲染逻辑
403
- return template;
404
- },
405
- // 数据访问(只读)
406
- props: Object.freeze({ ...props }),
407
- // 父组件上下文(只读)
408
- parent: parent ? Object.freeze(parent) : undefined,
409
- // 根模板(只读)
410
- root,
411
- // 子组件内容(React 概念)
412
- children: undefined,
413
- getValue: (template) => getValueWithRuntime(template, props),
414
- compile: (template) => compiler(template, props),
415
- };
416
- }
417
- export async function renderComponent(component, template, context) {
418
- const props = getProps(component, template, context);
419
- return component(props, context);
420
- }
421
- // 渲染函数 - 支持新的组件系统;无组件时仍对内容执行 ${...} 模板编译,与有组件时行为一致
422
- function messageElementsNeedCompile(content) {
423
- if (typeof content === 'string') {
424
- return content.includes('${');
425
- }
426
- const arr = Array.isArray(content) ? content : [content];
427
- for (const item of arr) {
428
- if (typeof item === 'string') {
429
- if (item.includes('${'))
430
- return true;
431
- continue;
432
- }
433
- if (item.type === 'text') {
434
- const text = item.data?.text;
435
- if (typeof text === 'string' && text.includes('${'))
436
- return true;
437
- }
438
- }
439
- return false;
440
- }
441
- function contentParts(content) {
442
- if (typeof content === 'string')
443
- return [content];
444
- return Array.isArray(content) ? content : [content];
445
- }
446
- function isJsxElement(item) {
447
- return typeof item !== 'string' && typeof item.type === 'function';
448
- }
449
- function contentHasJsxElement(content) {
450
- return contentParts(content).some(isJsxElement);
451
- }
452
- async function resolveJsxInContent(content, context) {
453
- const parts = contentParts(content);
454
- const out = [];
455
- for (const item of parts) {
456
- if (!isJsxElement(item)) {
457
- out.push(item);
458
- continue;
459
- }
460
- const rendered = await renderJSX(item, context);
461
- if (typeof rendered === 'string') {
462
- out.push(rendered);
463
- }
464
- else if (Array.isArray(rendered)) {
465
- out.push(...rendered);
466
- }
467
- else {
468
- out.push(rendered);
469
- }
470
- }
471
- if (out.length === 1)
472
- return out[0];
473
- return out;
474
- }
475
- /** 纯 MessageElement(如出站图片 base64)勿走 segment.toString→from,否则会超 400KB 模板上限 */
476
- function contentNeedsComponentPipeline(content, componentMap) {
477
- if (messageElementsNeedCompile(content))
478
- return true;
479
- if (componentMap.size === 0)
480
- return false;
481
- for (const item of contentParts(content)) {
482
- if (typeof item === 'string') {
483
- for (const name of componentMap.keys()) {
484
- if (item.includes(`<${name}`))
485
- return true;
486
- }
487
- continue;
488
- }
489
- if (item.type === 'text') {
490
- const text = item.data?.text;
491
- if (typeof text !== 'string')
492
- continue;
493
- for (const name of componentMap.keys()) {
494
- if (text.includes(`<${name}`))
495
- return true;
496
- }
497
- }
498
- }
499
- return false;
500
- }
501
- export async function renderComponents(componentMap, options, customContext) {
502
- if (contentHasJsxElement(options.content)) {
503
- const jsxContext = customContext || createComponentContext(options, undefined, '');
504
- options = {
505
- ...options,
506
- content: await resolveJsxInContent(options.content, jsxContext),
507
- };
508
- }
509
- if (typeof options.content !== 'string'
510
- && !contentNeedsComponentPipeline(options.content, componentMap)) {
511
- const arr = Array.isArray(options.content) ? options.content : [options.content];
512
- return { ...options, content: arr };
513
- }
514
- const template = typeof options.content === 'string'
515
- ? options.content
516
- : segment.toString(options.content);
517
- const rootContext = customContext || createComponentContext(options, undefined, template);
518
- if (!componentMap.size) {
519
- const compiled = rootContext.compile(template);
520
- return {
521
- ...options,
522
- content: typeof compiled === 'string' ? segment.from(compiled) : compiled,
523
- };
524
- }
525
- const components = [...Array.from(componentMap.values()), Fetch, Fragment];
526
- const renderWithContext = async (tpl, context) => {
527
- let result = context.compile(tpl);
528
- let hasChanges = true;
529
- let iterations = 0;
530
- const maxIterations = 10;
531
- while (hasChanges && iterations < maxIterations) {
532
- hasChanges = false;
533
- iterations++;
534
- for (const comp of components) {
535
- const match = matchComponent(comp, result);
536
- if (match) {
537
- const componentContext = createComponentContext(context.props, context, result);
538
- let SendContent;
539
- try {
540
- SendContent = await renderComponent(comp, match, componentContext);
541
- }
542
- catch (error) {
543
- SendContent = `[${comp.name} Error: ${error?.message || String(error)}]`;
544
- }
545
- const renderedString = typeof SendContent === 'string' ? SendContent : segment.toString(SendContent);
546
- result = result.replace(match, renderedString);
547
- hasChanges = true;
548
- break;
549
- }
550
- }
551
- }
552
- return result;
553
- };
554
- rootContext.render = async (tpl, context) => {
555
- return await renderWithContext(tpl, rootContext);
556
- };
557
- const output = await renderWithContext(rootContext.root, rootContext);
558
- const content = typeof output === 'string' ? segment.from(output) : output;
559
- return {
560
- ...options,
561
- content,
562
- };
563
- }
564
- // 内置组件
565
- export const Fragment = defineComponent(async (props, context) => {
566
- const children = props.children || '';
567
- if (Array.isArray(children)) {
568
- return children.join('');
569
- }
570
- if (typeof children === 'string') {
571
- try {
572
- const parsed = JSON.parse(segment.unescape(children));
573
- return context.render(parsed || '', context);
574
- }
575
- catch {
576
- return context.render(children || '', context);
577
- }
578
- }
579
- return String(children);
580
- }, 'Fragment');
581
- export const Fetch = defineComponent(async ({ url }) => {
582
- return await fetch(url, { signal: AbortSignal.timeout(30_000) }).then((r) => r.text());
583
- }, 'fetch');