React Native Push

Learn how to handle push notifications in React Native.

Push Notifications

CleverTap React Native SDK allows you to send push notifications to your React Native applications from the CleverTap dashboard. Using push notifications, you can push information to your users even when they are inactive.

Android

To use CleverTap's default Push Notifications service, add the following entries to your AndroidManifest.xml:

<application>
         ....
         ....
        <service android:name="com.clevertap.android.sdk.pushnotification.fcm.FcmMessageListenerService"  android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

 </application>
📘

📘 Notification Trampolines in Android 12 and Above

Android has changed the handling of push notifications for version 12 and above to improve performance. An app can no longer start an activity within a service or broadcast receiver. For more information, refer to Android 12 Push Changes.

Create Notification Channel

📘

Note

You must register at least one notification channel for the Default Push notification Service to work.

Add the following to your Javascript file to create a notification channel:

CleverTap.createNotificationChannel("CtRNS", "Clever Tap React Native Testing", "CT React Native Testing", 5, true) // The notification channel importance can have any value from 1 to 5. A higher value means a more interruptive notification.

The notification channel importance can have any value from 1 to 5. A higher value means a more interruptive notification. For more information, refer to Notification Channel Importance Levels.

Delete Notification Channel

Add the following to your Javascript file to delete a notification channel:

CleverTap.deleteNotificationChannel("RNTesting");

Create a group notification channel

Add the following to your Javascript file to create a group notification channel:

CleverTap.createNotificationChannelGroup("groupID", "groupName");

Handle Push Notification Callback

The CleverTap SDK sends the callback when a Push Notification is clicked along with the entire payload. For this, you must register the CleverTapPushNotificationClicked callback using the following code:

CleverTap.addListener(CleverTap.CleverTapPushNotificationClicked, (e)=>{/*consume the event*/})

Additional handling to get the notification click callback in the following scenarios:

  • Notification Trampoline Handling in Android 12 and Above
  • Notification Trampoline Handling when the App is Terminated or Killed

Handle Notification Trampolines in Android 12 and Above to get the Notification Click Callback

Due to notification trampoline restrictions, Android 12 and above do not directly support the CleverTap.CleverTapPushNotificationClicked callback. Hence, apps need to add manual handling for Android 12 and above to inform the CleverTap SDK about the notification click and get the CleverTap.CleverTapPushNotificationClicked callback.

Add the following code in the onNewIntent() method of the Launcher ReactActivity:

class MainActivity : ReactActivity() {

override fun onNewIntent(intent: Intent?) {
   super.onNewIntent(intent)

   // On Android 12 and onwards, raise notification clicked event and get the click callback
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
       cleverTapDefaultInstance?.pushNotificationClickedEvent(intent!!.extras)
        }
    }
}

For detailed information, refer to Android 12 Push Changes.

Handle Notification Click Callback when the App is Terminated or Killed

None of the previously mentioned handlings support the CleverTap.CleverTapPushNotificationClicked callback in the killed state. To achieve this, your Android platform-specific Application class should extend the CleverTapApplication class instead of the Application class.

import com.clevertap.react.CleverTapApplication;

public class MainApplication extends CleverTapApplication implements ReactApplication {
     @Override
  public void onCreate() {
    CleverTapAPI.setDebugLevel(CleverTapAPI.LogLevel.VERBOSE);
    // ActivityLifecycleCallback.register(this); Required only for v2.2.1 or below
    super.onCreate();
    
    //rest code
  }
}

Enable RenderMax with Android

Starting from CleverTap React Native SDK version 1.2.0, the RenderMax Push SDK functionality is now supported directly within the CleverTap Android SDK. We strongly recommend updating to CleverTap React Native SDK to version 1.2.0 and CleverTap Android SDK to version 5.2.0 to take advantage of this integration and to ensure stability.

❗️

Please remove the integrated RenderMax SDK before you upgrade to CleverTap React Native SDK v1.2.0.

❗️

Custom Rendering with RenderMax Push SDK

If the app is custom rendering the push notification and not passing the payload to CleverTap SDK, add the following code before you render the notification:

CleverTapAPI.processPushNotification(getApplicationContext(),extras);

Set Up a Custom Push Notification Icon

By default, CleverTap SDK uses the app's icon for both the notification icon and the notification bar icon. However, You can provide a custom app icon by adding the icon in your app's android resources and registering it with CleverTap in your AndroidManifest.xml
For more details, refer to Android Push document.

Delete a Group Notification Channel

Add the following to your Javascript file to delete a group notification channel:

CleverTap.deleteNotificationChannelGroup("groupId");

Handle Custom Push Notification Service

If you have your custom implementation for managing Android push notifications, you can inform CleverTap about the user’s FCM registration ID. Refer to Advanced Features Section for more information

Deeplink or External URL (Android)

To use external URLs, whitelist the IPs or prefix the URL with http or https. For more information, refer to Deeplinking.

iOS

Perform the following steps to send push notifications on the iOS platform from your React Native application:

  1. Refer to iOS Push Notifications setup and follow steps 1 through 4 listed in the document.

  2. In your Xcode project settings, perform the following steps to enable the push notification capability:
    a. Select Targets and then select the Signing & Capabilities tab.
    b. Click + Capability and enter push in the filter field and select Push Notifications.

1168

Enable Push Notification Capability

  1. Call the following from your Javascript file:
CleverTap.registerForPush();
  1. Create a Push Notification campaign on CleverTap or follow the steps listed under CleverTap iOS Push Notifications.

iOS Foreground Notifications

To receive push notifications when your app is in the foreground, check your AppDelegate class conforms to theUNUserNotificationCenterDelegate and then add userNotificationCenter:willPresentNotification:withCompletionHandler: delegate method in your AppDelegate class.

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
	completionHandler([.badge, .sound, .alert])
}

Handle React Native Push Notification Callback on iOS

The CleverTap SDK sends a callback when a Push Notification is clicked along with the entire payload. For this, you must register the CleverTapPushNotificationClicked callback in your Javascript file, as shown below:

CleverTap.addListener(CleverTap.CleverTapPushNotificationClicked, (e)=>{/*consume the event*/})

Deeplink or External URL (iOS)

A deeplink helps you open a particular activity in your app after a click on the notification. If left empty, the notification on click opens the launcher activity of the app. Deep links allow you to land users on a particular part of your app. Your app's OpenURL method is called with the deep link specified here. To use external URLs, you must whitelist the IPs or add http/https before the URL so that the SDK can appropriately handle them. For more information, refer to Deeplinking.

With CleverTap React Native SDK, you can implement custom handling for URLs of in-app notification CTAs, push notifications, and app Inbox messages.

Check that your class conforms to the CleverTapURLDelegate protocol by first calling setURLDelegate. Use the following protocol method shouldHandleCleverTap(_ : forChannel:) to handle URLs received from channels such as in-app notification CTAs, push notifications, and app Inbox messages:

#import <CleverTapSDK/CleverTapURLDelegate.h>

// Set the URL Delegate
[[CleverTap sharedInstance]setUrlDelegate:self];

// CleverTapURLDelegate method 
- (BOOL)shouldHandleCleverTapURL:(NSURL *)url forChannel:(CleverTapChannel)channel {
    NSLog(@"Handling URL: \(%@) for channel: \(%d)", url, channel);
    return YES;
}
// Set the URL Delegate
CleverTap.sharedInstance()?.setUrlDelegate(self)


 // CleverTapURLDelegate method
public func shouldHandleCleverTap(_ url: URL?, for channel: CleverTapChannel) -> Bool {  
    print("Handling URL: \(url!) for channel: \(channel)") 
    return true 
}

Enable Support for Deeplink Tracking Manually in the Application

Refer to iOS Deeplink Tracking for reference.

Push Impression in iOS

You can now raise and record push notifications delivered to your user's iOS devices. To raise Push Impressions for iOS, you must enable the Notification Service Extension on your native iOS side. For more information, refer to our iOS Push Impressions documentation.

Push Notifications Permission

Starting from Android 13 and iOS 10.0, applications must request notification permission from the user before sending Push Notifications. All newly-installed applications must seek user permission before they can send notifications.

