@runtypelabs/persona 4.17.1 → 4.18.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 (158) hide show
  1. package/dist/chunk-3I2S3I5P.js +1 -0
  2. package/dist/chunk-76IELU7F.js +1 -0
  3. package/dist/chunk-EFJBUH5F.js +1 -0
  4. package/dist/chunk-PDPVORUF.js +1 -0
  5. package/dist/chunk-Q735PSZL.js +1 -0
  6. package/dist/chunk-VK6JOIYJ.js +1 -0
  7. package/dist/codegen.cjs +4 -4
  8. package/dist/codegen.js +4 -4
  9. package/dist/{context-mentions-BTSTIBFC.js → context-mentions-MJL6S6P2.js} +1 -1
  10. package/dist/context-mentions.cjs +9 -8
  11. package/dist/context-mentions.d.cts +1212 -14
  12. package/dist/context-mentions.d.ts +1212 -14
  13. package/dist/context-mentions.js +9 -8
  14. package/dist/event-stream-view-4EZ7BGFK.js +1 -0
  15. package/dist/event-stream-view.cjs +129 -0
  16. package/dist/event-stream-view.d.cts +8384 -0
  17. package/dist/event-stream-view.d.ts +8384 -0
  18. package/dist/event-stream-view.js +129 -0
  19. package/dist/history-view-BD6OXLNA.js +898 -0
  20. package/dist/history-view.cjs +898 -0
  21. package/dist/history-view.d.cts +1461 -0
  22. package/dist/history-view.d.ts +1461 -0
  23. package/dist/history-view.js +898 -0
  24. package/dist/index.cjs +77 -77
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +1987 -17
  27. package/dist/index.d.ts +1987 -17
  28. package/dist/index.global.js +67 -66
  29. package/dist/index.global.js.map +1 -1
  30. package/dist/index.js +77 -77
  31. package/dist/index.js.map +1 -1
  32. package/dist/launcher.global.js +5 -4
  33. package/dist/launcher.global.js.map +1 -1
  34. package/dist/plugin-kit.cjs +1 -1
  35. package/dist/plugin-kit.d.cts +0 -8
  36. package/dist/plugin-kit.d.ts +0 -8
  37. package/dist/plugin-kit.js +1 -1
  38. package/dist/smart-dom-reader.d.cts +1212 -14
  39. package/dist/smart-dom-reader.d.ts +1212 -14
  40. package/dist/theme-editor-preview.cjs +970 -73
  41. package/dist/theme-editor-preview.d.cts +1331 -15
  42. package/dist/theme-editor-preview.d.ts +1331 -15
  43. package/dist/theme-editor-preview.js +81 -81
  44. package/dist/theme-editor.cjs +7 -7
  45. package/dist/theme-editor.d.cts +1215 -15
  46. package/dist/theme-editor.d.ts +1215 -15
  47. package/dist/theme-editor.js +9 -9
  48. package/dist/theme-reference.cjs +1 -1
  49. package/dist/theme-reference.d.cts +226 -7
  50. package/dist/theme-reference.d.ts +226 -7
  51. package/dist/theme-reference.js +1 -1
  52. package/dist/widget.css +1 -1
  53. package/package.json +16 -4
  54. package/src/client-history-rest.test.ts +1034 -0
  55. package/src/client-visitor-history.test.ts +596 -0
  56. package/src/client.ts +1040 -24
  57. package/src/components/artifact-inline.ts +8 -1
  58. package/src/components/artifact-pane.test.ts +278 -1
  59. package/src/components/artifact-pane.ts +135 -67
  60. package/src/components/artifact-preview.test.ts +14 -1
  61. package/src/components/artifact-preview.ts +9 -0
  62. package/src/components/header-builder.ts +3 -0
  63. package/src/components/header-layouts.test.ts +171 -7
  64. package/src/components/header-layouts.ts +83 -53
  65. package/src/components/header-parts.test.ts +154 -1
  66. package/src/components/header-parts.ts +266 -138
  67. package/src/components/history-confirm-dialog.ts +177 -0
  68. package/src/components/history-shell-copy.ts +99 -0
  69. package/src/components/history-view/announcer.ts +40 -0
  70. package/src/components/history-view/copy.ts +105 -0
  71. package/src/components/history-view/css.ts +1078 -0
  72. package/src/components/history-view/grouping.test.ts +142 -0
  73. package/src/components/history-view/grouping.ts +142 -0
  74. package/src/components/history-view/icons.ts +73 -0
  75. package/src/components/history-view/rows.ts +341 -0
  76. package/src/components/history-view/state.ts +309 -0
  77. package/src/components/history-view.test.ts +2660 -0
  78. package/src/components/history-view.ts +1891 -0
  79. package/src/components/launcher-surface.test.ts +133 -0
  80. package/src/components/launcher.test.ts +18 -0
  81. package/src/components/launcher.ts +7 -7
  82. package/src/components/panel.ts +17 -7
  83. package/src/components/welcome.ts +72 -2
  84. package/src/defaults.ts +36 -3
  85. package/src/event-stream-view-bundle.test.ts +69 -0
  86. package/src/event-stream-view-entry.ts +19 -0
  87. package/src/event-stream-view-loader.ts +31 -0
  88. package/src/event-stream-view.ts +19 -0
  89. package/src/generated/runtype-openapi-contract.ts +1 -0
  90. package/src/history-render.ts +325 -0
  91. package/src/history-view-bundle.test.ts +78 -0
  92. package/src/history-view-entry.ts +41 -0
  93. package/src/history-view-loader.test.ts +30 -0
  94. package/src/history-view-loader.ts +32 -0
  95. package/src/history-view.ts +28 -0
  96. package/src/index-core.ts +50 -2
  97. package/src/index-global.ts +55 -0
  98. package/src/internal/demo-history-provider.test.ts +402 -0
  99. package/src/internal/demo-history-provider.ts +689 -0
  100. package/src/internal/history-provider-registry.ts +25 -0
  101. package/src/internal/history-provider.ts +150 -0
  102. package/src/internal/runtype-history-provider.test.ts +313 -0
  103. package/src/internal/runtype-history-provider.ts +240 -0
  104. package/src/plugin-kit.test.ts +16 -0
  105. package/src/plugin-kit.ts +13 -5
  106. package/src/plugins/types.ts +177 -1
  107. package/src/session-history.test.ts +1397 -0
  108. package/src/session.ts +1200 -26
  109. package/src/styles/widget-styles.test.ts +133 -0
  110. package/src/styles/widget.css +227 -8
  111. package/src/theme-editor/preview-utils.test.ts +19 -0
  112. package/src/theme-editor/preview-utils.ts +15 -1
  113. package/src/theme-editor/preview.ts +7 -1
  114. package/src/theme-editor/role-mappings.ts +4 -1
  115. package/src/theme-editor/sections.test.ts +168 -1
  116. package/src/theme-editor/sections.ts +136 -7
  117. package/src/theme-editor/webmcp/summary.ts +16 -2
  118. package/src/theme-reference.ts +20 -6
  119. package/src/types/theme.ts +213 -7
  120. package/src/types.ts +927 -7
  121. package/src/ui.artifact-rail-resize.test.ts +235 -0
  122. package/src/ui.attachments-drop.test.ts +1 -0
  123. package/src/ui.header-update-stability.test.ts +2 -2
  124. package/src/ui.history-chunk.test.ts +72 -0
  125. package/src/ui.history-config-provider.test.ts +318 -0
  126. package/src/ui.history-controller.test.ts +711 -0
  127. package/src/ui.history-lifecycle.test.ts +456 -0
  128. package/src/ui.history-render-hooks.test.ts +904 -0
  129. package/src/ui.history-shell.test.ts +1887 -0
  130. package/src/ui.rail-overlay.test.ts +573 -0
  131. package/src/ui.rail-resize.test.ts +284 -0
  132. package/src/ui.rebuild-composer.test.ts +21 -0
  133. package/src/ui.render-welcome.test.ts +42 -0
  134. package/src/ui.shortcuts.test.ts +166 -0
  135. package/src/ui.ts +3071 -240
  136. package/src/utils/__fixtures__/client-conversation-history-wire.json +108 -0
  137. package/src/utils/artifact-file.ts +15 -0
  138. package/src/utils/artifact-gate.test.ts +4 -0
  139. package/src/utils/artifact-gate.ts +13 -17
  140. package/src/utils/artifact-resize.test.ts +28 -0
  141. package/src/utils/artifact-resize.ts +9 -2
  142. package/src/utils/buttons.ts +188 -1
  143. package/src/utils/config-merge.test.ts +91 -0
  144. package/src/utils/dropdown.ts +10 -1
  145. package/src/utils/history-messages.test.ts +284 -0
  146. package/src/utils/history-messages.ts +284 -0
  147. package/src/utils/icons.ts +3 -0
  148. package/src/utils/shortcuts.test.ts +288 -0
  149. package/src/utils/shortcuts.ts +221 -0
  150. package/src/utils/theme.test.ts +501 -4
  151. package/src/utils/theme.ts +42 -3
  152. package/src/utils/tokens.ts +153 -15
  153. package/src/utils/tooltip-timing.ts +4 -0
  154. package/src/utils/tooltip.test.ts +249 -7
  155. package/src/utils/tooltip.ts +146 -4
  156. package/src/utils/visitor-store.test.ts +425 -0
  157. package/src/utils/visitor-store.ts +337 -0
  158. package/dist/chunk-QJ4LV2KW.js +0 -1
