react-ai-renderer 0.1.19 → 0.1.21

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/dist/index.d.ts CHANGED
@@ -167,6 +167,6 @@ declare class MDXStreamingParser {
167
167
  reset(): void;
168
168
  }
169
169
 
170
- declare function ReactAIRenderer({ content, scope, components, children, componentHandlers, useGithubStyles, mdxLayoutClassName, mdxLayoutStyle }: ReactAIRendererProps): React.JSX.Element;
170
+ declare function ReactAIRenderer({ content, scope, components, children, componentHandlers, useGithubStyles, mdxLayoutClassName, mdxLayoutStyle }: ReactAIRendererProps): React.JSX.Element | null;
171
171
 
172
172
  export { ComponentData$1 as ComponentData, ComponentHandler, ComponentValue, EnhancedComponentConfig, MDXStreamingParser, MdxLayout, MdxLayoutProps, ParseResult, ParserState, ReactAIRendererProps, ReactMarkdownProps, Think, ThinkProps, ToolCall, ToolCallProps, ReactAIRenderer as default };
package/dist/index.js CHANGED
@@ -9,58 +9,6 @@ import { run, compile } from '@mdx-js/mdx';
9
9
  import RehypeKatex from 'rehype-katex';
10
10
  import RehypeHighlight from 'rehype-highlight';
11
11
 