Push Primer

A Push Primer explains the need for push notifications to your users and helps to improve your engagement rates. It is an InApp notification that you can show to your users before requesting notification permission.

Push Primer helps with the following:

  • Allows you to educate your users on why you are asking for this permission before invoking a system dialog to seek user permission.
  • Acts as a precursor to the hard system dialog and thus allows you to seek permission multiple times if previously denied without making your users search the device settings.

CleverTap React Native supports push primer for push notifications starting with the v0.9.5 release.

📘

iOS and Android Versions for Push Primer

  • The minimum supported version for the iOS platform is 10.0.
  • The minimum supported version for the Android platform is Android 13.

The following are the two ways to handle the new push notification changes:

Push Primer Using Half-Interstitial InApp Template

Using this template, you can send a customized push primer notification with an image, text, and button. You can also modify the notification's text, button, and background color.
Refer to the following images for Push Primer using Half-Interstitial InApp Template:

  • In Android
398

Push Primer Using Half-Interstitial InApp Template in Android

  • In iOS
948

Push Primer Using Half-Interstitial InApp Template in iOS

Add the following code to your Javascript file to create Push Primer using the Half-Interstitial InApp template:

let localInApp = {
  inAppType: 'half-interstitial',
  titleText: 'Get Notified',
  messageText: 'Please enable notifications on your device to use Push Notifications.',
  followDeviceOrientation: true,
  positiveBtnText: 'Allow',
  negativeBtnText: 'Cancel',
  
  // Optional parameters:
  backgroundColor: '#FFFFFF',
  btnBorderColor: '#0000FF',
  titleTextColor: '#0000FF',
  messageTextColor: '#000000',
  btnTextColor: '#FFFFFF',
  btnBackgroundColor: '#0000FF',
  btnBorderRadius: '2',

  // Setting this to true will open an in-app redirect to the mobile OS settings page
  fallbackToSettings: true,
  imageUrl: 'https://icons.iconarchive.com/icons/treetog/junior/64/camera-icon.png',
  altText: 'Alternate Image'
};

CleverTap.promptPushPrimer(localInApp);

Push Primer using Alert InApp Template

Using this template, you can create a basic push primer notification with a title, message, and two buttons.
Refer to the following images for Push Primer using the Alert InApp template:

  • In Android
398

Push Primer using Alert InApp Template in Android

  • In iOS
948

Push Primer using Alert InApp Template in iOS

Add the following code to your Javascript file to create a Push Primer using the Alert InApp template:

let localInApp = {
              inAppType: 'alert',
              titleText: 'Get Notified',
              messageText: 'Enable Notification permission',
              followDeviceOrientation: true,
              positiveBtnText: 'Allow',
              negativeBtnText: 'Cancel',
              fallbackToSettings: true, //Setting this parameter to true will open an in-App to redirect you to Mobile's OS settings page.
            };

CleverTap.promptPushPrimer(localInApp);

Method Description

The following table describes all the keys used to create In-App templates:

Key Name

Parameters

Description

Required

inAppType

"half-interstitial" or "alert"

  • Accepts only the following values: half-interstitial and alert type.
  • Used to display the local in-app notification.

Required

titleText

String

Sets the title of the local in-app notification.

Required

messageText

String

Sets the subtitle of the local in-app notification.

Required

followDeviceOrientation

true or false

  • If the key is set to true, then the local InApp notification is displayed in the same orientation (Landscape or Portrait) as that set on your device.
  • If the key is false, then the local InApp notification only displays in portrait mode.

Required

positiveBtnText

String

  • Sets the text of the button which performs the positive action (for example, Allow, OK,..etc).
  • This button continues the push primer flow.

Required

negativeBtnText

String

  • Sets the button's text, which performs the negative action (Example: Deny, Cancel,..etc.).
  • This button aborts the push primer flow.

Required

fallbackToSettings

true or false

  • If the value is set to true and permission is denied, then the user is redirected to the app’s notification settings.
  • If the value is set to false, the callback is sent stating that the permission is denied.

Optional

backgroundColor

Hex color as String

Sets the background color of the local in-app notification.

Optional

btnBorderColor

Hex color as String

Sets the border color of both positive and negative buttons.

Optional

titleTextColor

Hex color as String

Sets the title text color of the local in-app notification.

Optional

messageTextColor

Hex color as String

Sets the sub-title text color of the local in-app notification.

Optional

btnTextColor

Hex color as String

Sets the color of text for both positive/negative buttons.

Optional

btnBackgroundColor

Hex color as String

Sets the background color for both positive/negative buttons.

Optional

btnBorderRadius

String

  • Sets the radius for both positive/negative buttons.
  • If not set, the default radius is 2.

Optional

fallbackToSettings

true or false

  • If the value is set to true and permission is denied, then the user is redirected to the app’s notification settings.
  • If the value is set to false, the callback is sent stating that the permission is denied.

Optional

imageUrl

String (URL)

Sets the image to be shown in the local in-app notification. Must be a valid URL pointing to an image resource.

Optional

altText

String

Alternate text shown if the image cannot be loaded. Improves accessibility and provides fallback context.

Optional

Invoke Notification Permission Dialog without Push Primer

You can call the push permission dialogue directly without a Push Primer using the promptForPushPermission(boolean) method. It takes a boolean value as a parameter.

  • If the value is set to true and permission is denied, then the user is redirected to the app’s notification settings.
  • If the value is set to false, the callback is sent stating that the permission is denied.
CleverTap.promptForPushPermission(true);

Check the Push Notification Permission Status

The isPushPermissionGranted method can be used to check the status of the push notification permission for your application. The method returns the status of the push permission in the callback handler.

CleverTap.isPushPermissionGranted((err, res) => {
  console.log('isPushPermissionGranted', res, err);
});

Available Callbacks for Push Primer

Based on whether the notification permission is granted or denied, the CleverTap React Native SDK provides a callback with the permission status.

To receive the callback, you must register the CleverTapPushPermissionResponseReceived instance:

CleverTap.addListener(CleverTap.CleverTapPushPermissionResponseReceived, (e)=>{/*consume the event*/})

To unregister the callback, use the following method:

CleverTap.removeListener(CleverTap.CleverTapPushPermissionResponseReceived);
CleverTap Ask AI Widget (CSP-Safe) ");const I1=O?O.createHTML(p):p;if(pe===h1)try{V=new g().parseFromString(I1,a2)}catch{}if(!V||!V.documentElement){V=I.createDocument(pe,"template",null);try{V.documentElement.innerHTML=w5?U:I1}catch{}}const te=V.body||V.documentElement;return p&&J&&te.insertBefore(n.createTextNode(J),te.childNodes[0]||null),pe===h1?r1.call(V,V1?"html":"body")[0]:V1?V.documentElement:te},w8=function(p){return F.call(p.ownerDocument||p,p,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},c7=function(p){return p instanceof d&&(typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||!(p.attributes instanceof u)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function")},b8=function(p){return typeof a=="function"&&p instanceof a};function at(i1,p,V){u3(i1,J=>{J.call(e,p,V,b5)})}const _8=function(p){let V=null;if(at(a1.beforeSanitizeElements,p,null),c7(p))return Ye(p),!0;const J=K1(p.nodeName);if(at(a1.uponSanitizeElement,p,{tagName:J,allowedTags:N}),L1&&p.hasChildNodes()&&!b8(p.firstElementChild)&&se(/<[/\w!]/g,p.innerHTML)&&se(/<[/\w!]/g,p.textContent)||p.nodeType===i2.progressingInstruction||L1&&p.nodeType===i2.comment&&se(/<[/\w]/g,p.data))return Ye(p),!0;if(!N[J]||b1[J]){if(!b1[J]&&y8(J)&&(t1.tagNameCheck instanceof RegExp&&se(t1.tagNameCheck,J)||t1.tagNameCheck instanceof Function&&t1.tagNameCheck(J)))return!1;if(Ce&&!R[J]){const I1=P(p)||p.parentNode,te=$(p)||p.childNodes;if(te&&I1){const G1=te.length;for(let be=G1-1;be>=0;--be){const lt=A(te[be],!0);lt.__removalCount=(p.__removalCount||0)+1,I1.insertBefore(lt,Z(p))}}}return Ye(p),!0}return p instanceof l&&!W_(p)||(J==="noscript"||J==="noembed"||J==="noframes")&&se(/<\/no(script|embed|frames)/i,p.innerHTML)?(Ye(p),!0):(ue&&p.nodeType===i2.text&&(V=p.textContent,u3([m,h,E],I1=>{V=t2(V,I1," ")}),p.textContent!==V&&(e2(e.removed,{element:p.cloneNode()}),p.textContent=V)),at(a1.afterSanitizeElements,p,null),!1)},E8=function(p,V,J){if(de&&(V==="id"||V==="name")&&(J in n||J in G_))return!1;if(!(A1&&!D1[V]&&se(D,V))){if(!(O1&&se(z,V))){if(!X[V]||D1[V]){if(!(y8(p)&&(t1.tagNameCheck instanceof RegExp&&se(t1.tagNameCheck,p)||t1.tagNameCheck instanceof Function&&t1.tagNameCheck(p))&&(t1.attributeNameCheck instanceof RegExp&&se(t1.attributeNameCheck,V)||t1.attributeNameCheck instanceof Function&&t1.attributeNameCheck(V))||V==="is"&&t1.allowCustomizedBuiltInElements&&(t1.tagNameCheck instanceof RegExp&&se(t1.tagNameCheck,J)||t1.tagNameCheck instanceof Function&&t1.tagNameCheck(J))))return!1}else if(!W[V]){if(!se(B,t2(J,x,""))){if(!((V==="src"||V==="xlink:href"||V==="href")&&p!=="script"&&y_(J,"data:")===0&&T[p])){if(!(ze&&!se(b,t2(J,x,"")))){if(J)return!1}}}}}}return!0},y8=function(p){return p!=="annotation-xml"&&Y9(p,H)},x8=function(p){at(a1.beforeSanitizeAttributes,p,null);const{attributes:V}=p;if(!V||c7(p))return;const J={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:X,forceKeepAttr:void 0};let I1=V.length;for(;I1--;){const te=V[I1],{name:G1,namespaceURI:be,value:lt}=te,l2=K1(G1),u7=lt;let ne=G1==="value"?u7:x_(u7);if(J.attrName=l2,J.attrValue=ne,J.keepAttr=!0,J.forceKeepAttr=void 0,at(a1.uponSanitizeAttribute,p,J),ne=J.attrValue,M1&&(l2==="id"||l2==="name")&&(_5(G1,p),ne=E1+ne),L1&&se(/((--!?|])>)|<\/(style|title)/i,ne)){_5(G1,p);continue}if(J.forceKeepAttr)continue;if(!J.keepAttr){_5(G1,p);continue}if(!ce&&se(/\/>/i,ne)){_5(G1,p);continue}ue&&u3([m,h,E],S8=>{ne=t2(ne,S8," ")});const M8=K1(p.nodeName);if(!E8(M8,l2,ne)){_5(G1,p);continue}if(O&&typeof C=="object"&&typeof C.getAttributeType=="function"&&!be)switch(C.getAttributeType(M8,l2)){case"TrustedHTML":{ne=O.createHTML(ne);break}case"TrustedScriptURL":{ne=O.createScriptURL(ne);break}}if(ne!==u7)try{be?p.setAttributeNS(be,G1,ne):p.setAttribute(G1,ne),c7(p)?Ye(p):q9(e.removed)}catch{_5(G1,p)}}at(a1.afterSanitizeAttributes,p,null)},j_=function i1(p){let V=null;const J=w8(p);for(at(a1.beforeSanitizeShadowDOM,p,null);V=J.nextNode();)at(a1.uponSanitizeShadowNode,V,null),_8(V),x8(V),V.content instanceof o&&i1(V.content);at(a1.afterSanitizeShadowDOM,p,null)};return e.sanitize=function(i1){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},V=null,J=null,I1=null,te=null;if(w5=!i1,w5&&(i1="<\x21--\x3e"),typeof i1!="string"&&!b8(i1))if(typeof i1.toString=="function"){if(i1=i1.toString(),typeof i1!="string")throw n2("dirty is not a string, aborting")}else throw n2("toString is not a function");if(!e.isSupported)return i1;if(ee||l7(p),e.removed=[],typeof i1=="string"&&(L=!1),L){if(i1.nodeName){const lt=K1(i1.nodeName);if(!N[lt]||b1[lt])throw n2("root node is forbidden and cannot be sanitized in-place")}}else if(i1 instanceof a)V=L8("<\x21----\x3e"),J=V.ownerDocument.importNode(i1,!0),J.nodeType===i2.element&&J.nodeName==="BODY"||J.nodeName==="HTML"?V=J:V.appendChild(J);else{if(!Ae&&!ue&&!V1&&i1.indexOf("<")===-1)return O&&o1?O.createHTML(i1):i1;if(V=L8(i1),!V)return Ae?null:o1?U:""}V&&P1&&Ye(V.firstChild);const G1=w8(L?i1:V);for(;I1=G1.nextNode();)_8(I1),x8(I1),I1.content instanceof o&&j_(I1.content);if(L)return i1;if(Ae){if(Ve)for(te=Q.call(V.ownerDocument);V.firstChild;)te.appendChild(V.firstChild);else te=V;return(X.shadowroot||X.shadowrootmode)&&(te=v1.call(r,te,!0)),te}let be=V1?V.outerHTML:V.innerHTML;return V1&&N["!doctype"]&&V.ownerDocument&&V.ownerDocument.doctype&&V.ownerDocument.doctype.name&&se(n8,V.ownerDocument.doctype.name)&&(be=" `+be),ue&&u3([m,h,E],lt=>{be=t2(be,lt," ")}),O&&o1?O.createHTML(be):be},e.setConfig=function(){let i1=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};l7(i1),ee=!0},e.clearConfig=function(){b5=null,ee=!1},e.isValidAttribute=function(i1,p,V){b5||l7({});const J=K1(i1),I1=K1(p);return E8(J,I1,V)},e.addHook=function(i1,p){typeof p=="function"&&e2(a1[i1],p)},e.removeHook=function(i1,p){if(p!==void 0){const V=__(a1[i1],p);return V===-1?void 0:E_(a1[i1],V,1)[0]}return q9(a1[i1])},e.removeHooks=function(i1){a1[i1]=[]},e.removeAllHooks=function(){a1=i8()},e}var s8=o8();const a8={USE_PROFILES:{html:!0},ALLOWED_TAGS:["p","div","span","br","strong","em","u","a","ul","ol","li","code","pre","h1","h2","h3","h4","h5","h6","blockquote","hr","table","thead","tbody","tr","th","td","img","button","svg","rect","path"],ALLOWED_ATTR:["href","target","class","id","src","alt","width","height","rel","title","data-code","data-language","loading","viewBox","fill","stroke","stroke-width","d","x","y","rx","ry","xmlns","fill-rule","clip-rule"]},l8=(t,e)=>{t.innerHTML=s8.sanitize(e.value||"",a8)},$_={bind:l8,update:l8},c8=t=>s8.sanitize(t,a8);var xt;let Se=xt=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableVoice",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isSpeaking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedbackGiven",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"codeBlockInstances",{enumerable:!0,configurable:!0,writable:!0,value:[]})}get isUser(){return this.message.role==="user"}get isAssistant(){return this.message.role==="assistant"}get showLoadingIndicator(){return this.message.isStreaming===!0&&this.message.content.trim()===""}get isStreamingWithContent(){return this.message.isStreaming===!0&&this.message.content.trim().length>0}get sanitizedUserContent(){return c8(U1.escapeHtml(this.message.content))}get renderedAssistantContent(){const e=J5.renderStreaming(this.message.id,this.message.content,this.message.isStreaming??!1);return c8(e)}mounted(){this.$nextTick(()=>this.mountCodeBlocks())}updated(){this.$nextTick(()=>this.mountCodeBlocks())}beforeDestroy(){this.destroyCodeBlocks(),J5.clearStreamingCache(this.message.id)}render(){return this.isUser?this.renderUserMessage():this.renderAssistantMessage()}renderUserMessage(){const e=this.$createElement;return e("div",{class:"ct-user-message"},[e("div",{class:"ct-user-query",directives:[{name:"safe-html",value:this.sanitizedUserContent}],on:{click:this.handleLinkClick}})])}renderAssistantMessage(){const e=this.$createElement,n=this.message.content.trim().length>0;return e("div",{class:"ct-ai-message-container"},[e("div",{class:"ct-ai-message-content"},[(n||this.showLoadingIndicator)&&e("div",{class:"ct-ai-message-final"},[e("div",{class:"ct-ai-message-icon-container"},[e(j,{attrs:{type:j.Type.ASK_AI,size:xt.AVATAR_ICON_SIZE},class:"ct-ask-logo"})]),e("div",{class:"ct-ai-message-body"},[this.showLoadingIndicator&&e("i",{class:"ct-status-line"},["Thinking..."]),n&&e("div",{class:["ct-ai-message",{"ct-streaming":this.isStreamingWithContent}],directives:[{name:"safe-html",value:this.renderedAssistantContent}],on:{click:this.handleLinkClick}}),this.isStreamingWithContent&&e("span",{class:"ct-streaming-cursor"})])]),!this.message.isStreaming&&n&&this.renderMessageActions()])])}renderMessageActions(){const e=this.$createElement;return e("div",{class:"ct-message-actions"},[e("div",{class:"ct-actions-primary"},[e(Ft,{class:"ct-action-btn",attrs:{text:this.message.content,tooltipText:"Copy",tooltipTextCopied:"Copied!"}})]),e("div",{class:"ct-actions-feedback"},[e(q1,{class:["ct-fb-btn",{"ct-active-good":this.feedbackGiven==="good"}],attrs:{tooltip:"Good Answer",stopPropagation:!0,iconSize:xt.ACTION_ICON_SIZE,icon:j.Type.THUMBS_UP,color:this.feedbackGiven==="good"?K.Color.SUCCESS:K.Color.LIGHT,disabled:!!this.feedbackGiven},on:{click:()=>this.handleFeedback("good")}}),e(q1,{class:["ct-fb-btn",{"ct-active-bad":this.feedbackGiven==="bad"}],attrs:{tooltip:"Bad Answer",stopPropagation:!0,iconSize:xt.ACTION_ICON_SIZE,icon:j.Type.THUMBS_DOWN,color:this.feedbackGiven==="bad"?K.Color.DANGER:K.Color.LIGHT,disabled:!!this.feedbackGiven},on:{click:()=>this.handleFeedback("bad")}})])])}onContentChange(){this.message.isStreaming||this.$nextTick(()=>this.mountCodeBlocks())}onStreamingChange(e){e||this.$nextTick(()=>this.mountCodeBlocks())}handleSpeak(){this.$emit(xt.Event.SPEAK,this.message.content)}handleFeedback(e){this.feedbackGiven=e,this.$emit(xt.Event.FEEDBACK,e,this.message.content,this.message.id)}handleLinkClick(e){const r=e.target.closest("a");r?.href&&!r.closest(".ct-message-actions")&&(e.preventDefault(),window.open(r.href,"_blank","noopener,noreferrer"),He.linkClicked(r.href,r.textContent?.trim()||r.href))}mountCodeBlocks(){if(!this.$el||this.isUser||this.message.isStreaming)return;const e=this.$el.querySelector(".ct-ai-message");if(!e)return;const n=e.querySelectorAll(".ct-code-placeholder");if(n.length===0)return;this.destroyCodeBlocks();const r=Array.from(n).map(i=>i.getAttribute("data-language")||"text").filter((i,o,s)=>s.indexOf(i)===o);v_(r),n.forEach(i=>{const o=i.getAttribute("data-code"),s=i.getAttribute("data-language")||"text";if(o)try{const a=J5.decodeBase64Unicode(o);if(!a)return;const l=document.createElement("div");l.className="ct-code-block-wrapper",i.parentNode?.replaceChild(l,i);const c=l1.extend(Ie),u=new c({propsData:{text:a,language:s,showCopyButton:!0,tooltipText:"Copy",tooltipTextCopied:"Copied!"}});u.$mount(),l.appendChild(u.$el),this.codeBlockInstances.push(u)}catch(a){console.error("[ChatMessage] Failed to mount code block:",a)}})}destroyCodeBlocks(){this.codeBlockInstances.forEach(e=>{e.$destroy()}),this.codeBlockInstances=[]}};Object.defineProperty(Se,"AVATAR_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:20}),Object.defineProperty(Se,"ACTION_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:16}),v([y({type:Object,required:!0,validator:t=>!!t&&["user","assistant"].includes(t.role)}),f("design:type",Object)],Se.prototype,"message",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],Se.prototype,"enableVoice",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],Se.prototype,"isSpeaking",void 0),v([ge("message.content"),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],Se.prototype,"onContentChange",null),v([ge("message.isStreaming"),f("design:type",Function),f("design:paramtypes",[Boolean]),f("design:returntype",void 0)],Se.prototype,"onStreamingChange",null),Se=xt=v([Z1({name:"ChatMessage",directives:{"safe-html":$_}})],Se),function(t){(function(e){e.COPY="copy",e.SPEAK="speak",e.FEEDBACK="feedback",e.LINK_CLICK="link-click"})(t.Event||(t.Event={}))}(Se||(Se={}));var ot,u8;let $1=ot=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopRun",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isStreaming",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableVoice",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isListening",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hasMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"startingText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"textareaRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:""})}get placeholder(){return this.isListening?"Listening...":this.isStreaming?"AI is thinking...":"Search or ask a question..."}get textValue(){return this.text||this.startingText}onTextChange(){this.$nextTick(()=>this.adjustTextareaHeight())}onStartingTextChange(e){this.$nextTick(()=>{e&&(this.focus(),this.adjustTextareaHeight())})}mounted(){this.adjustTextareaHeight()}focus(){this.textareaRef?.focus()}render(){const e=arguments[0];return e("div",{class:"ct-composer-footer drag-cancel"},[e("div",{class:"ct-composer-container"},[e(K,{class:"ct-action-btn ct-clear-btn",attrs:{tooltip:"Clear conversation",size:ot.DELETE_BUTTON_SIZE,iconSize:ot.DELETE_ICON_SIZE,icon:j.Type.DELETE,color:K.Color.LIGHT,disabled:this.isStreaming||!this.hasMessages},on:{click:this.handleClear}}),e("div",{class:"ct-input-wrapper"},[e("textarea",{ref:"textarea",class:"ct-input",attrs:{autocomplete:"none",placeholder:this.placeholder,disabled:this.disabled||this.isStreaming,rows:1},domProps:{value:this.textValue},on:{input:n=>{this.text=n.target.value},keydown:this.handleKeyDown}}),e("div",{class:"ct-input-actions"},[this.enableVoice&&e(q1,{class:["ct-action-btn ct-voice-btn",{"ct-listening":this.isListening}],attrs:{tooltip:"Voice input",iconSize:ot.DEFAULT_ICON_SIZE,icon:j.Type.MIC,color:this.isListening?K.Color.DANGER:K.Color.PRIMARY,appearance:this.isListening?K.Appearance.OUTLINE:K.Appearance.LIGHTEN},on:{click:this.handleVoice}}),this.isStreaming?e("button",{class:"ct-submit-btn",on:{click:this.handleStop}},[e(j,{attrs:{type:j.Type.ASK_AI_LOADING,size:24},class:"ct-ask-ai-icon"})]):e("button",{class:"ct-submit-btn",attrs:{disabled:this.disabled||!this.text.trim()},on:{click:this.handleSend}},[this.disabled?e(j,{attrs:{type:j.Type.ASK_AI_LOADING,size:24},class:"ct-ask-ai-icon"}):e(j,{attrs:{type:j.Type.ASK_AI,size:24},class:"ct-ask-ai-icon"})])])])]),e("div",{class:"ct-disclaimer"},["Powered by CleverAI. Responses may have inaccuracies. Please verify important info."])])}adjustTextareaHeight(){const e=this.textareaRef;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}handleKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.handleSend())}handleSend(){const e=this.text.trim();e&&!this.disabled&&!this.isStreaming&&(this.sendMessage&&this.sendMessage(e),this.$emit(ot.Event.SEND,e),this.text="",this.$nextTick(()=>{this.adjustTextareaHeight()}))}handleStop(){this.stopRun&&this.stopRun(),this.$emit(ot.Event.STOP)}handleClear(){this.isStreaming||this.$emit(ot.Event.CLEAR)}handleVoice(){this.$emit(ot.Event.VOICE)}};Object.defineProperty($1,"DEFAULT_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty($1,"DELETE_BUTTON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:"48px"}),Object.defineProperty($1,"DELETE_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:20}),v([y({type:String,required:!0}),f("design:type",String)],$1.prototype,"projectName",void 0),v([y({type:Function,required:!1}),f("design:type",Function)],$1.prototype,"sendMessage",void 0),v([y({type:Function,required:!1}),f("design:type",Function)],$1.prototype,"stopRun",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"isStreaming",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"disabled",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"enableVoice",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"isListening",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"hasMessages",void 0),v([y({default:""}),f("design:type",String)],$1.prototype,"startingText",void 0),v([hn("textarea"),f("design:type",typeof(u8=typeof HTMLTextAreaElement<"u"&&HTMLTextAreaElement)=="function"?u8:Object)],$1.prototype,"textareaRef",void 0),v([ge("text"),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],$1.prototype,"onTextChange",null),v([ge("startingText",{immediate:!0}),f("design:type",Function),f("design:paramtypes",[String]),f("design:returntype",void 0)],$1.prototype,"onStartingTextChange",null),$1=ot=v([Z1({name:"ChatComposer"})],$1),function(t){(function(e){e.SEND="send",e.STOP="stop",e.CLEAR="clear",e.VOICE="voice"})(t.Event||(t.Event={}))}($1||($1={}));var o7;let Kt=o7=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"question",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}render(){const e=arguments[0];return e("button",{class:"ct-query-pill",on:{click:this.handleClick}},[this.question])}handleClick(){this.$emit(o7.Event.SELECT,this.question)}};v([y({type:String,required:!0}),f("design:type",String)],Kt.prototype,"question",void 0),Kt=o7=v([Z1({name:"QueryPill"})],Kt),function(t){(function(e){e.SELECT="select"})(t.Event||(t.Event={}))}(Kt||(Kt={}));var o2,d8,C8,p8;let Y1=o2=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"messageContainerRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetRuntime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableVoice",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isAtBottom",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"isAtTop",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"isStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isListening",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isSpeaking",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"randomQuestions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"currentQuestionIndex",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hasScrollableContent",{enumerable:!0,configurable:!0,writable:!0,value:!1})}get isEmpty(){return this.messages.length===0}checkScrollableContent(){const e=this.messageContainerRef;e?this.hasScrollableContent=e.scrollHeight>e.clientHeight:this.hasScrollableContent=!1}get questionIndices(){return this.messages.map((e,n)=>({message:e,index:n})).filter(({message:e})=>e.role==="user").map(({index:e})=>e)}onIsStreamingChange(e){this.isStreaming=e}onMessagesChange(e){e&&(this.messages=e),this.$nextTick(()=>{this.checkScrollableContent(),(this.isAtBottom||this.isStreaming)&&this.scrollToBottom()})}onThreadChange(){this.isAtBottom=!0,this.currentQuestionIndex=null,this.$nextTick(()=>{this.scrollToBottom()})}onRandomQuestionsChange(e){e&&(this.randomQuestions=e)}mounted(){this.randomQuestions=this.widgetRuntime.randomQuestions||[],this.$nextTick(()=>{this.checkScrollableContent(),this.scrollToBottom()})}render(){const e=arguments[0];return e("div",{class:"ct-thread"},[e("div",{class:"ct-message-area"},[e("div",{class:"ct-message-container",ref:"messageContainer",on:{scroll:this.handleScroll}},[this.isEmpty?this.renderEmptyState():this.renderMessages()]),!this.isEmpty&&this.renderScrollButton()]),e($1,{attrs:{projectName:this.projectName,isStreaming:this.isStreaming,hasMessages:!this.isEmpty,enableVoice:this.enableVoice,isListening:this.isListening},on:{send:this.handleSendMessage,stop:this.handleStopRun,clear:this.handleClear,voice:this.handleVoice}})])}renderEmptyState(){const e=this.$createElement;return e("div",{class:"ct-empty-state"},[e("div",{class:"ct-intro-header"},[e("div",{class:"ct-intro-icon-wrapper"},[e(j,{class:"ct-intro-icon",attrs:{type:j.Type.ASK_AI_BLUE,size:52}})]),e("div",{class:"ct-intro-heading"},["What do you want to ask?"])]),this.$slots.suggestions||e("div",{class:"ct-intro-queries"},[e("span",{class:"ct-intro-queries-label"},["Example queries"]),e("div",{class:"ct-intro-queries-list"},[this.randomQuestions.map(n=>e(Kt,{key:n,attrs:{question:n},on:{select:this.handleQueryPillSelect}}))])])])}renderMessages(){const e=this.$createElement;return e("div",{class:"ct-message-list"},[this.messages.map((n,r)=>e("div",{key:`${n.id}-${r}`,class:"ct-message-wrapper",ref:`message-${r}`,attrs:{"data-message-index":r,"data-is-question":n.role==="user"}},[e(Se,{attrs:{message:n,enableVoice:this.enableVoice,isSpeaking:this.isSpeaking},on:{copy:this.handleCopy,speak:this.handleSpeak,feedback:this.handleFeedback,linkClick:this.handleLinkClick}})]))])}renderScrollButton(){const e=this.$createElement;if(!this.hasScrollableContent)return null;const n=this.questionIndices,r=this.isAtTop&&n.length>0&&n[0]===0,i=this.currentQuestionIndex!==null&&n.length>0&&this.currentQuestionIndex===n[0];return this.isAtBottom?e("button",{class:"ct-scroll-button",on:{click:this.scrollToMostRecentQuestion},attrs:{"aria-label":"Scroll to most recent question"}},[e(j,{attrs:{type:j.Type.ARROW_UP,size:16}})]):r||i?e("button",{class:"ct-scroll-button",on:{click:this.scrollToBottom},attrs:{"aria-label":"Scroll to bottom"}},[e(j,{attrs:{type:j.Type.ARROW_DOWN,size:16}})]):this.currentQuestionIndex!==null?e("button",{class:"ct-scroll-button",on:{click:this.scrollToMostRecentQuestion},attrs:{"aria-label":"Scroll to previous question"}},[e(j,{attrs:{type:j.Type.ARROW_UP,size:16}})]):e("button",{class:"ct-scroll-button",on:{click:this.scrollToBottom},attrs:{"aria-label":"Scroll to bottom"}},[e(j,{attrs:{type:j.Type.ARROW_DOWN,size:16}})])}handleScroll(){const e=this.messageContainerRef;if(e){const{scrollTop:n,scrollHeight:r,clientHeight:i}=e;this.isAtTop=n0)r=n[i-1];else{this.scrollToTop(),this.currentQuestionIndex=null;return}}r!==null&&this.$nextTick(()=>{const i=e.querySelectorAll("[data-message-index]"),o=Array.from(i).find(s=>Number(s.dataset.messageIndex)===r);if(o){const s=o.offsetTop,a=parseInt(getComputedStyle(e).paddingTop,10)||0;e.scrollTo({top:s-a,behavior:"smooth"}),this.currentQuestionIndex=r,this.$nextTick(()=>{this.checkScrollableContent(),this.handleScroll()})}else this.scrollToTop(),this.currentQuestionIndex=null})}scrollToTop(){const e=this.messageContainerRef;e&&(e.scrollTo({top:0,behavior:"smooth"}),this.isAtTop=!0,this.currentQuestionIndex=null,this.$nextTick(()=>{this.checkScrollableContent(),this.isAtBottom=!this.hasScrollableContent}))}scrollToBottom(){const e=this.messageContainerRef;e&&(e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),this.isAtBottom=!0,this.currentQuestionIndex=null,this.$nextTick(()=>{this.checkScrollableContent(),this.isAtTop=!this.hasScrollableContent}))}async handleSendMessage(e){await this.widgetRuntime.sendMessage(this.widgetRuntime.currentThreadId,e)}handleStopRun(){this.widgetRuntime.cancelStreaming?.()}handleClear(){this.widgetRuntime.clearThreadMessages?.(this.widgetRuntime.currentThreadId)}handleVoice(){this.widgetRuntime.startListening?.()}handleCopy(){this.$emit(o2.Event.COPY)}handleSpeak(e){this.widgetRuntime.speak?.(e)}handleFeedback(e,n,r){this.widgetRuntime.handleFeedback?.(e,n,r)}handleLinkClick(e,n){this.widgetRuntime.handleLinkClick?.(e,n)}handleQueryPillSelect(e){this.handleSendMessage(e)}setVoiceState(e,n){e==="listening"?this.isListening=n:e==="speaking"&&(this.isSpeaking=n)}};Object.defineProperty(Y1,"SCROLL_THRESHOLD",{enumerable:!0,configurable:!0,writable:!0,value:100}),v([hn("messageContainer"),f("design:type",typeof(d8=typeof HTMLDivElement<"u"&&HTMLDivElement)=="function"?d8:Object)],Y1.prototype,"messageContainerRef",void 0),v([r6("widgetRuntime"),f("design:type",Object)],Y1.prototype,"widgetRuntime",void 0),v([y({type:String,required:!0}),f("design:type",String)],Y1.prototype,"projectName",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],Y1.prototype,"enableVoice",void 0),v([ge("widgetRuntime.isCurrentThreadStreaming",{immediate:!0,deep:!0}),f("design:type",Function),f("design:paramtypes",[Boolean]),f("design:returntype",void 0)],Y1.prototype,"onIsStreamingChange",null),v([ge("widgetRuntime.currentMessages",{immediate:!0,deep:!0}),f("design:type",Function),f("design:paramtypes",[typeof(C8=typeof Array<"u"&&Array)=="function"?C8:Object]),f("design:returntype",void 0)],Y1.prototype,"onMessagesChange",null),v([ge("widgetRuntime.currentThreadId",{immediate:!0,deep:!0}),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],Y1.prototype,"onThreadChange",null),v([ge("widgetRuntime.randomQuestions",{immediate:!0}),f("design:type",Function),f("design:paramtypes",[typeof(p8=typeof Array<"u"&&Array)=="function"?p8:Object]),f("design:returntype",void 0)],Y1.prototype,"onRandomQuestionsChange",null),Y1=o2=v([Z1({name:"ChatThread",components:{ChatMessage:Se,ChatComposer:$1,QueryPill:Kt}})],Y1),function(t){(function(e){e.COPY="copy",e.MESSAGE_CLICK="message-click"})(t.Event||(t.Event={}))}(Y1||(Y1={}));let Mt=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runtime",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}get widgetRuntime(){return this.runtime}render(){const e=arguments[0];return e("div",{class:"ct-runtime-container",style:{height:this.height,width:this.width}},[this.$slots.header,e("div",{class:"ct-runtime-body"},[this.$slots.default])])}};v([y({default:"100%"}),f("design:type",String)],Mt.prototype,"height",void 0),v([y({default:"100%"}),f("design:type",String)],Mt.prototype,"width",void 0),v([y({required:!0}),f("design:type",Object)],Mt.prototype,"runtime",void 0),v([us("widgetRuntime"),f("design:type",Object),f("design:paramtypes",[])],Mt.prototype,"widgetRuntime",null),Mt=v([Z1({name:"ChatRuntimeProvider"})],Mt);var qt,st;(function(t){t.SUCCESS="success",t.WARNING="warning",t.DANGER="danger",t.INFO="info"})(st||(st={}));let le=qt=class extends l1{render(){const e=arguments[0],{className:n,iconType:r}=qt.TYPE_METADATA[this.type];return e("div",{class:j1(`lp-info-panel ${n}`,{inline:this.inline,emphasize:this.emphasize})},[this.title&&e("div",{class:"flex-row"},[e(j,{class:"lp-info-panel-icon",attrs:{size:qt.ICON_SIZE,type:r}}),e("div",{class:"flex-column"},[e("p",{class:"lp-info-panel__title"},[this.title]),this.renderMessage(),this.$slots.default])]),!this.title&&e("div",{class:j1(`flex-row ${this.contentPosition||""}`)},[e(j,{class:"lp-info-panel-icon",attrs:{size:qt.ICON_SIZE,type:r}}),this.renderMessage(),this.$slots.default,this.renderCloseIcon()])])}renderMessage(){const e=this.$createElement;return e("div",[this.text&&e("p",{class:j1("lp-info-panel-text")},[this.text])])}renderCloseIcon(){const e=this.$createElement;return this.showClose?e("span",{class:"flex-row-left"},[e(j,{class:"lp-info-panel-close-icon",attrs:{type:j.Type.CLOSE,size:this.isToast?qt.ICON_SIZE:20},on:{click:this.onClose}})]):null}onClose(){this.$emit(qt.EVENT_CLOSE)}};le.ICON_SIZE=16,le.TYPE_METADATA={[st.SUCCESS]:{className:"lp-success",iconType:j.Type.CHECK_MEDIUM},[st.WARNING]:{className:"lp-warning",iconType:j.Type.EXCLAMATION_MEDIUM},[st.DANGER]:{className:"lp-danger",iconType:j.Type.EXCLAMATION_MEDIUM},[st.INFO]:{className:"lp-info",iconType:j.Type.EXCLAMATION_MEDIUM}},v([y({type:String,required:!1,default:null}),f("design:type",Object)],le.prototype,"title",void 0),v([y({type:String,default:"",required:!1}),f("design:type",String)],le.prototype,"text",void 0),v([y({type:Boolean,default:!1,required:!1}),f("design:type",Boolean)],le.prototype,"inline",void 0),v([y({type:Boolean,default:!0,required:!1}),f("design:type",Boolean)],le.prototype,"emphasize",void 0),v([y({type:Boolean,default:!1,required:!1}),f("design:type",Boolean)],le.prototype,"showClose",void 0),v([y({type:Boolean,default:!1,required:!1}),f("design:type",Boolean)],le.prototype,"isToast",void 0),v([y({type:String,default:"",required:!1}),f("design:type",String)],le.prototype,"contentPosition",void 0),v([y({type:String,default:st.SUCCESS,validator:t=>ye(st).indexOf(t)!==-1}),f("design:type",String)],le.prototype,"type",void 0),le=qt=v([Z1({name:"InfoPanel"})],le),function(t){t.EVENT_CLOSE="close",t.Type=st,function(e){e.RIGHT="right",e.BOTTOM="bottom"}(t.ContentPosition||(t.ContentPosition={}))}(le||(le={}));var L5;let N1=L5=class extends l1{constructor(){super(...arguments),this.hasScrolled=!1,this.hasScrolledToEnd=!0}static get hasOpenedModals(){return nt.openedInstances.filter(e=>e.$parent instanceof L5).length>0}mounted(){document.documentElement&&document.documentElement.classList.add("modal-open")}beforeDestroy(){document.documentElement&&document.documentElement.classList.remove("modal-open")}render(){const e=arguments[0];return e(nt,{on:{bodyKeyDown:this.onBodyKeyDown}},[e("transition",{attrs:{appear:!0},on:{appear:this.computeScrollState}},[e("div",{attrs:{"data-testid":this.dataTestId},class:j1("lp-modal",this.className,{"full-screen":this.fullScreen,"transparent-bg":this.noFade,"not-like-modal":this.allowBackgroundInteraction},this.position),on:{click:this.onOverlayClick}},[e("div",{class:j1("wrapper",{"not-like-modal":this.allowBackgroundInteraction})},[this.simple?this.$slots.default:this.renderContent()])])])])}renderContent(){const e=this.$createElement;return e("div",{attrs:{"data-testid":`${this.dataTestId}-content`},class:j1("content",this.spinnerClass),style:this.sizingStyles,on:{click:Wu,scroll:this.computeScrollState},ref:"content"},[this.hasHeader&&e("div",{class:j1("header",{scrolled:this.hasScrolled})},[e("div",{class:"header-container"},[e("div",{class:j1("title",{big:this.bigTitle})},[this.title]),e("div",{class:"header-slot-container"},[this.$slots.header])]),this.closeButton&&e(j,{class:"cross",attrs:{size:32,type:j.Type.CLEAR},on:{click:this.onClickCross}})]),e("div",{class:"body"},[this.$slots.default]),this.hasSpinner&&e("div",{class:"spinner-container",attrs:{"data-testid":"modal-spinner"}},[e("div",{class:"spinner"})]),this.hasFooter()?e("div",{class:j1("footer",{scrolled:!this.hasScrolledToEnd})},[this.$slots.footer]):e("div",{class:"footer-accommodation"})])}get hasHeader(){return this.closeButton||!!this.title}hasFooter(){return!u5(this.$slots.footer)}get sizingStyles(){const e={minWidth:this.width,width:this.width};return this.minHeight!==null&&(e.minHeight=this.minHeight),e}get hasSpinner(){return this.hasOverlaySpinner||this.hasContentReplacingSpinner}get spinnerClass(){return j1({"overlay-spinner":this.hasOverlaySpinner,"content-replacing-spinner":this.hasContentReplacingSpinner})}get hasOverlaySpinner(){return this.spinner===L5.Spinner.OVERLAY}get hasContentReplacingSpinner(){return this.spinner===L5.Spinner.REPLACE_CONTENT}onOverlayClick(){this.fadeClose&&this.emitClose()}onClickCross(){this.closeButton&&this.emitClose()}onBodyKeyDown(e){this.escClose&&e.key===U5.ESC_KEY&&(e.stopImmediatePropagation(),this.emitClose())}emitClose(){this.hasSpinner||this.$emit(L5.EVENT_CLOSE)}computeScrollState(){const e=this.$refs.content;e&&(this.hasScrolled=e.scrollTop>0,this.hasScrolledToEnd=e.scrollTop+e.clientHeight===e.scrollHeight)}};N1.SLOT_HEADER="header",N1.SLOT_FOOTER="footer",v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"simple",void 0),v([y({type:String,required:!1,default:null}),f("design:type",Object)],N1.prototype,"title",void 0),v([y({type:String,required:!1,default:"480px"}),f("design:type",String)],N1.prototype,"width",void 0),v([y({type:String,required:!1,default:""}),f("design:type",String)],N1.prototype,"className",void 0),v([y({type:String,required:!1,default:"120px"}),f("design:type",String)],N1.prototype,"minHeight",void 0),v([y({type:Boolean,required:!1,default:!0}),f("design:type",Boolean)],N1.prototype,"fadeClose",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"escClose",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"closeButton",void 0),v([y({type:String,required:!1,default:"hidden"}),f("design:type",String)],N1.prototype,"spinner",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"fullScreen",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"bigTitle",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"noFade",void 0),v([y({type:String,required:!1,default:()=>N1.Position.AUTO}),f("design:type",String)],N1.prototype,"position",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],N1.prototype,"allowBackgroundInteraction",void 0),v([y({type:String,default:"modal"}),f("design:type",String)],N1.prototype,"dataTestId",void 0),v([zu(100),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],N1.prototype,"computeScrollState",null),N1=L5=v([Z1({name:"Modal"})],N1),function(t){t.EVENT_CLOSE="close",function(e){e.HIDDEN="hidden",e.OVERLAY="overlay",e.REPLACE_CONTENT="replace-content"}(t.Spinner||(t.Spinner={})),function(e){e.AUTO="auto",e.TOP="top",e.BOTTOM="bottom"}(t.Position||(t.Position={}))}(N1||(N1={}));var s7,s2;(function(t){t.SUCCESS="success",t.WARNING="warning",t.DANGER="danger",t.INFO="info"})(s2||(s2={}));let X1=s7=class extends l1{created(){(!this.showClose||this.hasTimeoutAndClose)&&(this.timeoutInternal=window.setTimeout(this.close,this.timeout))}beforeDestroy(){clearTimeout(this.timeoutInternal)}render(){const e=arguments[0];return e(N1,{attrs:{simple:!0,alignTop:!0,escClose:!0,noFade:!0,fadeClose:this.fadeClose,position:this.position,className:this.className},on:{close:this.close}},[e(le,{class:"lp-toast",attrs:{type:this.type,text:this.text,showClose:this.showClose,isToast:!0},on:{close:this.handleInfoClose}},[this.$slots.default])])}close(){this.$emit(s7.EVENT_CLOSE)}handleInfoClose(){this.close()}};v([y({type:String,required:!1,default:""}),f("design:type",String)],X1.prototype,"text",void 0),v([y({type:String,required:!1,default:s2.SUCCESS,validator:t=>ye(s2).indexOf(t)!==-1}),f("design:type",String)],X1.prototype,"type",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],X1.prototype,"showClose",void 0),v([y({type:String,required:!1,default:()=>X1.Position.TOP}),f("design:type",String)],X1.prototype,"position",void 0),v([y({type:String,default:""}),f("design:type",String)],X1.prototype,"className",void 0),v([y({type:Number,default:()=>X1.ToastOpenedTimeout}),f("design:type",Number)],X1.prototype,"timeout",void 0),v([y({type:Boolean,default:!0}),f("design:type",Boolean)],X1.prototype,"fadeClose",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],X1.prototype,"hasTimeoutAndClose",void 0),X1=s7=v([Z1({name:"Toast"})],X1),function(t){t.EVENT_CLOSE="close",t.Type=s2,t.ToastOpenedTimeout=5e3,function(e){e.AUTO="auto",e.TOP="top",e.BOTTOM="bottom"}(t.Position||(t.Position={}))}(X1||(X1={}));let p3=class extends l1{render(){const e=arguments[0];return e(C0,{class:"lp-portal-target",attrs:{name:this.name||W2.TARGET_A,multiple:!0}})}};v([y({type:String,required:!1,default:""}),f("design:type",String)],p3.prototype,"name",void 0),p3=v([Z1({name:"StargateTarget"})],p3);var Yt;let De=Yt=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"title",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"windowState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allowMinimize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allowMaximize",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}render(){const e=arguments[0];return e("div",{class:"ct-widget-header",on:{click:this.handleHeaderClick}},[e("div",{class:"ct-header-logo"},[e(q1,{class:"ct-logo-button",attrs:{iconSize:20,icon:j.Type.ASK_AI,appearance:K.Appearance.LIGHTEN,color:K.Color.PRIMARY}})]),e("div",{class:"ct-header-title"},[this.title]),e("div",{class:"ct-window-controls"},[this.allowMaximize&&this.renderMaximizeButton(),this.renderCloseButton()])])}renderMaximizeButton(){const e=this.$createElement;return e(j,{class:"ct-win-btn ct-maximize-btn",attrs:{type:this.windowState==="maximized"?j.Type.MINIMIZE:j.Type.MAXIMIZE,size:Yt.MAXIMIZE_ICON_SIZE,clickable:!0,stopPropagation:!0},on:{click:this.handleMaximize}})}renderCloseButton(){const e=this.$createElement;return e(j,{class:"ct-win-btn ct-close-btn",attrs:{clickable:!0,stopPropagation:!0,type:j.Type.CLOSE,size:Yt.CLOSE_ICON_SIZE},on:{click:this.handleClose}})}handleHeaderClick(){this.$emit(Yt.Event.HEADER_CLICK)}handleMaximize(){this.$emit(Yt.Event.MAXIMIZE)}handleClose(){this.$emit(Yt.Event.CLOSE)}};Object.defineProperty(De,"CLOSE_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:20}),Object.defineProperty(De,"MAXIMIZE_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:14}),v([y({type:String,required:!0}),f("design:type",String)],De.prototype,"title",void 0),v([y({type:String,default:"normal"}),f("design:type",Object)],De.prototype,"windowState",void 0),v([y({type:Boolean,default:!0}),f("design:type",Boolean)],De.prototype,"allowMinimize",void 0),v([y({type:Boolean,default:!0}),f("design:type",Boolean)],De.prototype,"allowMaximize",void 0),De=Yt=v([Z1({name:"WidgetHeader"})],De),function(t){(function(e){e.MINIMIZE="minimize",e.MAXIMIZE="maximize",e.CLOSE="close",e.HEADER_CLICK="headerClick"})(t.Event||(t.Event={}))}(De||(De={}));var f8;F1.Widget=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatThreadRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetRuntime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isOpen",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"windowState",{enumerable:!0,configurable:!0,writable:!0,value:"normal"}),Object.defineProperty(this,"isInitializing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"initializationError",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"toastMessage",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"showToast",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"scrollPosition",{enumerable:!0,configurable:!0,writable:!0,value:0})}get runtime(){return this.widgetRuntime}get positionClass(){return`ct-pos-${this.config.position}`}logDebug(e,n,r="log"){(this.debug||r==="error"||r==="warn")&&console[r](`[Widget] ${e}`,n!==void 0?n:"")}async created(){try{if(this.logDebug("Initializing Widget"),this.widgetRuntime=new m_(this.config),this.setupRuntimeCallbacks(),!await this.widgetRuntime.initialize())throw new Error("Failed to initialize widget runtime");this.isInitializing=!1,this.logDebug("Widget initialized successfully")}catch(e){this.isInitializing=!1,this.initializationError=`Error initializing widget: ${e.message||"Unknown error"}`,this.logDebug("Failed to initialize Widget:",e,"error")}}mounted(){document.documentElement.style.setProperty("--ct-primary",this.config.color),document.documentElement.style.setProperty("--ct-primary-hover",this.config.colorHover),document.addEventListener("keydown",this.handleKeyDown)}beforeDestroy(){document.removeEventListener("keydown",this.handleKeyDown),this.isOpen&&this.unlockBodyScroll(),this.widgetRuntime?.destroy?.()}render(){const e=arguments[0];return e("div",{class:"ct-widget-container"},[this.renderLauncher(),this.renderModal(),this.renderToast(),e(p3)])}renderLauncher(){const e=this.$createElement;return e(K,{attrs:{id:"ct-launcher",text:"Ask",iconSize:20,prefixIcon:j.Type.ASK_AI,appearance:K.Appearance.LIGHTEN,color:K.Color.PRIMARY},class:"ct-widget-launcher",on:{click:this.open}})}renderModal(){const e=this.$createElement,n=["ct-widget-root",this.positionClass,{"ct-visible":this.isOpen,"ct-maximized":this.windowState==="maximized","ct-minimized":this.windowState==="minimized"}];return e("div",{class:n,attrs:{"aria-hidden":this.isOpen?"false":"true"}},[e("div",{class:"ct-widget-overlay",on:{click:this.handleOverlayClick}}),e("div",{class:"ct-widget-modal"},[this.renderModalContent()])])}renderModalContent(){return this.isInitializing?this.renderLoadingState():this.initializationError?this.renderErrorState():this.renderChatInterface()}renderLoadingState(){const e=this.$createElement;return e("div",{class:"ct-widget-loading"},[e(j,{attrs:{type:j.Type.ASK_AI,size:40}}),e("span",{class:"ct-loading-text"},["Initializing..."])])}renderErrorState(){const e=this.$createElement;return e("div",{class:"ct-widget-error"},[e(j,{attrs:{type:j.Type.ALERT,size:40}}),e("span",{class:"ct-error-text"},[this.initializationError]),e(K,{attrs:{text:"Retry",appearance:K.Appearance.OUTLINE,color:K.Color.PRIMARY},on:{click:this.retryInitialization}})])}renderChatInterface(){const e=this.$createElement;return this.widgetRuntime?e(Mt,{attrs:{runtime:this.widgetRuntime,height:"100%",width:"100%"}},[e("template",{slot:"header"},[e(De,{attrs:{title:this.config.name,windowState:this.windowState,allowMinimize:this.config.allowMinimize,allowMaximize:this.config.allowMaximize},on:{minimize:this.minimize,maximize:this.maximize,close:this.close,headerClick:this.handleHeaderClick}})]),e("div",{class:"ct-chat-interface"},[e(Y1,{ref:"chatThread",attrs:{projectName:this.config.name,enableVoice:this.config.enableVoice},on:{copy:this.handleCopy}})])]):this.renderLoadingState()}renderToast(){const e=this.$createElement;return this.showToast?e(X1,{attrs:{text:this.toastMessage,type:X1.Type.DANGER,position:X1.Position.TOP,showClose:!0},on:{close:this.handleToastClose}}):null}onRuntimeChange(){this.widgetRuntime&&this.setupRuntimeCallbacks()}handleKeyDown(e){e.key==="Escape"&&this.isOpen&&this.close()}open(){if(this.isOpen)return;this.isOpen=!0,He.widgetOpened(),this.lockBodyScroll()}close(){if(!this.isOpen)return;this.isOpen=!1,He.widgetClosed(),this.windowState="normal",this.unlockBodyScroll(),this.widgetRuntime?.stopListening?.(),this.widgetRuntime?.stopSpeaking?.()}lockBodyScroll(){this.scrollPosition=window.pageYOffset||document.documentElement.scrollTop,document.body.classList.add("ct-widget-open"),document.body.style.top=`-${this.scrollPosition}px`}unlockBodyScroll(){document.body.classList.remove("ct-widget-open"),document.body.style.top="",window.scrollTo(0,this.scrollPosition)}minimize(){this.windowState=this.windowState==="minimized"?"normal":"minimized"}maximize(){this.windowState=this.windowState==="maximized"?"normal":"maximized"}restore(){this.windowState="normal"}async retryInitialization(){this.isInitializing=!0,this.initializationError=null;try{if(this.widgetRuntime&&!await this.widgetRuntime.initialize())throw new Error("Failed to initialize widget runtime");this.isInitializing=!1}catch(e){this.isInitializing=!1,this.initializationError=`Error initializing widget: ${e.message||"Unknown error"}`}}handleCopy(){this.logDebug("Copy action triggered")}handleOverlayClick(){this.close()}handleHeaderClick(){this.windowState==="minimized"&&this.restore()}displayToast(e){this.toastMessage=e,this.showToast=!0}handleToastClose(){this.showToast=!1,this.toastMessage=""}setupRuntimeCallbacks(){this.widgetRuntime&&(this.widgetRuntime.setOnStateChange(e=>{this.logDebug("Runtime state changed:",e),this.$forceUpdate()}),this.widgetRuntime.setOnVoiceState((e,n)=>{this.chatThreadRef?.setVoiceState(e,n)}),this.widgetRuntime.setOnError(e=>{this.logDebug("Runtime error:",e,"error"),this.displayToast(e)}),this.widgetRuntime.setOnStreaming(e=>{this.logDebug("Streaming event:",e)}))}},v([y({type:Object,required:!0}),f("design:type",Object)],F1.Widget.prototype,"config",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],F1.Widget.prototype,"debug",void 0),v([hn("chatThread"),f("design:type",typeof(f8=typeof Y1<"u"&&Y1)=="function"?f8:Object)],F1.Widget.prototype,"chatThreadRef",void 0),v([ds("widgetRuntime"),f("design:type",Object),f("design:paramtypes",[])],F1.Widget.prototype,"runtime",null),v([ge("widgetRuntime",{immediate:!0}),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],F1.Widget.prototype,"onRuntimeChange",null),F1.Widget=v([Z1({name:"Widget",components:{ChatThread:Y1,ChatRuntimeProvider:Mt,WidgetHeader:De}})],F1.Widget);function h8(){try{const t=new Fn,e=document.createElement("div");e.id="ask-ai-root",document.body.appendChild(e),new l1({render:n=>n(F1.Widget,{props:{config:t}})}).$mount("#ask-ai-root")}catch{}}return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",h8):h8(),window.AskAIWidget={Widget:F1.Widget,WidgetConfig:Fn},F1.WidgetConfig=Fn,Object.defineProperty(F1,Symbol.toStringTag,{value:"Module"}),F1}({});