@@ -0,0 +1 @@
1
+ import{Activity as u,ArrowDown as h,ArrowUp as p,ArrowUpRight as g,Bot as m,ChevronDown as f,ChevronUp as w,ChevronRight as b,ChevronLeft as C,Check as S,Clipboard as k,ClipboardCopy as y,CodeXml as A,Copy as v,File as I,FileCode as x,FileSpreadsheet as L,FileText as E,ImagePlus as P,Loader as F,LoaderCircle as M,Mic as N,Paperclip as R,RefreshCw as T,Search as U,Send as B,ShieldAlert as D,ShieldCheck as H,ShieldX as O,Square as V,ThumbsDown as X,ThumbsUp as q,Upload as z,Volume2 as G,X as j,User as _,Mail as K,Phone as W,Calendar as Z,Clock as $,Building as J,MapPin as Q,Lock as Y,Key as ee,CreditCard as re,AtSign as te,Hash as ie,Globe as oe,Link as ne,CircleCheck as ae,CircleX as le,TriangleAlert as se,Info as ce,Ban as de,Shield as ue,ArrowLeft as he,ArrowRight as pe,ExternalLink as ge,Ellipsis as me,EllipsisVertical as fe,Menu as we,House as be,PanelLeft as Ce,Plus as Se,Minus as ke,Pencil as ye,PenLine as Ae,Trash as ve,Trash2 as Ie,Save as xe,Download as Le,Share as Ee,Funnel as Pe,Settings as Fe,RotateCw as Me,Maximize as Ne,Minimize as Re,ShoppingCart as Te,ShoppingBag as Ue,Package as Be,Truck as De,Tag as He,Gift as Oe,Receipt as Ve,Wallet as Xe,Store as qe,DollarSign as ze,Percent as Ge,Play as je,Pause as _e,VolumeX as Ke,Camera as We,Image as Ze,Film as $e,Headphones as Je,MessageCircle as Qe,MessageSquare as Ye,Bell as er,Heart as rr,Star as tr,Eye as ir,EyeOff as or,Bookmark as nr,CalendarDays as ar,History as lr,Timer as sr,Folder as cr,FolderOpen as dr,Files as ur,ChartColumn as hr,Sparkles as pr,Zap as gr,Sun as mr,Moon as fr,Flag as wr,Lightbulb as br,Monitor as Cr,Smartphone as Sr}from"lucide";var kr={activity:u,"arrow-down":h,"arrow-up":p,"arrow-up-right":g,bot:m,"chevron-down":f,"chevron-up":w,"chevron-right":b,"chevron-left":C,check:S,clipboard:k,"clipboard-copy":y,"code-xml":A,copy:v,file:I,"file-code":x,"file-spreadsheet":L,"file-text":E,"image-plus":P,loader:F,"loader-circle":M,mic:N,paperclip:R,"refresh-cw":T,search:U,send:B,"shield-alert":D,"shield-check":H,"shield-x":O,square:V,"thumbs-down":X,"thumbs-up":q,upload:z,"volume-2":G,x:j,user:_,mail:K,phone:W,calendar:Z,clock:$,building:J,"map-pin":Q,lock:Y,key:ee,"credit-card":re,"at-sign":te,hash:ie,globe:oe,link:ne,"circle-check":ae,"circle-x":le,"triangle-alert":se,info:ce,ban:de,shield:ue,"arrow-left":he,"arrow-right":pe,"external-link":ge,ellipsis:me,"ellipsis-vertical":fe,menu:we,house:be,"panel-left":Ce,plus:Se,minus:ke,pencil:ye,"pen-line":Ae,trash:ve,"trash-2":Ie,save:xe,download:Le,share:Ee,funnel:Pe,settings:Fe,"rotate-cw":Me,maximize:Ne,minimize:Re,"shopping-cart":Te,"shopping-bag":Ue,package:Be,truck:De,tag:He,gift:Oe,receipt:Ve,wallet:Xe,store:qe,"dollar-sign":ze,percent:Ge,play:je,pause:_e,"volume-x":Ke,camera:We,image:Ze,film:$e,headphones:Je,"message-circle":Qe,"message-square":Ye,bell:er,heart:rr,star:tr,eye:ir,"eye-off":or,bookmark:nr,"calendar-days":ar,history:lr,timer:sr,folder:cr,"folder-open":dr,files:ur,"chart-column":hr,sparkles:pr,zap:gr,sun:mr,moon:fr,flag:wr,lightbulb:br,monitor:Cr,smartphone:Sr},vr=(r,t=24,o="currentColor",n=2)=>{let e=kr[r];return e?yr(e,t,o,n):(console.warn(`Lucide icon "${r}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function yr(r,t,o,n){if(!Array.isArray(r))return null;let e=document.createElementNS("http://www.w3.org/2000/svg","svg");return e.setAttribute("width",String(t)),e.setAttribute("height",String(t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke",o),e.setAttribute("stroke-width",String(n)),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("aria-hidden","true"),r.forEach(i=>{if(!Array.isArray(i)||i.length<2)return;let c=i[0],a=i[1];if(!a)return;let l=document.createElementNS("http://www.w3.org/2000/svg",c);Object.entries(a).forEach(([s,d])=>{s!=="stroke"&&l.setAttribute(s,String(d))}),e.appendChild(l)}),e}export{vr as a};
@@ -0,0 +1 @@
1
+ var m=(n,e)=>{let a=document.createElement(n);return e&&(a.className=e),a};var i=()=>document.createDocumentFragment(),d=(n,e={},...a)=>{let t=document.createElement(n);if(e.className&&(t.className=e.className),e.text!==void 0&&(t.textContent=e.text),e.attrs)for(let[r,s]of Object.entries(e.attrs))t.setAttribute(r,s);if(e.style){let r=t.style,s=e.style;for(let c of Object.keys(s)){let o=s[c];o!=null&&(r[c]=o)}}let l=a.filter(r=>r!=null);return l.length>0&&t.append(...l),t},u=(...n)=>n.filter(Boolean).join(" ");export{m as a,i as b,d as c,u as d};
@@ -0,0 +1 @@
1
+ var i=class extends Error{constructor(o,r,e){super(r),this.name="HistoryProviderError",this.code=o,e?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds)}};function a(t){return t instanceof i}var s=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],n={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function d(t){if(!t)return n;let o={...n};for(let r of s){let e=t[r];typeof e=="string"&&e.length>0&&(o[r]=e)}return o}export{i as a,a as b,n as c,d};
@@ -0,0 +1 @@
1
+ function r(o){let e={trigger:o.trigger??"@",position:o.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton!==!1,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText},n=(o.triggers??[]).map(t=>({trigger:t.trigger,position:t.triggerPosition??"anywhere",allowSpaces:t.allowSpaces??!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton===!0,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText}));return[e,...n]}export{r as a};
@@ -0,0 +1 @@
1
+ var v=e=>e.nodeType===Node.DOCUMENT_NODE,N=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host!==void 0;function T(e){let t=e.getRootNode?.();return t&&N(t)||t&&v(t)?t:e.ownerDocument??document}function h(e,t,o){let i=v(e)?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(i.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let c=(v(e)?e:e.ownerDocument??document).createElement("style");c.setAttribute("data-persona-plugin-style",t),c.textContent=o,i.appendChild(c)}function S(e,t,o){if(v(e)||N(e)){h(e,t,o);return}let i=e;if(i.isConnected){h(T(i),t,o);return}let r=i.ownerDocument??document;h(r,t,o),queueMicrotask(()=>{let l=T(i);l!==r&&h(l,t,o)})}function P(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function C(e){let{anchor:t,content:o,placement:i="bottom-start",offset:r=6,matchAnchorWidth:l=!1,horizontalOffset:c,verticalOffset:b,zIndex:y=2147483e3,onOpen:O,onDismiss:x}=e,L=e.container??P(t),s=!1,m=null,w=()=>{if(!s)return;let n=t.getBoundingClientRect();o.style.position="fixed",l&&(o.style.minWidth=`${n.width}px`),c&&(o.style.maxWidth=`${n.width}px`);let a=o.getBoundingClientRect(),d=b?.()??null,f=d!=null?n.top+d:n.top,E=i==="top-start"||i==="top-end"?f-r-a.height:n.bottom+r,p=i==="bottom-end"||i==="top-end"?n.right-a.width:n.left,R=c?.()??null;if(R!=null){let M=Math.max(n.left,n.right-a.width);p=Math.min(Math.max(n.left+R,n.left),M)}o.style.top=`${E}px`,o.style.left=`${p}px`},u=()=>{s&&(s=!1,m&&(m(),m=null),o.remove())},D=()=>{if(s)return;s=!0,y!=null&&(o.style.zIndex=String(y)),L.appendChild(o),w();let n=(t.ownerDocument??document).defaultView??window,a=t.ownerDocument??document,d=()=>{if(!t.isConnected){u(),x?.("anchor-removed");return}w()},f=g=>{let p=typeof g.composedPath=="function"?g.composedPath():[];p.includes(o)||p.includes(t)||(u(),x?.("outside"))},E=n.setTimeout(()=>{a.addEventListener("pointerdown",f,!0)},0);n.addEventListener("scroll",d,!0),n.addEventListener("resize",d),m=()=>{n.clearTimeout(E),a.removeEventListener("pointerdown",f,!0),n.removeEventListener("scroll",d,!0),n.removeEventListener("resize",d)},O?.()};return{get isOpen(){return s},open:D,close:u,toggle:()=>s?u():D(),reposition:w,destroy:u}}function H(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(o=>o instanceof HTMLElement&&(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))}export{S as a,C as b,H as c};
@@ -0,0 +1 @@
1
+ function h(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function f(e=!0){let o=e;return{isFollowing:()=>o,pause:()=>o?(o=!1,!0):!1,resume:()=>o?!1:(o=!0,!0)}}function p(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function m(e,o){return p(e)-e.scrollTop<=o}function S(e){let{following:o,currentScrollTop:t,lastScrollTop:l,nearBottom:n,userScrollThreshold:a,isAutoScrolling:c=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:s=!1}=e,r=t-l;return c||Math.abs(r)<a?{action:"none",delta:r,nextLastScrollTop:t}:!o&&n&&(!s||r>0)?{action:"resume",delta:r,nextLastScrollTop:t}:o&&i&&r<0?{action:"pause",delta:r,nextLastScrollTop:t}:o&&u&&!n?{action:"pause",delta:r,nextLastScrollTop:t}:{action:"none",delta:r,nextLastScrollTop:t}}function b(e){let{following:o,deltaY:t,nearBottom:l=!1,resumeWhenNearBottom:n=!1}=e;return o&&t<0?"pause":!o&&n&&t>0&&l?"resume":"none"}function g(e,o){return!e||e.isCollapsed?!1:o.contains(e.anchorNode)||o.contains(e.focusNode)}function w(e){let o=Math.max(0,e.anchorOffsetTop-e.topOffset),t=Math.max(0,o+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:o,spacerHeight:t}}function x(e){let o=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-o)}export{h as a,f as b,p as c,m as d,S as e,b as f,g,w as h,x as i};
package/dist/codegen.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},W=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of T(i))!M.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=_(i,a))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var z={};R(z,{generateCodeSnippet:()=>I});module.exports=H(z);var x="4.17.1";var A=x;function w(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function D(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 j=`({ text, message }: any) => {
1
+ "use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},W=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of T(i))!M.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=_(i,a))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var z={};R(z,{generateCodeSnippet:()=>P});module.exports=H(z);var x="4.18.0";var A=x;function w(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function D(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 j=`({ 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
@@ -71,11 +71,11 @@
71
71
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
72
72
  return parsed.text || null;
73
73
  }`;function q(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function h(e){return e.parserType??q(e.streamParser)??"plain"}function g(e,i){let r=[];return e.toolCall&&(r.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&r.push(`${i} ${s}: "${a}",`)}),r.push(`${i}},`)),r}function m(e,i,r){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([n,o])=>n!=="onFeedback"&&n!=="onCopy"&&o!==void 0),t=r?.onFeedback||r?.onCopy;return(a||t)&&(s.push(`${i}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([n,o])=>{n==="onFeedback"||n==="onCopy"||(typeof o=="string"?s.push(`${i} ${n}: "${o}",`):typeof o=="boolean"&&s.push(`${i} ${n}: ${o},`))}),r?.onFeedback&&s.push(`${i} onFeedback: ${r.onFeedback},`),r?.onCopy&&s.push(`${i} onCopy: ${r.onCopy},`),s.push(`${i}},`)),s}function f(e,i){let r=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(r.push(`${i}markdown: {`),s&&(r.push(`${i} options: {`),Object.entries(e.markdown.options).forEach(([t,n])=>{typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`)}),r.push(`${i} },`)),a&&r.push(`${i} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${i}},`))}return r}function y(e,i){if(!e.suggestions)return[];let r=JSON.stringify(e.suggestions,null,2).split(`
74
- `);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function C(e,i){let r=[];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)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function S(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function P(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),P(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),P(e,r,`${s} `),e.push(`${s}},`))}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function I(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:D(r.hooks)}:void 0;return i==="esm"?L(s,a):i==="script-installer"?B(s,a):i==="script-advanced"?U(s,a):i==="react-component"?K(s,a):i==="react-advanced"?G(s,a):Y(s,a)}function L(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," 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(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
+ `);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function C(e,i){let r=[];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)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function S(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function v(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),v(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),v(e,r,`${s} `),e.push(`${s}},`))}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function P(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:D(r.hooks)}:void 0;return i==="esm"?L(s,a):i==="script-installer"?B(s,a):i==="script-advanced"?U(s,a):i==="react-component"?K(s,a):i==="react-advanced"?G(s,a):Y(s,a)}function L(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," 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(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
75
75
  `)}function K(e,i){let r=i?.hooks,s=h(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: '${c(i)}',`," 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(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.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(`
76
76
  `)}function G(e,i){let r=i?.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: '${c(i)}',`," 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(" },")),s.push(...y(e," ")),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(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...C(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${J}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${j}`),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(` ${j}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${E}`),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(` ${E}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.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(`
