@runtypelabs/persona 4.7.0 → 4.8.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.
- package/dist/animations/glyph-cycle.cjs +2 -2
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/glyph-cycle.js +2 -2
- package/dist/animations/{types-CSmiKRVa.d.cts → types-BsZtXPKK.d.cts} +43 -3
- package/dist/animations/{types-CSmiKRVa.d.ts → types-BsZtXPKK.d.ts} +43 -3
- package/dist/animations/wipe.cjs +2 -2
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-5EIIHQLQ.js +1 -0
- package/dist/codegen.cjs +12 -12
- package/dist/codegen.js +14 -14
- package/dist/index.cjs +91 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +877 -172
- package/dist/index.d.ts +877 -172
- package/dist/index.global.js +81 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +91 -68
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +3 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +24 -24
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.js +1 -1
- package/dist/runtype-tts-entry-UJAEF7NZ.js +1 -0
- package/dist/runtype-tts.js +1 -1
- package/dist/session-reconnect-JKIJBHS5.js +1 -0
- package/dist/smart-dom-reader.cjs +17 -17
- package/dist/smart-dom-reader.d.cts +753 -15
- package/dist/smart-dom-reader.d.ts +753 -15
- package/dist/smart-dom-reader.js +17 -17
- package/dist/testing.cjs +3 -3
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +81 -58
- package/dist/theme-editor-preview.d.cts +761 -15
- package/dist/theme-editor-preview.d.ts +761 -15
- package/dist/theme-editor-preview.js +81 -58
- package/dist/theme-editor.cjs +6 -6
- package/dist/theme-editor.d.cts +753 -15
- package/dist/theme-editor.d.ts +753 -15
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +74 -0
- package/dist/theme-reference.d.ts +74 -0
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +2 -2
- package/dist/voice-worklet-player.js +2 -2
- package/dist/webmcp-polyfill.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +2 -3
- package/src/artifacts-session.test.ts +178 -0
- package/src/client.test.ts +186 -1
- package/src/client.ts +92 -9
- package/src/components/artifact-card.test.ts +333 -0
- package/src/components/artifact-card.ts +75 -28
- package/src/components/artifact-inline.test.ts +1328 -0
- package/src/components/artifact-inline.ts +920 -0
- package/src/components/artifact-pane.test.ts +1042 -0
- package/src/components/artifact-pane.ts +440 -131
- package/src/components/artifact-preview.test.ts +1155 -0
- package/src/components/artifact-preview.ts +994 -0
- package/src/components/pill-composer-builder.test.ts +6 -2
- package/src/components/pill-composer-builder.ts +6 -6
- package/src/components/reasoning-bubble.ts +1 -13
- package/src/components/registry.ts +38 -3
- package/src/components/tool-bubble.ts +1 -13
- package/src/defaults.ts +1 -0
- package/src/generated/runtype-openapi-contract.ts +55 -3
- package/src/index-core.ts +20 -1
- package/src/index.ts +8 -0
- package/src/markdown-parsers-loader.test.ts +158 -0
- package/src/markdown-parsers-loader.ts +74 -9
- package/src/runtime/host-layout.test.ts +163 -0
- package/src/runtime/host-layout.ts +110 -7
- package/src/runtime/init.ts +18 -61
- package/src/session.ts +76 -22
- package/src/styles/widget.css +773 -26
- package/src/theme-editor/preview.ts +2 -0
- package/src/theme-editor/sections.test.ts +26 -1
- package/src/theme-editor/sections.ts +10 -2
- package/src/theme-reference.ts +2 -2
- package/src/tool-call-display-defaults.test.ts +1 -0
- package/src/types/theme.ts +77 -0
- package/src/types.ts +516 -17
- package/src/ui.artifact-pane-gating.test.ts +636 -0
- package/src/ui.component-directive.test.ts +104 -0
- package/src/ui.composer-bar.test.ts +60 -2
- package/src/ui.detached-panel.test.ts +1049 -0
- package/src/ui.tool-display.test.ts +51 -0
- package/src/ui.ts +698 -109
- package/src/utils/artifact-custom-actions.ts +128 -0
- package/src/utils/artifact-display.test.ts +42 -0
- package/src/utils/artifact-display.ts +84 -0
- package/src/utils/artifact-file.test.ts +116 -0
- package/src/utils/artifact-file.ts +117 -0
- package/src/utils/artifact-gate.test.ts +112 -5
- package/src/utils/artifact-gate.ts +39 -14
- package/src/utils/artifact-loading-status.ts +55 -0
- package/src/utils/artifact-status-label.ts +190 -0
- package/src/utils/buttons.ts +7 -1
- package/src/utils/code-highlight.test.ts +186 -0
- package/src/utils/code-highlight.ts +400 -0
- package/src/utils/icons.ts +2 -0
- package/src/utils/roving-tablist.test.ts +152 -0
- package/src/utils/roving-tablist.ts +111 -0
- package/src/utils/spinner.ts +45 -0
- package/src/utils/theme.test.ts +48 -0
- package/src/utils/theme.ts +7 -0
- package/src/utils/tokens.ts +91 -0
- package/src/utils/tool-loading-animation.test.ts +32 -0
- package/src/utils/tool-loading-animation.ts +24 -0
- package/dist/chunk-DFBSCFYN.js +0 -1
- package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
- package/dist/session-reconnect-U77QFUR7.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var n in t)m(e,n,{get:t[n],enumerable:!0})},W=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of L(t))!P.call(e,a)&&a!==n&&m(e,a,{get:()=>t[a],enumerable:!(r=v(t,a))||r.enumerable});return e};var R=e=>W(m({},"__esModule",{value:!0}),e);var X={};H(X,{default:()=>q,glyphCycle:()=>p});module.exports=R(X);var N=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],f=new Map;for(let e of N)f.set(e.name,e);var h=e=>{f.set(e.name,e)};var k=`
|
|
2
2
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
3
3
|
animation: persona-stream-glyph-cycle-fade
|
|
4
4
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -16,4 +16,4 @@
|
|
|
16
16
|
opacity: 1 !important;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
`.trim(),
|
|
19
|
+
`.trim(),s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",D=10,_=120,u=120,I=.4,F=50,B=e=>{if(!e)return u;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):u},w=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=B(t);return _*n/u},d=e=>{let t=s[Math.floor(Math.random()*s.length)];return e&&t===e&&(t=s[(s.indexOf(t)+1)%s.length]),t},O=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),r=!1;for(let a of Array.from(n)){if(a===e){r=!0;continue}r&&Math.random()<I&&(a.textContent=d())}},y=new WeakMap,A=25,S=.5,G=6,T=.25,b=new WeakMap,C=new WeakMap,U=(e,t)=>{if(!e)return A*S;let n=b.get(e);b.set(e,t);let r=C.get(e)??A;if(n!==void 0){let a=t-n;a>1&&(r=r*(1-T)+a*T,C.set(e,r))}return Math.max(G,r*S)},o=new Map,$=e=>e.closest("[data-message-id]")?.dataset.messageId??null,j=e=>{e&&o.set(e,(o.get(e)??0)+1)},K=e=>{if(!e)return;let t=o.get(e)??0;t<=1?o.delete(e):o.set(e,t-1)},E=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=d();let n=$(e);n&&(e.dataset.glyphCycleMessageId=n),j(n);let r=e.closest(".persona-stream-glyph-cycle"),a=Date.now(),i=U(r,a),l=w(e),x=D*l,c=a+x;if(r){let g=y.get(r);g!==void 0&&(c=Math.max(c,g)),y.set(r,c+i)}V(e,t,c)},V=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let r=w(e),a=e.textContent??void 0,i=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,K(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let l=d(a);e.textContent=l,a=l,O(e),setTimeout(i,r)};setTimeout(i,r)},M=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))E(n)},Y=e=>e.nodeType===1,p={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:k,bufferContent(e){if(e.length<F)return"";let t=0,n=-1,r=0;for(;r<e.length;){if(e[r]==="*"&&e[r+1]==="*"){t+=1,r+=2;continue}/\s/.test(e[r])&&t%2===0&&(n=r),r+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(o.get(e.id)??0)>0},onAttach(e){M(e);let t=new MutationObserver(n=>{for(let r of n)for(let a of Array.from(r.addedNodes))Y(a)&&(a.classList.contains("persona-stream-char")&&a.closest(".persona-stream-glyph-cycle")?E(a):M(a))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};h(p);var q=p;0&&(module.exports={glyphCycle});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],p=new Map;for(let e of x)p.set(e.name,e);var g=e=>{p.set(e.name,e)};var v=`
|
|
2
2
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
3
3
|
animation: persona-stream-glyph-cycle-fade
|
|
4
4
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -16,4 +16,4 @@ var v=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char"
|
|
|
16
16
|
opacity: 1 !important;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
`.trim(),
|
|
19
|
+
`.trim(),s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",L=10,P=120,m=120,H=.4,W=50,R=e=>{if(!e)return m;let r=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):m},C=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=R(t);return P*r/m},u=e=>{let t=s[Math.floor(Math.random()*s.length)];return e&&t===e&&(t=s[(s.indexOf(t)+1)%s.length]),t},N=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let a of Array.from(r)){if(a===e){n=!0;continue}n&&Math.random()<H&&(a.textContent=u())}},f=new WeakMap,h=25,y=.5,k=6,A=.25,S=new WeakMap,T=new WeakMap,D=(e,t)=>{if(!e)return h*y;let r=S.get(e);S.set(e,t);let n=T.get(e)??h;if(r!==void 0){let a=t-r;a>1&&(n=n*(1-A)+a*A,T.set(e,n))}return Math.max(k,n*y)},o=new Map,_=e=>e.closest("[data-message-id]")?.dataset.messageId??null,I=e=>{e&&o.set(e,(o.get(e)??0)+1)},F=e=>{if(!e)return;let t=o.get(e)??0;t<=1?o.delete(e):o.set(e,t-1)},M=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=u();let r=_(e);r&&(e.dataset.glyphCycleMessageId=r),I(r);let n=e.closest(".persona-stream-glyph-cycle"),a=Date.now(),i=D(n,a),l=C(e),E=L*l,c=a+E;if(n){let d=f.get(n);d!==void 0&&(c=Math.max(c,d)),f.set(n,c+i)}B(e,t,c)},B=(e,t,r)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let n=C(e),a=e.textContent??void 0,i=()=>{if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,F(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let l=u(a);e.textContent=l,a=l,N(e),setTimeout(i,n)};setTimeout(i,n)},b=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let r of Array.from(t))M(r)},O=e=>e.nodeType===1,w={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:v,bufferContent(e){if(e.length<W)return"";let t=0,r=-1,n=0;for(;n<e.length;){if(e[n]==="*"&&e[n+1]==="*"){t+=1,n+=2;continue}/\s/.test(e[n])&&t%2===0&&(r=n),n+=1}return r<0?"":e.slice(0,r)},isAnimating(e){return(o.get(e.id)??0)>0},onAttach(e){b(e);let t=new MutationObserver(r=>{for(let n of r)for(let a of Array.from(n.addedNodes))O(a)&&(a.classList.contains("persona-stream-char")&&a.closest(".persona-stream-glyph-cycle")?M(a):b(a))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};g(w);var $=w;export{$ as default,w as glyphCycle};
|
|
@@ -13,6 +13,7 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
13
13
|
totalSteps?: number;
|
|
14
14
|
type: "execution_start";
|
|
15
15
|
}) | ({
|
|
16
|
+
claudeManagedAgentId?: string;
|
|
16
17
|
completedAt?: string;
|
|
17
18
|
durationMs?: number;
|
|
18
19
|
executionId: string;
|
|
@@ -57,6 +58,15 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
57
58
|
completedAt?: string;
|
|
58
59
|
content?: string;
|
|
59
60
|
cost?: number;
|
|
61
|
+
estimatedContextBreakdown?: {
|
|
62
|
+
categories: Record<string, {
|
|
63
|
+
chars: number;
|
|
64
|
+
estimatedTokens: number;
|
|
65
|
+
}>;
|
|
66
|
+
contextWindowSize?: number;
|
|
67
|
+
estimatedTotalTokens: number;
|
|
68
|
+
estimatedUtilizationPercent?: number;
|
|
69
|
+
};
|
|
60
70
|
executionId: string;
|
|
61
71
|
fallback?: {
|
|
62
72
|
attempts: Array<{
|
|
@@ -94,6 +104,7 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
94
104
|
type: "step_start";
|
|
95
105
|
} | ({
|
|
96
106
|
completedAt?: string;
|
|
107
|
+
cost?: number;
|
|
97
108
|
durationMs?: number;
|
|
98
109
|
error?: string;
|
|
99
110
|
executionId: string;
|
|
@@ -199,6 +210,11 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
199
210
|
artifactType: "markdown" | "component";
|
|
200
211
|
component?: string;
|
|
201
212
|
executionId?: string;
|
|
213
|
+
file?: {
|
|
214
|
+
language?: string;
|
|
215
|
+
mimeType: string;
|
|
216
|
+
path: string;
|
|
217
|
+
};
|
|
202
218
|
id: string;
|
|
203
219
|
seq?: number;
|
|
204
220
|
title?: string;
|
|
@@ -307,6 +323,14 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
307
323
|
awaitReason?: string;
|
|
308
324
|
awaitedAt?: string;
|
|
309
325
|
crawlId?: string;
|
|
326
|
+
elicitation?: {
|
|
327
|
+
message: string;
|
|
328
|
+
mode: "form" | "url";
|
|
329
|
+
pauseCount?: number;
|
|
330
|
+
requestedSchema?: Record<string, unknown>;
|
|
331
|
+
serverName?: string;
|
|
332
|
+
url?: string;
|
|
333
|
+
};
|
|
310
334
|
executionId: string;
|
|
311
335
|
origin?: "webmcp" | "sdk";
|
|
312
336
|
pageOrigin?: string;
|
|
@@ -406,6 +430,14 @@ type RuntypeFlowSSEEvent = {
|
|
|
406
430
|
awaitReason?: string;
|
|
407
431
|
awaitedAt: string;
|
|
408
432
|
crawlId?: string;
|
|
433
|
+
elicitation?: {
|
|
434
|
+
message: string;
|
|
435
|
+
mode: "form" | "url";
|
|
436
|
+
pauseCount?: number;
|
|
437
|
+
requestedSchema?: Record<string, unknown>;
|
|
438
|
+
serverName?: string;
|
|
439
|
+
url?: string;
|
|
440
|
+
};
|
|
409
441
|
executionId?: string;
|
|
410
442
|
flowId: string;
|
|
411
443
|
origin?: "webmcp" | "sdk";
|
|
@@ -456,7 +488,7 @@ type RuntypeFlowSSEEvent = {
|
|
|
456
488
|
completedAt?: string;
|
|
457
489
|
duration?: number;
|
|
458
490
|
durationMs?: number;
|
|
459
|
-
error?: string;
|
|
491
|
+
error?: string | null;
|
|
460
492
|
executionId?: string;
|
|
461
493
|
executionTime?: number;
|
|
462
494
|
id?: string;
|
|
@@ -500,13 +532,21 @@ type RuntypeFlowSSEEvent = {
|
|
|
500
532
|
totalSteps: number;
|
|
501
533
|
type: "step_skip";
|
|
502
534
|
when: string;
|
|
503
|
-
} | {
|
|
535
|
+
} | ({
|
|
536
|
+
elicitation?: {
|
|
537
|
+
message: string;
|
|
538
|
+
mode: "form" | "url";
|
|
539
|
+
pauseCount?: number;
|
|
540
|
+
requestedSchema?: Record<string, unknown>;
|
|
541
|
+
serverName?: string;
|
|
542
|
+
url?: string;
|
|
543
|
+
};
|
|
504
544
|
executionId?: string;
|
|
505
545
|
reason?: string;
|
|
506
546
|
seq?: number;
|
|
507
547
|
type: "step_await";
|
|
508
548
|
[key: string]: unknown;
|
|
509
|
-
} | ({
|
|
549
|
+
}) | ({
|
|
510
550
|
agentContext?: {
|
|
511
551
|
executionId: string;
|
|
512
552
|
iteration: number;
|
|
@@ -13,6 +13,7 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
13
13
|
totalSteps?: number;
|
|
14
14
|
type: "execution_start";
|
|
15
15
|
}) | ({
|
|
16
|
+
claudeManagedAgentId?: string;
|
|
16
17
|
completedAt?: string;
|
|
17
18
|
durationMs?: number;
|
|
18
19
|
executionId: string;
|
|
@@ -57,6 +58,15 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
57
58
|
completedAt?: string;
|
|
58
59
|
content?: string;
|
|
59
60
|
cost?: number;
|
|
61
|
+
estimatedContextBreakdown?: {
|
|
62
|
+
categories: Record<string, {
|
|
63
|
+
chars: number;
|
|
64
|
+
estimatedTokens: number;
|
|
65
|
+
}>;
|
|
66
|
+
contextWindowSize?: number;
|
|
67
|
+
estimatedTotalTokens: number;
|
|
68
|
+
estimatedUtilizationPercent?: number;
|
|
69
|
+
};
|
|
60
70
|
executionId: string;
|
|
61
71
|
fallback?: {
|
|
62
72
|
attempts: Array<{
|
|
@@ -94,6 +104,7 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
94
104
|
type: "step_start";
|
|
95
105
|
} | ({
|
|
96
106
|
completedAt?: string;
|
|
107
|
+
cost?: number;
|
|
97
108
|
durationMs?: number;
|
|
98
109
|
error?: string;
|
|
99
110
|
executionId: string;
|
|
@@ -199,6 +210,11 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
199
210
|
artifactType: "markdown" | "component";
|
|
200
211
|
component?: string;
|
|
201
212
|
executionId?: string;
|
|
213
|
+
file?: {
|
|
214
|
+
language?: string;
|
|
215
|
+
mimeType: string;
|
|
216
|
+
path: string;
|
|
217
|
+
};
|
|
202
218
|
id: string;
|
|
203
219
|
seq?: number;
|
|
204
220
|
title?: string;
|
|
@@ -307,6 +323,14 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
307
323
|
awaitReason?: string;
|
|
308
324
|
awaitedAt?: string;
|
|
309
325
|
crawlId?: string;
|
|
326
|
+
elicitation?: {
|
|
327
|
+
message: string;
|
|
328
|
+
mode: "form" | "url";
|
|
329
|
+
pauseCount?: number;
|
|
330
|
+
requestedSchema?: Record<string, unknown>;
|
|
331
|
+
serverName?: string;
|
|
332
|
+
url?: string;
|
|
333
|
+
};
|
|
310
334
|
executionId: string;
|
|
311
335
|
origin?: "webmcp" | "sdk";
|
|
312
336
|
pageOrigin?: string;
|
|
@@ -406,6 +430,14 @@ type RuntypeFlowSSEEvent = {
|
|
|
406
430
|
awaitReason?: string;
|
|
407
431
|
awaitedAt: string;
|
|
408
432
|
crawlId?: string;
|
|
433
|
+
elicitation?: {
|
|
434
|
+
message: string;
|
|
435
|
+
mode: "form" | "url";
|
|
436
|
+
pauseCount?: number;
|
|
437
|
+
requestedSchema?: Record<string, unknown>;
|
|
438
|
+
serverName?: string;
|
|
439
|
+
url?: string;
|
|
440
|
+
};
|
|
409
441
|
executionId?: string;
|
|
410
442
|
flowId: string;
|
|
411
443
|
origin?: "webmcp" | "sdk";
|
|
@@ -456,7 +488,7 @@ type RuntypeFlowSSEEvent = {
|
|
|
456
488
|
completedAt?: string;
|
|
457
489
|
duration?: number;
|
|
458
490
|
durationMs?: number;
|
|
459
|
-
error?: string;
|
|
491
|
+
error?: string | null;
|
|
460
492
|
executionId?: string;
|
|
461
493
|
executionTime?: number;
|
|
462
494
|
id?: string;
|
|
@@ -500,13 +532,21 @@ type RuntypeFlowSSEEvent = {
|
|
|
500
532
|
totalSteps: number;
|
|
501
533
|
type: "step_skip";
|
|
502
534
|
when: string;
|
|
503
|
-
} | {
|
|
535
|
+
} | ({
|
|
536
|
+
elicitation?: {
|
|
537
|
+
message: string;
|
|
538
|
+
mode: "form" | "url";
|
|
539
|
+
pauseCount?: number;
|
|
540
|
+
requestedSchema?: Record<string, unknown>;
|
|
541
|
+
serverName?: string;
|
|
542
|
+
url?: string;
|
|
543
|
+
};
|
|
504
544
|
executionId?: string;
|
|
505
545
|
reason?: string;
|
|
506
546
|
seq?: number;
|
|
507
547
|
type: "step_await";
|
|
508
548
|
[key: string]: unknown;
|
|
509
|
-
} | ({
|
|
549
|
+
}) | ({
|
|
510
550
|
agentContext?: {
|
|
511
551
|
executionId: string;
|
|
512
552
|
iteration: number;
|
package/dist/animations/wipe.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var r=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var r=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var d=(e,t)=>{for(var a in t)r(e,a,{get:t[a],enumerable:!0})},u=(e,t,a,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of p(t))!c.call(e,n)&&n!==a&&r(e,n,{get:()=>t[n],enumerable:!(i=l(t,n))||i.enumerable});return e};var g=e=>u(r({},"__esModule",{value:!0}),e);var w={};d(w,{default:()=>S,wipe:()=>o});module.exports=g(w);var A=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],s=new Map;for(let e of A)s.set(e.name,e);var m=e=>{s.set(e.name,e)};var f=`
|
|
2
2
|
@keyframes persona-stream-wipe {
|
|
3
3
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
4
4
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -34,4 +34,4 @@
|
|
|
34
34
|
mask-image: none !important;
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
-
`.trim(),o={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:
|
|
37
|
+
`.trim(),o={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:f};m(o);var S=o;0&&(module.exports={wipe});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=class{constructor(e=24e3,t={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let i=Math.max(0,t.prebufferMs??0);this.waterlineSamples=Math.round(e*i/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window<"u"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let i=t.AudioContext||t.webkitAudioContext;this.ctx=new i({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let s=new Uint8Array(this.remainder.length+e.length);s.set(this.remainder),s.set(e,this.remainder.length),t=s,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let i=this.pcmToFloat32(t);i.length!==0&&(this.buffering?(this.pendingBuffers.push(i),this.pendingSamples+=i.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(i))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),i=t.createBuffer(1,e.length,this.sampleRate);i.getChannelData(0).set(e);let s=t.createBufferSource();s.buffer=i,s.connect(t.destination);let n=t.currentTime;if(this.nextStartTime===0?this.nextStartTime=n:this.nextStartTime<n&&(this.nextStartTime=n,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=i.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let r=this.startedCallbacks.slice();this.startedCallbacks=[];for(let h of r)h()}s.onended=()=>{let r=this.activeSources.indexOf(s);r!==-1&&this.activeSources.splice(r,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),i=new Float32Array(t),s=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let n=0;n<t;n++){let r=s.getInt16(n*2,!0);i[n]=r/32768}return i}};export{a};
|
package/dist/codegen.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var $=Object.defineProperty;var
|
|
1
|
+
"use strict";var $=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var T=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},M=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of I(r))!_.call(e,o)&&o!==n&&$(e,o,{get:()=>r[o],enumerable:!(s=v(r,o))||s.enumerable});return e};var R=e=>M($({},"__esModule",{value:!0}),e);var U={};T(U,{generateCodeSnippet:()=>k});module.exports=R(U);var S="4.8.0";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function H(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
|
|
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
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
12
12
|
} catch (e) { return null; }
|
|
13
13
|
return null;
|
|
14
|
-
}`,
|
|
14
|
+
}`,A=`function(ctx) {
|
|
15
15
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
16
16
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
17
17
|
var cleanJson = jsonSource
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
25
25
|
} catch (e) { return null; }
|
|
26
26
|
return null;
|
|
27
|
-
}`,
|
|
27
|
+
}`,j=`(action: any, context: any) => {
|
|
28
28
|
if (action.type !== 'nav_then_click') return;
|
|
29
29
|
const payload = action.payload || action.raw || {};
|
|
30
30
|
const url = payload?.page;
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
42
42
|
window.location.href = targetUrl;
|
|
43
43
|
return { handled: true, displayText: text };
|
|
44
|
-
}`,
|
|
44
|
+
}`,O=`function(action, context) {
|
|
45
45
|
if (action.type !== 'nav_then_click') return;
|
|
46
46
|
var payload = action.payload || action.raw || {};
|
|
47
47
|
var url = payload.page;
|
|
@@ -58,23 +58,23 @@
|
|
|
58
58
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
59
59
|
window.location.href = targetUrl;
|
|
60
60
|
return { handled: true, displayText: text };
|
|
61
|
-
}`,
|
|
61
|
+
}`,N=`(parsed: any) => {
|
|
62
62
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
63
63
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
64
64
|
if (parsed.action === 'message') return parsed.text || '';
|
|
65
65
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
66
66
|
return parsed.text || null;
|
|
67
|
-
}`,
|
|
67
|
+
}`,D=`function(parsed) {
|
|
68
68
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
69
69
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
70
70
|
if (parsed.action === 'message') return parsed.text || '';
|
|
71
71
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
72
72
|
return parsed.text || null;
|
|
73
|
-
}`;function
|
|
74
|
-
`)}function
|
|
75
|
-
`)}function K(e,r){let n=r==null?void 0:r.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(s,"theme",e.theme," "),e.launcher&&l(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n!=null&&n.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${D}),`)),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${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(" ],")),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${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(" ],")),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
76
|
-
`)}function
|
|
77
|
-
`)}function
|
|
73
|
+
}`;function F(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function g(e){return e.parserType??F(e.streamParser)??"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,o])=>{typeof o=="string"&&n.push(`${r} ${s}: "${o}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),t=n?.onFeedback||n?.onCopy;return(o||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?s.push(`${r} ${i}: "${a}",`):typeof a=="boolean"&&s.push(`${r} ${i}: ${a},`))}),n?.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n?.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(s||o)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),o&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||o)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),o&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([a,p])=>{typeof p=="string"?n.push(`${r} ${a}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${a}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?n.push(`${r} ${p}: "${l}",`):typeof l=="boolean"&&n.push(`${r} ${p}: ${l},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function w(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function E(e,r,n){Object.entries(r).forEach(([s,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${s}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${s}: {`),E(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(o)},`)}})}function d(e,r,n,s){n&&(e.push(`${s}${r}: {`),E(e,n,`${s} `),e.push(`${s}},`))}function h(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function k(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let o=n?{...n,hooks:H(n.hooks)}:void 0;return r==="esm"?J(s,o):r==="script-installer"?K(s,o):r==="script-advanced"?Y(s,o):r==="react-component"?q(s,o):r==="react-advanced"?L(s,o):G(s,o)}function J(e,r){let n=r?.hooks,s=g(e),o=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
74
|
+
`)}function q(e,r){let n=r?.hooks,s=g(e),o=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
|
|
75
|
+
`)}function L(e,r){let n=r?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${h(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n?.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${N}),`)),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
76
|
+
`)}function P(e){let r=g(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([t,i])=>{typeof i=="string"&&(o[t]=i)}),Object.keys(o).length>0&&(s.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([t,i])=>{t!=="onFeedback"&&t!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[t]=i)}),Object.keys(o).length>0&&(s.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(s.markdown=o)}if(e.layout){let o={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([i,a])=>{i!=="render"&&(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(o.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([i,a])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof a=="object"&&a!==null)t.avatar=a;else if(i==="timestamp"&&typeof a=="object"&&a!==null){let p={};Object.entries(a).forEach(([l,b])=>{l!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(p[l]=b)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(o.messages=t)}Object.keys(o).length>0&&(s.layout=o)}return s}function K(e,r){let n=P(e),o=!!(r?.windowKey||r?.target)?{config:n,...r?.windowKey?{windowKey:r.windowKey}:{},...r?.target?{target:r.target}:{}}:n,t=JSON.stringify(o,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function G(e,r){let n=r?.hooks,s=g(e),o=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${h(r)}',`,...r?.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n?.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
|
|
77
|
+
`)}function Y(e,r){let n=r?.hooks,s=P(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
|
|
78
78
|
`).map((i,a)=>a===0?i:" "+i).join(`
|
|
79
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n
|
|
79
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n?.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${D});`),t.push(" };")),t.push(""),n?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ];")),t.push(""),n?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${n.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ];")),t.push(""),n?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${n.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),n?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(n?.onFeedback||n?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${h(r)}',`," useShadowDom: false,",...r?.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
|
|
80
80
|
`)}0&&(module.exports={generateCodeSnippet});
|