12
- // SSR 兼容性 polyfill
13
- // 这个文件确保在服务端渲染时不会因为访问 document 而报错
14
- // 在模块加载时就设置全局保护
15
- if (typeof globalThis !== 'undefined' && globalThis.document === undefined) {
16
- // 为 SSR 环境创建一个模拟的 document 对象
17
- var mockElement_1 = {
18
- innerHTML: '',
19
- textContent: '',
20
- appendChild: function () {
21
- return mockElement_1;
22
- },
23
- removeChild: function () {
24
- return mockElement_1;
25
- },
26
- remove: function () {},
27
- id: '',
28
- className: '',
29
- setAttribute: function () {},
30
- getAttribute: function () {
31
- return null;
32
- },
33
- removeAttribute: function () {},
34
- querySelector: function () {
35
- return null;
36
- },
37
- querySelectorAll: function () {
38
- return [];
39
- }
40
- };
41
- // 创建模拟的 document 对象
42
- var mockDocument = {
43
- createElement: function () {
44
- return mockElement_1;
45
- },
46
- getElementById: function () {
47
- return null;
48
- },
49
- querySelector: function () {
50
- return null;
51
- },
52
- querySelectorAll: function () {
53
- return [];
54
- },
55
- body: mockElement_1,
56
- head: mockElement_1,
57
- addEventListener: function () {},
58
- removeEventListener: function () {}
59
- };
60
- // 在 SSR 环境中提供全局的 document
61
- globalThis.document = mockDocument;
62
- }
63
-
64
12
  /******************************************************************************
65
13
  Copyright (c) Microsoft Corporation.
66
14
 
@@ -197,6 +145,165 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
197
145
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
198
146
  };
199
147
 
148
+ if (typeof globalThis !== 'undefined' && typeof globalThis.window === 'undefined') {
149
+ var mockElement_1 = {
150
+ innerHTML: '',
151
+ textContent: '',
152
+ nodeValue: '',
153
+ appendChild: function () {
154
+ return mockElement_1;
155
+ },
156
+ removeChild: function () {
157
+ return mockElement_1;
158
+ },
159
+ insertBefore: function () {
160
+ return mockElement_1;
161
+ },
162
+ replaceChild: function () {
163
+ return mockElement_1;
164
+ },
165
+ cloneNode: function () {
166
+ return mockElement_1;
167
+ },
168
+ remove: function () {},
169
+ id: '',
170
+ className: '',
171
+ classList: {
172
+ add: function () {},
173
+ remove: function () {},
174
+ contains: function () {
175
+ return false;
176
+ },
177
+ toggle: function () {
178
+ return false;
179
+ }
180
+ },
181
+ style: {},
182
+ setAttribute: function () {},
183
+ getAttribute: function () {
184
+ return null;
185
+ },
186
+ removeAttribute: function () {},
187
+ hasAttribute: function () {
188
+ return false;
189
+ },
190
+ querySelector: function () {
191
+ return null;
192
+ },
193
+ querySelectorAll: function () {
194
+ return [];
195
+ },
196
+ getElementsByTagName: function () {
197
+ return [];
198
+ },
199
+ getElementsByClassName: function () {
200
+ return [];
201
+ },
202
+ addEventListener: function () {},
203
+ removeEventListener: function () {},
204
+ dispatchEvent: function () {
205
+ return true;
206
+ },
207
+ parentNode: null,
208
+ parentElement: null,
209
+ childNodes: [],
210
+ children: [],
211
+ firstChild: null,
212
+ lastChild: null,
213
+ nextSibling: null,
214
+ previousSibling: null
215
+ };
216
+ var mockDocument = {
217
+ createElement: function () {
218
+ return mockElement_1;
219
+ },
220
+ createElementNS: function () {
221
+ return mockElement_1;
222
+ },
223
+ createTextNode: function (text) {
224
+ return __assign(__assign({}, mockElement_1), {
225
+ nodeValue: text,
226
+ textContent: text
227
+ });
228
+ },
229
+ createDocumentFragment: function () {
230
+ return mockElement_1;
231
+ },
232
+ getElementById: function () {
233
+ return null;
234
+ },
235
+ querySelector: function () {
236
+ return null;
237
+ },
238
+ querySelectorAll: function () {
239
+ return [];
240
+ },
241
+ getElementsByTagName: function () {
242
+ return [];
243
+ },
244
+ getElementsByClassName: function () {
245
+ return [];
246
+ },
247
+ body: mockElement_1,
248
+ head: mockElement_1,
249
+ documentElement: mockElement_1,
250
+ addEventListener: function () {},
251
+ removeEventListener: function () {},
252
+ createEvent: function () {
253
+ return {};
254
+ }
255
+ };
256
+ var mockWindow = {
257
+ document: mockDocument,
258
+ location: {
259
+ href: '',
260
+ origin: '',
261
+ protocol: 'https:',
262
+ host: '',
263
+ hostname: '',
264
+ port: '',
265
+ pathname: '/',
266
+ search: '',
267
+ hash: ''
268
+ },
269
+ navigator: {
270
+ userAgent: '',
271
+ language: 'en-US',
272
+ platform: ''
273
+ },
274
+ addEventListener: function () {},
275
+ removeEventListener: function () {},
276
+ getComputedStyle: function () {
277
+ return {};
278
+ },
279
+ matchMedia: function () {
280
+ return {
281
+ matches: false,
282
+ media: '',
283
+ addListener: function () {},
284
+ removeListener: function () {},
285
+ addEventListener: function () {},
286
+ removeEventListener: function () {},
287
+ dispatchEvent: function () {
288
+ return true;
289
+ }
290
+ };
291
+ },
292
+ requestAnimationFrame: function (cb) {
293
+ return setTimeout(cb, 16);
294
+ },
295
+ cancelAnimationFrame: function (id) {
296
+ return clearTimeout(id);
297
+ },
298
+ setTimeout: setTimeout,
299
+ clearTimeout: clearTimeout,
300
+ setInterval: setInterval,
301
+ clearInterval: clearInterval
302
+ };
303
+ globalThis.window = mockWindow;
304
+ globalThis.document = mockDocument;
305
+ }
306
+
200
307
  var MDXStreamingParser = /** @class */function () {
201
308
  function MDXStreamingParser(components) {
202
309
  // 将组件名称存储在Set中,而不是整个组件对象
@@ -43136,8 +43243,6 @@ function decodeNamedCharacterReference(value) {
43136
43243
  // reference to decode was not a semicolon (`;`), we can assume that the
43137
43244
  // matching was not complete.
43138
43245
  if (
43139
- // @ts-expect-error: TypeScript is wrong that `textContent` on elements can
43140
- // yield `null`.
43141
43246
  character.charCodeAt(character.length - 1) === 59 /* `;` */ &&
43142
43247
  value !== 'semi'
43143
43248
  ) {
@@ -43146,8 +43251,6 @@ function decodeNamedCharacterReference(value) {
43146
43251
 
43147
43252
  // If the decoded string is equal to the input, the character reference was
43148
43253
  // not valid.
43149
- // @ts-expect-error: TypeScript is wrong that `textContent` on elements can
43150
- // yield `null`.
43151
43254
  return character === characterReference ? false : character
43152
43255
  }
43153
43256
 
@@ -54876,9 +54979,8 @@ function toResult(value) {
54876
54979
  }
54877
54980
 
54878
54981
  /**
54879
- * @typedef {import('unist').Node} UnistNode
54880
- * @typedef {import('unist').Parent} UnistParent
54881
- * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult
54982
+ * @import {Node as UnistNode, Parent as UnistParent} from 'unist'
54983
+ * @import {VisitorResult} from 'unist-util-visit-parents'
54882
54984
  */
54883
54985
 
54884
54986
 
@@ -58478,11 +58580,18 @@ function parseComponentRecursively(allComponentHandlers, item, scope) {
58478
58580
  }))];
58479
58581
  case 1:
58480
58582
  parsedChildren_1 = _a.sent();
58481
- item.children.map(function (item, index) {
58482
- if (item.type === 'text') {
58483
- childrenContent_1 += escapeContentForStream(parsedChildren_1[index].value); // encodeURIComponent(parsedChildren[index]);
58583
+ item.children.forEach(function (childItem, index) {
58584
+ var parsedChild = parsedChildren_1[index];
58585
+ if (!parsedChild) {
58586
+ return;
58587
+ }
58588
+ if (!parsedChild.value) {
58589
+ return;
58590
+ }
58591
+ if (childItem.type === 'text') {
58592
+ childrenContent_1 += escapeContentForStream(parsedChild.value);
58484
58593
  } else {
58485
- childrenContent_1 += parsedChildren_1[index].value;
58594
+ childrenContent_1 += parsedChild.value;
58486
58595
  }
58487
58596
  });
58488
58597
  _a.label = 2;
@@ -59187,7 +59296,6 @@ var ComponentPlaceholder = function (_a) {
59187
59296
  }
59188
59297
  } catch (e) {
59189
59298
  // 如果骨架图生成失败,继续使用默认占位内容
59190
- console.warn('Failed to generate skeleton:', e);
59191
59299
  }
59192
59300
  }
59193
59301
  // 默认占位内容
@@ -59292,37 +59400,55 @@ function extractComponent(value) {
59292
59400
  * 将 components 转换为 ComponentHandler 数组
59293
59401
  */
59294
59402
  function convertComponentsToHandlers(components, componentHandlers) {
59295
- return Object.entries(components).filter(function (_a) {
59296
- var _b = __read(_a, 1),
59297
- name = _b[0];
59298
- return !componentHandlers.some(function (handler) {
59299
- return handler.name === name;
59300
- });
59301
- }).map(function (_a) {
59302
- var _b = __read(_a, 2),
59303
- name = _b[0],
59304
- componentValue = _b[1];
59403
+ var e_1, _a;
59404
+ var handlers = [];
59405
+ var _loop_1 = function (name_1, componentValue) {
59406
+ if (!componentValue) return "continue";
59407
+ if (componentHandlers.some(function (handler) {
59408
+ return handler.name === name_1;
59409
+ })) return "continue";
59305
59410
  if (isEnhancedComponentConfig(componentValue)) {
59306
59411
  var config = componentValue;
59307
- return {
59412
+ if (!config.value) {
59413
+ return "continue";
59414
+ }
59415
+ handlers.push({
59308
59416
  component: config.value,
59309
- name: name,
59417
+ name: name_1,
59310
59418
  selfClosing: config.selfClosing !== undefined ? config.selfClosing : isSelfClosingComponent(config.value),
59311
59419
  onRenderStart: config.onRenderStart,
59312
59420
  onRenderProcess: config.onRenderProcess,
59313
59421
  onRenderFinished: config.onRenderFinished,
59314
59422
  loader: config.loader,
59315
59423
  label: config.label
59316
- };
59424
+ });
59317
59425
  } else {
59318
- // 普通模式:直接使用组件
59319
- return {
59426
+ handlers.push({
59320
59427
  component: componentValue,
59321
- name: name,
59428
+ name: name_1,
59322
59429
  selfClosing: isSelfClosingComponent(componentValue)
59323
- };
59430
+ });
59324
59431
  }
59325
- });
59432
+ };
59433
+ try {
59434
+ for (var _b = __values(Object.entries(components)), _c = _b.next(); !_c.done; _c = _b.next()) {
59435
+ var _d = __read(_c.value, 2),
59436
+ name_1 = _d[0],
59437
+ componentValue = _d[1];
59438
+ _loop_1(name_1, componentValue);
59439
+ }
59440
+ } catch (e_1_1) {
59441
+ e_1 = {
59442
+ error: e_1_1
59443
+ };
59444
+ } finally {
59445
+ try {
59446
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
59447
+ } finally {
59448
+ if (e_1) throw e_1.error;
59449
+ }
59450
+ }
59451
+ return handlers;
59326
59452
  }
59327
59453
  function ReactAIRenderer(_a) {
59328
59454
  var _this = this;
@@ -59337,34 +59463,28 @@ function ReactAIRenderer(_a) {
59337
59463
  useGithubStyles = _a.useGithubStyles,
59338
59464
  mdxLayoutClassName = _a.mdxLayoutClassName,
59339
59465
  mdxLayoutStyle = _a.mdxLayoutStyle;
59340
- // 检查是否在浏览器环境中
59466
+ var _e = __read(useState(null), 2),
59467
+ component = _e[0],
59468
+ setComponent = _e[1];
59469
+ var fallbackErrorRef = useRef({
59470
+ hasError: false
59471
+ });
59472
+ var completedComponentsCacheRef = useRef(new Map());
59341
59473
  var isBrowser = typeof window !== 'undefined';
59342
- // 在服务端直接返回空内容,避免使用 hooks
59343
- if (!isBrowser) {
59344
- return /*#__PURE__*/jsx(React__default.Fragment, {
59345
- children: null
59346
- });
59347
- }
59348
59474
  content = content || children || '';
59349
- // 构建 allComponents:从增强配置中提取实际的组件
59350
- var normalizedComponents = components ? Object.fromEntries(Object.entries(components).map(function (_a) {
59475
+ var normalizedComponents = components ? Object.fromEntries(Object.entries(components).filter(function (_a) {
59476
+ var _b = __read(_a, 2);
59477
+ _b[0];
59478
+ var value = _b[1];
59479
+ return value != null;
59480
+ }).map(function (_a) {
59351
59481
  var _b = __read(_a, 2),
59352
59482
  name = _b[0],
59353
59483
  value = _b[1];
59354
59484
  return [name, extractComponent(value)];
59355
59485
  })) : {};
59356
59486
  var allComponents = __assign(__assign({}, BuiltInComponents), normalizedComponents);
59357
- // 构建 allComponentHandlers:支持增强模式
59358
59487
  var allComponentHandlers = __spreadArray(__spreadArray([], __read(components ? convertComponentsToHandlers(components, componentHandlers) : []), false), __read(componentHandlers), false);
59359
- var _e = __read(useState(null), 2),
59360
- component = _e[0],
59361
- setComponent = _e[1];
59362
- // 用于跟踪 FallbackView 的错误状态
59363
- var fallbackErrorRef = useRef({
59364
- hasError: false
59365
- });
59366
- // 用于缓存已完成的组件,避免重复渲染
59367
- var completedComponentsCacheRef = useRef(new Map());
59368
59488
  var parser = new MDXStreamingParser(allComponentHandlers);
59369
59489
  var mdxContent = content || '';
59370
59490
  // FallbackView 错误状态变化时的回调
@@ -59375,10 +59495,11 @@ function ReactAIRenderer(_a) {
59375
59495
  };
59376
59496
  };
59377
59497
  useEffect(function () {
59498
+ if (!isBrowser) return;
59378
59499
  var parseMDX = function () {
59379
59500
  return __awaiter(_this, void 0, void 0, function () {
59380
- var ThinkComponent, ResultComponent, protectedContent, _a, thinkContent, resultContent, parsedData, parsedComponents, currentComponentCount, cacheKeys, cacheKeys_1, cacheKeys_1_1, key, indexMatch, index, finalComponent, fallbackComponent, _loop_1, i, MDXComponent, parsedDataLength, lastItem;
59381
- var e_1, _b;
59501
+ var ThinkComponent, ResultComponent, protectedContent, _a, thinkContent, resultContent, parsedData, parsedComponents, currentComponentCount, cacheKeys, cacheKeys_1, cacheKeys_1_1, key, indexMatch, index, finalComponent, fallbackComponent, _loop_2, i, MDXComponent, parsedDataLength, lastItem;
59502
+ var e_2, _b;
59382
59503
  return __generator(this, function (_c) {
59383
59504
  switch (_c.label) {
59384
59505
  case 0:
@@ -59396,7 +59517,6 @@ function ReactAIRenderer(_a) {
59396
59517
  if (!resultContent) return [3 /*break*/, 8];
59397
59518
  resultContent = fixMDXContent(resultContent);
59398
59519
  parsedData = parser.parse('magic', resultContent);
59399
- console.log('parsedData', parsedData);
59400
59520
  return [4 /*yield*/, Promise.all(parsedData.map(function (item) {
59401
59521
  return parseComponentRecursively(allComponentHandlers, item, scope);
59402
59522
  }))];
@@ -59416,20 +59536,20 @@ function ReactAIRenderer(_a) {
59416
59536
  }
59417
59537
  }
59418
59538
  }
59419
- } catch (e_1_1) {
59420
- e_1 = {
59421
- error: e_1_1
59539
+ } catch (e_2_1) {
59540
+ e_2 = {
59541
+ error: e_2_1
59422
59542
  };
59423
59543
  } finally {
59424
59544
  try {
59425
59545
  if (cacheKeys_1_1 && !cacheKeys_1_1.done && (_b = cacheKeys_1.return)) _b.call(cacheKeys_1);
59426
59546
  } finally {
59427
- if (e_1) throw e_1.error;
59547
+ if (e_2) throw e_2.error;
59428
59548
  }
59429
59549
  }
59430
59550
  finalComponent = [];
59431
59551
  fallbackComponent = [];
59432
- _loop_1 = function (i) {
59552
+ _loop_2 = function (i) {
59433
59553
  var item, currentParsedItem, _result, placeholderForFallback, componentNameMatch, componentName_1, componentHandler, displayName, cacheKey;
59434
59554
  return __generator(this, function (_d) {
59435
59555
  switch (_d.label) {
@@ -59518,7 +59638,7 @@ function ReactAIRenderer(_a) {
59518
59638
  _c.label = 4;
59519
59639
  case 4:
59520
59640
  if (!(i < parsedComponents.length)) return [3 /*break*/, 7];
59521
- return [5 /*yield**/, _loop_1(i)];
59641
+ return [5 /*yield**/, _loop_2(i)];
59522
59642
  case 5:
59523
59643
  _c.sent();
59524
59644
  _c.label = 6;
@@ -59562,6 +59682,9 @@ function ReactAIRenderer(_a) {
59562
59682
  };
59563
59683
  parseMDX();
59564
59684
  }, [content]);
59685
+ if (!isBrowser) {
59686
+ return null;
59687
+ }
59565
59688
  return /*#__PURE__*/jsx(ErrorBoundary, {
59566
59689
  content: content,
59567
59690
  children: /*#__PURE__*/jsx(React__default.Fragment, {
@@ -59748,7 +59871,6 @@ var getMermaid = function () {
59748
59871
  mermaidPromise = import('mermaid').then(function (module) {
59749
59872
  return module.default || module;
59750
59873
  }).catch(function (error) {
59751
- console.warn('Mermaid is not available. Install it to enable chart rendering.');
59752
59874
  return null;
59753
59875
  });
59754
59876
  return mermaidPromise;
@@ -59799,7 +59921,6 @@ function MermaidRenderer(_a) {
59799
59921
  if (!!mermaid.initialized) return [3 /*break*/, 4];
59800
59922
  // 设置全局错误处理函数
59801
59923
  mermaid.parseError = function (err) {
59802
- console.warn('Mermaid parse error:', err.message);
59803
59924
  };
59804
59925
  return [4 /*yield*/, mermaid.initialize({
59805
59926
  startOnLoad: false,