77
- `)}function v(e){let i=h(e),r=i!=="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),r&&(s.parserType=i),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.suggestions&&(s.suggestions=e.suggestions),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,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),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(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="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[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function B(e,i){let r=v(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"&#39;");return`<script src="${w(i)}/install.global.js" data-config='${t}'></script>`}function Y(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=w(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...C(e," ")),n.push(...S(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
78
- `)}function U(e,i){let r=i?.hooks,s=v(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
77
+ `)}function I(e){let i=h(e),r=i!=="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),r&&(s.parserType=i),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.suggestions&&(s.suggestions=e.suggestions),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,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),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(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="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[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function B(e,i){let r=I(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"&#39;");return`<script src="${w(i)}/install.global.js" data-config='${t}'></script>`}function Y(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=w(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...C(e," ")),n.push(...S(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
78
+ `)}function U(e,i){let r=i?.hooks,s=I(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
79
79
  `).map((n,o)=>o===0?n:" "+n).join(`
80
80
  `)};`,""," // Constants",` var CDN_BASE = '${w(i)}';`," 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 r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${F});`),t.push(" };")),t.push(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${O}`),t.push(" ];")),t.push(""),r?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${r.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${k}`),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(` ${k}`),t.push(" ];")),t.push(""),r?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${r.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(""),r?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(r?.onFeedback||r?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${r.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: '${c(i)}',`," useShadowDom: false,",...i?.windowKey?[` windowKey: '${i.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(`
