@blockspark/chat-widget 1.0.7 → 1.0.9
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/README.md +117 -140
- package/dist/_virtual/_plugin-vue_export-helper.cjs.js +2 -0
- package/dist/_virtual/_plugin-vue_export-helper.cjs.js.map +1 -0
- package/dist/_virtual/_plugin-vue_export-helper.esm.js +11 -0
- package/dist/_virtual/_plugin-vue_export-helper.esm.js.map +1 -0
- package/dist/components/ChatWidget.cjs.js +2 -0
- package/dist/components/ChatWidget.cjs.js.map +1 -0
- package/dist/components/ChatWidget.d.ts.map +1 -1
- package/dist/components/ChatWidget.esm.js +1129 -0
- package/dist/components/ChatWidget.esm.js.map +1 -0
- package/dist/components/ChatWidget.vue.cjs.js +2 -0
- package/dist/components/ChatWidget.vue.cjs.js.map +1 -0
- package/dist/components/ChatWidget.vue.cjs2.js +2 -0
- package/dist/components/ChatWidget.vue.cjs2.js.map +1 -0
- package/dist/components/ChatWidget.vue.esm.js +8 -0
- package/dist/components/ChatWidget.vue.esm.js.map +1 -0
- package/dist/components/ChatWidget.vue.esm2.js +374 -0
- package/dist/components/ChatWidget.vue.esm2.js.map +1 -0
- package/dist/composables/useChatWidget.cjs.js +2 -0
- package/dist/composables/useChatWidget.cjs.js.map +1 -0
- package/dist/composables/useChatWidget.d.ts +35 -0
- package/dist/composables/useChatWidget.d.ts.map +1 -0
- package/dist/composables/useChatWidget.esm.js +75 -0
- package/dist/composables/useChatWidget.esm.js.map +1 -0
- package/dist/core/stateManager.cjs.js +2 -0
- package/dist/core/stateManager.cjs.js.map +1 -0
- package/dist/core/stateManager.esm.js +915 -0
- package/dist/core/stateManager.esm.js.map +1 -0
- package/dist/entry/nuxt.d.ts +9 -4
- package/dist/entry/nuxt.d.ts.map +1 -1
- package/dist/entry/vanilla.cjs.js +2 -0
- package/dist/entry/vanilla.cjs.js.map +1 -0
- package/dist/entry/vanilla.esm.js +50 -0
- package/dist/entry/vanilla.esm.js.map +1 -0
- package/dist/entry/vue.d.ts +8 -5
- package/dist/entry/vue.d.ts.map +1 -1
- package/dist/hooks/useChatMode.cjs.js +2 -0
- package/dist/hooks/useChatMode.cjs.js.map +1 -0
- package/dist/hooks/useChatMode.esm.js +61 -0
- package/dist/hooks/useChatMode.esm.js.map +1 -0
- package/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.esm.js +16 -2
- package/dist/index.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.esm.js +21 -0
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.esm.js +84 -0
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jwt/produce.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/jwt/produce.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jwt/produce.esm.js +72 -0
- package/dist/node_modules/jose/dist/browser/jwt/produce.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jwt/sign.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/jwt/sign.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/jwt/sign.esm.js +22 -0
- package/dist/node_modules/jose/dist/browser/jwt/sign.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/key/import.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/key/import.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/key/import.esm.js +11 -0
- package/dist/node_modules/jose/dist/browser/key/import.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.esm.js +18 -0
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.esm.js +77 -0
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.esm.js +101 -0
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/epoch.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/epoch.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/epoch.esm.js +5 -0
- package/dist/node_modules/jose/dist/browser/lib/epoch.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.esm.js +32 -0
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.esm.js +25 -0
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.esm.js +20 -0
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/is_object.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/is_object.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/is_object.esm.js +20 -0
- package/dist/node_modules/jose/dist/browser/lib/is_object.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/secs.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/secs.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/secs.esm.js +59 -0
- package/dist/node_modules/jose/dist/browser/lib/secs.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.esm.js +34 -0
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/asn1.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/asn1.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/asn1.esm.js +103 -0
- package/dist/node_modules/jose/dist/browser/runtime/asn1.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/base64url.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/base64url.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/base64url.esm.js +43 -0
- package/dist/node_modules/jose/dist/browser/runtime/base64url.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.esm.js +12 -0
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.esm.js +25 -0
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.esm.js +13 -0
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.esm.js +107 -0
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.esm.js +71 -0
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/sign.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/sign.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/sign.esm.js +14 -0
- package/dist/node_modules/jose/dist/browser/runtime/sign.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.esm.js +32 -0
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.esm.js +7 -0
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.esm.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/util/errors.cjs.js +2 -0
- package/dist/node_modules/jose/dist/browser/util/errors.cjs.js.map +1 -0
- package/dist/node_modules/jose/dist/browser/util/errors.esm.js +131 -0
- package/dist/node_modules/jose/dist/browser/util/errors.esm.js.map +1 -0
- package/dist/node_modules/react-dom/client.cjs.js +2 -0
- package/dist/node_modules/react-dom/client.cjs.js.map +1 -0
- package/dist/node_modules/react-dom/client.esm.js +21 -0
- package/dist/node_modules/react-dom/client.esm.js.map +1 -0
- package/dist/nuxt.cjs.js +2 -0
- package/dist/nuxt.cjs.js.map +1 -0
- package/dist/nuxt.esm.js +10 -0
- package/dist/nuxt.esm.js.map +1 -0
- package/dist/services/chatService.cjs.js +2 -0
- package/dist/services/chatService.cjs.js.map +1 -0
- package/dist/services/chatService.esm.js +482 -0
- package/dist/services/chatService.esm.js.map +1 -0
- package/dist/services/dialogflowClient.cjs.js +2 -0
- package/dist/services/dialogflowClient.cjs.js.map +1 -0
- package/dist/services/dialogflowClient.esm.js +282 -0
- package/dist/services/dialogflowClient.esm.js.map +1 -0
- package/dist/services/sessionManager.cjs.js +2 -0
- package/dist/services/sessionManager.cjs.js.map +1 -0
- package/dist/services/sessionManager.esm.js +48 -0
- package/dist/services/sessionManager.esm.js.map +1 -0
- package/dist/styles.css +1 -596
- package/dist/utils/frameworkDetector.cjs.js +2 -0
- package/dist/utils/frameworkDetector.cjs.js.map +1 -0
- package/dist/utils/frameworkDetector.esm.js +125 -0
- package/dist/utils/frameworkDetector.esm.js.map +1 -0
- package/dist/utils/sanitize.cjs.js +2 -0
- package/dist/utils/sanitize.cjs.js.map +1 -0
- package/dist/utils/sanitize.d.ts +25 -0
- package/dist/utils/sanitize.d.ts.map +1 -0
- package/dist/utils/sanitize.esm.js +52 -0
- package/dist/utils/sanitize.esm.js.map +1 -0
- package/dist/utils/ssr.d.ts +35 -0
- package/dist/utils/ssr.d.ts.map +1 -0
- package/dist/vue.cjs.js +2 -1
- package/dist/vue.cjs.js.map +1 -0
- package/dist/vue.esm.js +10 -1
- package/dist/vue.esm.js.map +1 -0
- package/package.json +30 -23
- package/dist/index.cjs.js.LICENSE.txt +0 -27
- package/dist/index.esm.js.LICENSE.txt +0 -27
- package/dist/index.js +0 -2
- package/dist/index.js.LICENSE.txt +0 -9
- package/dist/index.umd.js +0 -2
- package/dist/index.umd.js.LICENSE.txt +0 -27
- package/dist/react.cjs.js +0 -2
- package/dist/react.cjs.js.LICENSE.txt +0 -9
- package/dist/react.esm.js +0 -2
- package/dist/react.esm.js.LICENSE.txt +0 -9
- package/dist/vue/ChatWidgetWrapper.d.ts +0 -182
- package/dist/vue/ChatWidgetWrapper.d.ts.map +0 -1
- package/dist/vue/index.d.ts +0 -191
- package/dist/vue/index.d.ts.map +0 -1
- package/dist/vue.js +0 -2
- package/dist/vue.js.LICENSE.txt +0 -39
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license React
|
|
3
|
-
* react-jsx-runtime.production.min.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* @vue/runtime-core v3.5.28
|
|
13
|
-
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
|
14
|
-
* @license MIT
|
|
15
|
-
**/
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* @vue/runtime-dom v3.5.28
|
|
19
|
-
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
|
20
|
-
* @license MIT
|
|
21
|
-
**/
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* @vue/shared v3.5.28
|
|
25
|
-
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
|
26
|
-
* @license MIT
|
|
27
|
-
**/
|
package/dist/react.cjs.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! For license information please see react.cjs.js.LICENSE.txt */
|
|
2
|
-
(()=>{"use strict";var e={20(e,t,s){var n=s(206),r=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,i=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,s){var n,o={},l=null,d=null;for(n in void 0!==s&&(l=""+s),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,n)&&!c.hasOwnProperty(n)&&(o[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps)void 0===o[n]&&(o[n]=t[n]);return{$$typeof:r,type:e,key:l,ref:d,props:o,_owner:i.current}}t.Fragment=o,t.jsx=l,t.jsxs=l},206(e){e.exports=require("react")},848(e,t,s){e.exports=s(20)}},t={};function s(n){var r=t[n];if(void 0!==r)return r.exports;var o=t[n]={exports:{}};return e[n](o,o.exports,s),o.exports}s.d=(e,t)=>{for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};s.r(n),s.d(n,{ChatWidget:()=>Yt});var r=s(848),o=s(206);const a="numeric",i="ascii",c="alpha",l="asciinumeric",d="alphanumeric",u="domain",h="emoji",m="scheme",g="slashscheme",p="whitespace";function f(e,t){return e in t||(t[e]=[]),t[e]}function y(e,t,s){t[a]&&(t[l]=!0,t[d]=!0),t[i]&&(t[l]=!0,t[c]=!0),t[l]&&(t[d]=!0),t[c]&&(t[d]=!0),t[d]&&(t[u]=!0),t[h]&&(t[u]=!0);for(const n in t){const t=f(n,s);t.indexOf(e)<0&&t.push(e)}}function w(e=null){this.j={},this.jr=[],this.jd=null,this.t=e}w.groups={},w.prototype={accepts(){return!!this.t},go(e){const t=this,s=t.j[e];if(s)return s;for(let s=0;s<t.jr.length;s++){const n=t.jr[s][0],r=t.jr[s][1];if(r&&n.test(e))return r}return t.jd},has(e,t=!1){return t?e in this.j:!!this.go(e)},ta(e,t,s,n){for(let r=0;r<e.length;r++)this.tt(e[r],t,s,n)},tr(e,t,s,n){let r;return n=n||w.groups,t&&t.j?r=t:(r=new w(t),s&&n&&y(t,s,n)),this.jr.push([e,r]),r},ts(e,t,s,n){let r=this;const o=e.length;if(!o)return r;for(let t=0;t<o-1;t++)r=r.tt(e[t]);return r.tt(e[o-1],t,s,n)},tt(e,t,s,n){n=n||w.groups;const r=this;if(t&&t.j)return r.j[e]=t,t;const o=t;let a,i=r.go(e);if(i?(a=new w,Object.assign(a.j,i.j),a.jr.push.apply(a.jr,i.jr),a.jd=i.jd,a.t=i.t):a=new w,o){if(n)if(a.t&&"string"==typeof a.t){const e=Object.assign(function(e,t){const s={};for(const n in t)t[n].indexOf(e)>=0&&(s[n]=!0);return s}(a.t,n),s);y(o,e,n)}else s&&y(o,s,n);a.t=o}return r.j[e]=a,a}};const S=(e,t,s,n,r)=>e.ta(t,s,n,r),E=(e,t,s,n,r)=>e.tr(t,s,n,r),b=(e,t,s,n,r)=>e.ts(t,s,n,r),k=(e,t,s,n,r)=>e.tt(t,s,n,r),A="WORD",_="UWORD",v="ASCIINUMERICAL",I="ALPHANUMERICAL",C="LOCALHOST",R="TLD",T="UTLD",x="SCHEME",P="SLASH_SCHEME",N="NUM",D="WS",j="NL",H="OPENBRACE",O="CLOSEBRACE",L="OPENBRACKET",W="CLOSEBRACKET",$="OPENPAREN",M="CLOSEPAREN",K="OPENANGLEBRACKET",U="CLOSEANGLEBRACKET",J="FULLWIDTHLEFTPAREN",F="FULLWIDTHRIGHTPAREN",B="LEFTCORNERBRACKET",V="RIGHTCORNERBRACKET",z="LEFTWHITECORNERBRACKET",q="RIGHTWHITECORNERBRACKET",G="FULLWIDTHLESSTHAN",Y="FULLWIDTHGREATERTHAN",X="AMPERSAND",Q="APOSTROPHE",Z="ASTERISK",ee="AT",te="BACKSLASH",se="BACKTICK",ne="CARET",re="COLON",oe="COMMA",ae="DOLLAR",ie="DOT",ce="EQUALS",le="EXCLAMATION",de="HYPHEN",ue="PERCENT",he="PIPE",me="PLUS",ge="POUND",pe="QUERY",fe="QUOTE",ye="FULLWIDTHMIDDLEDOT",we="SEMI",Se="SLASH",Ee="TILDE",be="UNDERSCORE",ke="EMOJI",Ae="SYM";var _e=Object.freeze({__proto__:null,ALPHANUMERICAL:I,AMPERSAND:X,APOSTROPHE:Q,ASCIINUMERICAL:v,ASTERISK:Z,AT:ee,BACKSLASH:te,BACKTICK:se,CARET:ne,CLOSEANGLEBRACKET:U,CLOSEBRACE:O,CLOSEBRACKET:W,CLOSEPAREN:M,COLON:re,COMMA:oe,DOLLAR:ae,DOT:ie,EMOJI:ke,EQUALS:ce,EXCLAMATION:le,FULLWIDTHGREATERTHAN:Y,FULLWIDTHLEFTPAREN:J,FULLWIDTHLESSTHAN:G,FULLWIDTHMIDDLEDOT:ye,FULLWIDTHRIGHTPAREN:F,HYPHEN:de,LEFTCORNERBRACKET:B,LEFTWHITECORNERBRACKET:z,LOCALHOST:C,NL:j,NUM:N,OPENANGLEBRACKET:K,OPENBRACE:H,OPENBRACKET:L,OPENPAREN:$,PERCENT:ue,PIPE:he,PLUS:me,POUND:ge,QUERY:pe,QUOTE:fe,RIGHTCORNERBRACKET:V,RIGHTWHITECORNERBRACKET:q,SCHEME:x,SEMI:we,SLASH:Se,SLASH_SCHEME:P,SYM:Ae,TILDE:Ee,TLD:R,UNDERSCORE:be,UTLD:T,UWORD:_,WORD:A,WS:D});const ve=/[a-z]/,Ie=/\p{L}/u,Ce=/\p{Emoji}/u,Re=/\d/,Te=/\s/;let xe=null,Pe=null;function Ne(e,t){const s=function(e){const t=[],s=e.length;let n=0;for(;n<s;){let r,o=e.charCodeAt(n),a=o<55296||o>56319||n+1===s||(r=e.charCodeAt(n+1))<56320||r>57343?e[n]:e.slice(n,n+2);t.push(a),n+=a.length}return t}(t.replace(/[A-Z]/g,e=>e.toLowerCase())),n=s.length,r=[];let o=0,a=0;for(;a<n;){let i=e,c=null,l=0,d=null,u=-1,h=-1;for(;a<n&&(c=i.go(s[a]));)i=c,i.accepts()?(u=0,h=0,d=i):u>=0&&(u+=s[a].length,h++),l+=s[a].length,o+=s[a].length,a++;o-=u,a-=h,l-=u,r.push({t:d.t,v:t.slice(o-l,o),s:o-l,e:o})}return r}function De(e,t,s,n,r){let o;const a=t.length;for(let s=0;s<a-1;s++){const a=t[s];e.j[a]?o=e.j[a]:(o=new w(n),o.jr=r.slice(),e.j[a]=o),e=o}return o=new w(s),o.jr=r.slice(),e.j[t[a-1]]=o,o}function je(e){const t=[],s=[];let n=0;for(;n<e.length;){let r=0;for(;"0123456789".indexOf(e[n+r])>=0;)r++;if(r>0){t.push(s.join(""));for(let t=parseInt(e.substring(n,n+r),10);t>0;t--)s.pop();n+=r}else s.push(e[n]),n++}return t}const He={defaultProtocol:"http",events:null,format:Le,formatHref:Le,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Oe(e,t=null){let s=Object.assign({},He);e&&(s=Object.assign(s,e instanceof Oe?e.o:e));const n=s.ignoreTags,r=[];for(let e=0;e<n.length;e++)r.push(n[e].toUpperCase());this.o=s,t&&(this.defaultRender=t),this.ignoreTags=r}function Le(e){return e}function We(e,t){this.t="token",this.v=e,this.tk=t}function $e(e,t){class s extends We{constructor(t,s){super(t,s),this.t=e}}for(const e in t)s.prototype[e]=t[e];return s.t=e,s}Oe.prototype={o:He,ignoreTags:[],defaultRender:e=>e,check(e){return this.get("validate",e.toString(),e)},get(e,t,s){const n=null!=t;let r=this.o[e];return r?("object"==typeof r?(r=s.t in r?r[s.t]:He[e],"function"==typeof r&&n&&(r=r(t,s))):"function"==typeof r&&n&&(r=r(t,s.t,s)),r):r},getObj(e,t,s){let n=this.o[e];return"function"==typeof n&&null!=t&&(n=n(t,s.t,s)),n},render(e){const t=e.render(this);return(this.get("render",null,e)||this.defaultRender)(t,e.t,e)}},We.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){const t=this.toString(),s=e.get("truncate",t,this),n=e.get("format",t,this);return s&&n.length>s?n.substring(0,s)+"…":n},toFormattedHref(e){return e.get("formatHref",this.toHref(e.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=He.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get("validate",this.toString(),this)},render(e){const t=this,s=this.toHref(e.get("defaultProtocol")),n=e.get("formatHref",s,this),r=e.get("tagName",s,t),o=this.toFormattedString(e),a={},i=e.get("className",s,t),c=e.get("target",s,t),l=e.get("rel",s,t),d=e.getObj("attributes",s,t),u=e.getObj("events",s,t);return a.href=n,i&&(a.class=i),c&&(a.target=c),l&&(a.rel=l),d&&Object.assign(a,d),{tagName:r,attributes:a,content:o,eventListeners:u}}};const Me=$e("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Ke=$e("text"),Ue=$e("nl"),Je=$e("url",{isLink:!0,toHref(e=He.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){const e=this.tk;return e.length>=2&&e[0].t!==C&&e[1].t===re}}),Fe=e=>new w(e);function Be(e,t,s){const n=s[0].s,r=s[s.length-1].e;return new e(t.slice(n,r),s)}"undefined"!=typeof console&&console&&console.warn;const Ve={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function ze(e){return Ve.initialized||function(){Ve.scanner=function(e=[]){const t={};w.groups=t;const s=new w;null==xe&&(xe=je("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==Pe&&(Pe=je("ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2")),k(s,"'",Q),k(s,"{",H),k(s,"}",O),k(s,"[",L),k(s,"]",W),k(s,"(",$),k(s,")",M),k(s,"<",K),k(s,">",U),k(s,"(",J),k(s,")",F),k(s,"「",B),k(s,"」",V),k(s,"『",z),k(s,"』",q),k(s,"<",G),k(s,">",Y),k(s,"&",X),k(s,"*",Z),k(s,"@",ee),k(s,"`",se),k(s,"^",ne),k(s,":",re),k(s,",",oe),k(s,"$",ae),k(s,".",ie),k(s,"=",ce),k(s,"!",le),k(s,"-",de),k(s,"%",ue),k(s,"|",he),k(s,"+",me),k(s,"#",ge),k(s,"?",pe),k(s,'"',fe),k(s,"/",Se),k(s,";",we),k(s,"~",Ee),k(s,"_",be),k(s,"\\",te),k(s,"・",ye);const n=E(s,Re,N,{[a]:!0});E(n,Re,n);const r=E(n,ve,v,{[l]:!0}),o=E(n,Ie,I,{[d]:!0}),f=E(s,ve,A,{[i]:!0});E(f,Re,r),E(f,ve,f),E(r,Re,r),E(r,ve,r);const S=E(s,Ie,_,{[c]:!0});E(S,ve),E(S,Re,o),E(S,Ie,S),E(o,Re,o),E(o,ve),E(o,Ie,o);const Ne=k(s,"\n",j,{[p]:!0}),He=k(s,"\r",D,{[p]:!0}),Oe=E(s,Te,D,{[p]:!0});k(s,"",Oe),k(He,"\n",Ne),k(He,"",Oe),E(He,Te,Oe),k(Oe,"\r"),k(Oe,"\n"),E(Oe,Te,Oe),k(Oe,"",Oe);const Le=E(s,Ce,ke,{[h]:!0});k(Le,"#"),E(Le,Ce,Le),k(Le,"️",Le);const We=k(Le,"");k(We,"#"),E(We,Ce,Le);const $e=[[ve,f],[Re,r]],Me=[[ve,null],[Ie,S],[Re,o]];for(let e=0;e<xe.length;e++)De(s,xe[e],R,A,$e);for(let e=0;e<Pe.length;e++)De(s,Pe[e],T,_,Me);y(R,{tld:!0,ascii:!0},t),y(T,{utld:!0,alpha:!0},t),De(s,"file",x,A,$e),De(s,"mailto",x,A,$e),De(s,"http",P,A,$e),De(s,"https",P,A,$e),De(s,"ftp",P,A,$e),De(s,"ftps",P,A,$e),y(x,{scheme:!0,ascii:!0},t),y(P,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){const n=e[t][0],r=e[t][1]?{[m]:!0}:{[g]:!0};n.indexOf("-")>=0?r[u]=!0:ve.test(n)?Re.test(n)?r[l]=!0:r[i]=!0:r[a]=!0,b(s,n,n,r)}return b(s,"localhost",C,{ascii:!0}),s.jd=new w(Ae),{start:s,tokens:Object.assign({groups:t},_e)}}(Ve.customSchemes);for(let e=0;e<Ve.tokenQueue.length;e++)Ve.tokenQueue[e][1]({scanner:Ve.scanner});Ve.parser=function({groups:e}){const t=e.domain.concat([X,Z,ee,te,se,ne,ae,ce,de,N,ue,he,me,ge,Se,Ae,Ee,be]),s=[Q,re,oe,ie,le,ue,pe,fe,we,K,U,H,O,W,L,$,M,J,F,B,V,z,q,G,Y],n=[X,Q,Z,te,se,ne,ae,ce,de,H,O,ue,he,me,ge,pe,Se,Ae,Ee,be],r=Fe(),o=k(r,Ee);S(o,n,o),S(o,e.domain,o);const a=Fe(),i=Fe(),c=Fe();S(r,e.domain,a),S(r,e.scheme,i),S(r,e.slashscheme,c),S(a,n,o),S(a,e.domain,a);const l=k(a,ee);k(o,ee,l),k(i,ee,l),k(c,ee,l);const d=k(o,ie);S(d,n,o),S(d,e.domain,o);const u=Fe();S(l,e.domain,u),S(u,e.domain,u);const h=k(u,ie);S(h,e.domain,u);const m=Fe(Me);S(h,e.tld,m),S(h,e.utld,m),k(l,C,m);const g=k(u,de);k(g,de,g),S(g,e.domain,u),S(m,e.domain,u),k(m,ie,h),k(m,de,g);const p=k(m,re);S(p,e.numeric,Me);const f=k(a,de),y=k(a,ie);k(f,de,f),S(f,e.domain,a),S(y,n,o),S(y,e.domain,a);const w=Fe(Je);S(y,e.tld,w),S(y,e.utld,w),S(w,e.domain,a),S(w,n,o),k(w,ie,y),k(w,de,f),k(w,ee,l);const E=k(w,re),b=Fe(Je);S(E,e.numeric,b);const A=Fe(Je),_=Fe();S(A,t,A),S(A,s,_),S(_,t,A),S(_,s,_),k(w,Se,A),k(b,Se,A);const v=k(i,re),I=k(c,re),R=k(I,Se),T=k(R,Se);S(i,e.domain,a),k(i,ie,y),k(i,de,f),S(c,e.domain,a),k(c,ie,y),k(c,de,f),S(v,e.domain,A),k(v,Se,A),k(v,pe,A),S(T,e.domain,A),S(T,t,A),k(T,Se,A);const x=[[H,O],[L,W],[$,M],[K,U],[J,F],[B,V],[z,q],[G,Y]];for(let e=0;e<x.length;e++){const[n,r]=x[e],o=k(A,n);k(_,n,o),k(o,r,A);const a=Fe(Je);S(o,t,a);const i=Fe();S(o,s),S(a,t,a),S(a,s,i),S(i,t,a),S(i,s,i),k(a,r,A),k(i,r,A)}return k(r,C,w),k(r,j,Ue),{start:r,tokens:_e}}(Ve.scanner.tokens);for(let e=0;e<Ve.pluginQueue.length;e++)Ve.pluginQueue[e][1]({scanner:Ve.scanner,parser:Ve.parser});Ve.initialized=!0}(),function(e,t,s){let n=s.length,r=0,o=[],a=[];for(;r<n;){let i=e,c=null,l=null,d=0,u=null,h=-1;for(;r<n&&!(c=i.go(s[r].t));)a.push(s[r++]);for(;r<n&&(l=c||i.go(s[r].t));)c=null,i=l,i.accepts()?(h=0,u=i):h>=0&&h++,r++,d++;if(h<0)r-=d,r<n&&(a.push(s[r]),r++);else{a.length>0&&(o.push(Be(Ke,t,a)),a=[]),r-=h,d-=h;const e=u.t,n=s.slice(r-d,r);o.push(Be(e,t,n))}}return a.length>0&&o.push(Be(Ke,t,a)),o}(Ve.parser.start,e,Ne(Ve.scanner.start,e))}function qe(e,t,s){if(0===o.Children.count(e.props.children))return e;const n=[];o.Children.forEach(e.props.children,e=>{"string"==typeof e?n.push.apply(n,function(e,t,s){const n=ze(e),r=[];for(let e=0;e<n.length;e++){const a=n[e];if("nl"===a.t&&t.get("nl2br")){const e="__linkify-el-"+s.elementId++;r.push(o.createElement("br",{key:e}))}else if(a.isLink&&t.check(a)){let e=t.render(a);if(!("key"in e.props)){const t="__linkify-el-"+s.elementId++,n=Object.assign({key:t},e.props);e=o.cloneElement(e,n)}r.push(e)}else r.push(a.toString())}return r}(e,t,s)):o.isValidElement(e)?"string"==typeof e.type&&t.ignoreTags.indexOf(e.type.toUpperCase())>=0?n.push(e):n.push(qe(e,t,s)):n.push(e)});const r="__linkify-el-"+s.elementId++,a=Object.assign({key:r},e.props);return o.cloneElement(e,a,n)}ze.scan=Ne;const Ge=e=>{let t=0;const s={key:"__linkify-wrapper"};for(const t in e)"options"!==t&&"as"!==t&&"tagName"!==t&&"children"!==t&&(s[t]=e[t]);const n=new Oe(e.options,({tagName:e,attributes:s,content:n})=>(s.key="__linkify-lnk-"+t++,s.class&&(s.className=s.class,delete s.class),o.createElement(e,s,n))),r=e.as||e.tagName||o.Fragment||"span",a=e.children;return qe(o.createElement(r,s,a),n,{elementId:0})},Ye=crypto,Xe=e=>e instanceof CryptoKey;class Qe extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Qe.code="ERR_JOSE_GENERIC",class extends Qe{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=s,this.reason=n,this.payload=t}}.code="ERR_JWT_CLAIM_VALIDATION_FAILED",class extends Qe{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=s,this.reason=n,this.payload=t}}.code="ERR_JWT_EXPIRED",class extends Qe{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}.code="ERR_JOSE_ALG_NOT_ALLOWED";class Ze extends Qe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}Ze.code="ERR_JOSE_NOT_SUPPORTED",class extends Qe{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}.code="ERR_JWE_DECRYPTION_FAILED",class extends Qe{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}.code="ERR_JWE_INVALID";class et extends Qe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}et.code="ERR_JWS_INVALID";class tt extends Qe{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}tt.code="ERR_JWT_INVALID",class extends Qe{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}.code="ERR_JWK_INVALID",class extends Qe{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}.code="ERR_JWKS_INVALID",class extends Qe{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}.code="ERR_JWKS_NO_MATCHING_KEY",Symbol.asyncIterator,class extends Qe{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",class extends Qe{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}.code="ERR_JWKS_TIMEOUT",class extends Qe{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const st=(e,t,s=0)=>{0===s&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],s);if(-1===n)return!1;const r=e.subarray(n,n+t.length);return r.length===t.length&&(r.every((e,s)=>e===t[s])||st(e,t,n+1))},nt=e=>{switch(!0){case st(e,[42,134,72,206,61,3,1,7]):return"P-256";case st(e,[43,129,4,0,34]):return"P-384";case st(e,[43,129,4,0,35]):return"P-521";case st(e,[43,101,110]):return"X25519";case st(e,[43,101,111]):return"X448";case st(e,[43,101,112]):return"Ed25519";case st(e,[43,101,113]):return"Ed448";default:throw new Ze("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},rt=(e,t,s)=>(async(e,t,s,n,r)=>{let o,a;const i=new Uint8Array(atob(s.replace(e,"")).split("").map(e=>e.charCodeAt(0))),c="spki"===t;switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=nt(i);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=c?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},a=c?["verify"]:["sign"];break;case"EdDSA":o={name:nt(i)},a=c?["verify"]:["sign"];break;default:throw new Ze('Invalid or unsupported "alg" (Algorithm) value')}return Ye.subtle.importKey(t,i,o,r?.extractable??!1,a)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,s),ot=new TextEncoder,at=new TextDecoder;const it=e=>(e=>{let t=e;"string"==typeof t&&(t=ot.encode(t));const s=[];for(let e=0;e<t.length;e+=32768)s.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(s.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),ct=e=>{let t=e;t instanceof Uint8Array&&(t=at.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};function lt(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function dt(e,t){return e.name===t}function ut(e){return parseInt(e.name.slice(4),10)}function ht(e,t,...s){switch(t){case"HS256":case"HS384":case"HS512":{if(!dt(e.algorithm,"HMAC"))throw lt("HMAC");const s=parseInt(t.slice(2),10);if(ut(e.algorithm.hash)!==s)throw lt(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!dt(e.algorithm,"RSASSA-PKCS1-v1_5"))throw lt("RSASSA-PKCS1-v1_5");const s=parseInt(t.slice(2),10);if(ut(e.algorithm.hash)!==s)throw lt(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!dt(e.algorithm,"RSA-PSS"))throw lt("RSA-PSS");const s=parseInt(t.slice(2),10);if(ut(e.algorithm.hash)!==s)throw lt(`SHA-${s}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw lt("Ed25519 or Ed448");break;case"Ed25519":if(!dt(e.algorithm,"Ed25519"))throw lt("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!dt(e.algorithm,"ECDSA"))throw lt("ECDSA");const s=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==s)throw lt(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const s=t.pop();e+=`one of ${t.join(", ")}, or ${s}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,s)}function mt(e,t,...s){if((s=s.filter(Boolean)).length>2){const t=s.pop();e+=`one of type ${s.join(", ")}, or ${t}.`}else 2===s.length?e+=`one of type ${s[0]} or ${s[1]}.`:e+=`of type ${s[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const gt=(e,...t)=>mt("Key must be ",e,...t);function pt(e,t,...s){return mt(`Key for the ${e} algorithm must be `,t,...s)}const ft=e=>!!Xe(e)||"KeyObject"===e?.[Symbol.toStringTag],yt=["CryptoKey"];function wt(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let s=e;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(e)===s}function St(e){return wt(e)&&"string"==typeof e.kty}const Et=e=>ct(e);let bt;const kt=e=>"KeyObject"===e?.[Symbol.toStringTag],At=async(e,t,s,n,r=!1)=>{let o=e.get(t);if(o?.[n])return o[n];const a=await(async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:s}=function(e){let t,s;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},s=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Ze('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},s=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},s=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new Ze('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},s=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new Ze('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new Ze('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:s}}(e),n=[t,e.ext??!1,e.key_ops??s],r={...e};return delete r.alg,delete r.use,Ye.subtle.importKey("jwk",r,...n)})({...s,alg:n});return r&&Object.freeze(t),o?o[n]=a:e.set(t,{[n]:a}),a},_t=async(e,t,s)=>{const n=await async function(e,t,s){if(t=await((e,t)=>{if(kt(e)){let s=e.export({format:"jwk"});return s.k?Et(s.k):(bt||(bt=new WeakMap),At(bt,e,s,t))}return St(e)?e.k?ct(e.k):(bt||(bt=new WeakMap),At(bt,e,e,t,!0)):e})(t,e),Xe(t))return ht(t,e,s),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(gt(t,...yt));return Ye.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(gt(t,...yt,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:s}=t.algorithm;if("number"!=typeof s||s<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,n);const r=await Ye.subtle.sign(function(e,t){const s=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new Ze(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,s);return new Uint8Array(r)},vt=e=>e?.[Symbol.toStringTag],It=(e,t,s)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(s))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function Ct(e,t,s,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,s,n)=>{if(!(t instanceof Uint8Array)){if(n&&St(t)){if(function(e){return St(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&It(e,t,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ft(t))throw new TypeError(pt(e,t,...yt,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${vt(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,s,n,e):((e,t,s,n)=>{if(n&&St(t))switch(s){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&It(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&It(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ft(t))throw new TypeError(pt(e,t,...yt,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===s&&"public"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===s&&"public"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===s&&"private"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===s&&"private"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,s,n,e)}Ct.bind(void 0,!1);const Rt=Ct.bind(void 0,!0);class Tt{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new et("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let s;for(const e of t){const t=Object.keys(e);if(s&&0!==s.size)for(const e of t){if(s.has(e))return!1;s.add(e)}else s=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new et("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(function(e,t,s,n,r){if(void 0!==r.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==s?new Map([...Object.entries(s),...t.entries()]):t;for(const t of n.crit){if(!o.has(t))throw new Ze(`Extension Header Parameter "${t}" is not recognized`);if(void 0===r[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(et,new Map([["b64",!0]]),t?.crit,this._protectedHeader,s).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new et('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:r}=s;if("string"!=typeof r||!r)throw new et('JWS "alg" (Algorithm) Header Parameter missing or invalid');Rt(r,e,"sign");let o,a=this._payload;n&&(a=ot.encode(it(a))),o=this._protectedHeader?ot.encode(it(JSON.stringify(this._protectedHeader))):ot.encode("");const i=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}(o,ot.encode("."),a),c=await _t(r,e,i),l={signature:it(c),payload:""};return n&&(l.payload=at.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=at.decode(o)),l}}class xt{constructor(e){this._flattened=new Tt(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const s=await this._flattened.sign(e,t);if(void 0===s.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${s.protected}.${s.payload}.${s.signature}`}}const Pt=e=>Math.floor(e.getTime()/1e3),Nt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Dt=e=>{const t=Nt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const s=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*s);break;case"day":case"days":case"d":n=Math.round(86400*s);break;case"week":case"weeks":case"w":n=Math.round(604800*s);break;default:n=Math.round(31557600*s)}return"-"===t[1]||"ago"===t[4]?-n:n};function jt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ht{constructor(e={}){if(!wt(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:jt("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:jt("setNotBefore",Pt(e))}:this._payload={...this._payload,nbf:Pt(new Date)+Dt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:jt("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:jt("setExpirationTime",Pt(e))}:this._payload={...this._payload,exp:Pt(new Date)+Dt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Pt(new Date)}:e instanceof Date?this._payload={...this._payload,iat:jt("setIssuedAt",Pt(e))}:this._payload="string"==typeof e?{...this._payload,iat:jt("setIssuedAt",Pt(new Date)+Dt(e))}:{...this._payload,iat:jt("setIssuedAt",e)},this}}class Ot extends Ht{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const s=new xt(ot.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new tt("JWTs MUST NOT use unencoded payload");return s.sign(e,t)}}async function Lt(e){if(e.accessToken)return e.accessToken;if(!e.serviceAccountKey)throw new Error("Either serviceAccountKey or accessToken must be provided");return await async function(e){const t=Math.floor(Date.now()/1e3);let s=e.private_key;if(!s)throw new Error("Private key is missing from service account key");if(s=s.trim(),s.includes("-----BEGIN")){if(s=s.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),s.includes("BEGIN RSA PRIVATE KEY"))throw new Error("Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY).");const e=s.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);if(e){const t=e[1].replace(/\s/g,"");(!t.includes("\n")||t.length>64)&&(s=`-----BEGIN PRIVATE KEY-----\n${t.match(/.{1,64}/g)?.join("\n")||t}\n-----END PRIVATE KEY-----`)}}else{const e=s.replace(/\s/g,"");s=`-----BEGIN PRIVATE KEY-----\n${e.match(/.{1,64}/g)?.join("\n")||e}\n-----END PRIVATE KEY-----`}try{const n=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return rt(e,"RS256",void 0)}(s),r=await new Ot({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuedAt(t).setExpirationTime(t+3600).setIssuer(e.client_email).setSubject(e.client_email).setAudience("https://oauth2.googleapis.com/token").sign(n),o=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:r})});if(!o.ok){const e=await o.json();throw new Error(e.error_description||"Failed to get access token")}return(await o.json()).access_token}catch(e){if(e.message&&e.message.includes("pkcs8"))throw new Error("Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format.");throw e}}(e.serviceAccountKey)}function Wt(e,t,s,n){return`projects/${e}/locations/${t}/agents/${s}/sessions/${n}`}function $t(e){let t=null;for(const s of e)if(s.payload){if(s.payload.richContent){t=s.payload.richContent;break}if(s.payload.fields&&s.payload.fields.richContent){const e=s.payload.fields.richContent;e.listValue&&e.listValue.values?t=e.listValue.values.map(e=>e.listValue&&e.listValue.values?e.listValue.values.map(e=>{if(e.structValue&&e.structValue.fields){const t=e.structValue.fields;if(t.type&&t.options)return{type:t.type.stringValue||t.type,options:t.options.listValue?t.options.listValue.values.map(e=>({text:e.structValue?.fields?.text?.stringValue||"",payload:e.structValue?.fields?.payload?.stringValue||""})):[]}}return e}):e):"object"!=typeof e||e.listValue||(t=e);break}}return t}const Mt="blockspark_chat_mode",Kt="blockspark_chat_id",Ut="blockspark_session_id",Jt="chat_session_id";class Ft{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(Jt):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(Jt,e):localStorage.removeItem(Jt))}updateSessionFromResponse(e){const t=e?.data?.session_id||e?.session_id;t&&"string"==typeof t&&this.saveSessionId(t)}getSessionId(){return this.sessionId||""}getSessionHeader(){return{"X-Session-ID":this.getSessionId()}}}let Bt=null;class Vt extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}const zt="undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_BASE_URL,qt="undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_WS_URL;class Gt{constructor(e={}){this.ws=null,this.wsReconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=null,this.pingInterval=null,this.currentChatId=null,this.currentSessionId=null,this.messageHandlers=new Set,this.connectionHandlers=new Set,this.baseUrl=e.baseUrl||zt,this.wsUrl=e.wsUrl||qt,this.debug=e.debug||!1,this.sessionManager=(Bt||(Bt=new Ft),Bt)}async startSupportChat(e,t,s,n){try{const r={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(r["X-Session-ID"]=e);const o={};t&&(o.name=t),s&&(o.email=s),n&&(o.mobile=n);const a=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:r,body:JSON.stringify(o)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${a.status}`)}const i=await a.json();if(this.sessionManager.updateSessionFromResponse(i),i.status&&i.data)return{chat_id:i.data.chat_id,session_id:i.data.session_id};if(i.chat_id&&i.session_id)return{chat_id:i.chat_id,session_id:i.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(e){throw console.error("Error starting support chat:",e),new Error(e.message||"Failed to start support chat session")}}async requestHandoff(e,t,s,n,r,o,a){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const i={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?i["X-Session-ID"]=t:n&&(i["X-Session-ID"]=n);const c={};s&&(c.reason=s),r&&(c.name=r),o&&(c.email=o),a&&(c.mobile=a);const l=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:i,body:JSON.stringify(c)});if(400===l.status||404===l.status){const e=await l.json().catch(()=>({}));throw new Error(e.message||"Invalid chat_id. Chat may have expired.")}if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${l.status}`)}const d=await l.json();return this.sessionManager.updateSessionFromResponse(d),d.status?{success:!0,message:d.message||d.data?.message}:{success:!0,message:d.message}}catch(e){throw console.error("Error requesting handoff:",e),e}}async sendMessageToAgent(e,t,s){try{const n={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:n,body:JSON.stringify({content:s})});if(401===r.status||404===r.status){const e=await r.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${r.status}`)}const o=await r.json();if(this.sessionManager.updateSessionFromResponse(o),!0===o?.ignored&&"chat_resolved"===o?.reason)throw new Vt;return{id:o.id,sender_type:"customer",content:s,timestamp:o.timestamp||(new Date).toISOString()}}catch(e){if(e instanceof Vt||"ChatResolvedError"===e?.name)throw e;throw console.error("Error sending message to agent:",e),new Error(e.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,s,n,r,o){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(s||null,n||null,r||null,o||null)}async loadMessageHistory(e,t){try{const s={...this.sessionManager.getSessionHeader()};t&&(s["X-Session-ID"]=t);const n=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:s});if(401===n.status||404===n.status){const e=await n.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${n.status}`)}const r=await n.json();return this.sessionManager.updateSessionFromResponse(r),r.messages||[]}catch(e){throw console.error("Error loading message history:",e),new Error(e.message||"Failed to load message history")}}connectWebSocket(e,t,s,n,r){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&this.ws.readyState===WebSocket.OPEN)return void(this.debug&&console.log("WebSocket already connected"));this.currentChatId=e,this.currentSessionId=t,s&&this.messageHandlers.add(s),n&&this.connectionHandlers.add(n);const o=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(o)}`;try{this.ws=new WebSocket(a),this.ws.onopen=()=>{this.debug&&console.log("WebSocket connected to:",a),console.log("✅ Customer WebSocket connected:",{chatId:e,sessionId:t,wsUrl:a}),this.wsReconnectAttempts=0,this.connectionHandlers.forEach(e=>e(!0)),this.startPingInterval()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);if(this.debug&&(console.log("WebSocket raw message received:",e.data),console.log("WebSocket parsed message:",t)),t.session_id&&this.sessionManager.updateSessionFromResponse({session_id:t.session_id}),"agent_accepted"!==t.type&&"chat_resolved"!==t.type&&"chat_ended"!==t.type||console.log("🔔 Received notification message:",{type:t.type,chat_id:t.chat_id,timestamp:t.timestamp,to_agent:t.to_agent,to_agent_id:t.to_agent_id}),"pong"===t.type)return;this.debug&&"message"===t.type&&console.log("Processing message type:",{type:t.type,sender_type:t.sender_type,content:t.content?.substring(0,50)+"...",id:t.id}),this.messageHandlers.forEach(e=>e(t))}catch(t){console.error("Error parsing WebSocket message:",t),this.debug&&console.error("Raw message data:",e.data)}},this.ws.onerror=e=>{console.error("❌ WebSocket error:",e),this.connectionHandlers.forEach(e=>e(!1))},this.ws.onclose=t=>{if(this.debug&&console.log("WebSocket closed:",t.code,t.reason),console.log("🔌 Customer WebSocket closed:",{code:t.code,reason:t.reason,chatId:e}),this.stopPingInterval(),this.connectionHandlers.forEach(e=>e(!1)),this.ws=null,r?.(t),4e3===t.code)return this.wsReconnectAttempts=this.maxReconnectAttempts,this.currentChatId=null,void(this.currentSessionId=null);if(this.wsReconnectAttempts<this.maxReconnectAttempts&&this.currentChatId&&this.currentSessionId){this.wsReconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.wsReconnectAttempts),3e4);this.debug&&console.log(`Reconnecting in ${e}ms (attempt ${this.wsReconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.currentChatId&&this.currentSessionId&&this.connectWebSocket(this.currentChatId,this.currentSessionId,s,n,r)},e)}else this.debug&&console.error("Max reconnection attempts reached")}}catch(e){console.error("Error creating WebSocket connection:",e),this.connectionHandlers.forEach(e=>e(!1))}}sendMessageViaWebSocket(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:"message",content:e})),!0}catch(e){return console.error("Error sending message via WebSocket:",e),!1}}sendTypingIndicator(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:e})),!0}catch(t){return console.error(`Error sending ${e} via WebSocket:`,t),!1}}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"ping"}))}catch(e){console.error("Error sending ping:",e)}},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}disconnectWebSocket(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopPingInterval(),this.ws&&(this.ws.close(),this.ws=null),this.messageHandlers.clear(),this.connectionHandlers.clear(),this.wsReconnectAttempts=0,this.currentChatId=null,this.currentSessionId=null}isWebSocketConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}removeMessageHandler(e){this.messageHandlers.delete(e)}removeConnectionHandler(e){this.connectionHandlers.delete(e)}}function Yt({title:e="💬 BlockSpark AI Assistant",subtitle:t="We're here to help",welcomeTitle:s="👋 Welcome to Blockspark",welcomeMessage:n="My name is BlockSpark AI Assistant and I'll guide you.",welcomeCta:a="💬 Click here to start chatting!",showWelcomePopup:i=!0,welcomePopupDelay:c=1500,fallbackWelcomeMessage:l="Hello! I'm BlockSpark AI Assistant. How can I help you today?",inputPlaceholder:d="Type your message...",emptyStateMessage:u="Hi! I'm BlockSpark AI Assistant. How can I help you today?",debug:h=!1,dfProjectId:m,dfLocation:g="us-central1",dfAgentId:p,serviceAccountKey:f,accessToken:y,languageCode:w="en",backendBaseUrl:S,backendWsUrl:E}){const[b,k]=(0,o.useState)(!1),[A,_]=(0,o.useState)(!1),[v,I]=(0,o.useState)([]),[C,R]=(0,o.useState)(""),[T,x]=(0,o.useState)(!1),[P,N]=(0,o.useState)(null),[D,j]=(0,o.useState)(!1),[H,O]=(0,o.useState)(!1),[L,W]=(0,o.useState)(!1),[$,M]=(0,o.useState)(!1),[K,U]=(0,o.useState)({name:"Agent"}),[J,F]=(0,o.useState)(!1),[B,V]=(0,o.useState)(!1),[z,q]=(0,o.useState)(!1),[G,Y]=(0,o.useState)(!1),[X,Q]=(0,o.useState)(null),[Z,ee]=(0,o.useState)(""),[te,se]=(0,o.useState)(""),[ne,re]=(0,o.useState)(""),oe=(0,o.useRef)(""),ae=(0,o.useRef)(null),ie=(0,o.useRef)(null),ce=(0,o.useRef)(null),le=(0,o.useRef)((de={baseUrl:S||"undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_BASE_URL,wsUrl:E||"undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_WS_URL,debug:h},new Gt(de)));var de;const ue=(0,o.useRef)(null),{currentMode:he,switchToHumanMode:me,switchToBotMode:ge,chatId:pe,sessionId:fe,setChatId:ye,setSessionId:we}=function(){const[e,t]=(0,o.useState)(()=>"HUMAN"===localStorage.getItem(Mt)?"HUMAN":"BOT"),[s,n]=(0,o.useState)(()=>localStorage.getItem(Kt)),[r,a]=(0,o.useState)(()=>localStorage.getItem(Ut));(0,o.useEffect)(()=>{localStorage.setItem(Mt,e)},[e]);const i=(0,o.useCallback)(e=>{n(e),e?localStorage.setItem(Kt,e):localStorage.removeItem(Kt)},[]),c=(0,o.useCallback)(e=>{a(e),e?localStorage.setItem(Ut,e):localStorage.removeItem(Ut)},[]),l=(0,o.useCallback)(()=>{t("HUMAN")},[]),d=(0,o.useCallback)(()=>{t("BOT")},[]),u=(0,o.useCallback)(e=>!1,[]);return{currentMode:e,switchToHumanMode:l,switchToBotMode:d,isHandoffTriggered:u,chatId:s,sessionId:r,setChatId:i,setSessionId:c}}(),Se=(0,o.useCallback)(e=>{V(!0),O(!1),Y(!1),M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null),le.current.disconnectWebSocket(),ye(null),we(null);const t={id:`resolved-${Date.now()}`,text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};I(e=>[...e,t]),setTimeout(()=>{ge(),V(!1),I([]),F(!1),Q(null),ee(""),se(""),re(""),oe.current="",Ie().catch(console.error)},2e3)},[ye,we,ge]),Ee=((0,o.useCallback)(async()=>{if(!z){q(!0);try{const e=oe.current||Z||null,t=te||null,s=ne||null,n=await le.current.startSupportChat(P||null,e,t,s);me(),ye(n.chat_id),we(n.session_id),V(!1),R("")}catch(e){console.error("Error starting new chat:",e),I(t=>[...t,{id:`error-new-chat-${Date.now()}`,text:h?`Error: ${e?.message||"Failed to start a new chat."}`:"Sorry, I couldn't start a new chat. Please try again.",sender:"bot",timestamp:new Date}])}finally{q(!1)}}},[te,ne,Z,h,z,P,ye,we,me]),()=>{if(m&&p)return{dfProjectId:m,dfLocation:g||"us-central1",dfAgentId:p,serviceAccountKey:f,accessToken:y,languageCode:w||"en"}});(0,o.useEffect)(()=>{if(!i)return;const e=setTimeout(()=>{_(!0)},c);return()=>clearTimeout(e)},[i,c]),(0,o.useEffect)(()=>{ae.current?.scrollIntoView({behavior:"smooth"})},[v]);const be=(0,o.useCallback)(e=>{if(e.to_agent){U({id:e.to_agent_id,name:e.to_agent});const t={id:`system-${Date.now()}`,text:e.from_agent?`Chat has been transferred from ${e.from_agent} to ${e.to_agent}`:`Chat has been transferred to ${e.to_agent}`,sender:"bot",timestamp:new Date};I(e=>[...e,t]),h&&console.log("Agent changed:",{from:e.from_agent,to:e.to_agent,reason:e.reason})}},[h]),ke=(0,o.useCallback)(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)h&&"customer"===e.sender_type&&console.log("Ignoring customer message from WebSocket (already added)");else{const t={id:e.id||`agent-${Date.now()}`,text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null)}else h&&console.warn("WebSocket message received without content:",e);break;case"typing_start":"agent"===e.sender_type&&(M(!0),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{M(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null));break;case"agent_changed":be(e);break;case"chat_info":h&&console.log("Chat info:",e),"active"===e.status?(O(!1),Y(!0)):"resolved"!==e.status&&"ended"!==e.status||Se(e.chat_id||null),e.agent_id&&U(t=>({...t,id:e.agent_id}));break;case"agent_accepted":Y(!0),O(!1);const t={id:e.id||`agent-accepted-${e.chat_id||Date.now()}-${Date.now()}`,text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&U({name:e.to_agent,id:e.to_agent_id}),h&&console.log("Agent accepted chat:",e);break;case"chat_resolved":case"chat_ended":Se(e.chat_id||null),h&&console.log("Chat resolved/ended:",e);break;case"error":console.error("WebSocket error:",e.error);const s={id:`error-${Date.now()}`,text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,s]);break;case"pong":break;default:h&&console.log("Unknown message type:",e.type)}},[h,Se,be]),Ae=(0,o.useCallback)(e=>{4e3===e.code&&Se(pe)},[pe,Se]),_e=(0,o.useCallback)(e=>{W(e),e&&O(!1)},[]);(0,o.useEffect)(()=>{if("HUMAN"===he&&pe&&fe)return le.current.connectWebSocket(pe,fe,ke,_e,Ae),()=>{le.current.disconnectWebSocket()}},[he,pe,fe,ke,_e,Ae]);const ve=(0,o.useCallback)(async(e=!0)=>{if(pe&&fe)try{x(!0);const t=(await le.current.loadMessageHistory(pe,fe)).map(e=>({id:e.id||`msg-${Date.now()}-${Math.random()}`,text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));I(e?e=>{const s=new Set(e.map(e=>e.id)),n=t.filter(e=>!s.has(e.id));return[...e,...n].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(e){if(console.error("Error loading message history:",e),h){const t={id:`error-${Date.now()}`,text:`Failed to load chat history: ${e.message}`,sender:"bot",timestamp:new Date};I(e=>[...e,t])}}finally{x(!1)}},[pe,fe,h]);(0,o.useEffect)(()=>{if("HUMAN"===he&&pe&&fe){const e=`${pe}-${fe}`;ue.current!==e&&(ue.current=e,setTimeout(()=>{0===v.length&&ve(!1).catch(console.error)},0))}else"BOT"===he&&(ue.current=null)},[he,pe,fe,ve,v.length]);const Ie=async()=>{if(P)return P;try{j(!0);const e=Ee();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const t=await async function(e){try{const t=await Lt(e),s=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n=e.dfLocation.split(" ")[0].trim(),r=`https://${n}-dialogflow.googleapis.com/v3/${Wt(e.dfProjectId,n,e.dfAgentId,s)}:detectIntent`,o={queryInput:{text:{text:"hello"},languageCode:e.languageCode||"en"}},a=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error?.message||`HTTP error! status: ${a.status}`)}const i=await a.json();let c="Hello! I'm BlockSpark AI Assistant. How can I help you today?",l=null;if(i.queryResult?.responseMessages){const e=i.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(c=e.join(" ")),l=$t(i.queryResult.responseMessages)}else i.queryResult?.fulfillmentText&&(c=i.queryResult.fulfillmentText);return{session_id:s,message:c,...l&&{richContent:l}}}catch(e){console.error("Error creating Dialogflow session:",e);const t=e.message||"Failed to create session";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");throw new Error(t)}}(e);if(N(t.session_id),t.message){h&&(console.log("Session response richContent:",t.richContent),console.log("Full session response:",t));const e={id:`welcome-${Date.now()}`,text:t.message,sender:"bot",timestamp:new Date,richContent:t.richContent};I([e])}return t.session_id}catch(e){console.error("Error creating session:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,config:Ee()});const t={id:`error-${Date.now()}`,text:h?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:l,sender:"bot",timestamp:new Date};return I([t]),null}finally{j(!1)}},Ce=async(e,t,s=!1)=>{if(!e.trim())return;if(J){if("name"===X){const t=e.trim();ee(t),oe.current=t,Q("email");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return I(e=>[...e,n]),void R("")}if("email"===X){const t=e.trim();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){const e={id:(Date.now()+1).toString(),text:"Please provide a valid email address:",sender:"bot",timestamp:new Date};return I(t=>[...t,e]),void R("")}se(t),Q("mobile");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return I(e=>[...e,n]),void R("")}if("mobile"===X){const t=e.trim();if(!/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(t)||t.length<10){const e={id:(Date.now()+1).toString(),text:"Please provide a valid mobile number (e.g., +1234567890):",sender:"bot",timestamp:new Date};return I(t=>[...t,e]),void R("")}re(t);const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n=oe.current,r=te;return F(!1),Q(null),oe.current="",await(async(e,t,s)=>{try{O(!0);const n=P,r=await le.current.ensureChatInitialized(pe,fe,n||null,e||null,t||null,s||null);if(!r||!r.chat_id)throw new Error("Failed to initialize chat session");const o=r.chat_id,a=r.session_id;o!==pe&&(ye(o),we(a),h&&console.log("✅ Chat initialized:",{chatId:o,sessionId:a}));try{await le.current.requestHandoff(o,a,"Customer requested human agent",n||null,e||null,t||null,s||null),h&&console.log("✅ Handoff requested successfully")}catch(r){if(!(r.message?.includes("Invalid chat_id")||r.message?.includes("Chat not found")||r.message?.includes("unauthorized")||r.message?.includes("400")||r.message?.includes("401")||r.message?.includes("404")||r.message?.includes("expired")))throw r;{h&&console.log("⚠️ Chat expired or not found. Re-initializing chat..."),ye(null),we(null);const r=await le.current.startSupportChat(n||null,e||null,t||null,s||null);if(!r||!r.chat_id)throw new Error("Failed to re-initialize chat session");const o=r.chat_id,a=r.session_id;ye(o),we(a),await le.current.requestHandoff(o,a,"Customer requested human agent",n||null,e||null,t||null,s||null),h&&console.log("✅ Handoff requested successfully after retry");const i=`${o}-${a}`;ue.current!==i&&(ue.current=i,await ve(!0))}}me(),V(!1),Y(!1);const i={id:`connecting-${Date.now()}`,text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};I(e=>[...e,i]);const c=`${o}-${a}`;ue.current=c}catch(e){console.error("Error handling handoff:",e);const t={id:`error-${Date.now()}`,text:h?`Handoff error: ${e.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t]),O(!1)}})(n,r,t),void R("")}}if("HUMAN"===he){if(!pe||!fe){const e={id:Date.now().toString(),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}if(!s){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,s])}le.current.sendTypingIndicator("typing_stop"),ie.current&&(clearTimeout(ie.current),ie.current=null),R(""),x(!0);try{le.current.sendMessageViaWebSocket(e.trim())||await le.current.sendMessageToAgent(pe,fe,e.trim())}catch(t){if(t instanceof Vt||"ChatResolvedError"===t?.name||"chat_resolved"===t?.message)return void Se(pe);if(console.error("Error sending message to agent:",t),t.message?.includes("Chat not found")||t.message?.includes("unauthorized")||t.message?.includes("401")||t.message?.includes("404")){h&&console.log("⚠️ Chat expired. Re-initializing..."),ye(null),we(null);try{const t=await le.current.startSupportChat(P||null,null,null,null);ye(t.chat_id),we(t.session_id);try{await le.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(e){if(e instanceof Vt||"ChatResolvedError"===e?.name||"chat_resolved"===e?.message)return void Se(t.chat_id);throw e}return}catch(e){if(e instanceof Vt||"ChatResolvedError"===e?.name||"chat_resolved"===e?.message)return void Se(pe);const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t])}}else{const e={id:(Date.now()+1).toString(),text:h?`Error: ${t.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(t=>[...t,e])}}finally{x(!1)}return}let n=P;if(!n)try{if(n=await Ie(),!n){const e={id:Date.now().toString(),text:h?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}}catch(e){console.error("Error in createSession:",e);const t={id:Date.now().toString(),text:h?`Connection Error: ${e.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void I(e=>[...e,t])}if(!s){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,s])}R(""),x(!0);try{const t=Ee();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const s=await async function(e,t,s){try{const n=await Lt(s),r=s.dfLocation.split(" ")[0].trim(),o=`https://${r}-dialogflow.googleapis.com/v3/${Wt(s.dfProjectId,r,s.dfAgentId,t)}:detectIntent`,a={queryInput:{text:{text:e.trim()},languageCode:s.languageCode||"en"}},i=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const e=await i.text();let t={};try{t=JSON.parse(e)}catch{t={message:e||`HTTP ${i.status}`}}const s=t.error?.message||t.message||`HTTP error! status: ${i.status}`;throw console.error("Dialogflow API Error (sendMessage):",{status:i.status,statusText:i.statusText,error:t,endpoint:o}),new Error(s)}const c=await i.json();let l="I'm sorry, I didn't understand that. Could you please rephrase?",d=null,u=!1;if(!0===c.queryResult?.parameters?.fields?.handoff?.boolValue)u=!0;else if(c.queryResult?.responseMessages)for(const e of c.queryResult.responseMessages)if(e.payload&&"object"==typeof e.payload){if(!0===e.payload.handoff){u=!0;break}if(!0===e.payload.fields?.handoff?.boolValue){u=!0;break}}if(!0===c.handoff&&(u=!0),c.queryResult?.responseMessages){const e=c.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(l=e.join(" ")),d=$t(c.queryResult.responseMessages)}else c.queryResult?.fulfillmentText&&(l=c.queryResult.fulfillmentText);return{response:l,session_id:t,source:"dialogflow",timestamp:(new Date).toISOString(),...d&&{richContent:d},...u&&{handoff:!0}}}catch(e){console.error("Error sending message to Dialogflow:",e);const t=e.message||"Failed to send message";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(t.includes("CORS"))throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");throw new Error(t)}}(e.trim(),n,t);if(h&&(console.log("Chat response richContent:",s.richContent),console.log("Full chat response:",s),console.log("Handoff detected:",s.handoff)),!0===s.handoff){const e={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(t=>[...t,e]),F(!0),Q("name"),ee(""),se(""),oe.current="";const t={id:(Date.now()+2).toString(),text:"To connect you with a human agent, I'll need some information. Please provide your name:",sender:"bot",timestamp:new Date};return void I(e=>[...e,t])}const r={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(e=>[...e,r])}catch(e){console.error("Error sending message:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,sessionId:n,config:Ee()});const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message. Please check your Dialogflow configuration."}`:e.message?.includes("Failed to fetch")||e.message?.includes("CORS")?"Unable to connect to Dialogflow. Please check your configuration and network.":"Sorry, I'm having trouble processing your message. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t])}finally{x(!1)}};(0,o.useEffect)(()=>()=>{ie.current&&clearTimeout(ie.current),ce.current&&clearTimeout(ce.current)},[]);const Re=async()=>{k(!0),_(!1),P||await Ie()};return(0,o.useEffect)(()=>()=>{le.current.disconnectWebSocket()},[]),(0,r.jsxs)(r.Fragment,{children:[A&&!b&&(0,r.jsxs)("div",{className:"custom-welcome-popup",onClick:Re,children:[(0,r.jsxs)("div",{className:"custom-welcome-header",children:[(0,r.jsx)("div",{className:"custom-welcome-title",children:s}),(0,r.jsx)("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),_(!1)},children:"×"})]}),(0,r.jsx)("div",{className:"custom-welcome-message",children:n}),(0,r.jsx)("div",{className:"custom-welcome-cta",children:a})]}),!b&&(0,r.jsx)("button",{className:"custom-chat-toggle-btn",onClick:Re,"aria-label":"Open chat",children:(0,r.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),b&&(0,r.jsxs)("div",{className:"custom-chat-window",children:[(0,r.jsxs)("div",{className:"custom-chat-header",children:[(0,r.jsxs)("div",{className:"custom-chat-header-content",children:[(0,r.jsx)("div",{className:"custom-chat-title",children:e}),(0,r.jsxs)("div",{className:"custom-chat-subtitle",children:[t,"HUMAN"===he&&(0,r.jsxs)("span",{className:"custom-mode-indicator",children:[" ","• ",L?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===he&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"custom-mode-badge",children:"Human Support Mode"}),(0,r.jsxs)("div",{className:"custom-agent-info",children:[(0,r.jsx)("span",{className:"custom-agent-label",children:"Agent:"}),(0,r.jsx)("span",{className:"custom-agent-name",children:K.name})]})]}),"BOT"===he&&(0,r.jsx)("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),(0,r.jsx)("button",{className:"custom-chat-close-btn",onClick:()=>{k(!1),"HUMAN"===he&&le.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),(0,r.jsxs)("div",{className:"custom-chat-messages",children:[D&&0===v.length&&(0,r.jsxs)("div",{className:"custom-chat-empty",children:[(0,r.jsxs)("div",{className:"custom-typing-indicator",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("p",{children:"Initializing chat..."})]}),!D&&0===v.length&&(0,r.jsxs)("div",{className:"custom-chat-empty",children:[(0,r.jsx)("div",{className:"custom-chat-empty-icon",children:"👋"}),(0,r.jsx)("p",{children:u})]}),v.map(e=>(0,r.jsxs)("div",{className:`custom-message custom-message-${e.sender}`,children:[(0,r.jsx)("div",{className:"custom-message-content",children:(0,r.jsx)(Ge,{options:{defaultProtocol:"https",target:{url:"_blank"},attributes:{rel:"noopener noreferrer"}},children:e.text})}),(h&&e.richContent&&(console.log("Rendering message with richContent:",e.richContent),console.log("richContent type:",typeof e.richContent),console.log("richContent is array:",Array.isArray(e.richContent)),console.log("richContent length:",e.richContent?.length)),e.richContent&&Array.isArray(e.richContent)&&e.richContent.length>0?(0,r.jsx)("div",{className:"custom-chips-container",children:e.richContent.map((e,t)=>{if(h&&console.log(`Processing contentGroup ${t}:`,e),!Array.isArray(e)){const s=e;return s&&"chips"===s.type&&s.options?(0,r.jsx)("div",{className:"custom-chips-group",children:s.options.map((e,t)=>(0,r.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};I(e=>[...e,t]),Ce(e.text,e.text,!0)},type:"button",children:e.text},t))},t):null}return e.map((e,s)=>(h&&console.log(`Processing content ${t}-${s}:`,e),e&&"chips"===e.type&&e.options?(0,r.jsx)("div",{className:"custom-chips-group",children:e.options.map((e,t)=>(0,r.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};I(e=>[...e,t]),Ce(e.text,e.text,!0)},type:"button",children:e.text},t))},`${t}-${s}`):null))})}):null),(0,r.jsx)("div",{className:"custom-message-time",children:e.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},e.id)),T&&(0,r.jsx)("div",{className:"custom-message custom-message-bot",children:(0,r.jsxs)("div",{className:"custom-typing-indicator",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]})}),H&&(0,r.jsxs)("div",{className:"custom-message custom-message-bot",children:[(0,r.jsxs)("div",{className:"custom-typing-indicator",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("div",{className:"custom-message-content",children:"Connecting to agent..."})]}),"HUMAN"===he&&$&&(0,r.jsxs)("div",{className:"custom-agent-typing-indicator",children:[(0,r.jsxs)("span",{className:"custom-typing-dots",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"custom-typing-text",children:"Agent is typing..."})]}),(0,r.jsx)("div",{ref:ae})]}),(0,r.jsxs)("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Ce(C)},children:[(0,r.jsx)("input",{type:"text",className:"custom-chat-input",value:C,onChange:e=>{const t=e.target.value;R(t),"HUMAN"===he&&L&&(le.current.sendTypingIndicator("typing_start"),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{le.current.sendTypingIndicator("typing_stop"),ie.current=null},2e3))},placeholder:d,disabled:T||D||z}),(0,r.jsx)("button",{type:"submit",className:"custom-chat-send-btn",disabled:!C.trim()||T||D||z,children:(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),(0,r.jsx)("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})}module.exports=n})();
|
package/dist/react.esm.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! For license information please see react.esm.js.LICENSE.txt */
|
|
2
|
-
import*as e from"react";var t={20(e,t,s){var n=s(649),r=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,i=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,s){var n,o={},l=null,d=null;for(n in void 0!==s&&(l=""+s),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,n)&&!c.hasOwnProperty(n)&&(o[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps)void 0===o[n]&&(o[n]=t[n]);return{$$typeof:r,type:e,key:l,ref:d,props:o,_owner:i.current}}t.Fragment=o,t.jsx=l,t.jsxs=l},649(t){t.exports=e},848(e,t,s){e.exports=s(20)}},s={};function n(e){var r=s[e];if(void 0!==r)return r.exports;var o=s[e]={exports:{}};return t[e](o,o.exports,n),o.exports}n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r=n(848),o=n(649);const a="numeric",i="ascii",c="alpha",l="asciinumeric",d="alphanumeric",u="domain",h="emoji",m="scheme",g="slashscheme",p="whitespace";function f(e,t){return e in t||(t[e]=[]),t[e]}function y(e,t,s){t[a]&&(t[l]=!0,t[d]=!0),t[i]&&(t[l]=!0,t[c]=!0),t[l]&&(t[d]=!0),t[c]&&(t[d]=!0),t[d]&&(t[u]=!0),t[h]&&(t[u]=!0);for(const n in t){const t=f(n,s);t.indexOf(e)<0&&t.push(e)}}function w(e=null){this.j={},this.jr=[],this.jd=null,this.t=e}w.groups={},w.prototype={accepts(){return!!this.t},go(e){const t=this,s=t.j[e];if(s)return s;for(let s=0;s<t.jr.length;s++){const n=t.jr[s][0],r=t.jr[s][1];if(r&&n.test(e))return r}return t.jd},has(e,t=!1){return t?e in this.j:!!this.go(e)},ta(e,t,s,n){for(let r=0;r<e.length;r++)this.tt(e[r],t,s,n)},tr(e,t,s,n){let r;return n=n||w.groups,t&&t.j?r=t:(r=new w(t),s&&n&&y(t,s,n)),this.jr.push([e,r]),r},ts(e,t,s,n){let r=this;const o=e.length;if(!o)return r;for(let t=0;t<o-1;t++)r=r.tt(e[t]);return r.tt(e[o-1],t,s,n)},tt(e,t,s,n){n=n||w.groups;const r=this;if(t&&t.j)return r.j[e]=t,t;const o=t;let a,i=r.go(e);if(i?(a=new w,Object.assign(a.j,i.j),a.jr.push.apply(a.jr,i.jr),a.jd=i.jd,a.t=i.t):a=new w,o){if(n)if(a.t&&"string"==typeof a.t){const e=Object.assign(function(e,t){const s={};for(const n in t)t[n].indexOf(e)>=0&&(s[n]=!0);return s}(a.t,n),s);y(o,e,n)}else s&&y(o,s,n);a.t=o}return r.j[e]=a,a}};const S=(e,t,s,n,r)=>e.ta(t,s,n,r),E=(e,t,s,n,r)=>e.tr(t,s,n,r),b=(e,t,s,n,r)=>e.ts(t,s,n,r),k=(e,t,s,n,r)=>e.tt(t,s,n,r),A="WORD",_="UWORD",v="ASCIINUMERICAL",I="ALPHANUMERICAL",C="LOCALHOST",R="TLD",T="UTLD",x="SCHEME",P="SLASH_SCHEME",N="NUM",D="WS",j="NL",H="OPENBRACE",O="CLOSEBRACE",L="OPENBRACKET",W="CLOSEBRACKET",$="OPENPAREN",M="CLOSEPAREN",K="OPENANGLEBRACKET",U="CLOSEANGLEBRACKET",J="FULLWIDTHLEFTPAREN",F="FULLWIDTHRIGHTPAREN",B="LEFTCORNERBRACKET",V="RIGHTCORNERBRACKET",z="LEFTWHITECORNERBRACKET",q="RIGHTWHITECORNERBRACKET",G="FULLWIDTHLESSTHAN",Y="FULLWIDTHGREATERTHAN",X="AMPERSAND",Q="APOSTROPHE",Z="ASTERISK",ee="AT",te="BACKSLASH",se="BACKTICK",ne="CARET",re="COLON",oe="COMMA",ae="DOLLAR",ie="DOT",ce="EQUALS",le="EXCLAMATION",de="HYPHEN",ue="PERCENT",he="PIPE",me="PLUS",ge="POUND",pe="QUERY",fe="QUOTE",ye="FULLWIDTHMIDDLEDOT",we="SEMI",Se="SLASH",Ee="TILDE",be="UNDERSCORE",ke="EMOJI",Ae="SYM";var _e=Object.freeze({__proto__:null,ALPHANUMERICAL:I,AMPERSAND:X,APOSTROPHE:Q,ASCIINUMERICAL:v,ASTERISK:Z,AT:ee,BACKSLASH:te,BACKTICK:se,CARET:ne,CLOSEANGLEBRACKET:U,CLOSEBRACE:O,CLOSEBRACKET:W,CLOSEPAREN:M,COLON:re,COMMA:oe,DOLLAR:ae,DOT:ie,EMOJI:ke,EQUALS:ce,EXCLAMATION:le,FULLWIDTHGREATERTHAN:Y,FULLWIDTHLEFTPAREN:J,FULLWIDTHLESSTHAN:G,FULLWIDTHMIDDLEDOT:ye,FULLWIDTHRIGHTPAREN:F,HYPHEN:de,LEFTCORNERBRACKET:B,LEFTWHITECORNERBRACKET:z,LOCALHOST:C,NL:j,NUM:N,OPENANGLEBRACKET:K,OPENBRACE:H,OPENBRACKET:L,OPENPAREN:$,PERCENT:ue,PIPE:he,PLUS:me,POUND:ge,QUERY:pe,QUOTE:fe,RIGHTCORNERBRACKET:V,RIGHTWHITECORNERBRACKET:q,SCHEME:x,SEMI:we,SLASH:Se,SLASH_SCHEME:P,SYM:Ae,TILDE:Ee,TLD:R,UNDERSCORE:be,UTLD:T,UWORD:_,WORD:A,WS:D});const ve=/[a-z]/,Ie=/\p{L}/u,Ce=/\p{Emoji}/u,Re=/\d/,Te=/\s/;let xe=null,Pe=null;function Ne(e,t){const s=function(e){const t=[],s=e.length;let n=0;for(;n<s;){let r,o=e.charCodeAt(n),a=o<55296||o>56319||n+1===s||(r=e.charCodeAt(n+1))<56320||r>57343?e[n]:e.slice(n,n+2);t.push(a),n+=a.length}return t}(t.replace(/[A-Z]/g,e=>e.toLowerCase())),n=s.length,r=[];let o=0,a=0;for(;a<n;){let i=e,c=null,l=0,d=null,u=-1,h=-1;for(;a<n&&(c=i.go(s[a]));)i=c,i.accepts()?(u=0,h=0,d=i):u>=0&&(u+=s[a].length,h++),l+=s[a].length,o+=s[a].length,a++;o-=u,a-=h,l-=u,r.push({t:d.t,v:t.slice(o-l,o),s:o-l,e:o})}return r}function De(e,t,s,n,r){let o;const a=t.length;for(let s=0;s<a-1;s++){const a=t[s];e.j[a]?o=e.j[a]:(o=new w(n),o.jr=r.slice(),e.j[a]=o),e=o}return o=new w(s),o.jr=r.slice(),e.j[t[a-1]]=o,o}function je(e){const t=[],s=[];let n=0;for(;n<e.length;){let r=0;for(;"0123456789".indexOf(e[n+r])>=0;)r++;if(r>0){t.push(s.join(""));for(let t=parseInt(e.substring(n,n+r),10);t>0;t--)s.pop();n+=r}else s.push(e[n]),n++}return t}const He={defaultProtocol:"http",events:null,format:Le,formatHref:Le,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Oe(e,t=null){let s=Object.assign({},He);e&&(s=Object.assign(s,e instanceof Oe?e.o:e));const n=s.ignoreTags,r=[];for(let e=0;e<n.length;e++)r.push(n[e].toUpperCase());this.o=s,t&&(this.defaultRender=t),this.ignoreTags=r}function Le(e){return e}function We(e,t){this.t="token",this.v=e,this.tk=t}function $e(e,t){class s extends We{constructor(t,s){super(t,s),this.t=e}}for(const e in t)s.prototype[e]=t[e];return s.t=e,s}Oe.prototype={o:He,ignoreTags:[],defaultRender:e=>e,check(e){return this.get("validate",e.toString(),e)},get(e,t,s){const n=null!=t;let r=this.o[e];return r?("object"==typeof r?(r=s.t in r?r[s.t]:He[e],"function"==typeof r&&n&&(r=r(t,s))):"function"==typeof r&&n&&(r=r(t,s.t,s)),r):r},getObj(e,t,s){let n=this.o[e];return"function"==typeof n&&null!=t&&(n=n(t,s.t,s)),n},render(e){const t=e.render(this);return(this.get("render",null,e)||this.defaultRender)(t,e.t,e)}},We.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){const t=this.toString(),s=e.get("truncate",t,this),n=e.get("format",t,this);return s&&n.length>s?n.substring(0,s)+"…":n},toFormattedHref(e){return e.get("formatHref",this.toHref(e.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=He.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get("validate",this.toString(),this)},render(e){const t=this,s=this.toHref(e.get("defaultProtocol")),n=e.get("formatHref",s,this),r=e.get("tagName",s,t),o=this.toFormattedString(e),a={},i=e.get("className",s,t),c=e.get("target",s,t),l=e.get("rel",s,t),d=e.getObj("attributes",s,t),u=e.getObj("events",s,t);return a.href=n,i&&(a.class=i),c&&(a.target=c),l&&(a.rel=l),d&&Object.assign(a,d),{tagName:r,attributes:a,content:o,eventListeners:u}}};const Me=$e("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Ke=$e("text"),Ue=$e("nl"),Je=$e("url",{isLink:!0,toHref(e=He.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){const e=this.tk;return e.length>=2&&e[0].t!==C&&e[1].t===re}}),Fe=e=>new w(e);function Be(e,t,s){const n=s[0].s,r=s[s.length-1].e;return new e(t.slice(n,r),s)}"undefined"!=typeof console&&console&&console.warn;const Ve={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function ze(e){return Ve.initialized||function(){Ve.scanner=function(e=[]){const t={};w.groups=t;const s=new w;null==xe&&(xe=je("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==Pe&&(Pe=je("ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2")),k(s,"'",Q),k(s,"{",H),k(s,"}",O),k(s,"[",L),k(s,"]",W),k(s,"(",$),k(s,")",M),k(s,"<",K),k(s,">",U),k(s,"(",J),k(s,")",F),k(s,"「",B),k(s,"」",V),k(s,"『",z),k(s,"』",q),k(s,"<",G),k(s,">",Y),k(s,"&",X),k(s,"*",Z),k(s,"@",ee),k(s,"`",se),k(s,"^",ne),k(s,":",re),k(s,",",oe),k(s,"$",ae),k(s,".",ie),k(s,"=",ce),k(s,"!",le),k(s,"-",de),k(s,"%",ue),k(s,"|",he),k(s,"+",me),k(s,"#",ge),k(s,"?",pe),k(s,'"',fe),k(s,"/",Se),k(s,";",we),k(s,"~",Ee),k(s,"_",be),k(s,"\\",te),k(s,"・",ye);const n=E(s,Re,N,{[a]:!0});E(n,Re,n);const r=E(n,ve,v,{[l]:!0}),o=E(n,Ie,I,{[d]:!0}),f=E(s,ve,A,{[i]:!0});E(f,Re,r),E(f,ve,f),E(r,Re,r),E(r,ve,r);const S=E(s,Ie,_,{[c]:!0});E(S,ve),E(S,Re,o),E(S,Ie,S),E(o,Re,o),E(o,ve),E(o,Ie,o);const Ne=k(s,"\n",j,{[p]:!0}),He=k(s,"\r",D,{[p]:!0}),Oe=E(s,Te,D,{[p]:!0});k(s,"",Oe),k(He,"\n",Ne),k(He,"",Oe),E(He,Te,Oe),k(Oe,"\r"),k(Oe,"\n"),E(Oe,Te,Oe),k(Oe,"",Oe);const Le=E(s,Ce,ke,{[h]:!0});k(Le,"#"),E(Le,Ce,Le),k(Le,"️",Le);const We=k(Le,"");k(We,"#"),E(We,Ce,Le);const $e=[[ve,f],[Re,r]],Me=[[ve,null],[Ie,S],[Re,o]];for(let e=0;e<xe.length;e++)De(s,xe[e],R,A,$e);for(let e=0;e<Pe.length;e++)De(s,Pe[e],T,_,Me);y(R,{tld:!0,ascii:!0},t),y(T,{utld:!0,alpha:!0},t),De(s,"file",x,A,$e),De(s,"mailto",x,A,$e),De(s,"http",P,A,$e),De(s,"https",P,A,$e),De(s,"ftp",P,A,$e),De(s,"ftps",P,A,$e),y(x,{scheme:!0,ascii:!0},t),y(P,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){const n=e[t][0],r=e[t][1]?{[m]:!0}:{[g]:!0};n.indexOf("-")>=0?r[u]=!0:ve.test(n)?Re.test(n)?r[l]=!0:r[i]=!0:r[a]=!0,b(s,n,n,r)}return b(s,"localhost",C,{ascii:!0}),s.jd=new w(Ae),{start:s,tokens:Object.assign({groups:t},_e)}}(Ve.customSchemes);for(let e=0;e<Ve.tokenQueue.length;e++)Ve.tokenQueue[e][1]({scanner:Ve.scanner});Ve.parser=function({groups:e}){const t=e.domain.concat([X,Z,ee,te,se,ne,ae,ce,de,N,ue,he,me,ge,Se,Ae,Ee,be]),s=[Q,re,oe,ie,le,ue,pe,fe,we,K,U,H,O,W,L,$,M,J,F,B,V,z,q,G,Y],n=[X,Q,Z,te,se,ne,ae,ce,de,H,O,ue,he,me,ge,pe,Se,Ae,Ee,be],r=Fe(),o=k(r,Ee);S(o,n,o),S(o,e.domain,o);const a=Fe(),i=Fe(),c=Fe();S(r,e.domain,a),S(r,e.scheme,i),S(r,e.slashscheme,c),S(a,n,o),S(a,e.domain,a);const l=k(a,ee);k(o,ee,l),k(i,ee,l),k(c,ee,l);const d=k(o,ie);S(d,n,o),S(d,e.domain,o);const u=Fe();S(l,e.domain,u),S(u,e.domain,u);const h=k(u,ie);S(h,e.domain,u);const m=Fe(Me);S(h,e.tld,m),S(h,e.utld,m),k(l,C,m);const g=k(u,de);k(g,de,g),S(g,e.domain,u),S(m,e.domain,u),k(m,ie,h),k(m,de,g);const p=k(m,re);S(p,e.numeric,Me);const f=k(a,de),y=k(a,ie);k(f,de,f),S(f,e.domain,a),S(y,n,o),S(y,e.domain,a);const w=Fe(Je);S(y,e.tld,w),S(y,e.utld,w),S(w,e.domain,a),S(w,n,o),k(w,ie,y),k(w,de,f),k(w,ee,l);const E=k(w,re),b=Fe(Je);S(E,e.numeric,b);const A=Fe(Je),_=Fe();S(A,t,A),S(A,s,_),S(_,t,A),S(_,s,_),k(w,Se,A),k(b,Se,A);const v=k(i,re),I=k(c,re),R=k(I,Se),T=k(R,Se);S(i,e.domain,a),k(i,ie,y),k(i,de,f),S(c,e.domain,a),k(c,ie,y),k(c,de,f),S(v,e.domain,A),k(v,Se,A),k(v,pe,A),S(T,e.domain,A),S(T,t,A),k(T,Se,A);const x=[[H,O],[L,W],[$,M],[K,U],[J,F],[B,V],[z,q],[G,Y]];for(let e=0;e<x.length;e++){const[n,r]=x[e],o=k(A,n);k(_,n,o),k(o,r,A);const a=Fe(Je);S(o,t,a);const i=Fe();S(o,s),S(a,t,a),S(a,s,i),S(i,t,a),S(i,s,i),k(a,r,A),k(i,r,A)}return k(r,C,w),k(r,j,Ue),{start:r,tokens:_e}}(Ve.scanner.tokens);for(let e=0;e<Ve.pluginQueue.length;e++)Ve.pluginQueue[e][1]({scanner:Ve.scanner,parser:Ve.parser});Ve.initialized=!0}(),function(e,t,s){let n=s.length,r=0,o=[],a=[];for(;r<n;){let i=e,c=null,l=null,d=0,u=null,h=-1;for(;r<n&&!(c=i.go(s[r].t));)a.push(s[r++]);for(;r<n&&(l=c||i.go(s[r].t));)c=null,i=l,i.accepts()?(h=0,u=i):h>=0&&h++,r++,d++;if(h<0)r-=d,r<n&&(a.push(s[r]),r++);else{a.length>0&&(o.push(Be(Ke,t,a)),a=[]),r-=h,d-=h;const e=u.t,n=s.slice(r-d,r);o.push(Be(e,t,n))}}return a.length>0&&o.push(Be(Ke,t,a)),o}(Ve.parser.start,e,Ne(Ve.scanner.start,e))}function qe(e,t,s){if(0===o.Children.count(e.props.children))return e;const n=[];o.Children.forEach(e.props.children,e=>{"string"==typeof e?n.push.apply(n,function(e,t,s){const n=ze(e),r=[];for(let e=0;e<n.length;e++){const a=n[e];if("nl"===a.t&&t.get("nl2br")){const e="__linkify-el-"+s.elementId++;r.push(o.createElement("br",{key:e}))}else if(a.isLink&&t.check(a)){let e=t.render(a);if(!("key"in e.props)){const t="__linkify-el-"+s.elementId++,n=Object.assign({key:t},e.props);e=o.cloneElement(e,n)}r.push(e)}else r.push(a.toString())}return r}(e,t,s)):o.isValidElement(e)?"string"==typeof e.type&&t.ignoreTags.indexOf(e.type.toUpperCase())>=0?n.push(e):n.push(qe(e,t,s)):n.push(e)});const r="__linkify-el-"+s.elementId++,a=Object.assign({key:r},e.props);return o.cloneElement(e,a,n)}ze.scan=Ne;const Ge=e=>{let t=0;const s={key:"__linkify-wrapper"};for(const t in e)"options"!==t&&"as"!==t&&"tagName"!==t&&"children"!==t&&(s[t]=e[t]);const n=new Oe(e.options,({tagName:e,attributes:s,content:n})=>(s.key="__linkify-lnk-"+t++,s.class&&(s.className=s.class,delete s.class),o.createElement(e,s,n))),r=e.as||e.tagName||o.Fragment||"span",a=e.children;return qe(o.createElement(r,s,a),n,{elementId:0})},Ye=crypto,Xe=e=>e instanceof CryptoKey;class Qe extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Qe.code="ERR_JOSE_GENERIC",class extends Qe{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=s,this.reason=n,this.payload=t}}.code="ERR_JWT_CLAIM_VALIDATION_FAILED",class extends Qe{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=s,this.reason=n,this.payload=t}}.code="ERR_JWT_EXPIRED",class extends Qe{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}.code="ERR_JOSE_ALG_NOT_ALLOWED";class Ze extends Qe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}Ze.code="ERR_JOSE_NOT_SUPPORTED",class extends Qe{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}.code="ERR_JWE_DECRYPTION_FAILED",class extends Qe{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}.code="ERR_JWE_INVALID";class et extends Qe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}et.code="ERR_JWS_INVALID";class tt extends Qe{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}tt.code="ERR_JWT_INVALID",class extends Qe{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}.code="ERR_JWK_INVALID",class extends Qe{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}.code="ERR_JWKS_INVALID",class extends Qe{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}.code="ERR_JWKS_NO_MATCHING_KEY",Symbol.asyncIterator,class extends Qe{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",class extends Qe{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}.code="ERR_JWKS_TIMEOUT",class extends Qe{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";const st=(e,t,s=0)=>{0===s&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],s);if(-1===n)return!1;const r=e.subarray(n,n+t.length);return r.length===t.length&&(r.every((e,s)=>e===t[s])||st(e,t,n+1))},nt=e=>{switch(!0){case st(e,[42,134,72,206,61,3,1,7]):return"P-256";case st(e,[43,129,4,0,34]):return"P-384";case st(e,[43,129,4,0,35]):return"P-521";case st(e,[43,101,110]):return"X25519";case st(e,[43,101,111]):return"X448";case st(e,[43,101,112]):return"Ed25519";case st(e,[43,101,113]):return"Ed448";default:throw new Ze("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}};async function rt(e,t,s){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return((e,t,s)=>(async(e,t,s,n,r)=>{let o,a;const i=new Uint8Array(atob(s.replace(e,"")).split("").map(e=>e.charCodeAt(0))),c="spki"===t;switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},a=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},a=c?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},a=c?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},a=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=nt(i);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},a=c?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},a=c?["verify"]:["sign"];break;case"EdDSA":o={name:nt(i)},a=c?["verify"]:["sign"];break;default:throw new Ze('Invalid or unsupported "alg" (Algorithm) value')}return Ye.subtle.importKey(t,i,o,r?.extractable??!1,a)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,s))(e,t,s)}const ot=new TextEncoder,at=new TextDecoder;const it=e=>(e=>{let t=e;"string"==typeof t&&(t=ot.encode(t));const s=[];for(let e=0;e<t.length;e+=32768)s.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(s.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),ct=e=>{let t=e;t instanceof Uint8Array&&(t=at.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};function lt(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function dt(e,t){return e.name===t}function ut(e){return parseInt(e.name.slice(4),10)}function ht(e,t,...s){switch(t){case"HS256":case"HS384":case"HS512":{if(!dt(e.algorithm,"HMAC"))throw lt("HMAC");const s=parseInt(t.slice(2),10);if(ut(e.algorithm.hash)!==s)throw lt(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!dt(e.algorithm,"RSASSA-PKCS1-v1_5"))throw lt("RSASSA-PKCS1-v1_5");const s=parseInt(t.slice(2),10);if(ut(e.algorithm.hash)!==s)throw lt(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!dt(e.algorithm,"RSA-PSS"))throw lt("RSA-PSS");const s=parseInt(t.slice(2),10);if(ut(e.algorithm.hash)!==s)throw lt(`SHA-${s}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw lt("Ed25519 or Ed448");break;case"Ed25519":if(!dt(e.algorithm,"Ed25519"))throw lt("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!dt(e.algorithm,"ECDSA"))throw lt("ECDSA");const s=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==s)throw lt(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const s=t.pop();e+=`one of ${t.join(", ")}, or ${s}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,s)}function mt(e,t,...s){if((s=s.filter(Boolean)).length>2){const t=s.pop();e+=`one of type ${s.join(", ")}, or ${t}.`}else 2===s.length?e+=`one of type ${s[0]} or ${s[1]}.`:e+=`of type ${s[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const gt=(e,...t)=>mt("Key must be ",e,...t);function pt(e,t,...s){return mt(`Key for the ${e} algorithm must be `,t,...s)}const ft=e=>!!Xe(e)||"KeyObject"===e?.[Symbol.toStringTag],yt=["CryptoKey"];function wt(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let s=e;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(e)===s}function St(e){return wt(e)&&"string"==typeof e.kty}const Et=e=>ct(e);let bt;const kt=e=>"KeyObject"===e?.[Symbol.toStringTag],At=async(e,t,s,n,r=!1)=>{let o=e.get(t);if(o?.[n])return o[n];const a=await(async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:s}=function(e){let t,s;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},s=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Ze('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},s=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},s=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new Ze('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},s=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new Ze('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new Ze('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:s}}(e),n=[t,e.ext??!1,e.key_ops??s],r={...e};return delete r.alg,delete r.use,Ye.subtle.importKey("jwk",r,...n)})({...s,alg:n});return r&&Object.freeze(t),o?o[n]=a:e.set(t,{[n]:a}),a},_t=async(e,t,s)=>{const n=await async function(e,t,s){if(t=await((e,t)=>{if(kt(e)){let s=e.export({format:"jwk"});return s.k?Et(s.k):(bt||(bt=new WeakMap),At(bt,e,s,t))}return St(e)?e.k?ct(e.k):(bt||(bt=new WeakMap),At(bt,e,e,t,!0)):e})(t,e),Xe(t))return ht(t,e,s),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(gt(t,...yt));return Ye.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(gt(t,...yt,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:s}=t.algorithm;if("number"!=typeof s||s<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,n);const r=await Ye.subtle.sign(function(e,t){const s=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new Ze(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,s);return new Uint8Array(r)},vt=e=>e?.[Symbol.toStringTag],It=(e,t,s)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(s))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function Ct(e,t,s,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,s,n)=>{if(!(t instanceof Uint8Array)){if(n&&St(t)){if(function(e){return St(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&It(e,t,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ft(t))throw new TypeError(pt(e,t,...yt,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${vt(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,s,n,e):((e,t,s,n)=>{if(n&&St(t))switch(s){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&It(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&It(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ft(t))throw new TypeError(pt(e,t,...yt,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===s&&"public"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===s&&"public"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===s&&"private"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===s&&"private"===t.type)throw new TypeError(`${vt(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,s,n,e)}Ct.bind(void 0,!1);const Rt=Ct.bind(void 0,!0);class Tt{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new et("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let s;for(const e of t){const t=Object.keys(e);if(s&&0!==s.size)for(const e of t){if(s.has(e))return!1;s.add(e)}else s=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new et("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(function(e,t,s,n,r){if(void 0!==r.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=void 0!==s?new Map([...Object.entries(s),...t.entries()]):t;for(const t of n.crit){if(!o.has(t))throw new Ze(`Extension Header Parameter "${t}" is not recognized`);if(void 0===r[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(o.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(et,new Map([["b64",!0]]),t?.crit,this._protectedHeader,s).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new et('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:r}=s;if("string"!=typeof r||!r)throw new et('JWS "alg" (Algorithm) Header Parameter missing or invalid');Rt(r,e,"sign");let o,a=this._payload;n&&(a=ot.encode(it(a))),o=this._protectedHeader?ot.encode(it(JSON.stringify(this._protectedHeader))):ot.encode("");const i=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}(o,ot.encode("."),a),c=await _t(r,e,i),l={signature:it(c),payload:""};return n&&(l.payload=at.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=at.decode(o)),l}}class xt{constructor(e){this._flattened=new Tt(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const s=await this._flattened.sign(e,t);if(void 0===s.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${s.protected}.${s.payload}.${s.signature}`}}const Pt=e=>Math.floor(e.getTime()/1e3),Nt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Dt=e=>{const t=Nt.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const s=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*s);break;case"day":case"days":case"d":n=Math.round(86400*s);break;case"week":case"weeks":case"w":n=Math.round(604800*s);break;default:n=Math.round(31557600*s)}return"-"===t[1]||"ago"===t[4]?-n:n};function jt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class Ht{constructor(e={}){if(!wt(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:jt("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:jt("setNotBefore",Pt(e))}:this._payload={...this._payload,nbf:Pt(new Date)+Dt(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:jt("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:jt("setExpirationTime",Pt(e))}:this._payload={...this._payload,exp:Pt(new Date)+Dt(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:Pt(new Date)}:e instanceof Date?this._payload={...this._payload,iat:jt("setIssuedAt",Pt(e))}:this._payload="string"==typeof e?{...this._payload,iat:jt("setIssuedAt",Pt(new Date)+Dt(e))}:{...this._payload,iat:jt("setIssuedAt",e)},this}}class Ot extends Ht{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const s=new xt(ot.encode(JSON.stringify(this._payload)));if(s.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new tt("JWTs MUST NOT use unencoded payload");return s.sign(e,t)}}async function Lt(e){if(e.accessToken)return e.accessToken;if(!e.serviceAccountKey)throw new Error("Either serviceAccountKey or accessToken must be provided");return await async function(e){const t=Math.floor(Date.now()/1e3);let s=e.private_key;if(!s)throw new Error("Private key is missing from service account key");if(s=s.trim(),s.includes("-----BEGIN")){if(s=s.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),s.includes("BEGIN RSA PRIVATE KEY"))throw new Error("Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY).");const e=s.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);if(e){const t=e[1].replace(/\s/g,"");(!t.includes("\n")||t.length>64)&&(s=`-----BEGIN PRIVATE KEY-----\n${t.match(/.{1,64}/g)?.join("\n")||t}\n-----END PRIVATE KEY-----`)}}else{const e=s.replace(/\s/g,"");s=`-----BEGIN PRIVATE KEY-----\n${e.match(/.{1,64}/g)?.join("\n")||e}\n-----END PRIVATE KEY-----`}try{const n=await rt(s,"RS256"),r=await new Ot({scope:"https://www.googleapis.com/auth/cloud-platform"}).setProtectedHeader({alg:"RS256"}).setIssuedAt(t).setExpirationTime(t+3600).setIssuer(e.client_email).setSubject(e.client_email).setAudience("https://oauth2.googleapis.com/token").sign(n),o=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:r})});if(!o.ok){const e=await o.json();throw new Error(e.error_description||"Failed to get access token")}return(await o.json()).access_token}catch(e){if(e.message&&e.message.includes("pkcs8"))throw new Error("Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format.");throw e}}(e.serviceAccountKey)}function Wt(e,t,s,n){return`projects/${e}/locations/${t}/agents/${s}/sessions/${n}`}function $t(e){let t=null;for(const s of e)if(s.payload){if(s.payload.richContent){t=s.payload.richContent;break}if(s.payload.fields&&s.payload.fields.richContent){const e=s.payload.fields.richContent;e.listValue&&e.listValue.values?t=e.listValue.values.map(e=>e.listValue&&e.listValue.values?e.listValue.values.map(e=>{if(e.structValue&&e.structValue.fields){const t=e.structValue.fields;if(t.type&&t.options)return{type:t.type.stringValue||t.type,options:t.options.listValue?t.options.listValue.values.map(e=>({text:e.structValue?.fields?.text?.stringValue||"",payload:e.structValue?.fields?.payload?.stringValue||""})):[]}}return e}):e):"object"!=typeof e||e.listValue||(t=e);break}}return t}const Mt="blockspark_chat_mode",Kt="blockspark_chat_id",Ut="blockspark_session_id",Jt="chat_session_id";class Ft{constructor(){this.sessionId=null,this.sessionId=this.loadSessionId()}loadSessionId(){return"undefined"!=typeof localStorage?localStorage.getItem(Jt):null}saveSessionId(e){this.sessionId=e,"undefined"!=typeof localStorage&&(e?localStorage.setItem(Jt,e):localStorage.removeItem(Jt))}updateSessionFromResponse(e){const t=e?.data?.session_id||e?.session_id;t&&"string"==typeof t&&this.saveSessionId(t)}getSessionId(){return this.sessionId||""}getSessionHeader(){return{"X-Session-ID":this.getSessionId()}}}let Bt=null;class Vt extends Error{constructor(e="chat_resolved"){super(e),this.reason="chat_resolved",this.name="ChatResolvedError"}}const zt="undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_BASE_URL,qt="undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_WS_URL;class Gt{constructor(e={}){this.ws=null,this.wsReconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimeout=null,this.pingInterval=null,this.currentChatId=null,this.currentSessionId=null,this.messageHandlers=new Set,this.connectionHandlers=new Set,this.baseUrl=e.baseUrl||zt,this.wsUrl=e.wsUrl||qt,this.debug=e.debug||!1,this.sessionManager=(Bt||(Bt=new Ft),Bt)}async startSupportChat(e,t,s,n){try{const r={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};e&&(r["X-Session-ID"]=e);const o={};t&&(o.name=t),s&&(o.email=s),n&&(o.mobile=n);const a=await fetch(`${this.baseUrl}/api/support/chat/start`,{method:"POST",headers:r,body:JSON.stringify(o)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${a.status}`)}const i=await a.json();if(this.sessionManager.updateSessionFromResponse(i),i.status&&i.data)return{chat_id:i.data.chat_id,session_id:i.data.session_id};if(i.chat_id&&i.session_id)return{chat_id:i.chat_id,session_id:i.session_id};throw new Error("Invalid response format from chat start endpoint")}catch(e){throw console.error("Error starting support chat:",e),new Error(e.message||"Failed to start support chat session")}}async requestHandoff(e,t,s,n,r,o,a){if(!e||"undefined"===e||"null"===e)throw new Error("Invalid chat_id. Chat must be initialized first.");try{const i={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t?i["X-Session-ID"]=t:n&&(i["X-Session-ID"]=n);const c={};s&&(c.reason=s),r&&(c.name=r),o&&(c.email=o),a&&(c.mobile=a);const l=await fetch(`${this.baseUrl}/api/support/chat/${e}/handoff`,{method:"POST",headers:i,body:JSON.stringify(c)});if(400===l.status||404===l.status){const e=await l.json().catch(()=>({}));throw new Error(e.message||"Invalid chat_id. Chat may have expired.")}if(!l.ok){const e=await l.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${l.status}`)}const d=await l.json();return this.sessionManager.updateSessionFromResponse(d),d.status?{success:!0,message:d.message||d.data?.message}:{success:!0,message:d.message}}catch(e){throw console.error("Error requesting handoff:",e),e}}async sendMessageToAgent(e,t,s){try{const n={"Content-Type":"application/json",...this.sessionManager.getSessionHeader()};t&&(n["X-Session-ID"]=t);const r=await fetch(`${this.baseUrl}/api/support/chat/${e}/message`,{method:"POST",headers:n,body:JSON.stringify({content:s})});if(401===r.status||404===r.status){const e=await r.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${r.status}`)}const o=await r.json();if(this.sessionManager.updateSessionFromResponse(o),!0===o?.ignored&&"chat_resolved"===o?.reason)throw new Vt;return{id:o.id,sender_type:"customer",content:s,timestamp:o.timestamp||(new Date).toISOString()}}catch(e){if(e instanceof Vt||"ChatResolvedError"===e?.name)throw e;throw console.error("Error sending message to agent:",e),new Error(e.message||"Failed to send message to agent")}}async ensureChatInitialized(e,t,s,n,r,o){return e&&"undefined"!==e&&"null"!==e&&t?{chat_id:e,session_id:t}:await this.startSupportChat(s||null,n||null,r||null,o||null)}async loadMessageHistory(e,t){try{const s={...this.sessionManager.getSessionHeader()};t&&(s["X-Session-ID"]=t);const n=await fetch(`${this.baseUrl}/api/support/chat/${e}/messages`,{method:"GET",headers:s});if(401===n.status||404===n.status){const e=await n.json().catch(()=>({}));throw new Error(e.message||"Chat not found or unauthorized")}if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.message||`HTTP error! status: ${n.status}`)}const r=await n.json();return this.sessionManager.updateSessionFromResponse(r),r.messages||[]}catch(e){throw console.error("Error loading message history:",e),new Error(e.message||"Failed to load message history")}}connectWebSocket(e,t,s,n,r){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&this.ws.readyState===WebSocket.OPEN)return void(this.debug&&console.log("WebSocket already connected"));this.currentChatId=e,this.currentSessionId=t,s&&this.messageHandlers.add(s),n&&this.connectionHandlers.add(n);const o=t||this.sessionManager.getSessionId()||"",a=`${this.wsUrl}/ws/support/${e}?X-Session-ID=${encodeURIComponent(o)}`;try{this.ws=new WebSocket(a),this.ws.onopen=()=>{this.debug&&console.log("WebSocket connected to:",a),console.log("✅ Customer WebSocket connected:",{chatId:e,sessionId:t,wsUrl:a}),this.wsReconnectAttempts=0,this.connectionHandlers.forEach(e=>e(!0)),this.startPingInterval()},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);if(this.debug&&(console.log("WebSocket raw message received:",e.data),console.log("WebSocket parsed message:",t)),t.session_id&&this.sessionManager.updateSessionFromResponse({session_id:t.session_id}),"agent_accepted"!==t.type&&"chat_resolved"!==t.type&&"chat_ended"!==t.type||console.log("🔔 Received notification message:",{type:t.type,chat_id:t.chat_id,timestamp:t.timestamp,to_agent:t.to_agent,to_agent_id:t.to_agent_id}),"pong"===t.type)return;this.debug&&"message"===t.type&&console.log("Processing message type:",{type:t.type,sender_type:t.sender_type,content:t.content?.substring(0,50)+"...",id:t.id}),this.messageHandlers.forEach(e=>e(t))}catch(t){console.error("Error parsing WebSocket message:",t),this.debug&&console.error("Raw message data:",e.data)}},this.ws.onerror=e=>{console.error("❌ WebSocket error:",e),this.connectionHandlers.forEach(e=>e(!1))},this.ws.onclose=t=>{if(this.debug&&console.log("WebSocket closed:",t.code,t.reason),console.log("🔌 Customer WebSocket closed:",{code:t.code,reason:t.reason,chatId:e}),this.stopPingInterval(),this.connectionHandlers.forEach(e=>e(!1)),this.ws=null,r?.(t),4e3===t.code)return this.wsReconnectAttempts=this.maxReconnectAttempts,this.currentChatId=null,void(this.currentSessionId=null);if(this.wsReconnectAttempts<this.maxReconnectAttempts&&this.currentChatId&&this.currentSessionId){this.wsReconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.wsReconnectAttempts),3e4);this.debug&&console.log(`Reconnecting in ${e}ms (attempt ${this.wsReconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.currentChatId&&this.currentSessionId&&this.connectWebSocket(this.currentChatId,this.currentSessionId,s,n,r)},e)}else this.debug&&console.error("Max reconnection attempts reached")}}catch(e){console.error("Error creating WebSocket connection:",e),this.connectionHandlers.forEach(e=>e(!1))}}sendMessageViaWebSocket(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:"message",content:e})),!0}catch(e){return console.error("Error sending message via WebSocket:",e),!1}}sendTypingIndicator(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return!1;try{return this.ws.send(JSON.stringify({type:e})),!0}catch(t){return console.error(`Error sending ${e} via WebSocket:`,t),!1}}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"ping"}))}catch(e){console.error("Error sending ping:",e)}},3e4)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}disconnectWebSocket(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.stopPingInterval(),this.ws&&(this.ws.close(),this.ws=null),this.messageHandlers.clear(),this.connectionHandlers.clear(),this.wsReconnectAttempts=0,this.currentChatId=null,this.currentSessionId=null}isWebSocketConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}removeMessageHandler(e){this.messageHandlers.delete(e)}removeConnectionHandler(e){this.connectionHandlers.delete(e)}}function Yt({title:e="💬 BlockSpark AI Assistant",subtitle:t="We're here to help",welcomeTitle:s="👋 Welcome to Blockspark",welcomeMessage:n="My name is BlockSpark AI Assistant and I'll guide you.",welcomeCta:a="💬 Click here to start chatting!",showWelcomePopup:i=!0,welcomePopupDelay:c=1500,fallbackWelcomeMessage:l="Hello! I'm BlockSpark AI Assistant. How can I help you today?",inputPlaceholder:d="Type your message...",emptyStateMessage:u="Hi! I'm BlockSpark AI Assistant. How can I help you today?",debug:h=!1,dfProjectId:m,dfLocation:g="us-central1",dfAgentId:p,serviceAccountKey:f,accessToken:y,languageCode:w="en",backendBaseUrl:S,backendWsUrl:E}){const[b,k]=(0,o.useState)(!1),[A,_]=(0,o.useState)(!1),[v,I]=(0,o.useState)([]),[C,R]=(0,o.useState)(""),[T,x]=(0,o.useState)(!1),[P,N]=(0,o.useState)(null),[D,j]=(0,o.useState)(!1),[H,O]=(0,o.useState)(!1),[L,W]=(0,o.useState)(!1),[$,M]=(0,o.useState)(!1),[K,U]=(0,o.useState)({name:"Agent"}),[J,F]=(0,o.useState)(!1),[B,V]=(0,o.useState)(!1),[z,q]=(0,o.useState)(!1),[G,Y]=(0,o.useState)(!1),[X,Q]=(0,o.useState)(null),[Z,ee]=(0,o.useState)(""),[te,se]=(0,o.useState)(""),[ne,re]=(0,o.useState)(""),oe=(0,o.useRef)(""),ae=(0,o.useRef)(null),ie=(0,o.useRef)(null),ce=(0,o.useRef)(null),le=(0,o.useRef)((de={baseUrl:S||"undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_BASE_URL,wsUrl:E||"undefined"!=typeof process&&"MISSING_ENV_VAR"?.REACT_APP_BACKEND_WS_URL,debug:h},new Gt(de)));var de;const ue=(0,o.useRef)(null),{currentMode:he,switchToHumanMode:me,switchToBotMode:ge,chatId:pe,sessionId:fe,setChatId:ye,setSessionId:we}=function(){const[e,t]=(0,o.useState)(()=>"HUMAN"===localStorage.getItem(Mt)?"HUMAN":"BOT"),[s,n]=(0,o.useState)(()=>localStorage.getItem(Kt)),[r,a]=(0,o.useState)(()=>localStorage.getItem(Ut));(0,o.useEffect)(()=>{localStorage.setItem(Mt,e)},[e]);const i=(0,o.useCallback)(e=>{n(e),e?localStorage.setItem(Kt,e):localStorage.removeItem(Kt)},[]),c=(0,o.useCallback)(e=>{a(e),e?localStorage.setItem(Ut,e):localStorage.removeItem(Ut)},[]),l=(0,o.useCallback)(()=>{t("HUMAN")},[]),d=(0,o.useCallback)(()=>{t("BOT")},[]),u=(0,o.useCallback)(e=>!1,[]);return{currentMode:e,switchToHumanMode:l,switchToBotMode:d,isHandoffTriggered:u,chatId:s,sessionId:r,setChatId:i,setSessionId:c}}(),Se=(0,o.useCallback)(e=>{V(!0),O(!1),Y(!1),M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null),le.current.disconnectWebSocket(),ye(null),we(null);const t={id:`resolved-${Date.now()}`,text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};I(e=>[...e,t]),setTimeout(()=>{ge(),V(!1),I([]),F(!1),Q(null),ee(""),se(""),re(""),oe.current="",Ie().catch(console.error)},2e3)},[ye,we,ge]),Ee=((0,o.useCallback)(async()=>{if(!z){q(!0);try{const e=oe.current||Z||null,t=te||null,s=ne||null,n=await le.current.startSupportChat(P||null,e,t,s);me(),ye(n.chat_id),we(n.session_id),V(!1),R("")}catch(e){console.error("Error starting new chat:",e),I(t=>[...t,{id:`error-new-chat-${Date.now()}`,text:h?`Error: ${e?.message||"Failed to start a new chat."}`:"Sorry, I couldn't start a new chat. Please try again.",sender:"bot",timestamp:new Date}])}finally{q(!1)}}},[te,ne,Z,h,z,P,ye,we,me]),()=>{if(m&&p)return{dfProjectId:m,dfLocation:g||"us-central1",dfAgentId:p,serviceAccountKey:f,accessToken:y,languageCode:w||"en"}});(0,o.useEffect)(()=>{if(!i)return;const e=setTimeout(()=>{_(!0)},c);return()=>clearTimeout(e)},[i,c]),(0,o.useEffect)(()=>{ae.current?.scrollIntoView({behavior:"smooth"})},[v]);const be=(0,o.useCallback)(e=>{if(e.to_agent){U({id:e.to_agent_id,name:e.to_agent});const t={id:`system-${Date.now()}`,text:e.from_agent?`Chat has been transferred from ${e.from_agent} to ${e.to_agent}`:`Chat has been transferred to ${e.to_agent}`,sender:"bot",timestamp:new Date};I(e=>[...e,t]),h&&console.log("Agent changed:",{from:e.from_agent,to:e.to_agent,reason:e.reason})}},[h]),ke=(0,o.useCallback)(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)h&&"customer"===e.sender_type&&console.log("Ignoring customer message from WebSocket (already added)");else{const t={id:e.id||`agent-${Date.now()}`,text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null)}else h&&console.warn("WebSocket message received without content:",e);break;case"typing_start":"agent"===e.sender_type&&(M(!0),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>{M(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(M(!1),ce.current&&(clearTimeout(ce.current),ce.current=null));break;case"agent_changed":be(e);break;case"chat_info":h&&console.log("Chat info:",e),"active"===e.status?(O(!1),Y(!0)):"resolved"!==e.status&&"ended"!==e.status||Se(e.chat_id||null),e.agent_id&&U(t=>({...t,id:e.agent_id}));break;case"agent_accepted":Y(!0),O(!1);const t={id:e.id||`agent-accepted-${e.chat_id||Date.now()}-${Date.now()}`,text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&U({name:e.to_agent,id:e.to_agent_id}),h&&console.log("Agent accepted chat:",e);break;case"chat_resolved":case"chat_ended":Se(e.chat_id||null),h&&console.log("Chat resolved/ended:",e);break;case"error":console.error("WebSocket error:",e.error);const s={id:`error-${Date.now()}`,text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,s]);break;case"pong":break;default:h&&console.log("Unknown message type:",e.type)}},[h,Se,be]),Ae=(0,o.useCallback)(e=>{4e3===e.code&&Se(pe)},[pe,Se]),_e=(0,o.useCallback)(e=>{W(e),e&&O(!1)},[]);(0,o.useEffect)(()=>{if("HUMAN"===he&&pe&&fe)return le.current.connectWebSocket(pe,fe,ke,_e,Ae),()=>{le.current.disconnectWebSocket()}},[he,pe,fe,ke,_e,Ae]);const ve=(0,o.useCallback)(async(e=!0)=>{if(pe&&fe)try{x(!0);const t=(await le.current.loadMessageHistory(pe,fe)).map(e=>({id:e.id||`msg-${Date.now()}-${Math.random()}`,text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));I(e?e=>{const s=new Set(e.map(e=>e.id)),n=t.filter(e=>!s.has(e.id));return[...e,...n].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(e){if(console.error("Error loading message history:",e),h){const t={id:`error-${Date.now()}`,text:`Failed to load chat history: ${e.message}`,sender:"bot",timestamp:new Date};I(e=>[...e,t])}}finally{x(!1)}},[pe,fe,h]);(0,o.useEffect)(()=>{if("HUMAN"===he&&pe&&fe){const e=`${pe}-${fe}`;ue.current!==e&&(ue.current=e,setTimeout(()=>{0===v.length&&ve(!1).catch(console.error)},0))}else"BOT"===he&&(ue.current=null)},[he,pe,fe,ve,v.length]);const Ie=async()=>{if(P)return P;try{j(!0);const e=Ee();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const t=await async function(e){try{const t=await Lt(e),s=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n=e.dfLocation.split(" ")[0].trim(),r=`https://${n}-dialogflow.googleapis.com/v3/${Wt(e.dfProjectId,n,e.dfAgentId,s)}:detectIntent`,o={queryInput:{text:{text:"hello"},languageCode:e.languageCode||"en"}},a=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error?.message||`HTTP error! status: ${a.status}`)}const i=await a.json();let c="Hello! I'm BlockSpark AI Assistant. How can I help you today?",l=null;if(i.queryResult?.responseMessages){const e=i.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(c=e.join(" ")),l=$t(i.queryResult.responseMessages)}else i.queryResult?.fulfillmentText&&(c=i.queryResult.fulfillmentText);return{session_id:s,message:c,...l&&{richContent:l}}}catch(e){console.error("Error creating Dialogflow session:",e);const t=e.message||"Failed to create session";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");throw new Error(t)}}(e);if(N(t.session_id),t.message){h&&(console.log("Session response richContent:",t.richContent),console.log("Full session response:",t));const e={id:`welcome-${Date.now()}`,text:t.message,sender:"bot",timestamp:new Date,richContent:t.richContent};I([e])}return t.session_id}catch(e){console.error("Error creating session:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,config:Ee()});const t={id:`error-${Date.now()}`,text:h?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:l,sender:"bot",timestamp:new Date};return I([t]),null}finally{j(!1)}},Ce=async(e,t,s=!1)=>{if(!e.trim())return;if(J){if("name"===X){const t=e.trim();ee(t),oe.current=t,Q("email");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return I(e=>[...e,n]),void R("")}if("email"===X){const t=e.trim();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){const e={id:(Date.now()+1).toString(),text:"Please provide a valid email address:",sender:"bot",timestamp:new Date};return I(t=>[...t,e]),void R("")}se(t),Q("mobile");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return I(e=>[...e,n]),void R("")}if("mobile"===X){const t=e.trim();if(!/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(t)||t.length<10){const e={id:(Date.now()+1).toString(),text:"Please provide a valid mobile number (e.g., +1234567890):",sender:"bot",timestamp:new Date};return I(t=>[...t,e]),void R("")}re(t);const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,s]);const n=oe.current,r=te;return F(!1),Q(null),oe.current="",await(async(e,t,s)=>{try{O(!0);const n=P,r=await le.current.ensureChatInitialized(pe,fe,n||null,e||null,t||null,s||null);if(!r||!r.chat_id)throw new Error("Failed to initialize chat session");const o=r.chat_id,a=r.session_id;o!==pe&&(ye(o),we(a),h&&console.log("✅ Chat initialized:",{chatId:o,sessionId:a}));try{await le.current.requestHandoff(o,a,"Customer requested human agent",n||null,e||null,t||null,s||null),h&&console.log("✅ Handoff requested successfully")}catch(r){if(!(r.message?.includes("Invalid chat_id")||r.message?.includes("Chat not found")||r.message?.includes("unauthorized")||r.message?.includes("400")||r.message?.includes("401")||r.message?.includes("404")||r.message?.includes("expired")))throw r;{h&&console.log("⚠️ Chat expired or not found. Re-initializing chat..."),ye(null),we(null);const r=await le.current.startSupportChat(n||null,e||null,t||null,s||null);if(!r||!r.chat_id)throw new Error("Failed to re-initialize chat session");const o=r.chat_id,a=r.session_id;ye(o),we(a),await le.current.requestHandoff(o,a,"Customer requested human agent",n||null,e||null,t||null,s||null),h&&console.log("✅ Handoff requested successfully after retry");const i=`${o}-${a}`;ue.current!==i&&(ue.current=i,await ve(!0))}}me(),V(!1),Y(!1);const i={id:`connecting-${Date.now()}`,text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};I(e=>[...e,i]);const c=`${o}-${a}`;ue.current=c}catch(e){console.error("Error handling handoff:",e);const t={id:`error-${Date.now()}`,text:h?`Handoff error: ${e.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t]),O(!1)}})(n,r,t),void R("")}}if("HUMAN"===he){if(!pe||!fe){const e={id:Date.now().toString(),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}if(!s){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,s])}le.current.sendTypingIndicator("typing_stop"),ie.current&&(clearTimeout(ie.current),ie.current=null),R(""),x(!0);try{le.current.sendMessageViaWebSocket(e.trim())||await le.current.sendMessageToAgent(pe,fe,e.trim())}catch(t){if(t instanceof Vt||"ChatResolvedError"===t?.name||"chat_resolved"===t?.message)return void Se(pe);if(console.error("Error sending message to agent:",t),t.message?.includes("Chat not found")||t.message?.includes("unauthorized")||t.message?.includes("401")||t.message?.includes("404")){h&&console.log("⚠️ Chat expired. Re-initializing..."),ye(null),we(null);try{const t=await le.current.startSupportChat(P||null,null,null,null);ye(t.chat_id),we(t.session_id);try{await le.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(e){if(e instanceof Vt||"ChatResolvedError"===e?.name||"chat_resolved"===e?.message)return void Se(t.chat_id);throw e}return}catch(e){if(e instanceof Vt||"ChatResolvedError"===e?.name||"chat_resolved"===e?.message)return void Se(pe);const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t])}}else{const e={id:(Date.now()+1).toString(),text:h?`Error: ${t.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(t=>[...t,e])}}finally{x(!1)}return}let n=P;if(!n)try{if(n=await Ie(),!n){const e={id:Date.now().toString(),text:h?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}}catch(e){console.error("Error in createSession:",e);const t={id:Date.now().toString(),text:h?`Connection Error: ${e.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void I(e=>[...e,t])}if(!s){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,s])}R(""),x(!0);try{const t=Ee();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const s=await async function(e,t,s){try{const n=await Lt(s),r=s.dfLocation.split(" ")[0].trim(),o=`https://${r}-dialogflow.googleapis.com/v3/${Wt(s.dfProjectId,r,s.dfAgentId,t)}:detectIntent`,a={queryInput:{text:{text:e.trim()},languageCode:s.languageCode||"en"}},i=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const e=await i.text();let t={};try{t=JSON.parse(e)}catch{t={message:e||`HTTP ${i.status}`}}const s=t.error?.message||t.message||`HTTP error! status: ${i.status}`;throw console.error("Dialogflow API Error (sendMessage):",{status:i.status,statusText:i.statusText,error:t,endpoint:o}),new Error(s)}const c=await i.json();let l="I'm sorry, I didn't understand that. Could you please rephrase?",d=null,u=!1;if(!0===c.queryResult?.parameters?.fields?.handoff?.boolValue)u=!0;else if(c.queryResult?.responseMessages)for(const e of c.queryResult.responseMessages)if(e.payload&&"object"==typeof e.payload){if(!0===e.payload.handoff){u=!0;break}if(!0===e.payload.fields?.handoff?.boolValue){u=!0;break}}if(!0===c.handoff&&(u=!0),c.queryResult?.responseMessages){const e=c.queryResult.responseMessages.filter(e=>e.text).map(e=>e.text.text.join(" "));e.length>0&&(l=e.join(" ")),d=$t(c.queryResult.responseMessages)}else c.queryResult?.fulfillmentText&&(l=c.queryResult.fulfillmentText);return{response:l,session_id:t,source:"dialogflow",timestamp:(new Date).toISOString(),...d&&{richContent:d},...u&&{handoff:!0}}}catch(e){console.error("Error sending message to Dialogflow:",e);const t=e.message||"Failed to send message";if(t.includes("401")||t.includes("Unauthorized"))throw new Error("Authentication failed. Please check your service account key or access token.");if(t.includes("403")||t.includes("Forbidden"))throw new Error("Access forbidden. Please check your Dialogflow API permissions.");if(t.includes("404")||t.includes("Not Found"))throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");if(t.includes("CORS"))throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");throw new Error(t)}}(e.trim(),n,t);if(h&&(console.log("Chat response richContent:",s.richContent),console.log("Full chat response:",s),console.log("Handoff detected:",s.handoff)),!0===s.handoff){const e={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(t=>[...t,e]),F(!0),Q("name"),ee(""),se(""),oe.current="";const t={id:(Date.now()+2).toString(),text:"To connect you with a human agent, I'll need some information. Please provide your name:",sender:"bot",timestamp:new Date};return void I(e=>[...e,t])}const r={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(e=>[...e,r])}catch(e){console.error("Error sending message:",e),h&&console.error("Full error details:",{message:e.message,stack:e.stack,sessionId:n,config:Ee()});const t={id:(Date.now()+1).toString(),text:h?`Error: ${e.message||"Failed to send message. Please check your Dialogflow configuration."}`:e.message?.includes("Failed to fetch")||e.message?.includes("CORS")?"Unable to connect to Dialogflow. Please check your configuration and network.":"Sorry, I'm having trouble processing your message. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,t])}finally{x(!1)}};(0,o.useEffect)(()=>()=>{ie.current&&clearTimeout(ie.current),ce.current&&clearTimeout(ce.current)},[]);const Re=async()=>{k(!0),_(!1),P||await Ie()};return(0,o.useEffect)(()=>()=>{le.current.disconnectWebSocket()},[]),(0,r.jsxs)(r.Fragment,{children:[A&&!b&&(0,r.jsxs)("div",{className:"custom-welcome-popup",onClick:Re,children:[(0,r.jsxs)("div",{className:"custom-welcome-header",children:[(0,r.jsx)("div",{className:"custom-welcome-title",children:s}),(0,r.jsx)("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),_(!1)},children:"×"})]}),(0,r.jsx)("div",{className:"custom-welcome-message",children:n}),(0,r.jsx)("div",{className:"custom-welcome-cta",children:a})]}),!b&&(0,r.jsx)("button",{className:"custom-chat-toggle-btn",onClick:Re,"aria-label":"Open chat",children:(0,r.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),b&&(0,r.jsxs)("div",{className:"custom-chat-window",children:[(0,r.jsxs)("div",{className:"custom-chat-header",children:[(0,r.jsxs)("div",{className:"custom-chat-header-content",children:[(0,r.jsx)("div",{className:"custom-chat-title",children:e}),(0,r.jsxs)("div",{className:"custom-chat-subtitle",children:[t,"HUMAN"===he&&(0,r.jsxs)("span",{className:"custom-mode-indicator",children:[" ","• ",L?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===he&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"custom-mode-badge",children:"Human Support Mode"}),(0,r.jsxs)("div",{className:"custom-agent-info",children:[(0,r.jsx)("span",{className:"custom-agent-label",children:"Agent:"}),(0,r.jsx)("span",{className:"custom-agent-name",children:K.name})]})]}),"BOT"===he&&(0,r.jsx)("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),(0,r.jsx)("button",{className:"custom-chat-close-btn",onClick:()=>{k(!1),"HUMAN"===he&&le.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),(0,r.jsxs)("div",{className:"custom-chat-messages",children:[D&&0===v.length&&(0,r.jsxs)("div",{className:"custom-chat-empty",children:[(0,r.jsxs)("div",{className:"custom-typing-indicator",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("p",{children:"Initializing chat..."})]}),!D&&0===v.length&&(0,r.jsxs)("div",{className:"custom-chat-empty",children:[(0,r.jsx)("div",{className:"custom-chat-empty-icon",children:"👋"}),(0,r.jsx)("p",{children:u})]}),v.map(e=>(0,r.jsxs)("div",{className:`custom-message custom-message-${e.sender}`,children:[(0,r.jsx)("div",{className:"custom-message-content",children:(0,r.jsx)(Ge,{options:{defaultProtocol:"https",target:{url:"_blank"},attributes:{rel:"noopener noreferrer"}},children:e.text})}),(h&&e.richContent&&(console.log("Rendering message with richContent:",e.richContent),console.log("richContent type:",typeof e.richContent),console.log("richContent is array:",Array.isArray(e.richContent)),console.log("richContent length:",e.richContent?.length)),e.richContent&&Array.isArray(e.richContent)&&e.richContent.length>0?(0,r.jsx)("div",{className:"custom-chips-container",children:e.richContent.map((e,t)=>{if(h&&console.log(`Processing contentGroup ${t}:`,e),!Array.isArray(e)){const s=e;return s&&"chips"===s.type&&s.options?(0,r.jsx)("div",{className:"custom-chips-group",children:s.options.map((e,t)=>(0,r.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};I(e=>[...e,t]),Ce(e.text,e.text,!0)},type:"button",children:e.text},t))},t):null}return e.map((e,s)=>(h&&console.log(`Processing content ${t}-${s}:`,e),e&&"chips"===e.type&&e.options?(0,r.jsx)("div",{className:"custom-chips-group",children:e.options.map((e,t)=>(0,r.jsx)("button",{className:"custom-chip-button",onClick:()=>{const t={id:Date.now().toString(),text:e.text,sender:"user",timestamp:new Date};I(e=>[...e,t]),Ce(e.text,e.text,!0)},type:"button",children:e.text},t))},`${t}-${s}`):null))})}):null),(0,r.jsx)("div",{className:"custom-message-time",children:e.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},e.id)),T&&(0,r.jsx)("div",{className:"custom-message custom-message-bot",children:(0,r.jsxs)("div",{className:"custom-typing-indicator",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]})}),H&&(0,r.jsxs)("div",{className:"custom-message custom-message-bot",children:[(0,r.jsxs)("div",{className:"custom-typing-indicator",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("div",{className:"custom-message-content",children:"Connecting to agent..."})]}),"HUMAN"===he&&$&&(0,r.jsxs)("div",{className:"custom-agent-typing-indicator",children:[(0,r.jsxs)("span",{className:"custom-typing-dots",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"custom-typing-text",children:"Agent is typing..."})]}),(0,r.jsx)("div",{ref:ae})]}),(0,r.jsxs)("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Ce(C)},children:[(0,r.jsx)("input",{type:"text",className:"custom-chat-input",value:C,onChange:e=>{const t=e.target.value;R(t),"HUMAN"===he&&L&&(le.current.sendTypingIndicator("typing_start"),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{le.current.sendTypingIndicator("typing_stop"),ie.current=null},2e3))},placeholder:d,disabled:T||D||z}),(0,r.jsx)("button",{type:"submit",className:"custom-chat-send-btn",disabled:!C.trim()||T||D||z,children:(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),(0,r.jsx)("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})}export{Yt as ChatWidget};
|