@runtypelabs/persona 4.8.0 → 4.10.0

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 (130) hide show
  1. package/README.md +14 -1
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-BsZtXPKK.d.cts → types-4ROVJ1gA.d.cts} +42 -0
  5. package/dist/animations/{types-BsZtXPKK.d.ts → types-4ROVJ1gA.d.ts} +42 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/chunk-IO5VVUKP.js +3 -0
  9. package/dist/chunk-IPVK3KOM.js +1 -0
  10. package/dist/chunk-UPO4GUFC.js +1 -0
  11. package/dist/codegen.cjs +6 -6
  12. package/dist/codegen.js +8 -8
  13. package/dist/context-mentions-7S5KVUTG.js +169 -0
  14. package/dist/context-mentions-inline-TTCN7ZM2.js +4 -0
  15. package/dist/context-mentions-inline.cjs +4 -0
  16. package/dist/context-mentions-inline.d.cts +203 -0
  17. package/dist/context-mentions-inline.d.ts +203 -0
  18. package/dist/context-mentions-inline.js +4 -0
  19. package/dist/context-mentions.cjs +295 -0
  20. package/dist/context-mentions.d.cts +7025 -0
  21. package/dist/context-mentions.d.ts +7025 -0
  22. package/dist/context-mentions.js +295 -0
  23. package/dist/index.cjs +72 -64
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +634 -3
  26. package/dist/index.d.ts +634 -3
  27. package/dist/index.global.js +59 -51
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +64 -56
  30. package/dist/index.js.map +1 -1
  31. package/dist/launcher.global.js +2 -2
  32. package/dist/launcher.global.js.map +1 -1
  33. package/dist/plugin-kit.cjs +1 -1
  34. package/dist/plugin-kit.d.cts +17 -0
  35. package/dist/plugin-kit.d.ts +17 -0
  36. package/dist/plugin-kit.js +1 -1
  37. package/dist/smart-dom-reader.cjs +17 -16
  38. package/dist/smart-dom-reader.d.cts +507 -1
  39. package/dist/smart-dom-reader.d.ts +507 -1
  40. package/dist/smart-dom-reader.js +17 -16
  41. package/dist/theme-editor-preview.cjs +236 -57
  42. package/dist/theme-editor-preview.d.cts +485 -1
  43. package/dist/theme-editor-preview.d.ts +485 -1
  44. package/dist/theme-editor-preview.js +53 -47
  45. package/dist/theme-editor.cjs +7 -7
  46. package/dist/theme-editor.d.cts +473 -0
  47. package/dist/theme-editor.d.ts +473 -0
  48. package/dist/theme-editor.js +5 -5
  49. package/dist/theme-reference.cjs +1 -1
  50. package/dist/theme-reference.d.cts +2 -0
  51. package/dist/theme-reference.d.ts +2 -0
  52. package/dist/widget.css +1 -1
  53. package/package.json +15 -3
  54. package/src/client.test.ts +69 -0
  55. package/src/client.ts +65 -51
  56. package/src/components/artifact-pane.test.ts +47 -0
  57. package/src/components/artifact-pane.ts +25 -2
  58. package/src/components/composer-parts.ts +3 -12
  59. package/src/components/context-mention-button.test.ts +70 -0
  60. package/src/components/context-mention-button.ts +82 -0
  61. package/src/components/context-mention-chip.ts +134 -0
  62. package/src/components/context-mention-menu.test.ts +508 -0
  63. package/src/components/context-mention-menu.ts +0 -0
  64. package/src/components/message-bubble.test.ts +175 -0
  65. package/src/components/message-bubble.ts +177 -19
  66. package/src/components/panel.ts +7 -10
  67. package/src/context-mentions-bundle.test.ts +163 -0
  68. package/src/context-mentions-entry.ts +185 -0
  69. package/src/context-mentions-inline-entry.test.ts +136 -0
  70. package/src/context-mentions-inline-entry.ts +226 -0
  71. package/src/context-mentions-inline-loader.test.ts +30 -0
  72. package/src/context-mentions-inline-loader.ts +36 -0
  73. package/src/context-mentions-inline.ts +15 -0
  74. package/src/context-mentions-loader.ts +32 -0
  75. package/src/context-mentions.ts +16 -0
  76. package/src/index-core.ts +27 -0
  77. package/src/index-global.ts +51 -0
  78. package/src/markdown-parsers-loader.ts +35 -44
  79. package/src/plugin-kit.test.ts +40 -0
  80. package/src/plugin-kit.ts +39 -5
  81. package/src/runtime/init-update-reset.test.ts +81 -0
  82. package/src/runtime/init.test.ts +62 -0
  83. package/src/runtime/init.ts +7 -14
  84. package/src/session.mentions.test.ts +175 -0
  85. package/src/session.test.ts +52 -4
  86. package/src/session.ts +121 -5
  87. package/src/smart-dom-reader.test.ts +129 -2
  88. package/src/smart-dom-reader.ts +127 -1
  89. package/src/styles/context-mention-menu-css.ts +176 -0
  90. package/src/styles/widget.css +243 -126
  91. package/src/theme-editor/sections.ts +3 -3
  92. package/src/types/theme.ts +2 -0
  93. package/src/types.ts +542 -0
  94. package/src/ui.artifact-pane-gating.test.ts +11 -1
  95. package/src/ui.attachments-drop.test.ts +90 -0
  96. package/src/ui.header-update-stability.test.ts +149 -0
  97. package/src/ui.launcher-update-merge.test.ts +83 -0
  98. package/src/ui.mention-submit.test.ts +235 -0
  99. package/src/ui.send-button-stream-update.test.ts +69 -0
  100. package/src/ui.ts +379 -84
  101. package/src/utils/chunk-loader.test.ts +97 -0
  102. package/src/utils/chunk-loader.ts +88 -0
  103. package/src/utils/composer-contenteditable.test.ts +507 -0
  104. package/src/utils/composer-contenteditable.ts +626 -0
  105. package/src/utils/composer-document.test.ts +280 -0
  106. package/src/utils/composer-document.ts +293 -0
  107. package/src/utils/composer-history.test.ts +35 -7
  108. package/src/utils/composer-history.ts +30 -20
  109. package/src/utils/composer-input.ts +159 -0
  110. package/src/utils/config-merge.test.ts +131 -0
  111. package/src/utils/config-merge.ts +61 -0
  112. package/src/utils/context-mention-controller.test.ts +1215 -0
  113. package/src/utils/context-mention-controller.ts +1186 -0
  114. package/src/utils/context-mention-manager.test.ts +422 -0
  115. package/src/utils/context-mention-manager.ts +410 -0
  116. package/src/utils/context-mention-orchestrator.test.ts +538 -0
  117. package/src/utils/context-mention-orchestrator.ts +348 -0
  118. package/src/utils/live-region.test.ts +108 -0
  119. package/src/utils/live-region.ts +94 -0
  120. package/src/utils/mention-channels.ts +63 -0
  121. package/src/utils/mention-llm-format.test.ts +91 -0
  122. package/src/utils/mention-llm-format.ts +79 -0
  123. package/src/utils/mention-matcher.test.ts +86 -0
  124. package/src/utils/mention-matcher.ts +221 -0
  125. package/src/utils/mention-token.ts +72 -0
  126. package/src/utils/mention-trigger.test.ts +155 -0
  127. package/src/utils/mention-trigger.ts +156 -0
  128. package/src/utils/theme.test.ts +54 -4
  129. package/src/utils/theme.ts +6 -3
  130. package/src/utils/tokens.ts +27 -11