81
81
  `)}0&&(module.exports={generateCodeSnippet});
package/dist/codegen.js CHANGED
@@ -1,4 +1,4 @@
1
- var S="4.17.1";var x=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${x}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function v(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 A=`({ text, message }: any) => {
1
+ var S="4.18.0";var x=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${x}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function I(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 A=`({ 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
@@ -71,11 +71,11 @@ var S="4.17.1";var x=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,""
71
71
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
72
72
  return parsed.text || null;
73
73
  }`;function M(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function h(e){return e.parserType??M(e.streamParser)??"plain"}function g(e,i){let r=[];return e.toolCall&&(r.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&r.push(`${i} ${s}: "${a}",`)}),r.push(`${i}},`)),r}function m(e,i,r){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([n,o])=>n!=="onFeedback"&&n!=="onCopy"&&o!==void 0),t=r?.onFeedback||r?.onCopy;return(a||t)&&(s.push(`${i}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([n,o])=>{n==="onFeedback"||n==="onCopy"||(typeof o=="string"?s.push(`${i} ${n}: "${o}",`):typeof o=="boolean"&&s.push(`${i} ${n}: ${o},`))}),r?.onFeedback&&s.push(`${i} onFeedback: ${r.onFeedback},`),r?.onCopy&&s.push(`${i} onCopy: ${r.onCopy},`),s.push(`${i}},`)),s}function f(e,i){let r=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(r.push(`${i}markdown: {`),s&&(r.push(`${i} options: {`),Object.entries(e.markdown.options).forEach(([t,n])=>{typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`)}),r.push(`${i} },`)),a&&r.push(`${i} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${i}},`))}return r}function y(e,i){if(!e.suggestions)return[];let r=JSON.stringify(e.suggestions,null,2).split(`
74
- `);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function C(e,i){let r=[];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)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function w(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function k(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),k(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),k(e,r,`${s} `),e.push(`${s}},`))}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function R(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:v(r.hooks)}:void 0;return i==="esm"?W(s,a):i==="script-installer"?D(s,a):i==="script-advanced"?F(s,a):i==="react-component"?H(s,a):i==="react-advanced"?N(s,a):J(s,a)}function W(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," 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(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...w(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
+ `);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function C(e,i){let r=[];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)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function w(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function k(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),k(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),k(e,r,`${s} `),e.push(`${s}},`))}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function R(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:I(r.hooks)}:void 0;return i==="esm"?W(s,a):i==="script-installer"?D(s,a):i==="script-advanced"?F(s,a):i==="react-component"?H(s,a):i==="react-advanced"?N(s,a):J(s,a)}function W(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," 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(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...w(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
75
75
  `)}function H(e,i){let r=i?.hooks,s=h(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: '${c(i)}',`," 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(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...w(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.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(`
76
76
  `)}function N(e,i){let r=i?.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: '${c(i)}',`," 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(" },")),s.push(...y(e," ")),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(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...C(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${_}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${A}`),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(` ${A}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${O}`),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(` ${O}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.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(`
77
- `)}function P(e){let i=h(e),r=i!=="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),r&&(s.parserType=i),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.suggestions&&(s.suggestions=e.suggestions),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,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),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(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="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[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function D(e,i){let r=P(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"&#39;");return`<script src="${$(i)}/install.global.js" data-config='${t}'></script>`}function J(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=$(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...C(e," ")),n.push(...w(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
78
- `)}function F(e,i){let r=i?.hooks,s=P(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
77
+ `)}function v(e){let i=h(e),r=i!=="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),r&&(s.parserType=i),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.suggestions&&(s.suggestions=e.suggestions),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,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),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(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="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[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function D(e,i){let r=v(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"&#39;");return`<script src="${$(i)}/install.global.js" data-config='${t}'></script>`}function J(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=$(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...C(e," ")),n.push(...w(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
78
+ `)}function F(e,i){let r=i?.hooks,s=v(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
79
79
  `).map((n,o)=>o===0?n:" "+n).join(`
80
80
  `)};`,""," // Constants",` var CDN_BASE = '${$(i)}';`," 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 r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${T});`),t.push(" };")),t.push(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${j}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${j}`),t.push(" ];")),t.push(""),r?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${r.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${E}`),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(` ${E}`),t.push(" ];")),t.push(""),r?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${r.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(""),r?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(r?.onFeedback||r?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${r.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: '${c(i)}',`," useShadowDom: false,",...i?.windowKey?[` windowKey: '${i.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(`
