@freeday-ai/webchat-sdk
Advanced tools
Comparing version 0.0.1-alpha.34 to 0.0.1-alpha.35
@@ -143,2 +143,3 @@ import { Channel } from 'phoenix'; | ||
updateState: (state: ChatState) => void; | ||
notifyUser: (type: "error" | "warning" | "info", message: string, options?: {}) => void; | ||
notify: (type: "traces" | "email", message: string, options?: {}) => void; | ||
@@ -181,2 +182,3 @@ } | ||
onStateUpdated?: (state: ChatState) => void; | ||
onNotifyUser?: (type: 'error' | 'warning' | 'info', message: string, options?: any) => void; | ||
}; | ||
@@ -183,0 +185,0 @@ |
@@ -1,2 +0,2 @@ | ||
var Ve=Object.defineProperty;var We=(I,T,L)=>T in I?Ve(I,T,{enumerable:!0,configurable:!0,writable:!0,value:L}):I[T]=L;var u=(I,T,L)=>We(I,typeof T!="symbol"?T+"":T,L);(function(){"use strict";var I={exports:{}};(function(t){var e=function(n){var s=Object.prototype,i=s.hasOwnProperty,o=Object.defineProperty||function(a,r,h){a[r]=h.value},c,l=typeof Symbol=="function"?Symbol:{},g=l.iterator||"@@iterator",v=l.asyncIterator||"@@asyncIterator",_=l.toStringTag||"@@toStringTag";function m(a,r,h){return Object.defineProperty(a,r,{value:h,enumerable:!0,configurable:!0,writable:!0}),a[r]}try{m({},"")}catch{m=function(r,h,p){return r[h]=p}}function V(a,r,h,p){var d=r&&r.prototype instanceof Z?r:Z,f=Object.create(d.prototype),b=new ne(p||[]);return o(f,"_invoke",{value:Be(a,h,b)}),f}n.wrap=V;function x(a,r,h){try{return{type:"normal",arg:a.call(r,h)}}catch(p){return{type:"throw",arg:p}}}var le="suspendedStart",$e="suspendedYield",ue="executing",W="completed",S={};function Z(){}function z(){}function O(){}var Q={};m(Q,g,function(){return this});var ee=Object.getPrototypeOf,q=ee&&ee(ee(se([])));q&&q!==s&&i.call(q,g)&&(Q=q);var j=O.prototype=Z.prototype=Object.create(Q);z.prototype=O,o(j,"constructor",{value:O,configurable:!0}),o(O,"constructor",{value:z,configurable:!0}),z.displayName=m(O,_,"GeneratorFunction");function de(a){["next","throw","return"].forEach(function(r){m(a,r,function(h){return this._invoke(r,h)})})}n.isGeneratorFunction=function(a){var r=typeof a=="function"&&a.constructor;return r?r===z||(r.displayName||r.name)==="GeneratorFunction":!1},n.mark=function(a){return Object.setPrototypeOf?Object.setPrototypeOf(a,O):(a.__proto__=O,m(a,_,"GeneratorFunction")),a.prototype=Object.create(j),a},n.awrap=function(a){return{__await:a}};function J(a,r){function h(f,b,y,C){var w=x(a[f],a,b);if(w.type==="throw")C(w.arg);else{var ie=w.arg,$=ie.value;return $&&typeof $=="object"&&i.call($,"__await")?r.resolve($.__await).then(function(M){h("next",M,y,C)},function(M){h("throw",M,y,C)}):r.resolve($).then(function(M){ie.value=M,y(ie)},function(M){return h("throw",M,y,C)})}}var p;function d(f,b){function y(){return new r(function(C,w){h(f,b,C,w)})}return p=p?p.then(y,y):y()}o(this,"_invoke",{value:d})}de(J.prototype),m(J.prototype,v,function(){return this}),n.AsyncIterator=J,n.async=function(a,r,h,p,d){d===void 0&&(d=Promise);var f=new J(V(a,r,h,p),d);return n.isGeneratorFunction(r)?f:f.next().then(function(b){return b.done?b.value:f.next()})};function Be(a,r,h){var p=le;return function(f,b){if(p===ue)throw new Error("Generator is already running");if(p===W){if(f==="throw")throw b;return Fe()}for(h.method=f,h.arg=b;;){var y=h.delegate;if(y){var C=pe(y,h);if(C){if(C===S)continue;return C}}if(h.method==="next")h.sent=h._sent=h.arg;else if(h.method==="throw"){if(p===le)throw p=W,h.arg;h.dispatchException(h.arg)}else h.method==="return"&&h.abrupt("return",h.arg);p=ue;var w=x(a,r,h);if(w.type==="normal"){if(p=h.done?W:$e,w.arg===S)continue;return{value:w.arg,done:h.done}}else w.type==="throw"&&(p=W,h.method="throw",h.arg=w.arg)}}}function pe(a,r){var h=r.method,p=a.iterator[h];if(p===c)return r.delegate=null,h==="throw"&&a.iterator.return&&(r.method="return",r.arg=c,pe(a,r),r.method==="throw")||h!=="return"&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+h+"' method")),S;var d=x(p,a.iterator,r.arg);if(d.type==="throw")return r.method="throw",r.arg=d.arg,r.delegate=null,S;var f=d.arg;if(!f)return r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,S;if(f.done)r[a.resultName]=f.value,r.next=a.nextLoc,r.method!=="return"&&(r.method="next",r.arg=c);else return f;return r.delegate=null,S}de(j),m(j,_,"Generator"),m(j,g,function(){return this}),m(j,"toString",function(){return"[object Generator]"});function Ge(a){var r={tryLoc:a[0]};1 in a&&(r.catchLoc=a[1]),2 in a&&(r.finallyLoc=a[2],r.afterLoc=a[3]),this.tryEntries.push(r)}function te(a){var r=a.completion||{};r.type="normal",delete r.arg,a.completion=r}function ne(a){this.tryEntries=[{tryLoc:"root"}],a.forEach(Ge,this),this.reset(!0)}n.keys=function(a){var r=Object(a),h=[];for(var p in r)h.push(p);return h.reverse(),function d(){for(;h.length;){var f=h.pop();if(f in r)return d.value=f,d.done=!1,d}return d.done=!0,d}};function se(a){if(a!=null){var r=a[g];if(r)return r.call(a);if(typeof a.next=="function")return a;if(!isNaN(a.length)){var h=-1,p=function d(){for(;++h<a.length;)if(i.call(a,h))return d.value=a[h],d.done=!1,d;return d.value=c,d.done=!0,d};return p.next=p}}throw new TypeError(typeof a+" is not iterable")}n.values=se;function Fe(){return{value:c,done:!0}}return ne.prototype={constructor:ne,reset:function(a){if(this.prev=0,this.next=0,this.sent=this._sent=c,this.done=!1,this.delegate=null,this.method="next",this.arg=c,this.tryEntries.forEach(te),!a)for(var r in this)r.charAt(0)==="t"&&i.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=c)},stop:function(){this.done=!0;var a=this.tryEntries[0],r=a.completion;if(r.type==="throw")throw r.arg;return this.rval},dispatchException:function(a){if(this.done)throw a;var r=this;function h(C,w){return f.type="throw",f.arg=a,r.next=C,w&&(r.method="next",r.arg=c),!!w}for(var p=this.tryEntries.length-1;p>=0;--p){var d=this.tryEntries[p],f=d.completion;if(d.tryLoc==="root")return h("end");if(d.tryLoc<=this.prev){var b=i.call(d,"catchLoc"),y=i.call(d,"finallyLoc");if(b&&y){if(this.prev<d.catchLoc)return h(d.catchLoc,!0);if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else if(b){if(this.prev<d.catchLoc)return h(d.catchLoc,!0)}else if(y){if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(a,r){for(var h=this.tryEntries.length-1;h>=0;--h){var p=this.tryEntries[h];if(p.tryLoc<=this.prev&&i.call(p,"finallyLoc")&&this.prev<p.finallyLoc){var d=p;break}}d&&(a==="break"||a==="continue")&&d.tryLoc<=r&&r<=d.finallyLoc&&(d=null);var f=d?d.completion:{};return f.type=a,f.arg=r,d?(this.method="next",this.next=d.finallyLoc,S):this.complete(f)},complete:function(a,r){if(a.type==="throw")throw a.arg;return a.type==="break"||a.type==="continue"?this.next=a.arg:a.type==="return"?(this.rval=this.arg=a.arg,this.method="return",this.next="end"):a.type==="normal"&&r&&(this.next=r),S},finish:function(a){for(var r=this.tryEntries.length-1;r>=0;--r){var h=this.tryEntries[r];if(h.finallyLoc===a)return this.complete(h.completion,h.afterLoc),te(h),S}},catch:function(a){for(var r=this.tryEntries.length-1;r>=0;--r){var h=this.tryEntries[r];if(h.tryLoc===a){var p=h.completion;if(p.type==="throw"){var d=p.arg;te(h)}return d}}throw new Error("illegal catch attempt")},delegateYield:function(a,r,h){return this.delegate={iterator:se(a),resultName:r,nextLoc:h},this.method==="next"&&(this.arg=c),S}},n}(t.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(I);var T={NVM_INC:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/include/node",COREPACK_ROOT:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/lib/node_modules/corepack",HERD_PHP_80_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/80/",TERM_PROGRAM:"vscode",NODE:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin/node",INIT_CWD:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",NVM_CD_FLAGS:"-q",npm_package_dependencies_axios:"^1.7.7",npm_package_dependencies_vite_plugin_dts:"^4.2.1",npm_package_devDependencies_typescript:"^5.6.2",TERM:"xterm-256color",SHELL:"/bin/zsh",npm_package_unpkg:"dist/freeday-webchat-sdk.iife.js",npm_package_devDependencies_vite:"^5.4.6",HOMEBREW_REPOSITORY:"/opt/homebrew",TMPDIR:"/var/folders/lt/0l1rfzpn6sq61y39zg58rb340000gn/T/",npm_package_scripts_lint:"eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",TERM_PROGRAM_VERSION:"1.96.0",npm_package_devDependencies__vitejs_plugin_react:"^4.3.1",npm_package_scripts_dev:"vite",ZDOTDIR:"/Users/beaudinngreve",ORIGINAL_XDG_CURRENT_DESKTOP:"undefined",MallocNanoZone:"0",npm_package_scripts_test_ci:"vitest --coverage --watch=false",npm_config_registry:"https://registry.npmjs.org/",HERD_PHP_83_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/83/",ZSH:"/Users/beaudinngreve/.oh-my-zsh",npm_package_dependencies_react_dom:"^18.3.1",npm_package_devDependencies_eslint_plugin_react_refresh:"^0.4.12",npm_package_dependencies_regenerator_runtime:"^0.14.1",NVM_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm",USER:"beaudinngreve",npm_package_description:"Freeday webchat sdk",LS_COLORS:"di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43",npm_package_license:"MIT",npm_package_devDependencies__types_react:"^18.3.7",COMMAND_MODE:"unix2003",PNPM_SCRIPT_SRC_DIR:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",npm_package_exports___import:"./dist/freeday-webchat-sdk-lib.js",SSH_AUTH_SOCK:"/private/tmp/com.apple.launchd.sgjnAxi6eg/Listeners",__CF_USER_TEXT_ENCODING:"0x1F5:0x0:0x5",npm_package_devDependencies_eslint:"^9.10.0",HERD_PHP_82_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/82/",npm_package_devDependencies__typescript_eslint_eslint_plugin:"^8.6.0",npm_execpath:"/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/bin/pnpm.cjs",PAGER:"less",npm_package_module:"./dist/freeday-webchat-widget-lib.js",LSCOLORS:"Gxfxcxdxbxegedabagacad",npm_package_devDependencies__types_react_dom:"^18.3.0",npm_config_frozen_lockfile:"",npm_package_devDependencies__typescript_eslint_parser:"^8.6.0",PATH:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.bin:/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node-gyp-bin:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.bin:/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node-gyp-bin:/opt/homebrew/share/google-cloud-sdk/bin:/opt/homebrew/opt/postgresql@16/bin:/Users/beaudinngreve/Library/Application Support/Herd/bin/:/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/homebrew/share/google-cloud-sdk/bin:/opt/homebrew/opt/postgresql@16/bin:/Users/beaudinngreve/Library/Application Support/Herd/bin/:/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/Users/beaudinngreve/Library/Application Support/Code/User/globalStorage/github.copilot-chat/debugCommand",COREPACK_ENABLE_DOWNLOAD_PROMPT:"1",USER_ZDOTDIR:"/Users/beaudinngreve",__CFBundleIdentifier:"com.microsoft.VSCode",npm_package_author:"freeday",PWD:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",npm_command:"run-script",npm_package_scripts_preview:"vite preview",npm_package_devDependencies_eslint_plugin_react_hooks:"^4.6.2",npm_lifecycle_event:"build-widget",LANG:"en_US.UTF-8",npm_package_name:"@freeday-ai/webchat-sdk",npm_package_types:"./dist/freeday-webchat-sdk-lib.d.ts",npm_package_packageManager:"pnpm@9.4.0",npm_package_scripts_build_widget:"vite build --config vite.widget.config.js",NODE_PATH:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.8_@types+node@22.7.5/node_modules/vite/bin/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.8_@types+node@22.7.5/node_modules/vite/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.8_@types+node@22.7.5/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/node_modules",npm_package_scripts_build:"pnpm build-module-bundle && pnpm build-widget",npm_package_dependencies_phoenix:"^1.7.14",npm_package_devDependencies__vitest_coverage_v8:"^2.1.2",VSCODE_GIT_ASKPASS_EXTRA_ARGS:"",XPC_FLAGS:"0x0",npm_package_devDependencies_vitest:"^2.1.2",npm_package_main:"./dist/freeday-webchat-sdk-lib.umd.cjs",npm_config_node_gyp:"/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node_modules/node-gyp/bin/node-gyp.js",XPC_SERVICE_NAME:"0",npm_package_version:"0.0.1-alpha.33",VSCODE_INJECTION:"1",SHLVL:"3",HOME:"/Users/beaudinngreve",npm_package_type:"module",VSCODE_GIT_ASKPASS_MAIN:"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/git/dist/askpass-main.js",npm_package_scripts_test:"vitest",HOMEBREW_PREFIX:"/opt/homebrew",LESS:"-R",LOGNAME:"beaudinngreve",npm_package_exports___require:"./dist/freeday-webchat-sdk-lib.umd.cjs",npm_lifecycle_script:"vite build --config vite.widget.config.js",VSCODE_GIT_IPC_HANDLE:"/var/folders/lt/0l1rfzpn6sq61y39zg58rb340000gn/T/vscode-git-acf59dfa1d.sock",npm_package_dependencies_react:"^18.3.1",NVM_BIN:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin",npm_config_user_agent:"pnpm/9.4.0 npm/? node/v20.13.1 darwin arm64",VSCODE_GIT_ASKPASS_NODE:"/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin)",GIT_ASKPASS:"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/git/dist/askpass.sh",HERD_PHP_74_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/74/",INFOPATH:"/opt/homebrew/share/info:/opt/homebrew/share/info:",HOMEBREW_CELLAR:"/opt/homebrew/Cellar",npm_package_devDependencies__types_node:"^22.7.5",npm_package_devDependencies__types_phoenix:"^1.6.5",npm_package_files_0:"dist",npm_package_scripts_build_module_bundle:"vite build --config vite.config.js ",COLORTERM:"truecolor",npm_node_execpath:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin/node",NODE_ENV:"production"};const L=T.NEXT_PUBLIC_BASE_URL||"https://webchat.freeday.chat",ge=t=>!!(t.location.hostname==="localhost"||t.location.hostname==="[::1]"||t.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)),fe=(t=L)=>{const[e,n]=t.split("://");return`${e==="https"?"wss":"ws"}://${n}/socket`},me=t=>!t||!t.length?!1:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),ve=t=>t.replace(/_([a-z])/g,(e,n)=>n.toUpperCase()),K=t=>Array.isArray(t)?t.map(e=>K(e)):t!==null&&typeof t=="object"?Object.keys(t).reduce((e,n)=>{const s=ve(n);return e[s]=K(t[n]),e},{}):t,re=t=>new Date(t).getTime();class _e{constructor(e=L){u(this,"baseUrl");this.baseUrl=e}getDefaultOptions(e,n){return{method:e,headers:{"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0}}get(e,n={}){const s=new URLSearchParams(n).toString(),i=`${this.baseUrl}${e}?${s}`;return fetch(i,this.getDefaultOptions("GET")).then(o=>{if(!o.ok)throw new Error(`GET request failed: ${o.statusText}`);return o.json()}).catch(o=>{throw new Error(`Error occurred during GET request: ${o.message}`)})}post(e,n){const s=`${this.baseUrl}${e}`;return fetch(s,this.getDefaultOptions("POST",n)).then(i=>{if(!i.ok)throw new Error(`POST request failed: ${i.statusText}`);return i.json()}).catch(i=>{throw new Error(`Error occurred during POST request: ${i.message}`)})}async put(e,n){const s=`${this.baseUrl}${e}`;return fetch(s,this.getDefaultOptions("PUT",n)).then(i=>{if(!i.ok)throw new Error(`PUT request failed: ${i.statusText}`);return i.json()}).catch(i=>{throw new Error(`Error occurred during PUT request: ${i.message}`)})}}class be{constructor(e,n){u(this,"http");u(this,"token");this.token=e,this.http=new _e(n)}async healthCheck(){return this.http.get("/api/health-check").then(e=>e.status)}async fetchWidgetSettings(){return this.http.get(`/api/widget/settings/${this.token}`).then(e=>K(e.data))}async updateWidgetSettingsMetadata(e){return this.http.put(`/api/widget/settings/${this.token}/metadata`,e)}async createNewUser(e={}){return this.http.post("/api/users",{user:{...e,first_seen:new Date().toISOString(),last_seen_at:new Date().toISOString()}}).then(n=>n.data)}async isValidUser(e){return this.http.get(`/api/users/${e}/exists`).then(n=>n.exists)}async updateUserMetadata(e,n){return this.http.put(`/api/users/${e}/metadata`,{metadata:n}).then(s=>s.data)}async findUserByExternalId(e){const n=this.token;return this.http.get("/api/users/identify",{external_id:e,token:n})}async fetchConversationById(e){return this.http.get(`/api/conversations/${e}`).then(n=>n.data)}async createNewConversation(e,n){return this.http.post("/api/conversations",{conversation:{user_id:e,token:n}}).then(s=>s.data)}async fetchUserConversations(e){return this.http.get("/api/conversations/user",e).then(n=>n.data)}}var N=t=>typeof t=="function"?t:function(){return t},ye=typeof self<"u"?self:null,P=typeof window<"u"?window:null,A=ye||P||A,we="2.0.0",E={connecting:0,open:1,closing:2,closed:3},ke=1e4,Ce=1e3,k={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},U={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},X={longpoll:"longpoll",websocket:"websocket"},Se={complete:4},B=class{constructor(t,e,n,s){this.channel=t,this.event=e,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:t,response:e,_ref:n}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},oe=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Ee=class{constructor(t,e,n){this.state=k.closed,this.topic=t,this.params=N(e||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new B(this,U.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new oe(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=k.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=k.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=k.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=k.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new B(this,U.leave,N({}),this.timeout).send(),this.state=k.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(U.reply,(s,i)=>{this.trigger(this.replyEventName(i),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(t){this.on(U.close,t)}onError(t){return this.on(U.error,e=>t(e))}on(t,e){let n=this.bindingRef++;return this.bindings.push({event:t,ref:n,callback:e}),n}off(t,e){this.bindings=this.bindings.filter(n=>!(n.event===t&&(typeof e>"u"||e===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,n=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new B(this,t,function(){return e},n);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=k.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(U.close,"leave")},n=new B(this,U.leave,N({}),t);return n.receive("ok",()=>e()).receive("timeout",()=>e()),n.send(),this.canPush()||n.trigger("ok",{}),n}onMessage(t,e,n){return e}isMember(t,e,n,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:n,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=k.joining,this.joinPush.resend(t))}trigger(t,e,n,s){let i=this.onMessage(t,e,n,s);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let o=this.bindings.filter(c=>c.event===t);for(let c=0;c<o.length;c++)o[c].callback(i,n,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===k.closed}isErrored(){return this.state===k.errored}isJoined(){return this.state===k.joined}isJoining(){return this.state===k.joining}isLeaving(){return this.state===k.leaving}},G=class{static request(t,e,n,s,i,o,c){if(A.XDomainRequest){let l=new A.XDomainRequest;return this.xdomainRequest(l,t,e,s,i,o,c)}else{let l=new A.XMLHttpRequest;return this.xhrRequest(l,t,e,n,s,i,o,c)}}static xdomainRequest(t,e,n,s,i,o,c){return t.timeout=i,t.open(e,n),t.onload=()=>{let l=this.parseJSON(t.responseText);c&&c(l)},o&&(t.ontimeout=o),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,n,s,i,o,c,l){return t.open(e,n,!0),t.timeout=o,t.setRequestHeader("Content-Type",s),t.onerror=()=>l&&l(null),t.onreadystatechange=()=>{if(t.readyState===Se.complete&&l){let g=this.parseJSON(t.responseText);l(g)}},c&&(t.ontimeout=c),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let n=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let i=e?`${e}[${s}]`:s,o=t[s];typeof o=="object"?n.push(this.serialize(o,i)):n.push(encodeURIComponent(i)+"="+encodeURIComponent(o))}return n.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let n=t.match(/\?/)?"&":"?";return`${t}${n}${this.serialize(e)}`}},Te=t=>{let e="",n=new Uint8Array(t),s=n.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(n[i]);return btoa(e)},D=class{constructor(t){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=E.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+X.websocket),"$1/"+X.longpoll)}endpointURL(){return G.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,n){this.close(t,e,n),this.readyState=E.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===E.open||this.readyState===E.connecting}poll(){this.ajax("GET","application/json",null,()=>this.ontimeout(),t=>{if(t){var{status:e,token:n,messages:s}=t;this.token=n}else e=0;switch(e){case 200:s.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=E.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(t){typeof t!="string"&&(t=Te(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",t.join(` | ||
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,n){for(let i of this.reqs)i.abort();this.readyState=E.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,n,s,i){let o,c=()=>{this.reqs.delete(o),s()};o=G.request(t,this.endpointURL(),e,n,this.timeout,c,l=>{this.reqs.delete(o),this.isActive()&&i(l)}),this.reqs.add(o)}},F={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let n=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(n))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[n,s,i,o,c]=JSON.parse(t);return e({join_ref:n,ref:s,topic:i,event:o,payload:c})}},binaryEncode(t){let{join_ref:e,ref:n,event:s,topic:i,payload:o}=t,c=this.META_LENGTH+e.length+n.length+i.length+s.length,l=new ArrayBuffer(this.HEADER_LENGTH+c),g=new DataView(l),v=0;g.setUint8(v++,this.KINDS.push),g.setUint8(v++,e.length),g.setUint8(v++,n.length),g.setUint8(v++,i.length),g.setUint8(v++,s.length),Array.from(e,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(n,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(i,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(s,m=>g.setUint8(v++,m.charCodeAt(0)));var _=new Uint8Array(l.byteLength+o.byteLength);return _.set(new Uint8Array(l),0),_.set(new Uint8Array(o),l.byteLength),_.buffer},binaryDecode(t){let e=new DataView(t),n=e.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,n){let s=e.getUint8(1),i=e.getUint8(2),o=e.getUint8(3),c=this.HEADER_LENGTH+this.META_LENGTH-1,l=n.decode(t.slice(c,c+s));c=c+s;let g=n.decode(t.slice(c,c+i));c=c+i;let v=n.decode(t.slice(c,c+o));c=c+o;let _=t.slice(c,t.byteLength);return{join_ref:l,ref:null,topic:g,event:v,payload:_}},decodeReply(t,e,n){let s=e.getUint8(1),i=e.getUint8(2),o=e.getUint8(3),c=e.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,g=n.decode(t.slice(l,l+s));l=l+s;let v=n.decode(t.slice(l,l+i));l=l+i;let _=n.decode(t.slice(l,l+o));l=l+o;let m=n.decode(t.slice(l,l+c));l=l+c;let V=t.slice(l,t.byteLength),x={status:m,response:V};return{join_ref:g,ref:v,topic:_,event:U.reply,payload:x}},decodeBroadcast(t,e,n){let s=e.getUint8(1),i=e.getUint8(2),o=this.HEADER_LENGTH+2,c=n.decode(t.slice(o,o+s));o=o+s;let l=n.decode(t.slice(o,o+i));o=o+i;let g=t.slice(o,t.byteLength);return{join_ref:null,ref:null,topic:c,event:l,payload:g}}},Ue=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||ke,this.transport=e.transport||A.WebSocket||D,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||A&&A.sessionStorage,this.establishedConnections=0,this.defaultEncoder=F.encode.bind(F),this.defaultDecoder=F.decode.bind(F),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==D?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;P&&P.addEventListener&&(P.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),n=this.connectClock)}),P.addEventListener("pageshow",s=>{n===this.connectClock&&(n=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,i,o)=>{console.log(`${s}: ${i}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=N(e.params||{}),this.endPoint=`${t}/${X.websocket}`,this.vsn=e.vsn||we,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new oe(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return D}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=G.appendParams(G.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,n){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(t,e,n)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=N(t)),!this.conn&&(this.longPollFallbackMs&&this.transport!==D?this.connectWithFallback(D,this.longPollFallbackMs):this.transportConnect())}log(t,e,n){this.logger&&this.logger(t,e,n)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),n=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(i=>{i.ref===e&&(this.off([s]),t(Date.now()-n))});return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let n=!1,s=!0,i,o,c=l=>{this.log("transport",`falling back to ${t.name}...`,l),this.off([i,o]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${t.name}`))return c("memorized");this.fallbackTimer=setTimeout(c,e),o=this.onError(l=>{this.log("transport","error",l),s&&!n&&(clearTimeout(this.fallbackTimer),c(l))}),this.onOpen(()=>{if(n=!0,!s)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t.name}`,"true"),this.log("transport",`established ${t.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,t])=>t())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Ce,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,n){if(!this.conn)return t&&t();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,n||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(t,e+1)},150*e)}waitForSocketClosed(t,e=1){if(e===5||!this.conn||this.conn.readyState===E.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(t,e+1)},150*e)}onConnClose(t){let e=t&&t.code;this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,n])=>n(t))}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,n=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,s])=>{s(t,e,n)}),(e===this.transport||n>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(U.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case E.connecting:return"connecting";case E.open:return"open";case E.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([n])=>t.indexOf(n)===-1)}channel(t,e={}){let n=new Ee(t,e,this);return this.channels.push(n),n}push(t){if(this.hasLogger()){let{topic:e,event:n,payload:s,ref:i,join_ref:o}=t;this.log("push",`${e} ${n} (${o}, ${i})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:n,event:s,payload:i,ref:o,join_ref:c}=e;o&&o===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${i.status||""} ${n} ${s} ${o&&"("+o+")"||""}`,i);for(let l=0;l<this.channels.length;l++){const g=this.channels[l];g.isMember(n,s,i,c)&&g.trigger(s,i,o,c)}for(let l=0;l<this.stateChangeCallbacks.message.length;l++){let[,g]=this.stateChangeCallbacks.message[l];g(e)}})}leaveOpenTopic(t){let e=this.channels.find(n=>n.topic===t&&(n.isJoined()||n.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Re{constructor(e){u(this,"debugModeEnabled");this.debugModeEnabled=!!e}debug(...e){this.debugModeEnabled&&console.debug("[@freeday/webchat-sdk]",...e)}log(...e){this.debugModeEnabled&&console.log("[@freeday/webchat-sdk]",...e)}info(...e){console.info("[@freeday/webchat-sdk]",...e)}warn(...e){console.warn("[@freeday/webchat-sdk]",...e)}error(...e){console.error("[@freeday/webchat-sdk]",...e)}}const ae="__FREEDAY__",Ie=t=>{try{return t&&(t.localStorage||t.sessionStorage)}catch{return{_db:{},getItem(n){return this._db[n]||null},setItem(n,s){this._db[n]=s},removeItem(n){delete this._db[n]}}}};function Le(t){const e=Ie(t),n=o=>{const c=e.getItem(`${ae}${o}`);if(!c)return null;try{return JSON.parse(c)}catch{return c}},s=(o,c)=>{e.setItem(`${ae}${o}`,JSON.stringify(c))},i=o=>{e.removeItem(o)};return{getUserId:()=>n("__USER_ID__"),setUserId:o=>s("__USER_ID__",o),removeUserId:()=>i("__USER_ID__")}}var H=(t=>(t.TOGGLE="freeday:toggle",t.RESTART="freeday:restart",t.OPEN="freeday:open",t.CLOSE="freeday:close",t))(H||{});const R=class R{constructor(e){u(this,"socket");u(this,"channel");u(this,"api");u(this,"logger");u(this,"storage");u(this,"config");u(this,"userId");u(this,"conversationId");u(this,"messages");u(this,"settings");u(this,"connectionState","disconnected");u(this,"loading",!1);u(this,"reconnectTimer");u(this,"state","input");u(this,"start",async()=>{this.connect();const e=await this.fetchWidgetSettings(),n=this.userId,s=this.config.user||{},i=await this.checkForExistingUser(s,n);return this.conversationId?this.setWidgetSettings(e).setUserId(i).fetchConversation(this.conversationId):this.setWidgetSettings(e).setUserId(i).fetchLatestConversation()});u(this,"connect",()=>{this.socket.connect()});u(this,"disconnect",()=>{this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.channel&&this.channel.leave(),this.socket&&this.socket.disconnect(()=>{this.logger.debug("Socket disconnected.")})});u(this,"restart",()=>{var e;(e=this.channel)==null||e.push("request_restart",{}),this.setMessages([]),setTimeout(()=>this.updateState("input"),2e3)});u(this,"sendActionEvent",(e,n)=>{var s;console.log("Sending action event:",n,e),(s=this.channel)==null||s.push("action-event",{name:e,...n})});u(this,"setWidgetSettings",e=>(this.settings=e,this));u(this,"setUserId",e=>{var n,s;return this.logger.debug("Setting user ID:",e),this.userId=e,this.cacheUserId(e),window.dispatchEvent(new CustomEvent("freeday:user:set",{detail:e})),(s=(n=this.config).onSetUserId)==null||s.call(n,e),this});u(this,"fetchConversation",async e=>{try{const n=this.userId;this.logger.debug("Fetching conversation for user:",n,"conversationId:",e);const s=await this.fetchUserConversationById(e);return s?(this.setConversationId(e).setMessages([]),s):(this.logger.debug("Conversation not exist"),null)}catch(n){return this.logger.debug("Error fetching conversation!",n),null}});u(this,"fetchLatestConversation",async(e=null)=>{try{const n=this.userId??e;if(!n)return this.initializeNewConversation(n),null;this.logger.debug("Fetching conversations for user:",n);const s=await this.fetchLatestUserConversation(n);if(!s)return this.initializeNewConversation(n),null;const{id:i,events:o=[]}=s,c=o.sort((v,_)=>re(v.sent_at)-re(_.sent_at)),[l]=c,g=l==null?void 0:l.sent_at;return this.setConversationId(i).setMessages([...this.getDefaultGreeting({sent_at:g}),...c]),s}catch(n){this.logger.debug("Error fetching conversations!",n)}});u(this,"getDefaultGreeting",(e={})=>{var s;const n=this.config.greeting??((s=this.settings)==null?void 0:s.greeting);return n?[this.constructMessagePayload(n,"bot",new Date().toISOString(),e)]:[]});u(this,"fetchUserConversationById",async e=>this.api.fetchConversationById(e).then(n=>(n?this.logger.debug("Found conversation:",n):this.logger.debug("No conversation found with id:",e),n||null)));u(this,"setConversationId",e=>(this.conversationId=e,this.joinConversationChannel(e),this));u(this,"listenForNewConversations",e=>{const n=this.socket.channel(`conversations:lobby:${e}`,{});return n.on("conversation:created",s=>{this.config.onConversationCreated&&this.config.onConversationCreated(e,s),setTimeout(()=>this.fetchLatestConversation(e),1e3)}),n.join().receive("ok",s=>{this.logger.debug("Successfully listening for new conversations!",s)}).receive("error",s=>{this.logger.debug("Unable to listen for new conversations!",s)}),this});u(this,"joinConversationChannel",e=>{this.channel&&this.channel.leave&&this.channel.leave(),this.logger.debug("Joining channel:",e),this.channel=this.socket.channel(`conversations:${e}`,{user_id:this.userId}),this.channel.on("phx_error",s=>{}),this.channel.on("stream_message",s=>{this.logger.debug("New conversation data received",s),this.updateState("streaming"),this.handleMessageCreated(s)}),this.channel.on("stream_event",s=>{this.logger.debug("New event data received",s),this.handleMessageCreated(s)}),this.channel.on("loading",s=>{const{status:i}=s;this.state!="sending"&&this.updateState(i?"loading":"input")});const n=this.channel.onMessage.bind(this.channel);return this.channel.onMessage=(s,i,o)=>(this.logger.debug("Channel onMessage:",s,i,o),n(s,i,o)),this.channel.join().receive("ok",s=>{this.logger.debug("Joined conversation successfully!",s)}).receive("error",s=>{this.logger.debug("Unable to join conversation!",s)}).receive("timeout",()=>{this.logger.debug("Channel join attempt timed out."),setTimeout(()=>this.joinConversationChannel(e),5e3)}),this});u(this,"handleSocketDisconnect",()=>{if(this.reconnectTimer)return;let e=0;const n=()=>{if(this.socket.isConnected()){this.logger.debug("Socket reconnected successfully!"),clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}e+=1,this.logger.debug(`Reconnection attempt #${e}`),this.socket.connect();const s=Math.min(1e3*Math.pow(2,e),3e4);this.reconnectTimer=setTimeout(n,s)};n()});u(this,"handleMessageCreated",e=>{const{messages:n=[]}=this,s=n.find(o=>o.id===e.id&&o.sender_id===e.sender_id),i=s?n.map(o=>o.sent_at===s.sent_at?e:o):[...n,e];this.setMessages(i)});u(this,"setMessages",e=>(this.messages=e,this.config.onMessagesUpdated&&this.config.onMessagesUpdated(e),this));u(this,"validateMessageContent",e=>!(!e||e.trim().length===0));u(this,"constructMessagePayload",(e,n,s,i={})=>({blocks:[{id:"1",type:"text",text:e}],id:"temp-id",request_user_feedback:!1,user_feedback_value:null,sender_id:n,sender_name:null,sent_at:s,type:"message",...i}));u(this,"pushMessageToChannel",e=>{var n;this.updateState("sending"),(n=this.channel)==null||n.push("new_text",e).receive("ok",s=>(console.log("Message sent successfully",s),this.updateState("sending"),this.setMessages([...this.messages,s[0]]),s)).receive("error",s=>{this.logger.error("Error sending message",s)}).receive("timeout",()=>{this.logger.error("Push request timed out")})});u(this,"sendNewMessage",async e=>{const{userId:n,conversationId:s}=this;if(!this.validateMessageContent(e)){console.warn("Invalid message content, skipping send");return}(!n||!s)&&await this.initializeNewConversation(n),this.pushMessageToChannel(e)});u(this,"createNewConversation",async e=>{const{token:n}=this.config;return this.api.createNewConversation(e,n)});u(this,"initializeNewConversation",async e=>{const{user:n={}}=this.config,s=n,i=await this.createOrUpdateUser(e,s),{id:o}=await this.createNewConversation(i);return this.setUserId(i).setConversationId(o)});u(this,"createNewUser",e=>(this.logger.debug("Creating new user:",e),this.api.createNewUser(e)));u(this,"identify",async(e,n={})=>{try{const s=this.userId||this.getCachedUserId(),i=await this.isValidUserId(s),o={...n,external_id:e};if(i){this.logger.debug("Valid user found for ID:",s);const{id:g}=await this.api.updateUserMetadata(s,n);return this.setUserId(g)}const c=await this.checkForExistingUser(o),{id:l}=c?await this.api.updateUserMetadata(c,n):await this.createNewUser(o);return this.setUserId(l)}catch(s){this.logger.error("Failed to update or create user:",s),this.logger.error("Retrying...");const{id:i}=await this.createNewUser(n);return this.setUserId(i)}});u(this,"createOrUpdateUser",async(e,n={})=>{try{const s=e?await this.api.updateUserMetadata(e,n):await this.createNewUser(n),{id:i}=s;return i}catch(s){this.logger.error("Failed to update or create user:",s),this.logger.error("Retrying...");const{id:i}=await this.createNewUser(n);return i}});u(this,"fetchWidgetSettings",async()=>{const e={};return this.api.fetchWidgetSettings().then(n=>n||e).catch(()=>e)});u(this,"fetchLatestUserConversation",async e=>{const{token:n}=this.config,s={user_id:e,token:n};return this.api.fetchUserConversations(s).then(i=>{this.logger.debug("Found existing conversations:",i);const[o]=i??[];return o||null})});u(this,"updateWidgetSettingsMetadata",async e=>this.api.updateWidgetSettingsMetadata(e).catch(n=>{this.logger.error("Failed to update widget metadata:",n)}));u(this,"findUserByExternalId",async e=>{const n=await this.api.findUserByExternalId(e);return(n==null?void 0:n.id)||null});u(this,"findUserByMetadata",async e=>{if(!e||!(e!=null&&e.external_id))return null;const{external_id:n}=e;return await this.findUserByExternalId(n)});u(this,"checkForExistingUser",async(e,n=null)=>n);u(this,"updateExistingUser",async(e,n)=>{if(n)try{await this.api.updateUserMetadata(e,n)}catch(s){this.logger.debug("Error updating user metadata!",s)}});u(this,"getCachedUserId",()=>this.storage.getUserId());u(this,"cacheUserId",e=>{this.logger.debug("Caching user ID:",e),e?this.storage.setUserId(e):this.storage.removeUserId()});u(this,"isValidUserId",async e=>{if(!e||!e.length||!me(e))return!1;try{return await this.api.isValidUser(e)}catch{return this.logger.warn("Failed to validate user ID."),this.logger.warn("You might be on an older version of Freeday."),!0}});u(this,"checkHealth",async()=>this.api.healthCheck().then(()=>!0).catch(()=>!1));u(this,"updateState",e=>{this.state=e,this.config.onStateUpdated&&this.config.onStateUpdated(e)});u(this,"notify",(e,n,s={})=>{this.logger.debug({type:e,message:n,options:s})});const n=window,{baseUrl:s,token:i,conversationId:o,userId:c,debug:l=!1}=e,g=ge(n)||l;this.config=e,this.api=new be(i,s),this.logger=new Re(g),this.storage=Le(n),this.userId=c||this.getCachedUserId()||null,this.conversationId=o||null,this.messages=[];const v=fe(s);this.socket=new Ue(v,{params:{token:i},heartbeatIntervalMs:3e4,reconnectAfterMs:_=>[1e3,2e3,4e3,8e3,16e3][_-1]||3e4}),this.socket.onOpen(()=>{this.connectionState="connected"}),this.socket.onError(()=>{this.logger.debug("Socket error occurred."),this.handleSocketDisconnect()}),this.socket.onClose(()=>{this.connectionState="disconnected",this.logger.debug("Socket connection closed."),this.handleSocketDisconnect()})}};u(R,"init",e=>new R(e)),u(R,"open",()=>window.dispatchEvent(new Event(H.OPEN))),u(R,"close",()=>window.dispatchEvent(new Event(H.CLOSE))),u(R,"toggle",()=>window.dispatchEvent(new Event(H.TOGGLE))),u(R,"restart",()=>window.dispatchEvent(new Event(H.RESTART)));let Y=R;const he=window,Ae=he.Freeday&&he.Freeday.config||{},{token:ce,userId:Oe,baseUrl:Me,greeting:je,debug:Ne,onSetUserId:Pe,onSetConversationId:De,onSetWidgetSettings:He,onPresenceSync:xe}=Ae;if(!ce)throw new Error("An account token is required to start Freeday!");Y.init({token:ce,userId:Oe,baseUrl:Me,greeting:je,debug:Ne,onSetUserId:Pe,onSetConversationId:De,onSetWidgetSettings:He,onPresenceSync:xe})})(); | ||
var Ve=Object.defineProperty;var We=(I,T,A)=>T in I?Ve(I,T,{enumerable:!0,configurable:!0,writable:!0,value:A}):I[T]=A;var u=(I,T,A)=>We(I,typeof T!="symbol"?T+"":T,A);(function(){"use strict";var I={exports:{}};(function(t){var e=function(n){var s=Object.prototype,i=s.hasOwnProperty,r=Object.defineProperty||function(a,o,h){a[o]=h.value},c,l=typeof Symbol=="function"?Symbol:{},g=l.iterator||"@@iterator",v=l.asyncIterator||"@@asyncIterator",_=l.toStringTag||"@@toStringTag";function m(a,o,h){return Object.defineProperty(a,o,{value:h,enumerable:!0,configurable:!0,writable:!0}),a[o]}try{m({},"")}catch{m=function(o,h,p){return o[h]=p}}function V(a,o,h,p){var d=o&&o.prototype instanceof Z?o:Z,f=Object.create(d.prototype),b=new ne(p||[]);return r(f,"_invoke",{value:Be(a,h,b)}),f}n.wrap=V;function x(a,o,h){try{return{type:"normal",arg:a.call(o,h)}}catch(p){return{type:"throw",arg:p}}}var le="suspendedStart",$e="suspendedYield",ue="executing",W="completed",S={};function Z(){}function z(){}function O(){}var Q={};m(Q,g,function(){return this});var ee=Object.getPrototypeOf,q=ee&&ee(ee(se([])));q&&q!==s&&i.call(q,g)&&(Q=q);var j=O.prototype=Z.prototype=Object.create(Q);z.prototype=O,r(j,"constructor",{value:O,configurable:!0}),r(O,"constructor",{value:z,configurable:!0}),z.displayName=m(O,_,"GeneratorFunction");function de(a){["next","throw","return"].forEach(function(o){m(a,o,function(h){return this._invoke(o,h)})})}n.isGeneratorFunction=function(a){var o=typeof a=="function"&&a.constructor;return o?o===z||(o.displayName||o.name)==="GeneratorFunction":!1},n.mark=function(a){return Object.setPrototypeOf?Object.setPrototypeOf(a,O):(a.__proto__=O,m(a,_,"GeneratorFunction")),a.prototype=Object.create(j),a},n.awrap=function(a){return{__await:a}};function J(a,o){function h(f,b,y,C){var w=x(a[f],a,b);if(w.type==="throw")C(w.arg);else{var ie=w.arg,$=ie.value;return $&&typeof $=="object"&&i.call($,"__await")?o.resolve($.__await).then(function(M){h("next",M,y,C)},function(M){h("throw",M,y,C)}):o.resolve($).then(function(M){ie.value=M,y(ie)},function(M){return h("throw",M,y,C)})}}var p;function d(f,b){function y(){return new o(function(C,w){h(f,b,C,w)})}return p=p?p.then(y,y):y()}r(this,"_invoke",{value:d})}de(J.prototype),m(J.prototype,v,function(){return this}),n.AsyncIterator=J,n.async=function(a,o,h,p,d){d===void 0&&(d=Promise);var f=new J(V(a,o,h,p),d);return n.isGeneratorFunction(o)?f:f.next().then(function(b){return b.done?b.value:f.next()})};function Be(a,o,h){var p=le;return function(f,b){if(p===ue)throw new Error("Generator is already running");if(p===W){if(f==="throw")throw b;return Fe()}for(h.method=f,h.arg=b;;){var y=h.delegate;if(y){var C=pe(y,h);if(C){if(C===S)continue;return C}}if(h.method==="next")h.sent=h._sent=h.arg;else if(h.method==="throw"){if(p===le)throw p=W,h.arg;h.dispatchException(h.arg)}else h.method==="return"&&h.abrupt("return",h.arg);p=ue;var w=x(a,o,h);if(w.type==="normal"){if(p=h.done?W:$e,w.arg===S)continue;return{value:w.arg,done:h.done}}else w.type==="throw"&&(p=W,h.method="throw",h.arg=w.arg)}}}function pe(a,o){var h=o.method,p=a.iterator[h];if(p===c)return o.delegate=null,h==="throw"&&a.iterator.return&&(o.method="return",o.arg=c,pe(a,o),o.method==="throw")||h!=="return"&&(o.method="throw",o.arg=new TypeError("The iterator does not provide a '"+h+"' method")),S;var d=x(p,a.iterator,o.arg);if(d.type==="throw")return o.method="throw",o.arg=d.arg,o.delegate=null,S;var f=d.arg;if(!f)return o.method="throw",o.arg=new TypeError("iterator result is not an object"),o.delegate=null,S;if(f.done)o[a.resultName]=f.value,o.next=a.nextLoc,o.method!=="return"&&(o.method="next",o.arg=c);else return f;return o.delegate=null,S}de(j),m(j,_,"Generator"),m(j,g,function(){return this}),m(j,"toString",function(){return"[object Generator]"});function Ge(a){var o={tryLoc:a[0]};1 in a&&(o.catchLoc=a[1]),2 in a&&(o.finallyLoc=a[2],o.afterLoc=a[3]),this.tryEntries.push(o)}function te(a){var o=a.completion||{};o.type="normal",delete o.arg,a.completion=o}function ne(a){this.tryEntries=[{tryLoc:"root"}],a.forEach(Ge,this),this.reset(!0)}n.keys=function(a){var o=Object(a),h=[];for(var p in o)h.push(p);return h.reverse(),function d(){for(;h.length;){var f=h.pop();if(f in o)return d.value=f,d.done=!1,d}return d.done=!0,d}};function se(a){if(a!=null){var o=a[g];if(o)return o.call(a);if(typeof a.next=="function")return a;if(!isNaN(a.length)){var h=-1,p=function d(){for(;++h<a.length;)if(i.call(a,h))return d.value=a[h],d.done=!1,d;return d.value=c,d.done=!0,d};return p.next=p}}throw new TypeError(typeof a+" is not iterable")}n.values=se;function Fe(){return{value:c,done:!0}}return ne.prototype={constructor:ne,reset:function(a){if(this.prev=0,this.next=0,this.sent=this._sent=c,this.done=!1,this.delegate=null,this.method="next",this.arg=c,this.tryEntries.forEach(te),!a)for(var o in this)o.charAt(0)==="t"&&i.call(this,o)&&!isNaN(+o.slice(1))&&(this[o]=c)},stop:function(){this.done=!0;var a=this.tryEntries[0],o=a.completion;if(o.type==="throw")throw o.arg;return this.rval},dispatchException:function(a){if(this.done)throw a;var o=this;function h(C,w){return f.type="throw",f.arg=a,o.next=C,w&&(o.method="next",o.arg=c),!!w}for(var p=this.tryEntries.length-1;p>=0;--p){var d=this.tryEntries[p],f=d.completion;if(d.tryLoc==="root")return h("end");if(d.tryLoc<=this.prev){var b=i.call(d,"catchLoc"),y=i.call(d,"finallyLoc");if(b&&y){if(this.prev<d.catchLoc)return h(d.catchLoc,!0);if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else if(b){if(this.prev<d.catchLoc)return h(d.catchLoc,!0)}else if(y){if(this.prev<d.finallyLoc)return h(d.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(a,o){for(var h=this.tryEntries.length-1;h>=0;--h){var p=this.tryEntries[h];if(p.tryLoc<=this.prev&&i.call(p,"finallyLoc")&&this.prev<p.finallyLoc){var d=p;break}}d&&(a==="break"||a==="continue")&&d.tryLoc<=o&&o<=d.finallyLoc&&(d=null);var f=d?d.completion:{};return f.type=a,f.arg=o,d?(this.method="next",this.next=d.finallyLoc,S):this.complete(f)},complete:function(a,o){if(a.type==="throw")throw a.arg;return a.type==="break"||a.type==="continue"?this.next=a.arg:a.type==="return"?(this.rval=this.arg=a.arg,this.method="return",this.next="end"):a.type==="normal"&&o&&(this.next=o),S},finish:function(a){for(var o=this.tryEntries.length-1;o>=0;--o){var h=this.tryEntries[o];if(h.finallyLoc===a)return this.complete(h.completion,h.afterLoc),te(h),S}},catch:function(a){for(var o=this.tryEntries.length-1;o>=0;--o){var h=this.tryEntries[o];if(h.tryLoc===a){var p=h.completion;if(p.type==="throw"){var d=p.arg;te(h)}return d}}throw new Error("illegal catch attempt")},delegateYield:function(a,o,h){return this.delegate={iterator:se(a),resultName:o,nextLoc:h},this.method==="next"&&(this.arg=c),S}},n}(t.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(I);var T={NVM_INC:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/include/node",COREPACK_ROOT:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/lib/node_modules/corepack",HERD_PHP_80_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/80/",TERM_PROGRAM:"vscode",NODE:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin/node",INIT_CWD:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",NVM_CD_FLAGS:"-q",npm_package_dependencies_axios:"^1.7.7",npm_package_dependencies_vite_plugin_dts:"^4.2.1",npm_package_devDependencies_typescript:"^5.6.2",TERM:"xterm-256color",SHELL:"/bin/zsh",npm_package_unpkg:"dist/freeday-webchat-sdk.iife.js",npm_package_devDependencies_vite:"^5.4.6",HOMEBREW_REPOSITORY:"/opt/homebrew",TMPDIR:"/var/folders/lt/0l1rfzpn6sq61y39zg58rb340000gn/T/",npm_package_scripts_lint:"eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",TERM_PROGRAM_VERSION:"1.96.0",npm_package_devDependencies__vitejs_plugin_react:"^4.3.1",npm_package_scripts_dev:"vite",ZDOTDIR:"/Users/beaudinngreve",ORIGINAL_XDG_CURRENT_DESKTOP:"undefined",MallocNanoZone:"0",npm_package_scripts_test_ci:"vitest --coverage --watch=false",npm_config_registry:"https://registry.npmjs.org/",HERD_PHP_83_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/83/",ZSH:"/Users/beaudinngreve/.oh-my-zsh",npm_package_dependencies_react_dom:"^18.3.1",npm_package_devDependencies_eslint_plugin_react_refresh:"^0.4.12",npm_package_dependencies_regenerator_runtime:"^0.14.1",NVM_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm",USER:"beaudinngreve",npm_package_description:"Freeday webchat sdk",LS_COLORS:"di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43",npm_package_license:"MIT",npm_package_devDependencies__types_react:"^18.3.7",COMMAND_MODE:"unix2003",PNPM_SCRIPT_SRC_DIR:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",npm_package_exports___import:"./dist/freeday-webchat-sdk-lib.js",SSH_AUTH_SOCK:"/private/tmp/com.apple.launchd.sgjnAxi6eg/Listeners",__CF_USER_TEXT_ENCODING:"0x1F5:0x0:0x5",npm_package_devDependencies_eslint:"^9.10.0",HERD_PHP_82_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/82/",npm_package_devDependencies__typescript_eslint_eslint_plugin:"^8.6.0",npm_execpath:"/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/bin/pnpm.cjs",PAGER:"less",npm_package_module:"./dist/freeday-webchat-widget-lib.js",LSCOLORS:"Gxfxcxdxbxegedabagacad",npm_package_devDependencies__types_react_dom:"^18.3.0",npm_config_frozen_lockfile:"",npm_package_devDependencies__typescript_eslint_parser:"^8.6.0",PATH:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.bin:/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node-gyp-bin:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.bin:/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node-gyp-bin:/opt/homebrew/share/google-cloud-sdk/bin:/opt/homebrew/opt/postgresql@16/bin:/Users/beaudinngreve/Library/Application Support/Herd/bin/:/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/homebrew/share/google-cloud-sdk/bin:/opt/homebrew/opt/postgresql@16/bin:/Users/beaudinngreve/Library/Application Support/Herd/bin/:/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/Users/beaudinngreve/Library/Application Support/Code/User/globalStorage/github.copilot-chat/debugCommand",COREPACK_ENABLE_DOWNLOAD_PROMPT:"1",USER_ZDOTDIR:"/Users/beaudinngreve",__CFBundleIdentifier:"com.microsoft.VSCode",npm_package_author:"freeday",PWD:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk",npm_command:"run-script",npm_package_scripts_preview:"vite preview",npm_package_devDependencies_eslint_plugin_react_hooks:"^4.6.2",npm_lifecycle_event:"build-widget",LANG:"en_US.UTF-8",npm_package_name:"@freeday-ai/webchat-sdk",npm_package_types:"./dist/freeday-webchat-sdk-lib.d.ts",npm_package_packageManager:"pnpm@9.4.0",npm_package_scripts_build_widget:"vite build --config vite.widget.config.js",NODE_PATH:"/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.8_@types+node@22.7.5/node_modules/vite/bin/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.8_@types+node@22.7.5/node_modules/vite/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/vite@5.4.8_@types+node@22.7.5/node_modules:/Users/beaudinngreve/Code/work/freeday/cx-api/webchat-sdk/node_modules/.pnpm/node_modules",npm_package_scripts_build:"pnpm build-module-bundle && pnpm build-widget",npm_package_dependencies_phoenix:"^1.7.14",npm_package_devDependencies__vitest_coverage_v8:"^2.1.2",VSCODE_GIT_ASKPASS_EXTRA_ARGS:"",XPC_FLAGS:"0x0",npm_package_devDependencies_vitest:"^2.1.2",npm_package_main:"./dist/freeday-webchat-sdk-lib.umd.cjs",npm_config_node_gyp:"/Users/beaudinngreve/.cache/node/corepack/v1/pnpm/9.4.0/dist/node_modules/node-gyp/bin/node-gyp.js",XPC_SERVICE_NAME:"0",npm_package_version:"0.0.1-alpha.35",VSCODE_INJECTION:"1",SHLVL:"3",HOME:"/Users/beaudinngreve",npm_package_type:"module",VSCODE_GIT_ASKPASS_MAIN:"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/git/dist/askpass-main.js",npm_package_scripts_test:"vitest",HOMEBREW_PREFIX:"/opt/homebrew",LESS:"-R",LOGNAME:"beaudinngreve",npm_package_exports___require:"./dist/freeday-webchat-sdk-lib.umd.cjs",npm_lifecycle_script:"vite build --config vite.widget.config.js",VSCODE_GIT_IPC_HANDLE:"/var/folders/lt/0l1rfzpn6sq61y39zg58rb340000gn/T/vscode-git-acf59dfa1d.sock",npm_package_dependencies_react:"^18.3.1",NVM_BIN:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin",npm_config_user_agent:"pnpm/9.4.0 npm/? node/v20.13.1 darwin arm64",VSCODE_GIT_ASKPASS_NODE:"/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin)",GIT_ASKPASS:"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/git/dist/askpass.sh",HERD_PHP_74_INI_SCAN_DIR:"/Users/beaudinngreve/Library/Application Support/Herd/config/php/74/",INFOPATH:"/opt/homebrew/share/info:/opt/homebrew/share/info:",HOMEBREW_CELLAR:"/opt/homebrew/Cellar",npm_package_devDependencies__types_node:"^22.7.5",npm_package_devDependencies__types_phoenix:"^1.6.5",npm_package_files_0:"dist",npm_package_scripts_build_module_bundle:"vite build --config vite.config.js ",COLORTERM:"truecolor",npm_node_execpath:"/Users/beaudinngreve/Library/Application Support/Herd/config/nvm/versions/node/v20.13.1/bin/node",NODE_ENV:"production"};const A=T.NEXT_PUBLIC_BASE_URL||"https://webchat.freeday.chat",ge=t=>!!(t.location.hostname==="localhost"||t.location.hostname==="[::1]"||t.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)),fe=(t=A)=>{const[e,n]=t.split("://");return`${e==="https"?"wss":"ws"}://${n}/socket`},me=t=>!t||!t.length?!1:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),ve=t=>t.replace(/_([a-z])/g,(e,n)=>n.toUpperCase()),K=t=>Array.isArray(t)?t.map(e=>K(e)):t!==null&&typeof t=="object"?Object.keys(t).reduce((e,n)=>{const s=ve(n);return e[s]=K(t[n]),e},{}):t,re=t=>new Date(t).getTime();class _e{constructor(e=A){u(this,"baseUrl");this.baseUrl=e}getDefaultOptions(e,n){return{method:e,headers:{"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0}}get(e,n={}){const s=new URLSearchParams(n).toString(),i=`${this.baseUrl}${e}?${s}`;return fetch(i,this.getDefaultOptions("GET")).then(r=>{if(!r.ok)throw new Error(`GET request failed: ${r.statusText}`);return r.json()}).catch(r=>{throw new Error(`Error occurred during GET request: ${r.message}`)})}post(e,n){const s=`${this.baseUrl}${e}`;return fetch(s,this.getDefaultOptions("POST",n)).then(i=>{if(!i.ok)throw new Error(`POST request failed: ${i.statusText}`);return i.json()}).catch(i=>{throw new Error(`Error occurred during POST request: ${i.message}`)})}async put(e,n){const s=`${this.baseUrl}${e}`;return fetch(s,this.getDefaultOptions("PUT",n)).then(i=>{if(!i.ok)throw new Error(`PUT request failed: ${i.statusText}`);return i.json()}).catch(i=>{throw new Error(`Error occurred during PUT request: ${i.message}`)})}}class be{constructor(e,n){u(this,"http");u(this,"token");this.token=e,this.http=new _e(n)}async healthCheck(){return this.http.get("/api/health-check").then(e=>e.status)}async fetchWidgetSettings(){return this.http.get(`/api/widget/settings/${this.token}`).then(e=>K(e.data))}async updateWidgetSettingsMetadata(e){return this.http.put(`/api/widget/settings/${this.token}/metadata`,e)}async createNewUser(e={}){return this.http.post("/api/users",{user:{...e,first_seen:new Date().toISOString(),last_seen_at:new Date().toISOString()}}).then(n=>n.data)}async isValidUser(e){return this.http.get(`/api/users/${e}/exists`).then(n=>n.exists)}async updateUserMetadata(e,n){return this.http.put(`/api/users/${e}/metadata`,{metadata:n}).then(s=>s.data)}async findUserByExternalId(e){const n=this.token;return this.http.get("/api/users/identify",{external_id:e,token:n})}async fetchConversationById(e){return this.http.get(`/api/conversations/${e}`).then(n=>n.data)}async createNewConversation(e,n){return this.http.post("/api/conversations",{conversation:{user_id:e,token:n}}).then(s=>s.data)}async fetchUserConversations(e){return this.http.get("/api/conversations/user",e).then(n=>n.data)}}var N=t=>typeof t=="function"?t:function(){return t},ye=typeof self<"u"?self:null,P=typeof window<"u"?window:null,L=ye||P||L,we="2.0.0",E={connecting:0,open:1,closing:2,closed:3},ke=1e4,Ce=1e3,k={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},U={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},X={longpoll:"longpoll",websocket:"websocket"},Se={complete:4},B=class{constructor(t,e,n,s){this.channel=t,this.event=e,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:t,response:e,_ref:n}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},oe=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Ee=class{constructor(t,e,n){this.state=k.closed,this.topic=t,this.params=N(e||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new B(this,U.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new oe(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=k.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=k.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=k.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=k.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new B(this,U.leave,N({}),this.timeout).send(),this.state=k.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(U.reply,(s,i)=>{this.trigger(this.replyEventName(i),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(t){this.on(U.close,t)}onError(t){return this.on(U.error,e=>t(e))}on(t,e){let n=this.bindingRef++;return this.bindings.push({event:t,ref:n,callback:e}),n}off(t,e){this.bindings=this.bindings.filter(n=>!(n.event===t&&(typeof e>"u"||e===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,n=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new B(this,t,function(){return e},n);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=k.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(U.close,"leave")},n=new B(this,U.leave,N({}),t);return n.receive("ok",()=>e()).receive("timeout",()=>e()),n.send(),this.canPush()||n.trigger("ok",{}),n}onMessage(t,e,n){return e}isMember(t,e,n,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:n,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=k.joining,this.joinPush.resend(t))}trigger(t,e,n,s){let i=this.onMessage(t,e,n,s);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(c=>c.event===t);for(let c=0;c<r.length;c++)r[c].callback(i,n,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===k.closed}isErrored(){return this.state===k.errored}isJoined(){return this.state===k.joined}isJoining(){return this.state===k.joining}isLeaving(){return this.state===k.leaving}},G=class{static request(t,e,n,s,i,r,c){if(L.XDomainRequest){let l=new L.XDomainRequest;return this.xdomainRequest(l,t,e,s,i,r,c)}else{let l=new L.XMLHttpRequest;return this.xhrRequest(l,t,e,n,s,i,r,c)}}static xdomainRequest(t,e,n,s,i,r,c){return t.timeout=i,t.open(e,n),t.onload=()=>{let l=this.parseJSON(t.responseText);c&&c(l)},r&&(t.ontimeout=r),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,n,s,i,r,c,l){return t.open(e,n,!0),t.timeout=r,t.setRequestHeader("Content-Type",s),t.onerror=()=>l&&l(null),t.onreadystatechange=()=>{if(t.readyState===Se.complete&&l){let g=this.parseJSON(t.responseText);l(g)}},c&&(t.ontimeout=c),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let n=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let i=e?`${e}[${s}]`:s,r=t[s];typeof r=="object"?n.push(this.serialize(r,i)):n.push(encodeURIComponent(i)+"="+encodeURIComponent(r))}return n.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let n=t.match(/\?/)?"&":"?";return`${t}${n}${this.serialize(e)}`}},Te=t=>{let e="",n=new Uint8Array(t),s=n.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(n[i]);return btoa(e)},D=class{constructor(t){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=E.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+X.websocket),"$1/"+X.longpoll)}endpointURL(){return G.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,n){this.close(t,e,n),this.readyState=E.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===E.open||this.readyState===E.connecting}poll(){this.ajax("GET","application/json",null,()=>this.ontimeout(),t=>{if(t){var{status:e,token:n,messages:s}=t;this.token=n}else e=0;switch(e){case 200:s.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=E.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${e}`)}})}send(t){typeof t!="string"&&(t=Te(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",t.join(` | ||
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,n){for(let i of this.reqs)i.abort();this.readyState=E.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,n,s,i){let r,c=()=>{this.reqs.delete(r),s()};r=G.request(t,this.endpointURL(),e,n,this.timeout,c,l=>{this.reqs.delete(r),this.isActive()&&i(l)}),this.reqs.add(r)}},F={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let n=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(n))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[n,s,i,r,c]=JSON.parse(t);return e({join_ref:n,ref:s,topic:i,event:r,payload:c})}},binaryEncode(t){let{join_ref:e,ref:n,event:s,topic:i,payload:r}=t,c=this.META_LENGTH+e.length+n.length+i.length+s.length,l=new ArrayBuffer(this.HEADER_LENGTH+c),g=new DataView(l),v=0;g.setUint8(v++,this.KINDS.push),g.setUint8(v++,e.length),g.setUint8(v++,n.length),g.setUint8(v++,i.length),g.setUint8(v++,s.length),Array.from(e,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(n,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(i,m=>g.setUint8(v++,m.charCodeAt(0))),Array.from(s,m=>g.setUint8(v++,m.charCodeAt(0)));var _=new Uint8Array(l.byteLength+r.byteLength);return _.set(new Uint8Array(l),0),_.set(new Uint8Array(r),l.byteLength),_.buffer},binaryDecode(t){let e=new DataView(t),n=e.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,n){let s=e.getUint8(1),i=e.getUint8(2),r=e.getUint8(3),c=this.HEADER_LENGTH+this.META_LENGTH-1,l=n.decode(t.slice(c,c+s));c=c+s;let g=n.decode(t.slice(c,c+i));c=c+i;let v=n.decode(t.slice(c,c+r));c=c+r;let _=t.slice(c,t.byteLength);return{join_ref:l,ref:null,topic:g,event:v,payload:_}},decodeReply(t,e,n){let s=e.getUint8(1),i=e.getUint8(2),r=e.getUint8(3),c=e.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,g=n.decode(t.slice(l,l+s));l=l+s;let v=n.decode(t.slice(l,l+i));l=l+i;let _=n.decode(t.slice(l,l+r));l=l+r;let m=n.decode(t.slice(l,l+c));l=l+c;let V=t.slice(l,t.byteLength),x={status:m,response:V};return{join_ref:g,ref:v,topic:_,event:U.reply,payload:x}},decodeBroadcast(t,e,n){let s=e.getUint8(1),i=e.getUint8(2),r=this.HEADER_LENGTH+2,c=n.decode(t.slice(r,r+s));r=r+s;let l=n.decode(t.slice(r,r+i));r=r+i;let g=t.slice(r,t.byteLength);return{join_ref:null,ref:null,topic:c,event:l,payload:g}}},Ue=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=e.timeout||ke,this.transport=e.transport||L.WebSocket||D,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||L&&L.sessionStorage,this.establishedConnections=0,this.defaultEncoder=F.encode.bind(F),this.defaultDecoder=F.decode.bind(F),this.closeWasClean=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==D?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;P&&P.addEventListener&&(P.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),n=this.connectClock)}),P.addEventListener("pageshow",s=>{n===this.connectClock&&(n=null,this.connect())})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,i,r)=>{console.log(`${s}: ${i}`,r)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=N(e.params||{}),this.endPoint=`${t}/${X.websocket}`,this.vsn=e.vsn||we,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new oe(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return D}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=G.appendParams(G.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,n){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(t,e,n)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=N(t)),!this.conn&&(this.longPollFallbackMs&&this.transport!==D?this.connectWithFallback(D,this.longPollFallbackMs):this.transportConnect())}log(t,e,n){this.logger&&this.logger(t,e,n)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),n=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(i=>{i.ref===e&&(this.off([s]),t(Date.now()-n))});return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let n=!1,s=!0,i,r,c=l=>{this.log("transport",`falling back to ${t.name}...`,l),this.off([i,r]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${t.name}`))return c("memorized");this.fallbackTimer=setTimeout(c,e),r=this.onError(l=>{this.log("transport","error",l),s&&!n&&(clearTimeout(this.fallbackTimer),c(l))}),this.onOpen(()=>{if(n=!0,!s)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t.name}`,"true"),this.log("transport",`established ${t.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,t])=>t())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Ce,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,n){if(!this.conn)return t&&t();this.waitForBufferDone(()=>{this.conn&&(e?this.conn.close(e,n||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(t,e+1)},150*e)}waitForSocketClosed(t,e=1){if(e===5||!this.conn||this.conn.readyState===E.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(t,e+1)},150*e)}onConnClose(t){let e=t&&t.code;this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,n])=>n(t))}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,n=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,s])=>{s(t,e,n)}),(e===this.transport||n>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(U.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case E.connecting:return"connecting";case E.open:return"open";case E.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([n])=>t.indexOf(n)===-1)}channel(t,e={}){let n=new Ee(t,e,this);return this.channels.push(n),n}push(t){if(this.hasLogger()){let{topic:e,event:n,payload:s,ref:i,join_ref:r}=t;this.log("push",`${e} ${n} (${r}, ${i})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:n,event:s,payload:i,ref:r,join_ref:c}=e;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${i.status||""} ${n} ${s} ${r&&"("+r+")"||""}`,i);for(let l=0;l<this.channels.length;l++){const g=this.channels[l];g.isMember(n,s,i,c)&&g.trigger(s,i,r,c)}for(let l=0;l<this.stateChangeCallbacks.message.length;l++){let[,g]=this.stateChangeCallbacks.message[l];g(e)}})}leaveOpenTopic(t){let e=this.channels.find(n=>n.topic===t&&(n.isJoined()||n.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Re{constructor(e){u(this,"debugModeEnabled");this.debugModeEnabled=!!e}debug(...e){this.debugModeEnabled&&console.debug("[@freeday/webchat-sdk]",...e)}log(...e){this.debugModeEnabled&&console.log("[@freeday/webchat-sdk]",...e)}info(...e){console.info("[@freeday/webchat-sdk]",...e)}warn(...e){console.warn("[@freeday/webchat-sdk]",...e)}error(...e){console.error("[@freeday/webchat-sdk]",...e)}}const ae="__FREEDAY__",Ie=t=>{try{return t&&(t.localStorage||t.sessionStorage)}catch{return{_db:{},getItem(n){return this._db[n]||null},setItem(n,s){this._db[n]=s},removeItem(n){delete this._db[n]}}}};function Ae(t){const e=Ie(t),n=r=>{const c=e.getItem(`${ae}${r}`);if(!c)return null;try{return JSON.parse(c)}catch{return c}},s=(r,c)=>{e.setItem(`${ae}${r}`,JSON.stringify(c))},i=r=>{e.removeItem(r)};return{getUserId:()=>n("__USER_ID__"),setUserId:r=>s("__USER_ID__",r),removeUserId:()=>i("__USER_ID__")}}var H=(t=>(t.TOGGLE="freeday:toggle",t.RESTART="freeday:restart",t.OPEN="freeday:open",t.CLOSE="freeday:close",t))(H||{});const R=class R{constructor(e){u(this,"socket");u(this,"channel");u(this,"api");u(this,"logger");u(this,"storage");u(this,"config");u(this,"userId");u(this,"conversationId");u(this,"messages");u(this,"settings");u(this,"connectionState","disconnected");u(this,"loading",!1);u(this,"reconnectTimer");u(this,"state","input");u(this,"start",async()=>{this.connect();const e=await this.fetchWidgetSettings(),n=this.userId,s=this.config.user||{},i=await this.checkForExistingUser(s,n);return this.conversationId?this.setWidgetSettings(e).setUserId(i).fetchConversation(this.conversationId):this.setWidgetSettings(e).setUserId(i).fetchLatestConversation()});u(this,"connect",()=>{this.socket.connect()});u(this,"disconnect",()=>{this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.channel&&this.channel.leave(),this.socket&&this.socket.disconnect(()=>{this.logger.debug("Socket disconnected.")})});u(this,"restart",()=>{var e;(e=this.channel)==null||e.push("request_restart",{}),this.setMessages([]),setTimeout(()=>this.updateState("input"),2e3)});u(this,"sendActionEvent",(e,n)=>{var s;console.log("Sending action event:",n,e),(s=this.channel)==null||s.push("action-event",{name:e,...n})});u(this,"setWidgetSettings",e=>(this.settings=e,this));u(this,"setUserId",e=>{var n,s;return this.logger.debug("Setting user ID:",e),this.userId=e,this.cacheUserId(e),window.dispatchEvent(new CustomEvent("freeday:user:set",{detail:e})),(s=(n=this.config).onSetUserId)==null||s.call(n,e),this});u(this,"fetchConversation",async e=>{try{const n=this.userId;this.logger.debug("Fetching conversation for user:",n,"conversationId:",e);const s=await this.fetchUserConversationById(e);return s?(this.setConversationId(e).setMessages([]),s):(this.logger.debug("Conversation not exist"),null)}catch(n){return this.logger.debug("Error fetching conversation!",n),null}});u(this,"fetchLatestConversation",async(e=null)=>{try{const n=this.userId??e;if(!n)return this.initializeNewConversation(n),null;this.logger.debug("Fetching conversations for user:",n);const s=await this.fetchLatestUserConversation(n);if(!s)return this.initializeNewConversation(n),null;const{id:i,events:r=[]}=s,c=r.sort((v,_)=>re(v.sent_at)-re(_.sent_at)),[l]=c,g=l==null?void 0:l.sent_at;return this.setConversationId(i).setMessages([...this.getDefaultGreeting({sent_at:g}),...c]),s}catch(n){this.logger.debug("Error fetching conversations!",n)}});u(this,"getDefaultGreeting",(e={})=>{var s;const n=this.config.greeting??((s=this.settings)==null?void 0:s.greeting);return n?[this.constructMessagePayload(n,"bot",new Date().toISOString(),e)]:[]});u(this,"fetchUserConversationById",async e=>this.api.fetchConversationById(e).then(n=>(n?this.logger.debug("Found conversation:",n):this.logger.debug("No conversation found with id:",e),n||null)));u(this,"setConversationId",e=>(this.conversationId=e,this.joinConversationChannel(e),this));u(this,"listenForNewConversations",e=>{const n=this.socket.channel(`conversations:lobby:${e}`,{});return n.on("conversation:created",s=>{this.config.onConversationCreated&&this.config.onConversationCreated(e,s),setTimeout(()=>this.fetchLatestConversation(e),1e3)}),n.join().receive("ok",s=>{this.logger.debug("Successfully listening for new conversations!",s)}).receive("error",s=>{this.logger.debug("Unable to listen for new conversations!",s)}),this});u(this,"joinConversationChannel",e=>{this.channel&&this.channel.leave&&this.channel.leave(),this.logger.debug("Joining channel:",e),this.channel=this.socket.channel(`conversations:${e}`,{user_id:this.userId}),this.channel.on("phx_error",s=>{this.notifyUser("error","An error occurred",s)}),this.channel.on("stream_message",s=>{this.logger.debug("New conversation data received",s),this.updateState("streaming"),this.handleMessageCreated(s)}),this.channel.on("stream_event",s=>{this.logger.debug("New event data received",s),this.handleMessageCreated(s)}),this.channel.on("loading",s=>{const{status:i}=s;this.state!="sending"&&this.updateState(i?"loading":"input")});const n=this.channel.onMessage.bind(this.channel);return this.channel.onMessage=(s,i,r)=>(this.logger.debug("Channel onMessage:",s,i,r),n(s,i,r)),this.channel.join().receive("ok",s=>{this.logger.debug("Joined conversation successfully!",s),this.updateState("input")}).receive("error",s=>{this.logger.debug("Unable to join conversation!",s),this.notifyUser("error","Unable to join conversation")}).receive("timeout",()=>{this.logger.debug("Channel join attempt timed out."),this.notifyUser("error","Channel join attempt timed out"),setTimeout(()=>this.joinConversationChannel(e),5e3)}),this});u(this,"handleSocketDisconnect",()=>{if(this.reconnectTimer)return;let e=0;const n=()=>{if(this.socket.isConnected()){this.logger.debug("Socket reconnected successfully!"),clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}e+=1,this.logger.debug(`Reconnection attempt #${e}`),this.socket.connect();const s=Math.min(1e3*Math.pow(2,e),3e4);this.reconnectTimer=setTimeout(n,s)};n()});u(this,"handleMessageCreated",e=>{const{messages:n=[]}=this,s=n.find(r=>r.id===e.id&&r.sender_id===e.sender_id),i=s?n.map(r=>r.sent_at===s.sent_at?e:r):[...n,e];this.setMessages(i)});u(this,"setMessages",e=>(this.messages=e,this.config.onMessagesUpdated&&this.config.onMessagesUpdated(e),this));u(this,"validateMessageContent",e=>!(!e||e.trim().length===0));u(this,"constructMessagePayload",(e,n,s,i={})=>({blocks:[{id:"1",type:"text",text:e}],id:"temp-id",request_user_feedback:!1,user_feedback_value:null,sender_id:n,sender_name:null,sent_at:s,type:"message",...i}));u(this,"pushMessageToChannel",e=>{var n;this.updateState("sending"),(n=this.channel)==null||n.push("new_text",e).receive("ok",s=>(console.log("Message sent successfully",s),this.updateState("sending"),this.setMessages([...this.messages,s[0]]),s)).receive("error",s=>{this.logger.error("Error sending message",s)}).receive("timeout",()=>{this.logger.error("Push request timed out")})});u(this,"sendNewMessage",async e=>{const{userId:n,conversationId:s}=this;if(!this.validateMessageContent(e)){console.warn("Invalid message content, skipping send");return}(!n||!s)&&await this.initializeNewConversation(n),this.pushMessageToChannel(e)});u(this,"createNewConversation",async e=>{const{token:n}=this.config;return this.api.createNewConversation(e,n)});u(this,"initializeNewConversation",async e=>{const{user:n={}}=this.config,s=n,i=await this.createOrUpdateUser(e,s),{id:r}=await this.createNewConversation(i);return this.setUserId(i).setConversationId(r)});u(this,"createNewUser",e=>(this.logger.debug("Creating new user:",e),this.api.createNewUser(e)));u(this,"identify",async(e,n={})=>{try{const s=this.userId||this.getCachedUserId(),i=await this.isValidUserId(s),r={...n,external_id:e};if(i){this.logger.debug("Valid user found for ID:",s);const{id:g}=await this.api.updateUserMetadata(s,n);return this.setUserId(g)}const c=await this.checkForExistingUser(r),{id:l}=c?await this.api.updateUserMetadata(c,n):await this.createNewUser(r);return this.setUserId(l)}catch(s){this.logger.error("Failed to update or create user:",s),this.logger.error("Retrying...");const{id:i}=await this.createNewUser(n);return this.setUserId(i)}});u(this,"createOrUpdateUser",async(e,n={})=>{try{const s=e?await this.api.updateUserMetadata(e,n):await this.createNewUser(n),{id:i}=s;return i}catch(s){this.logger.error("Failed to update or create user:",s),this.logger.error("Retrying...");const{id:i}=await this.createNewUser(n);return i}});u(this,"fetchWidgetSettings",async()=>{const e={};return this.api.fetchWidgetSettings().then(n=>n||e).catch(()=>e)});u(this,"fetchLatestUserConversation",async e=>{const{token:n}=this.config,s={user_id:e,token:n};return this.api.fetchUserConversations(s).then(i=>{this.logger.debug("Found existing conversations:",i);const[r]=i??[];return r||null})});u(this,"updateWidgetSettingsMetadata",async e=>this.api.updateWidgetSettingsMetadata(e).catch(n=>{this.logger.error("Failed to update widget metadata:",n)}));u(this,"findUserByExternalId",async e=>{const n=await this.api.findUserByExternalId(e);return(n==null?void 0:n.id)||null});u(this,"findUserByMetadata",async e=>{if(!e||!(e!=null&&e.external_id))return null;const{external_id:n}=e;return await this.findUserByExternalId(n)});u(this,"checkForExistingUser",async(e,n=null)=>n);u(this,"updateExistingUser",async(e,n)=>{if(n)try{await this.api.updateUserMetadata(e,n)}catch(s){this.logger.debug("Error updating user metadata!",s)}});u(this,"getCachedUserId",()=>this.storage.getUserId());u(this,"cacheUserId",e=>{this.logger.debug("Caching user ID:",e),e?this.storage.setUserId(e):this.storage.removeUserId()});u(this,"isValidUserId",async e=>{if(!e||!e.length||!me(e))return!1;try{return await this.api.isValidUser(e)}catch{return this.logger.warn("Failed to validate user ID."),this.logger.warn("You might be on an older version of Freeday."),!0}});u(this,"checkHealth",async()=>this.api.healthCheck().then(()=>!0).catch(()=>!1));u(this,"updateState",e=>{this.state=e,this.config.onStateUpdated&&this.config.onStateUpdated(e)});u(this,"notifyUser",(e,n,s={})=>{var i,r;(r=(i=this.config).onNotifyUser)==null||r.call(i,e,n,s)});u(this,"notify",(e,n,s={})=>{this.logger.debug({type:e,message:n,options:s})});const n=window,{baseUrl:s,token:i,conversationId:r,userId:c,debug:l=!1}=e,g=ge(n)||l;this.config=e,this.api=new be(i,s),this.logger=new Re(g),this.storage=Ae(n),this.userId=c||this.getCachedUserId()||null,this.conversationId=r||null,this.messages=[];const v=fe(s);this.socket=new Ue(v,{params:{token:i},heartbeatIntervalMs:3e4,reconnectAfterMs:_=>[1e3,2e3,4e3,8e3,16e3][_-1]||3e4}),this.socket.onOpen(()=>{this.connectionState="connected"}),this.socket.onError(()=>{this.logger.debug("Socket error occurred."),this.handleSocketDisconnect()}),this.socket.onClose(()=>{this.connectionState="disconnected",this.logger.debug("Socket connection closed."),this.handleSocketDisconnect()})}};u(R,"init",e=>new R(e)),u(R,"open",()=>window.dispatchEvent(new Event(H.OPEN))),u(R,"close",()=>window.dispatchEvent(new Event(H.CLOSE))),u(R,"toggle",()=>window.dispatchEvent(new Event(H.TOGGLE))),u(R,"restart",()=>window.dispatchEvent(new Event(H.RESTART)));let Y=R;const he=window,Le=he.Freeday&&he.Freeday.config||{},{token:ce,userId:Oe,baseUrl:Me,greeting:je,debug:Ne,onSetUserId:Pe,onSetConversationId:De,onSetWidgetSettings:He,onPresenceSync:xe}=Le;if(!ce)throw new Error("An account token is required to start Freeday!");Y.init({token:ce,userId:Oe,baseUrl:Me,greeting:je,debug:Ne,onSetUserId:Pe,onSetConversationId:De,onSetWidgetSettings:He,onPresenceSync:xe})})(); |
{ | ||
"name": "@freeday-ai/webchat-sdk", | ||
"description": "Freeday webchat sdk", | ||
"version": "0.0.1-alpha.34", | ||
"version": "0.0.1-alpha.35", | ||
"author": "freeday", | ||
@@ -6,0 +6,0 @@ "license": "MIT", |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
340879
2595