package/README.md CHANGED
@@ -86,7 +86,19 @@ const docked = initAgentWidget({
86
86
  });
87
87
  ```
88
88
 
89
- ### Initialization options
89
+ ### Update merge policy
90
+
91
+ `update()` applies a recursive patch, not a shallow replace. A key merges into the
92
+ live config only when both the previous value and the patch value are plain
93
+ objects, so a partial patch (for example `launcher.title`) preserves defaulted and
94
+ earlier-set sibling values instead of dropping them. Arrays, functions, class
95
+ instances, and scalar values replace wholesale, and so do a small set of
96
+ replace-leaf fields whose plain-object values must not be spliced together:
97
+ `headers`, `agent`, `storageAdapter`, `components`, `targetProviders`,
98
+ `voiceRecognition.provider.custom`, and `features.streamAnimation.plugins`.
99
+ Omitting a key preserves its current value: to reset a field, pass it explicitly
100
+ with `undefined`, which falls back to the field's default, or leaves it unset
101
+ when no default exists.
90
102
 
91
103
  `initAgentWidget` accepts the following options:
92
104
 
@@ -121,6 +133,7 @@ The full reference lives in [`docs/`](./docs/) and the theming guide:
121
133
  - [UI Features & Components](./docs/UI-COMPONENTS.md): message actions and feedback, loading/idle indicators, approvals, built-in `ask_user_question` and `suggest_replies` tools, dropdown menus, button utilities, dynamic forms
122
134
  - [Script Tag Installation & Framework Integration](./docs/INSTALLATION-FRAMEWORKS.md): automatic installer, deferred launcher lifecycle hooks, manual script tag setup, React, Next.js, Remix, Gatsby, and Astro guides
123
135
  - [Configuration Reference](./docs/CONFIGURATION-REFERENCE.md): every config option: core, client token mode, agent mode, UI & theme, launcher/docking, layout, voice, WebMCP, tool calls, features, suggestion chips, state & storage
136
+ - [Context Mentions](./docs/CONTEXT-MENTIONS.md): `@`-mention sources, resolve lifecycle, chip vs inline display, menu positioning, slash commands, and render overrides
124
137
  - [Stream Parser Configuration](./docs/STREAM-PARSERS.md): JSON, XML, and plain-text stream parsers and custom parser factories
125
138
  - [Message Injection](./docs/MESSAGE-INJECTION.md): full injection and component-directive reference
126
139
  - [Dynamic Forms](./docs/DYNAMIC-FORMS.md): field schema, form styles, and recipes
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BsZtXPKK.cjs';
1
+ import { S as StreamAnimationPlugin } from './types-4ROVJ1gA.cjs';
2
2
 
3
3
  declare const glyphCycle: StreamAnimationPlugin;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BsZtXPKK.js';
1
+ import { S as StreamAnimationPlugin } from './types-4ROVJ1gA.js';
2
2
 
3
3
  declare const glyphCycle: StreamAnimationPlugin;
4
4
 
@@ -734,6 +734,29 @@ type VideoContentPart = {
734
734
  * Union type for all content part types
735
735
  */
736
736
  type ContentPart = TextContentPart | ImageContentPart | FileContentPart | AudioContentPart | VideoContentPart;
737
+ /** Reference stored on a sent message for transcript fidelity + chip rendering. */
738
+ type AgentWidgetContextMentionRef = {
739
+ sourceId: string;
740
+ itemId: string;
741
+ label: string;
742
+ iconName?: string;
743
+ /** Accent color for the inline token (see `AgentWidgetContextMentionItem.color`). */
744
+ color?: string;
745
+ };
746
+ /**
747
+ * One ordered segment of a sent message's prose, for inline mention rendering
748
+ * (`contextMentions.display: "inline"`). Text runs and atomic mention tokens
749
+ * interleave in document order so the sent bubble re-renders `@tokens` in place
750
+ * and composer history can round-trip them. Display/transcript concern only —
751
+ * the model still sees resolved bodies via `llmContent`/`contentParts`.
752
+ */
753
+ type AgentWidgetContentSegment = {
754
+ kind: "text";
755
+ text: string;
756
+ } | {
757
+ kind: "mention";
758
+ ref: AgentWidgetContextMentionRef;
759
+ };
737
760
  /**
738
761
  * Metadata attached to messages created during agent execution.
739
762
  */
@@ -967,6 +990,25 @@ type AgentWidgetMessage = {
967
990
  * The `content` field contains the text-only representation for display.
968
991
  */
969
992
  contentParts?: ContentPart[];
993
+ /**
994
+ * Context mentions attached to this (user) message, for transcript fidelity +
995
+ * chip rendering in the sent bubble. Refs only — the resolved payloads are
996
+ * merged into `llmContent`/`contentParts` (model-visible) at send time.
997
+ */
998
+ contextMentions?: AgentWidgetContextMentionRef[];
999
+ /**
1000
+ * Ordered prose + mention blocks for inline-mode rendering and composer history
1001
+ * recall (`contextMentions.display: "inline"`). Present only on inline-mode user
1002
+ * messages; when omitted the sent bubble falls back to the chip row derived from
1003
+ * `contextMentions`. Display/transcript concern only — not the model channel.
1004
+ */
1005
+ contentSegments?: AgentWidgetContentSegment[];
1006
+ /**
1007
+ * Resolved opt-in structured mention context for this (user) message, merged
1008
+ * into the request `context` under `mentions.<sourceId>.<itemId>` by the
1009
+ * client. Internal: set at send time from each source's `resolve().context`.
1010
+ */
1011
+ mentionContext?: Record<string, unknown>;
970
1012
  streaming?: boolean;
971
1013
  variant?: AgentWidgetMessageVariant;
972
1014
  sequence?: number;
@@ -734,6 +734,29 @@ type VideoContentPart = {
734
734
  * Union type for all content part types
735
735
  */
736
736
  type ContentPart = TextContentPart | ImageContentPart | FileContentPart | AudioContentPart | VideoContentPart;
737
+ /** Reference stored on a sent message for transcript fidelity + chip rendering. */
738
+ type AgentWidgetContextMentionRef = {
739
+ sourceId: string;
740
+ itemId: string;
741
+ label: string;
742
+ iconName?: string;
743
+ /** Accent color for the inline token (see `AgentWidgetContextMentionItem.color`). */
744
+ color?: string;
745
+ };
746
+ /**
747
+ * One ordered segment of a sent message's prose, for inline mention rendering
748
+ * (`contextMentions.display: "inline"`). Text runs and atomic mention tokens
749
+ * interleave in document order so the sent bubble re-renders `@tokens` in place
750
+ * and composer history can round-trip them. Display/transcript concern only —
751
+ * the model still sees resolved bodies via `llmContent`/`contentParts`.
752
+ */
753
+ type AgentWidgetContentSegment = {
754
+ kind: "text";
755
+ text: string;
756
+ } | {
757
+ kind: "mention";
758
+ ref: AgentWidgetContextMentionRef;
759
+ };
737
760
  /**
738
761
  * Metadata attached to messages created during agent execution.
739
762
  */
@@ -967,6 +990,25 @@ type AgentWidgetMessage = {
967
990
  * The `content` field contains the text-only representation for display.
968
991
  */
969
992
  contentParts?: ContentPart[];
993
+ /**
994
+ * Context mentions attached to this (user) message, for transcript fidelity +
995
+ * chip rendering in the sent bubble. Refs only — the resolved payloads are
996
+ * merged into `llmContent`/`contentParts` (model-visible) at send time.
997
+ */
998
+ contextMentions?: AgentWidgetContextMentionRef[];
999
+ /**
1000
+ * Ordered prose + mention blocks for inline-mode rendering and composer history
1001
+ * recall (`contextMentions.display: "inline"`). Present only on inline-mode user
1002
+ * messages; when omitted the sent bubble falls back to the chip row derived from
1003
+ * `contextMentions`. Display/transcript concern only — not the model channel.
1004
+ */
1005
+ contentSegments?: AgentWidgetContentSegment[];
1006
+ /**
1007
+ * Resolved opt-in structured mention context for this (user) message, merged
1008
+ * into the request `context` under `mentions.<sourceId>.<itemId>` by the
1009
+ * client. Internal: set at send time from each source's `resolve().context`.
1010
+ */
1011
+ mentionContext?: Record<string, unknown>;
970
1012
  streaming?: boolean;
971
1013
  variant?: AgentWidgetMessageVariant;
972
1014
  sequence?: number;
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BsZtXPKK.cjs';
1
+ import { S as StreamAnimationPlugin } from './types-4ROVJ1gA.cjs';
2
2
 
3
3
  declare const wipe: StreamAnimationPlugin;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BsZtXPKK.js';
1
+ import { S as StreamAnimationPlugin } from './types-4ROVJ1gA.js';
2
2
 
3
3
  declare const wipe: StreamAnimationPlugin;
4
4
 
@@ -0,0 +1,3 @@
1
+ var u=/\s/;function g(n,e,t){if(t==="input-start")return e===0;let r=e>0?n[e-1]:"";return t==="line-start"?r===""||r===`
2
+ `:r===""||u.test(r)}function l(n,e,t="@",r="anywhere",o=!1){if(!t||e<=0||e>n.length)return null;let i=e-1;for(;i>=0;){let s=n[i];if(s===t)return g(n,i,r)?{triggerIndex:i,query:n.slice(i+1,e)}:null;if(s===`
3
+ `||s==="\uFFFC"||!o&&u.test(s))return null;i--}return null}function c(n,e,t){for(let r of t){let o=l(n,e,r.trigger,r.position??"anywhere",r.allowSpaces??!1);if(o)return{channel:r,match:o}}return null}function a(n){return n?n!=="insertFromPaste"&&n!=="insertFromDrop":!0}function f(n,e,t){return{value:n.slice(0,e.triggerIndex)+n.slice(t),caret:e.triggerIndex}}export{c as a,a as b,f as c};
@@ -0,0 +1 @@
1
+ var zt=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Bt=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Ft=()=>document.createDocumentFragment(),Kt=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let c of Object.keys(a)){let l=a[c];l!=null&&(s[c]=l)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Wt=(...e)=>e.filter(Boolean).join(" ");import{Activity as A,ArrowDown as k,ArrowUp as P,ArrowUpRight as L,Bot as I,ChevronDown as R,ChevronUp as D,ChevronRight as H,ChevronLeft as O,Check as z,Clipboard as B,ClipboardCopy as F,CodeXml as K,Copy as W,File as U,FileCode as j,FileSpreadsheet as $,FileText as q,ImagePlus as V,Loader as X,LoaderCircle as G,Mic as _,Paperclip as Y,RefreshCw as Z,Search as J,Send as Q,ShieldAlert as ee,ShieldCheck as te,ShieldX as ne,Square as oe,ThumbsDown as re,ThumbsUp as ie,Upload as se,Volume2 as ae,X as le,User as ce,Mail as de,Phone as ue,Calendar as me,Clock as pe,Building as ge,MapPin as he,Lock as fe,Key as we,CreditCard as ye,AtSign as be,Hash as ve,Globe as xe,Link as Ce,CircleCheck as Se,CircleX as Ee,TriangleAlert as Te,Info as Me,Ban as Ne,Shield as Ae,ArrowLeft as ke,ArrowRight as Pe,ExternalLink as Le,Ellipsis as Ie,EllipsisVertical as Re,Menu as De,House as He,Plus as Oe,Minus as ze,Pencil as Be,Trash as Fe,Trash2 as Ke,Save as We,Download as Ue,Share as je,Funnel as $e,Settings as qe,RotateCw as Ve,Maximize as Xe,Minimize as Ge,ShoppingCart as _e,ShoppingBag as Ye,Package as Ze,Truck as Je,Tag as Qe,Gift as et,Receipt as tt,Wallet as nt,Store as ot,DollarSign as rt,Percent as it,Play as st,Pause as at,VolumeX as lt,Camera as ct,Image as dt,Film as ut,Headphones as mt,MessageCircle as pt,MessageSquare as gt,Bell as ht,Heart as ft,Star as wt,Eye as yt,EyeOff as bt,Bookmark as vt,CalendarDays as xt,History as Ct,Timer as St,Folder as Et,FolderOpen as Tt,Files as Mt,Sparkles as Nt,Zap as At,Sun as kt,Moon as Pt,Flag as Lt,Monitor as It,Smartphone as Rt}from"lucide";var Dt={activity:A,"arrow-down":k,"arrow-up":P,"arrow-up-right":L,bot:I,"chevron-down":R,"chevron-up":D,"chevron-right":H,"chevron-left":O,check:z,clipboard:B,"clipboard-copy":F,"code-xml":K,copy:W,file:U,"file-code":j,"file-spreadsheet":$,"file-text":q,"image-plus":V,loader:X,"loader-circle":G,mic:_,paperclip:Y,"refresh-cw":Z,search:J,send:Q,"shield-alert":ee,"shield-check":te,"shield-x":ne,square:oe,"thumbs-down":re,"thumbs-up":ie,upload:se,"volume-2":ae,x:le,user:ce,mail:de,phone:ue,calendar:me,clock:pe,building:ge,"map-pin":he,lock:fe,key:we,"credit-card":ye,"at-sign":be,hash:ve,globe:xe,link:Ce,"circle-check":Se,"circle-x":Ee,"triangle-alert":Te,info:Me,ban:Ne,shield:Ae,"arrow-left":ke,"arrow-right":Pe,"external-link":Le,ellipsis:Ie,"ellipsis-vertical":Re,menu:De,house:He,plus:Oe,minus:ze,pencil:Be,trash:Fe,"trash-2":Ke,save:We,download:Ue,share:je,funnel:$e,settings:qe,"rotate-cw":Ve,maximize:Xe,minimize:Ge,"shopping-cart":_e,"shopping-bag":Ye,package:Ze,truck:Je,tag:Qe,gift:et,receipt:tt,wallet:nt,store:ot,"dollar-sign":rt,percent:it,play:st,pause:at,"volume-x":lt,camera:ct,image:dt,film:ut,headphones:mt,"message-circle":pt,"message-square":gt,bell:ht,heart:ft,star:wt,eye:yt,"eye-off":bt,bookmark:vt,"calendar-days":xt,history:Ct,timer:St,folder:Et,"folder-open":Tt,files:Mt,sparkles:Nt,zap:At,sun:kt,moon:Pt,flag:Lt,monitor:It,smartphone:Rt},$t=(e,t=24,n="currentColor",o=2)=>{let r=Dt[e];return r?Ht(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Ht(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],c=s[1];if(!c)return;let l=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(c).forEach(([h,f])=>{h!=="stroke"&&l.setAttribute(h,String(f))}),r.appendChild(l)}),r}function Vt(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}function T(e){let t=e.getRootNode?.();return t instanceof ShadowRoot||t instanceof Document?t:e.ownerDocument??document}function b(e,t,n){let o=e instanceof Document?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(e instanceof Document?e:e.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",t),a.textContent=n,o.appendChild(a)}function Gt(e,t,n){if(e instanceof Document||e instanceof ShadowRoot){b(e,t,n);return}let o=e;if(o.isConnected){b(T(o),t,n);return}let r=o.ownerDocument??document;b(r,t,n),queueMicrotask(()=>{let s=T(o);s!==r&&b(s,t,n)})}function Ot(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function _t(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:c,zIndex:l=2147483e3,onOpen:h,onDismiss:f}=e,M=e.container??Ot(t),d=!1,w=null,v=()=>{if(!d)return;let i=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${i.width}px`),a&&(n.style.maxWidth=`${i.width}px`);let m=n.getBoundingClientRect(),u=c?.()??null,y=u!=null?i.top+u:i.top,x=o==="top-start"||o==="top-end"?y-r-m.height:i.bottom+r,g=o==="bottom-end"||o==="top-end"?i.right-m.width:i.left,E=a?.()??null;if(E!=null){let N=Math.max(i.left,i.right-m.width);g=Math.min(Math.max(i.left+E,i.left),N)}n.style.top=`${x}px`,n.style.left=`${g}px`},p=()=>{d&&(d=!1,w&&(w(),w=null),n.remove())},S=()=>{if(d)return;d=!0,l!=null&&(n.style.zIndex=String(l)),M.appendChild(n),v();let i=(t.ownerDocument??document).defaultView??window,m=t.ownerDocument??document,u=()=>{if(!t.isConnected){p(),f?.("anchor-removed");return}v()},y=C=>{let g=typeof C.composedPath=="function"?C.composedPath():[];g.includes(n)||g.includes(t)||(p(),f?.("outside"))},x=i.setTimeout(()=>{m.addEventListener("pointerdown",y,!0)},0);i.addEventListener("scroll",u,!0),i.addEventListener("resize",u),w=()=>{i.clearTimeout(x),m.removeEventListener("pointerdown",y,!0),i.removeEventListener("scroll",u,!0),i.removeEventListener("resize",u)},h?.()};return{get isOpen(){return d},open:S,close:p,toggle:()=>d?p():S(),reposition:v,destroy:p}}function Yt(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}export{zt as a,Bt as b,Ft as c,Kt as d,Wt as e,$t as f,Vt as g,Gt as h,_t as i,Yt as j};
@@ -0,0 +1 @@
1
+ function i(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function r(e){let o=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:e,getValue:()=>e.value,getLogicalText:()=>e.value,getSelection:()=>({start:e.selectionStart??0,end:e.selectionEnd??0}),setSelection:(t,n=t)=>{e.setSelectionRange(t,n)},setValueWithCaret:(t,n)=>{e.value=t,e.setSelectionRange(n,n)},setValue:t=>{e.value=t,e.setSelectionRange(t.length,t.length),o(),e.focus()},submit:()=>i(e.form),dispatchInput:o,focus:()=>e.focus()}}export{i as a,r as b};
package/dist/codegen.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var $=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var T=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},M=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of I(r))!_.call(e,o)&&o!==n&&$(e,o,{get:()=>r[o],enumerable:!(s=v(r,o))||s.enumerable});return e};var R=e=>M($({},"__esModule",{value:!0}),e);var U={};T(U,{generateCodeSnippet:()=>k});module.exports=R(U);var S="4.8.0";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function H(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
1
+ "use strict";var $=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var T=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},M=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of I(r))!_.call(e,a)&&a!==n&&$(e,a,{get:()=>r[a],enumerable:!(s=v(r,a))||s.enumerable});return e};var R=e=>M($({},"__esModule",{value:!0}),e);var U={};T(U,{generateCodeSnippet:()=>k});module.exports=R(U);var x="4.10.0";var c=x;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function H(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var S=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
@@ -70,11 +70,11 @@
70
70
  if (parsed.action === 'message') return parsed.text || '';
71
71
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
72
72
  return parsed.text || null;
73
- }`;function F(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function g(e){return e.parserType??F(e.streamParser)??"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,o])=>{typeof o=="string"&&n.push(`${r} ${s}: "${o}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),t=n?.onFeedback||n?.onCopy;return(o||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?s.push(`${r} ${i}: "${a}",`):typeof a=="boolean"&&s.push(`${r} ${i}: ${a},`))}),n?.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n?.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(s||o)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),o&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||o)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),o&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([a,p])=>{typeof p=="string"?n.push(`${r} ${a}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${a}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?n.push(`${r} ${p}: "${l}",`):typeof l=="boolean"&&n.push(`${r} ${p}: ${l},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function w(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function E(e,r,n){Object.entries(r).forEach(([s,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${s}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${s}: {`),E(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(o)},`)}})}function d(e,r,n,s){n&&(e.push(`${s}${r}: {`),E(e,n,`${s} `),e.push(`${s}},`))}function h(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function k(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let o=n?{...n,hooks:H(n.hooks)}:void 0;return r==="esm"?J(s,o):r==="script-installer"?K(s,o):r==="script-advanced"?Y(s,o):r==="react-component"?q(s,o):r==="react-advanced"?L(s,o):G(s,o)}function J(e,r){let n=r?.hooks,s=g(e),o=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
- `)}function q(e,r){let n=r?.hooks,s=g(e),o=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
75
- `)}function L(e,r){let n=r?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n?.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${N}),`)),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
76
- `)}function P(e){let r=g(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([t,i])=>{typeof i=="string"&&(o[t]=i)}),Object.keys(o).length>0&&(s.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([t,i])=>{t!=="onFeedback"&&t!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[t]=i)}),Object.keys(o).length>0&&(s.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(s.markdown=o)}if(e.layout){let o={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([i,a])=>{i!=="render"&&(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(o.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([i,a])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof a=="object"&&a!==null)t.avatar=a;else if(i==="timestamp"&&typeof a=="object"&&a!==null){let p={};Object.entries(a).forEach(([l,b])=>{l!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(p[l]=b)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(o.messages=t)}Object.keys(o).length>0&&(s.layout=o)}return s}function K(e,r){let n=P(e),o=!!(r?.windowKey||r?.target)?{config:n,...r?.windowKey?{windowKey:r.windowKey}:{},...r?.target?{target:r.target}:{}}:n,t=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function G(e,r){let n=r?.hooks,s=g(e),o=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${h(r)}',`,...r?.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
73
+ }`;function F(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function g(e){return e.parserType??F(e.streamParser)??"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&n.push(`${r} ${s}: "${a}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([i,o])=>i!=="onFeedback"&&i!=="onCopy"&&o!==void 0),t=n?.onFeedback||n?.onCopy;return(a||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,o])=>{i==="onFeedback"||i==="onCopy"||(typeof o=="string"?s.push(`${r} ${i}: "${o}",`):typeof o=="boolean"&&s.push(`${r} ${i}: ${o},`))}),n?.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n?.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),a&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),a=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||a)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),a&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([o,p])=>{typeof p=="string"?n.push(`${r} ${o}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${o}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?n.push(`${r} ${p}: "${l}",`):typeof l=="boolean"&&n.push(`${r} ${p}: ${l},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function w(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function E(e,r,n){Object.entries(r).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${n}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${n}${s}: {`),E(e,a,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(a)},`)}})}function d(e,r,n,s){n&&(e.push(`${s}${r}: {`),E(e,n,`${s} `),e.push(`${s}},`))}function h(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function k(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=n?{...n,hooks:H(n.hooks)}:void 0;return r==="esm"?J(s,a):r==="script-installer"?K(s,a):r==="script-advanced"?Y(s,a):r==="react-component"?q(s,a):r==="react-advanced"?L(s,a):G(s,a)}function J(e,r){let n=r?.hooks,s=g(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,o])=>{t.push(` ${i}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"?t.push(` ${i}: ${o},`):typeof o=="number"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,o])=>{t.push(` ${i}: ${o},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
+ `)}function q(e,r){let n=r?.hooks,s=g(e),a=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,o])=>{t.push(` ${i}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"?t.push(` ${i}: ${o},`):typeof o=="number"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,o])=>{t.push(` ${i}: ${o},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
75
+ `)}function L(e,r){let n=r?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n?.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${N}),`)),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${S}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${S}`),s.push(" ],")),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
76
+ `)}function P(e){let r=g(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([t,i])=>{typeof i=="string"&&(a[t]=i)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,i])=>{t!=="onFeedback"&&t!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(a[t]=i)}),Object.keys(a).length>0&&(s.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(s.markdown=a)}if(e.layout){let a={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([i,o])=>{i!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[i]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([i,o])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(i==="timestamp"&&typeof o=="object"&&o!==null){let p={};Object.entries(o).forEach(([l,b])=>{l!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(p[l]=b)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof o=="string"||typeof o=="boolean")&&(t[i]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function K(e,r){let n=P(e),a=!!(r?.windowKey||r?.target)?{config:n,...r?.windowKey?{windowKey:r.windowKey}:{},...r?.target?{target:r.target}:{}}:n,t=JSON.stringify(a,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function G(e,r){let n=r?.hooks,s=g(e),a=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${h(r)}',`,...r?.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,o])=>{t.push(` ${i}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"?t.push(` ${i}: ${o},`):typeof o=="number"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,o])=>{typeof o=="string"?t.push(` ${i}: "${o}",`):typeof o=="boolean"&&t.push(` ${i}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,o])=>{t.push(` ${i}: ${o},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
77
77
  `)}function Y(e,r){let n=r?.hooks,s=P(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
78
- `).map((i,a)=>a===0?i:" "+i).join(`
78
+ `).map((i,o)=>o===0?i:" "+i).join(`
79
79
  `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n?.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${D});`),t.push(" };")),t.push(""),n?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ];")),t.push(""),n?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${n.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ];")),t.push(""),n?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${n.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),n?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(n?.onFeedback||n?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${h(r)}',`," useShadowDom: false,",...r?.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
80
80
  `)}0&&(module.exports={generateCodeSnippet});