81
81
  `)}export{R as generateCodeSnippet};
@@ -1,4 +1,4 @@
1
- import{a as S,c as C,e as N,f as X,g as J,h as Z}from"./chunk-QJ4LV2KW.js";import{b as ee}from"./chunk-UPO4GUFC.js";import{a as _,c as Y}from"./chunk-IO5VVUKP.js";function te(s){let{ref:e,config:t,onRemove:n}=s;if(t.renderMentionChip){let u="resolving",A,T=t.renderMentionChip({ref:e,status:u,payload:A,remove:n});return{get el(){return T},setStatus:(z,E)=>{if(z===u&&E===A)return;u=z,A=E;let B=t.renderMentionChip({ref:e,status:u,payload:A,remove:n});T.replaceWith(B),T=B}}}let i=e.iconName??t.chipIconName??"at-sign",o=C("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),r=S("span","persona-mention-chip-icon"),d=u=>{r.replaceChildren();let A=N(u,13,"currentColor",2);A&&r.appendChild(A)};d(i);let a=S("span","persona-mention-chip-spinner"),l=C("span",{className:"persona-mention-chip-label",text:e.label}),x=C("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),p=N("x",11,"currentColor",2.5);return p?x.appendChild(p):x.textContent="\xD7",x.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),o.appendChild(a),o.appendChild(l),o.appendChild(x),{el:o,setStatus:u=>{o.setAttribute("data-status",u),u==="resolving"?(a.parentNode!==o&&o.insertBefore(a,l),r.parentNode===o&&r.remove(),o.setAttribute("title",e.label)):(a.parentNode===o&&a.remove(),r.parentNode!==o&&o.insertBefore(r,l),u==="error"?(d("triangle-alert"),o.setAttribute("title",`Couldn't add ${e.label} to context`)):(d(i),o.setAttribute("title",e.label)))}}}function ce(s){let e=0;for(let t of s.split(`
1
+ import{a as X}from"./chunk-PDPVORUF.js";import{b as ee}from"./chunk-UPO4GUFC.js";import{a as _,c as Y}from"./chunk-IO5VVUKP.js";import{a as N}from"./chunk-3I2S3I5P.js";import{a as J,b as Z}from"./chunk-Q735PSZL.js";import{a as S,c as C}from"./chunk-76IELU7F.js";function te(s){let{ref:e,config:t,onRemove:n}=s;if(t.renderMentionChip){let u="resolving",A,T=t.renderMentionChip({ref:e,status:u,payload:A,remove:n});return{get el(){return T},setStatus:(z,E)=>{if(z===u&&E===A)return;u=z,A=E;let B=t.renderMentionChip({ref:e,status:u,payload:A,remove:n});T.replaceWith(B),T=B}}}let i=e.iconName??t.chipIconName??"at-sign",o=C("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),r=S("span","persona-mention-chip-icon"),d=u=>{r.replaceChildren();let A=N(u,13,"currentColor",2);A&&r.appendChild(A)};d(i);let a=S("span","persona-mention-chip-spinner"),l=C("span",{className:"persona-mention-chip-label",text:e.label}),x=C("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),p=N("x",11,"currentColor",2.5);return p?x.appendChild(p):x.textContent="\xD7",x.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),o.appendChild(a),o.appendChild(l),o.appendChild(x),{el:o,setStatus:u=>{o.setAttribute("data-status",u),u==="resolving"?(a.parentNode!==o&&o.insertBefore(a,l),r.parentNode===o&&r.remove(),o.setAttribute("title",e.label)):(a.parentNode===o&&a.remove(),r.parentNode!==o&&o.insertBefore(r,l),u==="error"?(d("triangle-alert"),o.setAttribute("title",`Couldn't add ${e.label} to context`)):(d(i),o.setAttribute("title",e.label)))}}}function ce(s){let e=0;for(let t of s.split(`
2
2
  `)){let n=/^ {0,3}(`+)/.exec(t);n&&n[1].length>e&&(e=n[1].length)}return e}function Q(s,e){let t="`".repeat(Math.max(3,ce(e)+1));return`${t}${s}
3
3
  ${e}
4
4
  ${t}`}function de(s,e,t){return e.includes("</document_content>")?Q(s,e):`<document index="${t+1}">