@meltingspot/embed 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ <!--
4
+ To add a new release, copy from this template:
5
+
6
+ ## vX.Y.Z
7
+
8
+ Date: YYYY-MM-DD
9
+
10
+ ### Major Changes
11
+
12
+ ### Minor Changes
13
+
14
+ ### Patch Changes
15
+
16
+ -->
17
+
18
+ ## v1.0.0
19
+
20
+ Date: 2026-06-17
21
+
22
+ ### Major Changes
23
+
24
+ Initial release of the `@meltingspot/embed` SDK.
package/README.md CHANGED
@@ -6,12 +6,11 @@ Embed a full MeltingSpot spot into your own web application through an iframe, w
6
6
 
7
7
  ### Via `<script>` (CDN)
8
8
 
9
- The standalone bundle is self-contained — it exposes `window.MeltingSpot.Embed`.
9
+ The standalone bundle is self-contained: it exposes `window.MeltingSpot.Embed`.
10
10
 
11
11
  ```html
12
12
  <script
13
13
  crossorigin
14
- async
15
14
  src="https://cdn.jsdelivr.net/npm/@meltingspot/embed"
16
15
  ></script>
17
16
  ```
@@ -26,9 +25,6 @@ npm install @meltingspot/embed
26
25
  import { Embed } from '@meltingspot/embed';
27
26
  ```
28
27
 
29
- > The npm package declares `@meltingspot/core` as a dependency so your bundler
30
- > resolves a single shared core instance.
31
-
32
28
  ## Usage
33
29
 
34
30
  Add a container element and inject your spot into it:
@@ -39,6 +35,7 @@ Add a container element and inject your spot into it:
39
35
  window.addEventListener('DOMContentLoaded', function () {
40
36
  window.MeltingSpot.Embed.injectSpotInto('meltingspot-frame', {
41
37
  spotId: 'YOUR_SPOT_ID',
38
+ authToken: 'CURRENT_USER_SSO_TOKEN',
42
39
  themeMode: 'auto',
43
40
  });
44
41
  });
@@ -52,33 +49,91 @@ import { Embed } from '@meltingspot/embed';
52
49
 
53
50
  Embed.injectSpotInto('meltingspot-frame', {
54
51
  spotId: 'YOUR_SPOT_ID',
52
+ authToken: 'CURRENT_USER_SSO_TOKEN',
55
53
  themeMode: 'auto',
56
54
  });
57
55
  ```
58
56
 
57
+ ### Authentication (`authToken`)
58
+
59
+ `authToken` is the **MeltingSpot SSO token** of the current user. Provide it to
60
+ embed the spot as an authenticated member, so the user sees the same content and
61
+ permissions as inside MeltingSpot. Activate [SSO](https://help.meltingspot.io/english/manage-spot/sso)
62
+ on your spot to obtain these tokens.
63
+
64
+ Omit `authToken` to embed in **public mode**: only publicly available content is
65
+ shown and the visitor is treated as anonymous.
66
+
67
+ ## `injectSpotInto(target, options)`
68
+
69
+ `target` (required) is the container: an element `id` (string) or an `HTMLElement`.
70
+
71
+ | Option | Type | Required | Default | Description |
72
+ | --------------- | ----------------------------------------- | -------- | --------------------------------------------- | --------------------------------------------------------- |
73
+ | `spotId` | `string` | Yes | n/a | Target spot id. Required here unless set via the config. |
74
+ | `authToken` | `string` | No | `ms_token` URL param, else none (public mode) | Current user's MeltingSpot SSO token. |
75
+ | `themeMode` | `'auto' \| 'system' \| 'light' \| 'dark'` | No | `'auto'` | Force a theme. |
76
+ | `deeplink` | `string` | No | `ms_url` URL param, else none | In-spot page opened on load. See [`deeplink`](#deeplink). |
77
+ | `domain` | `string` | No | none (default MeltingSpot domain) | Custom domain key of your spot. See [`domain`](#domain). |
78
+ | `utmParameters` | `UtmParameters` | No | parsed from the page URL params | UTM params appended to the embed URL. |
79
+ | `rootDocument` | `Document` | No | current `document` | Document to inject into. |
80
+ | `onReady` | `() => void` | No | none | Called when the embedded content is fully rendered. |
81
+ | `onError` | `(error) => void` | No | none | Called on a loading error inside the iframe. |
82
+
83
+ ### `deeplink`
84
+
85
+ The in-spot page the embed opens on load (a path or URL, e.g. a channel, course
86
+ or post). It is normalized to the spot route (`/spot/{spotId}/...`), preserving
87
+ the query string and hash.
88
+
89
+ > If omitted, the SDK auto-detects a deeplink from the `ms_url` query param that
90
+ > MeltingSpot injects into the links generated by the app (e.g. links sent in
91
+ > emails). Setting `deeplink` explicitly **disables that automatic detection** and
92
+ > forces your value instead.
93
+
94
+ See the [embed guide](https://help.meltingspot.io/english/manage-spot/embed) for details.
95
+
96
+ ### `domain`
97
+
98
+ The custom domain key of your spot. It is forwarded to the embedded content so
99
+ the links it generates point to your custom domain instead of the default
100
+ MeltingSpot one.
101
+
102
+ See the ["Multi-domains" section of the embed guide](https://help.meltingspot.io/english/manage-spot/embed) for details.
103
+
104
+ ### `UtmParameters`
105
+
106
+ Appended to the embed URL as `utm_*` query params (`source` becomes `utm_source`, etc.).
107
+
108
+ | Field | Type | Required | Default | Description |
109
+ | ---------- | -------- | -------- | ------- | --------------------- |
110
+ | `source` | `string` | Yes | n/a | `utm_source` value. |
111
+ | `medium` | `string` | No | unset | `utm_medium` value. |
112
+ | `campaign` | `string` | No | unset | `utm_campaign` value. |
113
+ | `term` | `string` | No | unset | `utm_term` value. |
114
+ | `content` | `string` | No | unset | `utm_content` value. |
115
+
59
116
  ## Lifecycle callbacks
60
117
 
61
- `injectSpotInto` accepts optional `onReady` / `onError` callbacks, backed by
62
- `postMessage` signals (`meltingspot:ready` / `meltingspot:error`) with origin
63
- validation.
118
+ `onReady` / `onError` are backed by `postMessage` signals
119
+ (`meltingspot:ready` / `meltingspot:error`) with origin validation.
64
120
 
65
121
  ```typescript
66
122
  Embed.injectSpotInto('meltingspot-frame', {
67
123
  spotId: 'YOUR_SPOT_ID',
124
+ authToken: 'CURRENT_USER_SSO_TOKEN',
68
125
  themeMode: 'auto',
69
126
  onReady: () => console.info('MeltingSpot embed is ready'),
70
127
  onError: (error) => console.error('MeltingSpot embed error:', error.message),
71
128
  });
72
129
  ```
73
130
 
131
+ The `error` object passed to `onError`:
132
+
74
133
  | Property | Type | Description |
75
134
  | --------- | -------- | --------------------------------- |
76
135
  | `type` | `string` | Optional error type |
77
136
  | `message` | `string` | Human-readable error message |
78
137
  | `code` | `string` | Optional error code for debugging |
79
138
 
80
- See the [Embed helpdesk](https://help.meltingspot.io/manage-spot/embed) for the full integration guide.
81
-
82
- ```
83
-
84
- ```
139
+ See the [Embed helpdesk](https://help.meltingspot.io/english/manage-spot/embed) for the full integration guide.
package/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@meltingspot/core"),L="0.1.0",l=new s.Logger({appName:"Embed SDK",appVersion:L});class g{constructor(e){this.content=e}#e=null;#t=null;set onRemove(e){this.#t=e}inject(e){this.remove();const i=s.getHTMLElement({input:e,rootDocument:this.content.rootDocument});this.#e=this.content.iframe,this.#e.classList.add("ms-embed"),i.appendChild(this.#e)}remove(){this.#e&&(this.#e.contentWindow&&this.#t?.(this.#e.contentWindow),this.#e.remove(),this.#e=null)}}class w{constructor(e){this.baseURL=s.formatBaseUrl(e.baseURL),this.spotId=s.formatUUID(e.spotId),this.authToken=e.authToken??null,this.themeMode=e.themeMode??"auto",this.domain=e.domain??null,this.deeplink=e.deeplink?s.formatDeeplink({deeplink:e.deeplink,spotId:this.spotId}):null,this.utmParameters=e.utmParameters??null,this.rootDocument=e.rootDocument}get iframe(){const e=this.authToken&&this.authToken.trim().length>0?"/sso/jwt":"",i=new URL(`/spot/${this.spotId}${e}`,s.trimSlashRight(this.baseURL)),n=s.createIframe({url:i,searchParams:{embed:this.spotId,themeMode:this.themeMode,ms_token:this.authToken,domain:this.domain,deeplink:this.deeplink,...s.flattenUtmParameters(this.utmParameters)},rootDocument:this.rootDocument});return n.classList.add("ms-spot"),n}}const m={READY:"meltingspot:ready",ERROR:"meltingspot:error"},t=class t{static injectSpotInto(e,i){const{onReady:n,onError:a,...o}=i,{spotId:u,rootDocument:E,msCommunityWebBaseUrl:k}=s.ConfigurationService.getConfiguration({spotId:o.spotId,rootDocument:o.rootDocument,msCommunityWebBaseUrl:o.baseURL});if(!u)throw l.error("Spot ID is required"),new Error("Spot ID is not configured. Please set the spotId in the configuration.");const d=new URLSearchParams(window.location.search),p={spotId:u,authToken:o.authToken??d.get("ms_token"),domain:o.domain,deeplink:o.deeplink??d.get("ms_url"),themeMode:o.themeMode,utmParameters:o.utmParameters??s.parseUtmParameters(d),baseURL:k,rootDocument:E},r=new g(new w(p));if(r.inject(e),t.embeds.push(r),n||a){const f=r.content.iframe.contentWindow;f&&(t.iframeCallbacks.set(f,{onReady:n,onError:a}),r.onRemove=R=>{t.iframeCallbacks.delete(R)}),t.ensureMessageListener()}return l.log("Spot injected",p,e),r}static clear(){t.embeds.forEach(e=>{e.remove()}),t.embeds=[],t.iframeCallbacks.clear(),t.messageListened&&(window.removeEventListener("message",t.handleMessageEvent),t.messageListened=!1),l.log("All MeltingSpot embeds cleared")}static handleMessageEvent(e){if(!e.data||typeof e.data!="object"||e.data.type!==m.READY&&e.data.type!==m.ERROR)return;const i=e.source,n=t.iframeCallbacks.get(i);if(!n)return;const{msCommunityWebBaseUrl:a}=s.ConfigurationService.getConfiguration({});if(a)try{const o=new URL(a).origin;if(e.origin!==o)return}catch{}e.data.type===m.READY?n.onReady?.():n.onError?.(e.data.error)}static ensureMessageListener(){t.messageListened||(window.addEventListener("message",t.handleMessageEvent),t.messageListened=!0)}};t.embeds=[],t.messageListened=!1,t.iframeCallbacks=new Map;let c=t;const h=globalThis;h.MeltingSpot||(h.MeltingSpot={});h.MeltingSpot.Embed=c;exports.EMBED_POST_MESSAGE_TYPE=m;exports.Embed=c;exports.EmbedFrame=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@meltingspot/core"),L="1.0.0",l=new s.Logger({appName:"Embed SDK",appVersion:L});class g{constructor(e){this.content=e}#e=null;#t=null;set onRemove(e){this.#t=e}inject(e){this.remove();const i=s.getHTMLElement({input:e,rootDocument:this.content.rootDocument});this.#e=this.content.iframe,this.#e.classList.add("ms-embed"),i.appendChild(this.#e)}remove(){this.#e&&(this.#e.contentWindow&&this.#t?.(this.#e.contentWindow),this.#e.remove(),this.#e=null)}}class w{constructor(e){this.baseURL=s.formatBaseUrl(e.baseURL),this.spotId=s.formatUUID(e.spotId),this.authToken=e.authToken??null,this.themeMode=e.themeMode??"auto",this.domain=e.domain??null,this.deeplink=e.deeplink?s.formatDeeplink({deeplink:e.deeplink,spotId:this.spotId}):null,this.utmParameters=e.utmParameters??null,this.rootDocument=e.rootDocument}get iframe(){const e=this.authToken&&this.authToken.trim().length>0?"/sso/jwt":"",i=new URL(`/spot/${this.spotId}${e}`,s.trimSlashRight(this.baseURL)),n=s.createIframe({url:i,searchParams:{embed:this.spotId,themeMode:this.themeMode,ms_token:this.authToken,domain:this.domain,deeplink:this.deeplink,...s.flattenUtmParameters(this.utmParameters)},rootDocument:this.rootDocument});return n.classList.add("ms-spot"),n}}const m={READY:"meltingspot:ready",ERROR:"meltingspot:error"},t=class t{static injectSpotInto(e,i){const{onReady:n,onError:a,...o}=i,{spotId:u,rootDocument:E,msCommunityWebBaseUrl:k}=s.ConfigurationService.getConfiguration({spotId:o.spotId,rootDocument:o.rootDocument,msCommunityWebBaseUrl:o.baseURL});if(!u)throw l.error("Spot ID is required"),new Error("Spot ID is not configured. Please set the spotId in the configuration.");const d=new URLSearchParams(window.location.search),p={spotId:u,authToken:o.authToken??d.get("ms_token"),domain:o.domain,deeplink:o.deeplink??d.get("ms_url"),themeMode:o.themeMode,utmParameters:o.utmParameters??s.parseUtmParameters(d),baseURL:k,rootDocument:E},r=new g(new w(p));if(r.inject(e),t.embeds.push(r),n||a){const f=r.content.iframe.contentWindow;f&&(t.iframeCallbacks.set(f,{onReady:n,onError:a}),r.onRemove=R=>{t.iframeCallbacks.delete(R)}),t.ensureMessageListener()}return l.log("Spot injected",p,e),r}static clear(){t.embeds.forEach(e=>{e.remove()}),t.embeds=[],t.iframeCallbacks.clear(),t.messageListened&&(window.removeEventListener("message",t.handleMessageEvent),t.messageListened=!1),l.log("All MeltingSpot embeds cleared")}static handleMessageEvent(e){if(!e.data||typeof e.data!="object"||e.data.type!==m.READY&&e.data.type!==m.ERROR)return;const i=e.source,n=t.iframeCallbacks.get(i);if(!n)return;const{msCommunityWebBaseUrl:a}=s.ConfigurationService.getConfiguration({});if(a)try{const o=new URL(a).origin;if(e.origin!==o)return}catch{}e.data.type===m.READY?n.onReady?.():n.onError?.(e.data.error)}static ensureMessageListener(){t.messageListened||(window.addEventListener("message",t.handleMessageEvent),t.messageListened=!0)}};t.embeds=[],t.messageListened=!1,t.iframeCallbacks=new Map;let c=t;const h=globalThis;h.MeltingSpot||(h.MeltingSpot={});h.MeltingSpot.Embed=c;exports.EMBED_POST_MESSAGE_TYPE=m;exports.Embed=c;exports.EmbedFrame=g;
package/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Logger as L, getHTMLElement as w, formatBaseUrl as E, formatUUID as D, formatDeeplink as U, trimSlashRight as I, createIframe as M, flattenUtmParameters as P, ConfigurationService as f, parseUtmParameters as S } from "@meltingspot/core";
2
- const C = "0.1.0", m = new L({ appName: "Embed SDK", appVersion: C });
2
+ const C = "1.0.0", m = new L({ appName: "Embed SDK", appVersion: C });
3
3
  class y {
4
4
  constructor(e) {
5
5
  this.content = e;
@@ -17,4 +17,4 @@ __p += '`),tn&&(y+=`' +
17
17
  function print() { __p += __j.call(arguments, '') }
18
18
  `:`;
19
19
  `)+y+`return __p
20
- }`;var Z=Ka(function(){return un(f,D+"return "+y).apply(i,l)});if(Z.source=y,Lu(Z))throw Z;return Z}function lm(n){return on(n).toLowerCase()}function hm(n){return on(n).toUpperCase()}function dm(n,e,t){if(n=on(n),n&&(t||e===i))return to(n);if(!n||!(e=ne(e)))return n;var r=ve(n),o=ve(e),f=ro(r,o),l=io(r,o)+1;return Ze(r,f,l).join("")}function pm(n,e,t){if(n=on(n),n&&(t||e===i))return n.slice(0,so(n)+1);if(!n||!(e=ne(e)))return n;var r=ve(n),o=io(r,ve(e))+1;return Ze(r,0,o).join("")}function _m(n,e,t){if(n=on(n),n&&(t||e===i))return n.replace(Li,"");if(!n||!(e=ne(e)))return n;var r=ve(n),o=ro(r,ve(e));return Ze(r,o).join("")}function gm(n,e){var t=cn,r=rn;if(En(e)){var o="separator"in e?e.separator:o;t="length"in e?Q(e.length):t,r="omission"in e?ne(e.omission):r}n=on(n);var f=n.length;if(Tt(n)){var l=ve(n);f=l.length}if(t>=f)return n;var h=t-yt(r);if(h<1)return r;var g=l?Ze(l,0,h).join(""):n.slice(0,h);if(o===i)return g+r;if(l&&(h+=g.length-h),bu(o)){if(n.slice(h).search(o)){var w,T=g;for(o.global||(o=qi(o.source,on(Is.exec(o))+"g")),o.lastIndex=0;w=o.exec(T);)var y=w.index;g=g.slice(0,y===i?h:y)}}else if(n.indexOf(ne(o),h)!=h){var O=g.lastIndexOf(o);O>-1&&(g=g.slice(0,O))}return g+r}function mm(n){return n=on(n),n&&xc.test(n)?n.replace(Ts,ql):n}var vm=Lt(function(n,e,t){return n+(t?" ":"")+e.toUpperCase()}),Nu=Zo("toUpperCase");function Qa(n,e,t){return n=on(n),e=t?i:e,e===i?kl(n)?Zl(n):Dl(n):n.match(e)||[]}var Ka=J(function(n,e){try{return Vn(n,i,e)}catch(t){return Lu(t)?t:new k(t)}}),Em=Ue(function(n,e){return oe(e,function(t){t=Me(t),Ne(n,t,Mu(n[t],n))}),n});function wm(n){var e=n==null?0:n.length,t=U();return n=e?_n(n,function(r){if(typeof r[1]!="function")throw new ae(_);return[t(r[0]),r[1]]}):[],J(function(r){for(var o=-1;++o<e;){var f=n[o];if(Vn(f[0],this,r))return Vn(f[1],this,r)}})}function Tm(n){return qh(ce(n,N))}function $u(n){return function(){return n}}function ym(n,e){return n==null||n!==n?e:n}var Am=Xo(),Im=Xo(!0);function Kn(n){return n}function Uu(n){return Mo(typeof n=="function"?n:ce(n,N))}function Om(n){return Lo(ce(n,N))}function Rm(n,e){return bo(n,ce(e,N))}var Mm=J(function(n,e){return function(t){return Zt(t,n,e)}}),xm=J(function(n,e){return function(t){return Zt(n,t,e)}});function Pu(n,e,t){var r=Dn(e),o=zr(e,r);t==null&&!(En(e)&&(o.length||!r.length))&&(t=e,e=n,n=this,o=zr(e,Dn(e)));var f=!(En(t)&&"chain"in t)||!!t.chain,l=Fe(n);return oe(o,function(h){var g=e[h];n[h]=g,l&&(n.prototype[h]=function(){var w=this.__chain__;if(f||w){var T=n(this.__wrapped__),y=T.__actions__=zn(this.__actions__);return y.push({func:g,args:arguments,thisArg:n}),T.__chain__=w,T}return g.apply(n,Be([this.value()],arguments))})}),n}function Lm(){return Pn._===this&&(Pn._=eh),this}function Fu(){}function bm(n){return n=Q(n),J(function(e){return So(e,n)})}var Sm=pu(_n),Dm=pu(Xs),Nm=pu(Ci);function Za(n){return Tu(n)?Hi(Me(n)):fd(n)}function $m(n){return function(e){return n==null?i:ot(n,e)}}var Um=jo(),Pm=jo(!0);function Yu(){return[]}function Cu(){return!1}function Fm(){return{}}function Ym(){return""}function Cm(){return!0}function Hm(n,e){if(n=Q(n),n<1||n>I)return[];var t=X,r=Cn(n,X);e=U(e),n-=X;for(var o=Bi(r,e);++t<n;)e(t);return o}function km(n){return B(n)?_n(n,Me):ee(n)?[n]:zn(_a(on(n)))}function Wm(n){var e=++jl;return on(n)+e}var Bm=Xr(function(n,e){return n+e},0),Gm=_u("ceil"),zm=Xr(function(n,e){return n/e},1),qm=_u("floor");function Qm(n){return n&&n.length?Gr(n,Kn,nu):i}function Km(n,e){return n&&n.length?Gr(n,U(e,2),nu):i}function Zm(n){return no(n,Kn)}function Jm(n,e){return no(n,U(e,2))}function Xm(n){return n&&n.length?Gr(n,Kn,iu):i}function Vm(n,e){return n&&n.length?Gr(n,U(e,2),iu):i}var jm=Xr(function(n,e){return n*e},1),n0=_u("round"),e0=Xr(function(n,e){return n-e},0);function t0(n){return n&&n.length?Wi(n,Kn):0}function r0(n,e){return n&&n.length?Wi(n,U(e,2)):0}return a.after=O_,a.ary=Ra,a.assign=hg,a.assignIn=Ha,a.assignInWith=ci,a.assignWith=dg,a.at=pg,a.before=Ma,a.bind=Mu,a.bindAll=Em,a.bindKey=xa,a.castArray=F_,a.chain=Aa,a.chunk=qd,a.compact=Qd,a.concat=Kd,a.cond=wm,a.conforms=Tm,a.constant=$u,a.countBy=t_,a.create=_g,a.curry=La,a.curryRight=ba,a.debounce=Sa,a.defaults=gg,a.defaultsDeep=mg,a.defer=R_,a.delay=M_,a.difference=Zd,a.differenceBy=Jd,a.differenceWith=Xd,a.drop=Vd,a.dropRight=jd,a.dropRightWhile=np,a.dropWhile=ep,a.fill=tp,a.filter=i_,a.flatMap=o_,a.flatMapDeep=a_,a.flatMapDepth=f_,a.flatten=Ea,a.flattenDeep=rp,a.flattenDepth=ip,a.flip=x_,a.flow=Am,a.flowRight=Im,a.fromPairs=up,a.functions=Ig,a.functionsIn=Og,a.groupBy=c_,a.initial=op,a.intersection=ap,a.intersectionBy=fp,a.intersectionWith=cp,a.invert=Mg,a.invertBy=xg,a.invokeMap=h_,a.iteratee=Uu,a.keyBy=d_,a.keys=Dn,a.keysIn=Qn,a.map=ii,a.mapKeys=bg,a.mapValues=Sg,a.matches=Om,a.matchesProperty=Rm,a.memoize=si,a.merge=Dg,a.mergeWith=ka,a.method=Mm,a.methodOf=xm,a.mixin=Pu,a.negate=oi,a.nthArg=bm,a.omit=Ng,a.omitBy=$g,a.once=L_,a.orderBy=p_,a.over=Sm,a.overArgs=b_,a.overEvery=Dm,a.overSome=Nm,a.partial=xu,a.partialRight=Da,a.partition=__,a.pick=Ug,a.pickBy=Wa,a.property=Za,a.propertyOf=$m,a.pull=pp,a.pullAll=Ta,a.pullAllBy=_p,a.pullAllWith=gp,a.pullAt=mp,a.range=Um,a.rangeRight=Pm,a.rearg=S_,a.reject=v_,a.remove=vp,a.rest=D_,a.reverse=Ou,a.sampleSize=w_,a.set=Fg,a.setWith=Yg,a.shuffle=T_,a.slice=Ep,a.sortBy=I_,a.sortedUniq=Rp,a.sortedUniqBy=Mp,a.split=om,a.spread=N_,a.tail=xp,a.take=Lp,a.takeRight=bp,a.takeRightWhile=Sp,a.takeWhile=Dp,a.tap=Qp,a.throttle=$_,a.thru=ri,a.toArray=Fa,a.toPairs=Ba,a.toPairsIn=Ga,a.toPath=km,a.toPlainObject=Ca,a.transform=Cg,a.unary=U_,a.union=Np,a.unionBy=$p,a.unionWith=Up,a.uniq=Pp,a.uniqBy=Fp,a.uniqWith=Yp,a.unset=Hg,a.unzip=Ru,a.unzipWith=ya,a.update=kg,a.updateWith=Wg,a.values=Dt,a.valuesIn=Bg,a.without=Cp,a.words=Qa,a.wrap=P_,a.xor=Hp,a.xorBy=kp,a.xorWith=Wp,a.zip=Bp,a.zipObject=Gp,a.zipObjectDeep=zp,a.zipWith=qp,a.entries=Ba,a.entriesIn=Ga,a.extend=Ha,a.extendWith=ci,Pu(a,a),a.add=Bm,a.attempt=Ka,a.camelCase=Qg,a.capitalize=za,a.ceil=Gm,a.clamp=Gg,a.clone=Y_,a.cloneDeep=H_,a.cloneDeepWith=k_,a.cloneWith=C_,a.conformsTo=W_,a.deburr=qa,a.defaultTo=ym,a.divide=zm,a.endsWith=Kg,a.eq=we,a.escape=Zg,a.escapeRegExp=Jg,a.every=r_,a.find=u_,a.findIndex=ma,a.findKey=vg,a.findLast=s_,a.findLastIndex=va,a.findLastKey=Eg,a.floor=qm,a.forEach=Ia,a.forEachRight=Oa,a.forIn=wg,a.forInRight=Tg,a.forOwn=yg,a.forOwnRight=Ag,a.get=Su,a.gt=B_,a.gte=G_,a.has=Rg,a.hasIn=Du,a.head=wa,a.identity=Kn,a.includes=l_,a.indexOf=sp,a.inRange=zg,a.invoke=Lg,a.isArguments=ct,a.isArray=B,a.isArrayBuffer=z_,a.isArrayLike=qn,a.isArrayLikeObject=yn,a.isBoolean=q_,a.isBuffer=Je,a.isDate=Q_,a.isElement=K_,a.isEmpty=Z_,a.isEqual=J_,a.isEqualWith=X_,a.isError=Lu,a.isFinite=V_,a.isFunction=Fe,a.isInteger=Na,a.isLength=ai,a.isMap=$a,a.isMatch=j_,a.isMatchWith=ng,a.isNaN=eg,a.isNative=tg,a.isNil=ig,a.isNull=rg,a.isNumber=Ua,a.isObject=En,a.isObjectLike=wn,a.isPlainObject=er,a.isRegExp=bu,a.isSafeInteger=ug,a.isSet=Pa,a.isString=fi,a.isSymbol=ee,a.isTypedArray=St,a.isUndefined=sg,a.isWeakMap=og,a.isWeakSet=ag,a.join=lp,a.kebabCase=Xg,a.last=he,a.lastIndexOf=hp,a.lowerCase=Vg,a.lowerFirst=jg,a.lt=fg,a.lte=cg,a.max=Qm,a.maxBy=Km,a.mean=Zm,a.meanBy=Jm,a.min=Xm,a.minBy=Vm,a.stubArray=Yu,a.stubFalse=Cu,a.stubObject=Fm,a.stubString=Ym,a.stubTrue=Cm,a.multiply=jm,a.nth=dp,a.noConflict=Lm,a.noop=Fu,a.now=ui,a.pad=nm,a.padEnd=em,a.padStart=tm,a.parseInt=rm,a.random=qg,a.reduce=g_,a.reduceRight=m_,a.repeat=im,a.replace=um,a.result=Pg,a.round=n0,a.runInContext=d,a.sample=E_,a.size=y_,a.snakeCase=sm,a.some=A_,a.sortedIndex=wp,a.sortedIndexBy=Tp,a.sortedIndexOf=yp,a.sortedLastIndex=Ap,a.sortedLastIndexBy=Ip,a.sortedLastIndexOf=Op,a.startCase=am,a.startsWith=fm,a.subtract=e0,a.sum=t0,a.sumBy=r0,a.template=cm,a.times=Hm,a.toFinite=Ye,a.toInteger=Q,a.toLength=Ya,a.toLower=lm,a.toNumber=de,a.toSafeInteger=lg,a.toString=on,a.toUpper=hm,a.trim=dm,a.trimEnd=pm,a.trimStart=_m,a.truncate=gm,a.unescape=mm,a.uniqueId=Wm,a.upperCase=vm,a.upperFirst=Nu,a.each=Ia,a.eachRight=Oa,a.first=wa,Pu(a,(function(){var n={};return Oe(a,function(e,t){fn.call(a.prototype,t)||(n[t]=e)}),n})(),{chain:!1}),a.VERSION=c,oe(["bind","bindKey","curry","curryRight","partial","partialRight"],function(n){a[n].placeholder=a}),oe(["drop","take"],function(n,e){j.prototype[n]=function(t){t=t===i?1:bn(Q(t),0);var r=this.__filtered__&&!e?new j(this):this.clone();return r.__filtered__?r.__takeCount__=Cn(t,r.__takeCount__):r.__views__.push({size:Cn(t,X),type:n+(r.__dir__<0?"Right":"")}),r},j.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}}),oe(["filter","map","takeWhile"],function(n,e){var t=e+1,r=t==Y||t==R;j.prototype[n]=function(o){var f=this.clone();return f.__iteratees__.push({iteratee:U(o,3),type:t}),f.__filtered__=f.__filtered__||r,f}}),oe(["head","last"],function(n,e){var t="take"+(e?"Right":"");j.prototype[n]=function(){return this[t](1).value()[0]}}),oe(["initial","tail"],function(n,e){var t="drop"+(e?"":"Right");j.prototype[n]=function(){return this.__filtered__?new j(this):this[t](1)}}),j.prototype.compact=function(){return this.filter(Kn)},j.prototype.find=function(n){return this.filter(n).head()},j.prototype.findLast=function(n){return this.reverse().find(n)},j.prototype.invokeMap=J(function(n,e){return typeof n=="function"?new j(this):this.map(function(t){return Zt(t,n,e)})}),j.prototype.reject=function(n){return this.filter(oi(U(n)))},j.prototype.slice=function(n,e){n=Q(n);var t=this;return t.__filtered__&&(n>0||e<0)?new j(t):(n<0?t=t.takeRight(-n):n&&(t=t.drop(n)),e!==i&&(e=Q(e),t=e<0?t.dropRight(-e):t.take(e-n)),t)},j.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},j.prototype.toArray=function(){return this.take(X)},Oe(j.prototype,function(n,e){var t=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),o=a[r?"take"+(e=="last"?"Right":""):e],f=r||/^find/.test(e);o&&(a.prototype[e]=function(){var l=this.__wrapped__,h=r?[1]:arguments,g=l instanceof j,w=h[0],T=g||B(l),y=function(V){var tn=o.apply(a,Be([V],h));return r&&O?tn[0]:tn};T&&t&&typeof w=="function"&&w.length!=1&&(g=T=!1);var O=this.__chain__,D=!!this.__actions__.length,P=f&&!O,Z=g&&!D;if(!f&&T){l=Z?l:new j(this);var F=n.apply(l,h);return F.__actions__.push({func:ri,args:[y],thisArg:i}),new fe(F,O)}return P&&Z?n.apply(this,h):(F=this.thru(y),P?r?F.value()[0]:F.value():F)})}),oe(["pop","push","shift","sort","splice","unshift"],function(n){var e=Lr[n],t=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",r=/^(?:pop|shift)$/.test(n);a.prototype[n]=function(){var o=arguments;if(r&&!this.__chain__){var f=this.value();return e.apply(B(f)?f:[],o)}return this[t](function(l){return e.apply(B(l)?l:[],o)})}}),Oe(j.prototype,function(n,e){var t=a[e];if(t){var r=t.name+"";fn.call(Rt,r)||(Rt[r]=[]),Rt[r].push({name:e,func:t})}}),Rt[Jr(i,hn).name]=[{name:"wrapper",func:i}],j.prototype.clone=mh,j.prototype.reverse=vh,j.prototype.value=Eh,a.prototype.at=Kp,a.prototype.chain=Zp,a.prototype.commit=Jp,a.prototype.next=Xp,a.prototype.plant=jp,a.prototype.reverse=n_,a.prototype.toJSON=a.prototype.valueOf=a.prototype.value=e_,a.prototype.first=a.prototype.head,Wt&&(a.prototype[Wt]=Vp),a}),At=Jl();tt?((tt.exports=At)._=At,Ui._=At):Pn._=At}).call(kf)})(Ut,Ut.exports)),Ut.exports}Wf();const Bf="0.1.0";class us{constructor(u){this.debug=!1,this.debug=u?.debug??!1,this.appName=u?.appName,this.appVersion=u?.appVersion}log(u,...i){this.debug&&this.print(u,"info",i)}warn(u,...i){this.print(u,"warn",i)}error(u,...i){this.print(u,"error",i)}print(u,i,c){const _=[`[${["MeltingSpot",this.appName,this.appVersion].filter(Boolean).join(" - ")}] ${u}`];c.length&&_.push(...c),console[i](..._)}}const Gf=new us({appName:"Core SDK",appVersion:Bf}),zf=s=>s.toLowerCase().replace(/[^a-z0-9-]/g,""),qf=["/user"],Qf=({deeplink:s,spotId:u})=>{try{const i=new URL(s,"https://unused.com");let c=i.pathname;return i.search&&(c+=i.search),i.hash&&(c+=i.hash),qf.some(p=>c.startsWith(p))||(c=`/spot/${u}/${rf(c)}`),c}catch(i){return Gf.warn("Failed to parse deeplink URL",i),null}},Kf=[/(^|\.)meltingspot\.io$/i],Zf=s=>{let u;try{const v=zu(s);u=new URL(v)}catch{throw new Error(`Invalid baseURL: ${s}`)}const i=u.hostname==="localhost"||u.hostname==="127.0.0.1",c=u.protocol==="https:",p=Kf.some(v=>v.test(u.hostname));if(!i&&(!c||!p))throw new Error(`Untrusted baseURL origin: ${u.origin}`);return u.origin},Jf={msApiBaseUrl:"https://openapi.meltingspot.io/",msCommunityWebBaseUrl:"https://go.meltingspot.io/",ssoToken:void 0,spotId:"",rootDocument:globalThis.document};class ue{constructor(){this.configuration=Jf}static getInstance(){return ue.instance||(ue.instance=new ue),ue.instance}setConfiguration(u){this.configuration={...this.configuration,...u}}static getConfiguration(u={}){return{...ue.getInstance().configuration,...u}}}const ss="%[a-f0-9]{2}",os=new RegExp("("+ss+")|([^%]+?)","gi"),as=new RegExp("("+ss+")+","gi");function di(s,u){try{return[decodeURIComponent(s.join(""))]}catch{}if(s.length===1)return s;u=u||1;const i=s.slice(0,u),c=s.slice(u);return Array.prototype.concat.call([],di(i),di(c))}function Xf(s){try{return decodeURIComponent(s)}catch{let u=s.match(os)||[];for(let i=1;i<u.length;i++)s=di(u,i).join(""),u=s.match(os)||[];return s}}function Vf(s){const u={"%FE%FF":"��","%FF%FE":"��"};let i=as.exec(s);for(;i;){try{u[i[0]]=decodeURIComponent(i[0])}catch{const p=Xf(i[0]);p!==i[0]&&(u[i[0]]=p)}i=as.exec(s)}u["%C2"]="�";const c=Object.keys(u);for(const p of c)s=s.replace(new RegExp(p,"g"),u[p]);return s}function jf(s){if(typeof s!="string")throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof s+"`");try{return decodeURIComponent(s)}catch{return Vf(s)}}function nc(s,u){const i={};if(Array.isArray(u))for(const c of u){const p=Object.getOwnPropertyDescriptor(s,c);p?.enumerable&&Object.defineProperty(i,c,p)}else for(const c of Reflect.ownKeys(s)){const p=Object.getOwnPropertyDescriptor(s,c);if(p.enumerable){const v=s[c];u(c,v,s)&&Object.defineProperty(i,c,p)}}return i}function fs(s,u){if(!(typeof s=="string"&&typeof u=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(s===""||u==="")return[];const i=s.indexOf(u);return i===-1?[]:[s.slice(0,i),s.slice(i+u.length)]}const ec=s=>s==null,tc=s=>encodeURIComponent(s).replaceAll(/[!'()*]/g,u=>`%${u.charCodeAt(0).toString(16).toUpperCase()}`),pi=Symbol("encodeFragmentIdentifier");function rc(s){switch(s.arrayFormat){case"index":return u=>(i,c)=>{const p=i.length;return c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,[In(u,s),"[",p,"]"].join("")]:[...i,[In(u,s),"[",In(p,s),"]=",In(c,s)].join("")]};case"bracket":return u=>(i,c)=>c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,[In(u,s),"[]"].join("")]:[...i,[In(u,s),"[]=",In(c,s)].join("")];case"colon-list-separator":return u=>(i,c)=>c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,[In(u,s),":list="].join("")]:[...i,[In(u,s),":list=",In(c,s)].join("")];case"comma":case"separator":case"bracket-separator":{const u=s.arrayFormat==="bracket-separator"?"[]=":"=";return i=>(c,p)=>p===void 0||s.skipNull&&p===null||s.skipEmptyString&&p===""?c:(p=p===null?"":p,c.length===0?[[In(i,s),u,In(p,s)].join("")]:[[c,In(p,s)].join(s.arrayFormatSeparator)])}default:return u=>(i,c)=>c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,In(u,s)]:[...i,[In(u,s),"=",In(c,s)].join("")]}}function ic(s){let u;switch(s.arrayFormat){case"index":return(i,c,p)=>{if(u=/\[(\d*)]$/.exec(i),i=i.replace(/\[\d*]$/,""),!u){p[i]=c;return}p[i]===void 0&&(p[i]={}),p[i][u[1]]=c};case"bracket":return(i,c,p)=>{if(u=/(\[])$/.exec(i),i=i.replace(/\[]$/,""),!u){p[i]=c;return}if(p[i]===void 0){p[i]=[c];return}p[i]=[...p[i],c]};case"colon-list-separator":return(i,c,p)=>{if(u=/(:list)$/.exec(i),i=i.replace(/:list$/,""),!u){p[i]=c;return}if(p[i]===void 0){p[i]=[c];return}p[i]=[...p[i],c]};case"comma":case"separator":return(i,c,p)=>{const v=typeof c=="string"&&c.includes(s.arrayFormatSeparator),_=typeof c=="string"&&!v&&xe(c,s).includes(s.arrayFormatSeparator);c=_?xe(c,s):c;const A=v||_?c.split(s.arrayFormatSeparator).map(x=>xe(x,s)):c===null?c:xe(c,s);p[i]=A};case"bracket-separator":return(i,c,p)=>{const v=/(\[])$/.test(i);if(i=i.replace(/\[]$/,""),!v){p[i]=c&&xe(c,s);return}const _=c===null?[]:xe(c,s).split(s.arrayFormatSeparator);if(p[i]===void 0){p[i]=_;return}p[i]=[...p[i],..._]};default:return(i,c,p)=>{if(p[i]===void 0){p[i]=c;return}p[i]=[...[p[i]].flat(),c]}}}function cs(s){if(typeof s!="string"||s.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function In(s,u){return u.encode?u.strict?tc(s):encodeURIComponent(s):s}function xe(s,u){return u.decode?jf(s):s}function ls(s){return Array.isArray(s)?s.sort():typeof s=="object"?ls(Object.keys(s)).sort((u,i)=>Number(u)-Number(i)).map(u=>s[u]):s}function hs(s){const u=s.indexOf("#");return u!==-1&&(s=s.slice(0,u)),s}function uc(s){let u="";const i=s.indexOf("#");return i!==-1&&(u=s.slice(i)),u}function ds(s,u,i){return i==="string"&&typeof s=="string"?s:typeof i=="function"&&typeof s=="string"?i(s):i==="boolean"&&s===null?!0:i==="boolean"&&s!==null&&(s.toLowerCase()==="true"||s.toLowerCase()==="false")?s.toLowerCase()==="true":i==="boolean"&&s!==null&&(s.toLowerCase()==="1"||s.toLowerCase()==="0")?s.toLowerCase()==="1":i==="string[]"&&u.arrayFormat!=="none"&&typeof s=="string"?[s]:i==="number[]"&&u.arrayFormat!=="none"&&!Number.isNaN(Number(s))&&typeof s=="string"&&s.trim()!==""?[Number(s)]:i==="number"&&!Number.isNaN(Number(s))&&typeof s=="string"&&s.trim()!==""?Number(s):u.parseBooleans&&s!==null&&(s.toLowerCase()==="true"||s.toLowerCase()==="false")?s.toLowerCase()==="true":u.parseNumbers&&!Number.isNaN(Number(s))&&typeof s=="string"&&s.trim()!==""?Number(s):s}function _i(s){s=hs(s);const u=s.indexOf("?");return u===-1?"":s.slice(u+1)}function gi(s,u){u={decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1,types:Object.create(null),...u},cs(u.arrayFormatSeparator);const i=ic(u),c=Object.create(null);if(typeof s!="string"||(s=s.trim().replace(/^[?#&]/,""),!s))return c;for(const p of s.split("&")){if(p==="")continue;const v=u.decode?p.replaceAll("+"," "):p;let[_,A]=fs(v,"=");_===void 0&&(_=v),A=A===void 0?null:["comma","separator","bracket-separator"].includes(u.arrayFormat)?A:xe(A,u),i(xe(_,u),A,c)}for(const[p,v]of Object.entries(c))if(typeof v=="object"&&v!==null&&u.types[p]!=="string")for(const[_,A]of Object.entries(v)){const x=u.types[p]?u.types[p].replace("[]",""):void 0;v[_]=ds(A,u,x)}else typeof v=="object"&&v!==null&&u.types[p]==="string"?c[p]=Object.values(v).join(u.arrayFormatSeparator):c[p]=ds(v,u,u.types[p]);return u.sort===!1?c:(u.sort===!0?Object.keys(c).sort():Object.keys(c).sort(u.sort)).reduce((p,v)=>{const _=c[v];return p[v]=_&&typeof _=="object"&&!Array.isArray(_)?ls(_):_,p},Object.create(null))}function ps(s,u){if(!s)return"";u={encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:",",...u},cs(u.arrayFormatSeparator);const i=_=>u.skipNull&&ec(s[_])||u.skipEmptyString&&s[_]==="",c=rc(u),p={};for(const[_,A]of Object.entries(s))i(_)||(p[_]=A);const v=Object.keys(p);return u.sort!==!1&&v.sort(u.sort),v.map(_=>{const A=s[_];return A===void 0?"":A===null?In(_,u):Array.isArray(A)?A.length===0&&u.arrayFormat==="bracket-separator"?In(_,u)+"[]":A.reduce(c(_),[]).join("&"):In(_,u)+"="+In(A,u)}).filter(_=>_.length>0).join("&")}function _s(s,u){u={decode:!0,...u};let[i,c]=fs(s,"#");return i===void 0&&(i=s),{url:i?.split("?")?.[0]??"",query:gi(_i(s),u),...u&&u.parseFragmentIdentifier&&c?{fragmentIdentifier:xe(c,u)}:{}}}function gs(s,u){u={encode:!0,strict:!0,[pi]:!0,...u};const i=hs(s.url).split("?")[0]||"",c=_i(s.url),p={...gi(c,{sort:!1,...u}),...s.query};let v=ps(p,u);v&&=`?${v}`;let _=uc(s.url);if(typeof s.fragmentIdentifier=="string"){const A=new URL(i);A.hash=s.fragmentIdentifier,_=u[pi]?A.hash:`#${s.fragmentIdentifier}`}return`${i}${v}${_}`}function ms(s,u,i){i={parseFragmentIdentifier:!0,[pi]:!1,...i};const{url:c,query:p,fragmentIdentifier:v}=_s(s,i);return gs({url:c,query:nc(p,u),fragmentIdentifier:v},i)}function sc(s,u,i){const c=Array.isArray(u)?p=>!u.includes(p):(p,v)=>!u(p,v);return ms(s,c,i)}const oc=Object.freeze(Object.defineProperty({__proto__:null,exclude:sc,extract:_i,parse:gi,parseUrl:_s,pick:ms,stringify:ps,stringifyUrl:gs},Symbol.toStringTag,{value:"Module"}));class Gn extends Error{constructor(u,i){super(`HTTP Error ${u}${i?`: ${i}`:""}`),this.code=u,this.name="HttpError",Object.setPrototypeOf(this,Gn.prototype)}}var Nn=(s=>(s.GET="GET",s.PATCH="PATCH",s.POST="POST",s))(Nn||{});class ac{constructor(){this.headers={}}setHeaders(u){this.headers=u}async get(u){try{const i=u.query?`${u.url}?${this.serializeQuery(u.query)}`:u.url,c=await fetch(i,{headers:{...this.headers,...u.headers,"Content-Type":"application/json"}});return c.ok?an(await c.json()):K(new Gn(c.status,await c.text()))}catch(i){const c=i instanceof Error?i.message:"Unknown error";return K(new Gn(ie.INTERNAL_SERVER_ERROR,c))}}async post(u){try{const i=await fetch(u.url,{method:"POST",headers:{...this.headers,...u.headers,"Content-Type":"application/json"},body:JSON.stringify(u.payload)});return i.ok?an(await i.json()):K(new Gn(i.status,await i.text()))}catch(i){const c=i instanceof Error?i.message:"Unknown error";return K(new Gn(ie.INTERNAL_SERVER_ERROR,c))}}async patch(u){try{const i=await fetch(u.url,{method:"PATCH",headers:{...this.headers,...u.headers,"Content-Type":"application/json"},body:JSON.stringify(u.payload)});return i.ok?an(await i.json()):K(new Gn(i.status,await i.text()))}catch(i){const c=i instanceof Error?i.message:"Unknown error";return K(new Gn(ie.INTERNAL_SERVER_ERROR,c))}}serializeQuery(u){if(typeof u=="string")return u;if(typeof u=="object")for(const i in u)u[i]===void 0&&delete u[i];return u=oc.stringify(u,{arrayFormat:"none"}),u}}const mr={accessToken:{email:"/v1/auth/accessToken/email",sso:{jwt:"/v1/auth/accessToken/sso/jwt"}},refreshAccessToken:"/v1/auth/accessToken~refresh",password:{reset:"/v1/auth/password~reset"}};class ke extends EventTarget{constructor(){super(),this.accessToken=null,this.refreshToken=null}static getInstance(){return ke.instance||(ke.instance=new ke),ke.instance}async loginWithPassword(u,i){const c=await this.callApi({endpoint:mr.accessToken.email,method:"POST",body:{email:u,password:i},withSpotId:!0});if(c.isErr())return K(c.error);const{accessToken:p,refreshToken:v}=c.value;return this.setTokens(p.token,v.token),an({accessToken:p.token,refreshToken:v.token})}async loginWithSsoToken(u){const i=await this.callApi({endpoint:mr.accessToken.sso.jwt,method:"POST",body:{token:u},withSpotId:!0});if(i.isErr())return K(i.error);const{accessToken:c,refreshToken:p}=i.value;return this.setTokens(c.token,p.token),an({accessToken:c.token,refreshToken:p.token})}loginWithAuthTokens(u,i){return this.setTokens(u,i),{accessToken:u,refreshToken:i}}resetPassword(u){return this.callApi({endpoint:mr.password.reset,method:"POST",body:{email:u}})}async refresh(){const u=await this.callApi({endpoint:mr.refreshAccessToken,method:"POST",body:{refreshToken:this.refreshToken}});if(u.isErr())return K(u.error);const{accessToken:i,refreshToken:c}=u.value;return this.setTokens(i.token,c.token),an({accessToken:i.token,refreshToken:c.token})}async logout(){this.setTokens(null,null)}getAccessToken(){return this.accessToken}getRefreshToken(){return this.refreshToken}setTokens(u,i){if(this.accessToken!==u||this.refreshToken!==i){this.accessToken=u,this.refreshToken=i;const c=new CustomEvent("auth:tokens-updated",{detail:{accessToken:u,refreshToken:i}});this.dispatchEvent(c)}}async callApi(u){try{const{spotId:i,msApiBaseUrl:c}=ue.getConfiguration(),p=hi(u.endpoint,c),v={"Content-Type":"application/json",...u.headers};u.withSpotId&&i&&(v[vs.SpotId]=i);const _=await fetch(p,{method:u.method,body:u.body?JSON.stringify(u.body):void 0,headers:v});if(!_.ok)return K(new Gn(_.status,_.statusText));if(_.status===ie.NO_CONTENT)return an(void 0);const A=await _.json();return an(A)}catch(i){return K(new Gn(ie.INTERNAL_SERVER_ERROR,i instanceof Error?i.message:String(i)))}}}var vs=(s=>(s.Authorization="Authorization",s.SpotId="x-spotid",s))(vs||{});class ye{constructor(){this.queue=[],this.isProcessing=!1,this.isPaused=!1,this.authService=ke.getInstance(),this.httpService=new ac}static getInstance(){return ye.instance||(ye.instance=new ye),ye.instance}static buildAuthenticatedRequest(u){const{msApiBaseUrl:i,spotId:c}=ue.getConfiguration(),p=hi(u,i),v=ke.getInstance().getAccessToken();if(!v)return K(new Error("Not authenticated"));const _={"Content-Type":"application/json",Authorization:`Bearer ${v}`};return c&&(_["x-spotid"]=c),an({url:p,headers:_})}static async stream(u,i,c){const p=ye.buildAuthenticatedRequest(u);if(p.isErr())return K(p.error);const{url:v,headers:_}=p.value;try{const A=await fetch(v,{method:"POST",headers:_,...i!==void 0?{body:JSON.stringify(i)}:{},...c?{signal:c}:{}});if(!A.ok){const x=await A.text();return K(new Error(`HTTP ${A.status}: ${x}`))}return A.body?an(A.body):K(new Error("Response body is empty"))}catch(A){const x=A instanceof Error?A.message:"Unknown error";return K(A instanceof Error?A:new Error(x))}}get pendingCount(){return this.queue.length}enqueue(u){return new Promise(i=>{const c=async()=>{try{const p=await u();i(p)}catch(p){i(K(new Gn(ie.INTERNAL_SERVER_ERROR,p instanceof Error?p.message:"Unknown error")))}};this.queue.push(c),this.processQueue()})}async processQueue(){if(!this.isProcessing){this.isProcessing=!0;try{for(;!this.isPaused&&this.queue.length>0;){const u=this.queue.shift();if(!u)break;await u()}}finally{this.isProcessing=!1,!this.isPaused&&this.queue.length>0&&Promise.resolve().then(()=>this.processQueue())}}}pauseQueue(){this.isPaused=!0}resumeQueue(){const u=this.isPaused;this.isPaused=!1,u&&this.processQueue()}async call(u){return this.enqueue(async()=>{const i=async()=>{const{spotId:p,msApiBaseUrl:v}=ue.getConfiguration(),_={...u.options?.headers??{}};p&&(_["x-spotid"]=p);const A=this.authService.getAccessToken(),{requiresAuth:x=!0}=u;if(!A&&x)return K(new Gn(ie.UNAUTHORIZED));A&&(_.Authorization=`Bearer ${A}`);const q=hi(u.endpoint,v);switch(u.method){case Nn.GET:return this.httpService.get({...u.options??{},headers:_,url:q});case Nn.PATCH:return this.httpService.patch({...u.options??{},headers:_,url:q});case Nn.POST:return this.httpService.post({...u.options??{},headers:_,url:q});default:return K(new Gn(ie.METHOD_NOT_ALLOWED,"Method not allowed"))}};let c=await i();if(c.isErr()&&c.error.code===ie.UNAUTHORIZED){const p=await this.authService.refresh();if(p.isErr())return K(new Gn(ie.UNAUTHORIZED,p.error.message));c=await i()}return c})}}const Ae={playbooks:"/v1/playbooks",pages:s=>`/v1/playbooks/${s}/pages`,hotspots:(s,u)=>`/v1/playbooks/${s}/pages/${u}/hotspots`,hotspot:(s,u,i)=>`/v1/playbooks/${s}/pages/${u}/hotspots/${i}`,accessibleIntents:(s,u)=>`/v1/playbooks/${s}/pages/${u}/accessibleIntents`,intents:(s,u,i)=>`/v1/playbooks/${s}/pages/${u}/hotspots/${i}/intents`,intent:(s,u,i,c)=>`/v1/playbooks/${s}/pages/${u}/hotspots/${i}/intents/${c}`},vr=50;class lt{static getInstance(){return lt.instance||(lt.instance=new lt),lt.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async listPlaybooks(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.playbooks,options:{query:{page:u?.page??1,limit:u?.limit??vr,...u?.domain?{"domain[eq]":u.domain}:{}}}});return i.isErr()?K(i.error):an(i.value)}async listPlaybookPages(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.pages(u.playbookId),options:{query:{page:u.page??1,limit:u.limit??vr,...u.url?{"url[eq]":u.url}:{}}}});return i.isErr()?K(i.error):an(i.value)}async createPlaybookPage(u,i){const c=await this.meltingSpotApi.call({method:Nn.POST,endpoint:Ae.pages(u.playbookId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async listAccessiblePlaybookIntents(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.accessibleIntents(u.playbookId,u.pageId),options:{query:{...u.domain?{"domain[eq]":u.domain}:{}}}});return i.isErr()?K(i.error):an(i.value)}async listPlaybookHotspots(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.hotspots(u.playbookId,u.pageId),options:{query:{page:u.page??1,limit:u.limit??vr,...u.intentStatus?{"intentStatus[eq]":u.intentStatus}:{},...u.widgetType?{"widgetType[eq]":u.widgetType}:{}}}});return i.isErr()?K(i.error):an(i.value)}async createPlaybookHotspot(u,i){const c=await this.meltingSpotApi.call({method:Nn.POST,endpoint:Ae.hotspots(u.playbookId,u.pageId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async updatePlaybookHotspot(u,i){const c=await this.meltingSpotApi.call({method:Nn.PATCH,endpoint:Ae.hotspot(u.playbookId,u.pageId,u.hotspotId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async listPlaybookIntents(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.intents(u.playbookId,u.pageId,u.hotspotId),options:{query:{page:u.page??1,limit:u.limit??vr,...u.status?{"status[eq]":u.status}:{}}}});return i.isErr()?K(i.error):an(i.value)}async createPlaybookIntent(u,i){const c=await this.meltingSpotApi.call({method:Nn.POST,endpoint:Ae.intents(u.playbookId,u.pageId,u.hotspotId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async updatePlaybookIntent(u,i){const c=await this.meltingSpotApi.call({method:Nn.PATCH,endpoint:Ae.intent(u.playbookId,u.pageId,u.hotspotId,u.intentId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}}const fc={me:"/v1/spots/me"},cc=50;class ht{static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async listSpotsForMe(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:fc.me,options:{query:{page:1,limit:cc,...u?.spotMemberRole?{"spotMemberRole[eq]":u.spotMemberRole}:{}}}});return i.isErr()?K(i.error):an(i.value)}}const lc={spotMember:{me:"/v1/spotMembers/me"}};class dt{static getInstance(){return dt.instance||(dt.instance=new dt),dt.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async getSpotMemberForMe(){const u=await this.meltingSpotApi.call({method:Nn.GET,endpoint:lc.spotMember.me});return u.isErr()?K(u.error):an(u.value)}}const hc={spotMemberSsoToken:"/v1/spotMembers/auth/sso/jwt"};class pt{static getInstance(){return pt.instance||(pt.instance=new pt),pt.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async generateSsoToken(){const u=await this.meltingSpotApi.call({method:Nn.POST,endpoint:hc.spotMemberSsoToken,options:{payload:{}}});return u.isErr()?K(u.error):an(u.value.token)}}class _t{static getInstance(){return _t.instance||(_t.instance=new _t),_t.instance}constructor(){this.spotMemberAuthApiService=pt.getInstance()}async generateSsoToken(){return this.spotMemberAuthApiService.generateSsoToken()}}const dc=s=>{const u=s.get("utm_source");if(u)return{source:u,medium:s.get("utm_medium")??void 0,campaign:s.get("utm_campaign")??void 0,term:s.get("utm_term")??void 0,content:s.get("utm_content")??void 0}},pc=s=>s?Object.entries(s).reduce((u,[i,c])=>(c!=null&&(u[`utm_${i}`]=c),u),{}):{},_c=ue.getInstance(),gc=ke.getInstance(),mc=_t.getInstance(),vc={Playbook:lt.getInstance(),Spot:ht.getInstance(),SpotMember:dt.getInstance()},gt=globalThis;gt.MeltingSpot||(gt.MeltingSpot={}),gt.MeltingSpot.Configuration=_c,gt.MeltingSpot.Auth=gc,gt.MeltingSpot.Sso=mc,gt.MeltingSpot.Api=vc;const Ec="0.1.0",mi=new us({appName:"Embed SDK",appVersion:Ec});class Es{constructor(u){this.content=u}#n=null;#e=null;set onRemove(u){this.#e=u}inject(u){this.remove();const i=sf({input:u,rootDocument:this.content.rootDocument});this.#n=this.content.iframe,this.#n.classList.add("ms-embed"),i.appendChild(this.#n)}remove(){this.#n&&(this.#n.contentWindow&&this.#e?.(this.#n.contentWindow),this.#n.remove(),this.#n=null)}}class wc{constructor(u){this.baseURL=Zf(u.baseURL),this.spotId=zf(u.spotId),this.authToken=u.authToken??null,this.themeMode=u.themeMode??"auto",this.domain=u.domain??null,this.deeplink=u.deeplink?Qf({deeplink:u.deeplink,spotId:this.spotId}):null,this.utmParameters=u.utmParameters??null,this.rootDocument=u.rootDocument}get iframe(){const u=this.authToken&&this.authToken.trim().length>0?"/sso/jwt":"",i=new URL(`/spot/${this.spotId}${u}`,zu(this.baseURL)),c=af({url:i,searchParams:{embed:this.spotId,themeMode:this.themeMode,ms_token:this.authToken,domain:this.domain,deeplink:this.deeplink,...pc(this.utmParameters)},rootDocument:this.rootDocument});return c.classList.add("ms-spot"),c}}const Er={READY:"meltingspot:ready",ERROR:"meltingspot:error"},Mn=class Mn{static injectSpotInto(u,i){const{onReady:c,onError:p,...v}=i,{spotId:_,rootDocument:A,msCommunityWebBaseUrl:x}=ue.getConfiguration({spotId:v.spotId,rootDocument:v.rootDocument,msCommunityWebBaseUrl:v.baseURL});if(!_)throw mi.error("Spot ID is required"),new Error("Spot ID is not configured. Please set the spotId in the configuration.");const q=new URLSearchParams(window.location.search),nn={spotId:_,authToken:v.authToken??q.get("ms_token"),domain:v.domain,deeplink:v.deeplink??q.get("ms_url"),themeMode:v.themeMode,utmParameters:v.utmParameters??dc(q),baseURL:x,rootDocument:A},N=new Es(new wc(nn));if(N.inject(u),Mn.embeds.push(N),c||p){const $=N.content.iframe.contentWindow;$&&(Mn.iframeCallbacks.set($,{onReady:c,onError:p}),N.onRemove=G=>{Mn.iframeCallbacks.delete(G)}),Mn.ensureMessageListener()}return mi.log("Spot injected",nn,u),N}static clear(){Mn.embeds.forEach(u=>{u.remove()}),Mn.embeds=[],Mn.iframeCallbacks.clear(),Mn.messageListened&&(window.removeEventListener("message",Mn.handleMessageEvent),Mn.messageListened=!1),mi.log("All MeltingSpot embeds cleared")}static handleMessageEvent(u){if(!u.data||typeof u.data!="object"||u.data.type!==Er.READY&&u.data.type!==Er.ERROR)return;const i=u.source,c=Mn.iframeCallbacks.get(i);if(!c)return;const{msCommunityWebBaseUrl:p}=ue.getConfiguration({});if(p)try{const v=new URL(p).origin;if(u.origin!==v)return}catch{}u.data.type===Er.READY?c.onReady?.():c.onError?.(u.data.error)}static ensureMessageListener(){Mn.messageListened||(window.addEventListener("message",Mn.handleMessageEvent),Mn.messageListened=!0)}};Mn.embeds=[],Mn.messageListened=!1,Mn.iframeCallbacks=new Map;let wr=Mn;const vi=globalThis;vi.MeltingSpot||(vi.MeltingSpot={}),vi.MeltingSpot.Embed=wr,He.EMBED_POST_MESSAGE_TYPE=Er,He.Embed=wr,He.EmbedFrame=Es,Object.defineProperty(He,Symbol.toStringTag,{value:"Module"})}));
20
+ }`;var Z=Ka(function(){return un(f,D+"return "+y).apply(i,l)});if(Z.source=y,Lu(Z))throw Z;return Z}function lm(n){return on(n).toLowerCase()}function hm(n){return on(n).toUpperCase()}function dm(n,e,t){if(n=on(n),n&&(t||e===i))return to(n);if(!n||!(e=ne(e)))return n;var r=ve(n),o=ve(e),f=ro(r,o),l=io(r,o)+1;return Ze(r,f,l).join("")}function pm(n,e,t){if(n=on(n),n&&(t||e===i))return n.slice(0,so(n)+1);if(!n||!(e=ne(e)))return n;var r=ve(n),o=io(r,ve(e))+1;return Ze(r,0,o).join("")}function _m(n,e,t){if(n=on(n),n&&(t||e===i))return n.replace(Li,"");if(!n||!(e=ne(e)))return n;var r=ve(n),o=ro(r,ve(e));return Ze(r,o).join("")}function gm(n,e){var t=cn,r=rn;if(En(e)){var o="separator"in e?e.separator:o;t="length"in e?Q(e.length):t,r="omission"in e?ne(e.omission):r}n=on(n);var f=n.length;if(Tt(n)){var l=ve(n);f=l.length}if(t>=f)return n;var h=t-yt(r);if(h<1)return r;var g=l?Ze(l,0,h).join(""):n.slice(0,h);if(o===i)return g+r;if(l&&(h+=g.length-h),bu(o)){if(n.slice(h).search(o)){var w,T=g;for(o.global||(o=qi(o.source,on(Is.exec(o))+"g")),o.lastIndex=0;w=o.exec(T);)var y=w.index;g=g.slice(0,y===i?h:y)}}else if(n.indexOf(ne(o),h)!=h){var O=g.lastIndexOf(o);O>-1&&(g=g.slice(0,O))}return g+r}function mm(n){return n=on(n),n&&xc.test(n)?n.replace(Ts,ql):n}var vm=Lt(function(n,e,t){return n+(t?" ":"")+e.toUpperCase()}),Nu=Zo("toUpperCase");function Qa(n,e,t){return n=on(n),e=t?i:e,e===i?kl(n)?Zl(n):Dl(n):n.match(e)||[]}var Ka=J(function(n,e){try{return Vn(n,i,e)}catch(t){return Lu(t)?t:new k(t)}}),Em=Ue(function(n,e){return oe(e,function(t){t=Me(t),Ne(n,t,Mu(n[t],n))}),n});function wm(n){var e=n==null?0:n.length,t=U();return n=e?_n(n,function(r){if(typeof r[1]!="function")throw new ae(_);return[t(r[0]),r[1]]}):[],J(function(r){for(var o=-1;++o<e;){var f=n[o];if(Vn(f[0],this,r))return Vn(f[1],this,r)}})}function Tm(n){return qh(ce(n,N))}function $u(n){return function(){return n}}function ym(n,e){return n==null||n!==n?e:n}var Am=Xo(),Im=Xo(!0);function Kn(n){return n}function Uu(n){return Mo(typeof n=="function"?n:ce(n,N))}function Om(n){return Lo(ce(n,N))}function Rm(n,e){return bo(n,ce(e,N))}var Mm=J(function(n,e){return function(t){return Zt(t,n,e)}}),xm=J(function(n,e){return function(t){return Zt(n,t,e)}});function Pu(n,e,t){var r=Dn(e),o=zr(e,r);t==null&&!(En(e)&&(o.length||!r.length))&&(t=e,e=n,n=this,o=zr(e,Dn(e)));var f=!(En(t)&&"chain"in t)||!!t.chain,l=Fe(n);return oe(o,function(h){var g=e[h];n[h]=g,l&&(n.prototype[h]=function(){var w=this.__chain__;if(f||w){var T=n(this.__wrapped__),y=T.__actions__=zn(this.__actions__);return y.push({func:g,args:arguments,thisArg:n}),T.__chain__=w,T}return g.apply(n,Be([this.value()],arguments))})}),n}function Lm(){return Pn._===this&&(Pn._=eh),this}function Fu(){}function bm(n){return n=Q(n),J(function(e){return So(e,n)})}var Sm=pu(_n),Dm=pu(Xs),Nm=pu(Ci);function Za(n){return Tu(n)?Hi(Me(n)):fd(n)}function $m(n){return function(e){return n==null?i:ot(n,e)}}var Um=jo(),Pm=jo(!0);function Yu(){return[]}function Cu(){return!1}function Fm(){return{}}function Ym(){return""}function Cm(){return!0}function Hm(n,e){if(n=Q(n),n<1||n>I)return[];var t=X,r=Cn(n,X);e=U(e),n-=X;for(var o=Bi(r,e);++t<n;)e(t);return o}function km(n){return B(n)?_n(n,Me):ee(n)?[n]:zn(_a(on(n)))}function Wm(n){var e=++jl;return on(n)+e}var Bm=Xr(function(n,e){return n+e},0),Gm=_u("ceil"),zm=Xr(function(n,e){return n/e},1),qm=_u("floor");function Qm(n){return n&&n.length?Gr(n,Kn,nu):i}function Km(n,e){return n&&n.length?Gr(n,U(e,2),nu):i}function Zm(n){return no(n,Kn)}function Jm(n,e){return no(n,U(e,2))}function Xm(n){return n&&n.length?Gr(n,Kn,iu):i}function Vm(n,e){return n&&n.length?Gr(n,U(e,2),iu):i}var jm=Xr(function(n,e){return n*e},1),n0=_u("round"),e0=Xr(function(n,e){return n-e},0);function t0(n){return n&&n.length?Wi(n,Kn):0}function r0(n,e){return n&&n.length?Wi(n,U(e,2)):0}return a.after=O_,a.ary=Ra,a.assign=hg,a.assignIn=Ha,a.assignInWith=ci,a.assignWith=dg,a.at=pg,a.before=Ma,a.bind=Mu,a.bindAll=Em,a.bindKey=xa,a.castArray=F_,a.chain=Aa,a.chunk=qd,a.compact=Qd,a.concat=Kd,a.cond=wm,a.conforms=Tm,a.constant=$u,a.countBy=t_,a.create=_g,a.curry=La,a.curryRight=ba,a.debounce=Sa,a.defaults=gg,a.defaultsDeep=mg,a.defer=R_,a.delay=M_,a.difference=Zd,a.differenceBy=Jd,a.differenceWith=Xd,a.drop=Vd,a.dropRight=jd,a.dropRightWhile=np,a.dropWhile=ep,a.fill=tp,a.filter=i_,a.flatMap=o_,a.flatMapDeep=a_,a.flatMapDepth=f_,a.flatten=Ea,a.flattenDeep=rp,a.flattenDepth=ip,a.flip=x_,a.flow=Am,a.flowRight=Im,a.fromPairs=up,a.functions=Ig,a.functionsIn=Og,a.groupBy=c_,a.initial=op,a.intersection=ap,a.intersectionBy=fp,a.intersectionWith=cp,a.invert=Mg,a.invertBy=xg,a.invokeMap=h_,a.iteratee=Uu,a.keyBy=d_,a.keys=Dn,a.keysIn=Qn,a.map=ii,a.mapKeys=bg,a.mapValues=Sg,a.matches=Om,a.matchesProperty=Rm,a.memoize=si,a.merge=Dg,a.mergeWith=ka,a.method=Mm,a.methodOf=xm,a.mixin=Pu,a.negate=oi,a.nthArg=bm,a.omit=Ng,a.omitBy=$g,a.once=L_,a.orderBy=p_,a.over=Sm,a.overArgs=b_,a.overEvery=Dm,a.overSome=Nm,a.partial=xu,a.partialRight=Da,a.partition=__,a.pick=Ug,a.pickBy=Wa,a.property=Za,a.propertyOf=$m,a.pull=pp,a.pullAll=Ta,a.pullAllBy=_p,a.pullAllWith=gp,a.pullAt=mp,a.range=Um,a.rangeRight=Pm,a.rearg=S_,a.reject=v_,a.remove=vp,a.rest=D_,a.reverse=Ou,a.sampleSize=w_,a.set=Fg,a.setWith=Yg,a.shuffle=T_,a.slice=Ep,a.sortBy=I_,a.sortedUniq=Rp,a.sortedUniqBy=Mp,a.split=om,a.spread=N_,a.tail=xp,a.take=Lp,a.takeRight=bp,a.takeRightWhile=Sp,a.takeWhile=Dp,a.tap=Qp,a.throttle=$_,a.thru=ri,a.toArray=Fa,a.toPairs=Ba,a.toPairsIn=Ga,a.toPath=km,a.toPlainObject=Ca,a.transform=Cg,a.unary=U_,a.union=Np,a.unionBy=$p,a.unionWith=Up,a.uniq=Pp,a.uniqBy=Fp,a.uniqWith=Yp,a.unset=Hg,a.unzip=Ru,a.unzipWith=ya,a.update=kg,a.updateWith=Wg,a.values=Dt,a.valuesIn=Bg,a.without=Cp,a.words=Qa,a.wrap=P_,a.xor=Hp,a.xorBy=kp,a.xorWith=Wp,a.zip=Bp,a.zipObject=Gp,a.zipObjectDeep=zp,a.zipWith=qp,a.entries=Ba,a.entriesIn=Ga,a.extend=Ha,a.extendWith=ci,Pu(a,a),a.add=Bm,a.attempt=Ka,a.camelCase=Qg,a.capitalize=za,a.ceil=Gm,a.clamp=Gg,a.clone=Y_,a.cloneDeep=H_,a.cloneDeepWith=k_,a.cloneWith=C_,a.conformsTo=W_,a.deburr=qa,a.defaultTo=ym,a.divide=zm,a.endsWith=Kg,a.eq=we,a.escape=Zg,a.escapeRegExp=Jg,a.every=r_,a.find=u_,a.findIndex=ma,a.findKey=vg,a.findLast=s_,a.findLastIndex=va,a.findLastKey=Eg,a.floor=qm,a.forEach=Ia,a.forEachRight=Oa,a.forIn=wg,a.forInRight=Tg,a.forOwn=yg,a.forOwnRight=Ag,a.get=Su,a.gt=B_,a.gte=G_,a.has=Rg,a.hasIn=Du,a.head=wa,a.identity=Kn,a.includes=l_,a.indexOf=sp,a.inRange=zg,a.invoke=Lg,a.isArguments=ct,a.isArray=B,a.isArrayBuffer=z_,a.isArrayLike=qn,a.isArrayLikeObject=yn,a.isBoolean=q_,a.isBuffer=Je,a.isDate=Q_,a.isElement=K_,a.isEmpty=Z_,a.isEqual=J_,a.isEqualWith=X_,a.isError=Lu,a.isFinite=V_,a.isFunction=Fe,a.isInteger=Na,a.isLength=ai,a.isMap=$a,a.isMatch=j_,a.isMatchWith=ng,a.isNaN=eg,a.isNative=tg,a.isNil=ig,a.isNull=rg,a.isNumber=Ua,a.isObject=En,a.isObjectLike=wn,a.isPlainObject=er,a.isRegExp=bu,a.isSafeInteger=ug,a.isSet=Pa,a.isString=fi,a.isSymbol=ee,a.isTypedArray=St,a.isUndefined=sg,a.isWeakMap=og,a.isWeakSet=ag,a.join=lp,a.kebabCase=Xg,a.last=he,a.lastIndexOf=hp,a.lowerCase=Vg,a.lowerFirst=jg,a.lt=fg,a.lte=cg,a.max=Qm,a.maxBy=Km,a.mean=Zm,a.meanBy=Jm,a.min=Xm,a.minBy=Vm,a.stubArray=Yu,a.stubFalse=Cu,a.stubObject=Fm,a.stubString=Ym,a.stubTrue=Cm,a.multiply=jm,a.nth=dp,a.noConflict=Lm,a.noop=Fu,a.now=ui,a.pad=nm,a.padEnd=em,a.padStart=tm,a.parseInt=rm,a.random=qg,a.reduce=g_,a.reduceRight=m_,a.repeat=im,a.replace=um,a.result=Pg,a.round=n0,a.runInContext=d,a.sample=E_,a.size=y_,a.snakeCase=sm,a.some=A_,a.sortedIndex=wp,a.sortedIndexBy=Tp,a.sortedIndexOf=yp,a.sortedLastIndex=Ap,a.sortedLastIndexBy=Ip,a.sortedLastIndexOf=Op,a.startCase=am,a.startsWith=fm,a.subtract=e0,a.sum=t0,a.sumBy=r0,a.template=cm,a.times=Hm,a.toFinite=Ye,a.toInteger=Q,a.toLength=Ya,a.toLower=lm,a.toNumber=de,a.toSafeInteger=lg,a.toString=on,a.toUpper=hm,a.trim=dm,a.trimEnd=pm,a.trimStart=_m,a.truncate=gm,a.unescape=mm,a.uniqueId=Wm,a.upperCase=vm,a.upperFirst=Nu,a.each=Ia,a.eachRight=Oa,a.first=wa,Pu(a,(function(){var n={};return Oe(a,function(e,t){fn.call(a.prototype,t)||(n[t]=e)}),n})(),{chain:!1}),a.VERSION=c,oe(["bind","bindKey","curry","curryRight","partial","partialRight"],function(n){a[n].placeholder=a}),oe(["drop","take"],function(n,e){j.prototype[n]=function(t){t=t===i?1:bn(Q(t),0);var r=this.__filtered__&&!e?new j(this):this.clone();return r.__filtered__?r.__takeCount__=Cn(t,r.__takeCount__):r.__views__.push({size:Cn(t,X),type:n+(r.__dir__<0?"Right":"")}),r},j.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}}),oe(["filter","map","takeWhile"],function(n,e){var t=e+1,r=t==Y||t==R;j.prototype[n]=function(o){var f=this.clone();return f.__iteratees__.push({iteratee:U(o,3),type:t}),f.__filtered__=f.__filtered__||r,f}}),oe(["head","last"],function(n,e){var t="take"+(e?"Right":"");j.prototype[n]=function(){return this[t](1).value()[0]}}),oe(["initial","tail"],function(n,e){var t="drop"+(e?"":"Right");j.prototype[n]=function(){return this.__filtered__?new j(this):this[t](1)}}),j.prototype.compact=function(){return this.filter(Kn)},j.prototype.find=function(n){return this.filter(n).head()},j.prototype.findLast=function(n){return this.reverse().find(n)},j.prototype.invokeMap=J(function(n,e){return typeof n=="function"?new j(this):this.map(function(t){return Zt(t,n,e)})}),j.prototype.reject=function(n){return this.filter(oi(U(n)))},j.prototype.slice=function(n,e){n=Q(n);var t=this;return t.__filtered__&&(n>0||e<0)?new j(t):(n<0?t=t.takeRight(-n):n&&(t=t.drop(n)),e!==i&&(e=Q(e),t=e<0?t.dropRight(-e):t.take(e-n)),t)},j.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},j.prototype.toArray=function(){return this.take(X)},Oe(j.prototype,function(n,e){var t=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),o=a[r?"take"+(e=="last"?"Right":""):e],f=r||/^find/.test(e);o&&(a.prototype[e]=function(){var l=this.__wrapped__,h=r?[1]:arguments,g=l instanceof j,w=h[0],T=g||B(l),y=function(V){var tn=o.apply(a,Be([V],h));return r&&O?tn[0]:tn};T&&t&&typeof w=="function"&&w.length!=1&&(g=T=!1);var O=this.__chain__,D=!!this.__actions__.length,P=f&&!O,Z=g&&!D;if(!f&&T){l=Z?l:new j(this);var F=n.apply(l,h);return F.__actions__.push({func:ri,args:[y],thisArg:i}),new fe(F,O)}return P&&Z?n.apply(this,h):(F=this.thru(y),P?r?F.value()[0]:F.value():F)})}),oe(["pop","push","shift","sort","splice","unshift"],function(n){var e=Lr[n],t=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",r=/^(?:pop|shift)$/.test(n);a.prototype[n]=function(){var o=arguments;if(r&&!this.__chain__){var f=this.value();return e.apply(B(f)?f:[],o)}return this[t](function(l){return e.apply(B(l)?l:[],o)})}}),Oe(j.prototype,function(n,e){var t=a[e];if(t){var r=t.name+"";fn.call(Rt,r)||(Rt[r]=[]),Rt[r].push({name:e,func:t})}}),Rt[Jr(i,hn).name]=[{name:"wrapper",func:i}],j.prototype.clone=mh,j.prototype.reverse=vh,j.prototype.value=Eh,a.prototype.at=Kp,a.prototype.chain=Zp,a.prototype.commit=Jp,a.prototype.next=Xp,a.prototype.plant=jp,a.prototype.reverse=n_,a.prototype.toJSON=a.prototype.valueOf=a.prototype.value=e_,a.prototype.first=a.prototype.head,Wt&&(a.prototype[Wt]=Vp),a}),At=Jl();tt?((tt.exports=At)._=At,Ui._=At):Pn._=At}).call(kf)})(Ut,Ut.exports)),Ut.exports}Wf();const Bf="1.0.0";class us{constructor(u){this.debug=!1,this.debug=u?.debug??!1,this.appName=u?.appName,this.appVersion=u?.appVersion}log(u,...i){this.debug&&this.print(u,"info",i)}warn(u,...i){this.print(u,"warn",i)}error(u,...i){this.print(u,"error",i)}print(u,i,c){const _=[`[${["MeltingSpot",this.appName,this.appVersion].filter(Boolean).join(" - ")}] ${u}`];c.length&&_.push(...c),console[i](..._)}}const Gf=new us({appName:"Core SDK",appVersion:Bf}),zf=s=>s.toLowerCase().replace(/[^a-z0-9-]/g,""),qf=["/user"],Qf=({deeplink:s,spotId:u})=>{try{const i=new URL(s,"https://unused.com");let c=i.pathname;return i.search&&(c+=i.search),i.hash&&(c+=i.hash),qf.some(p=>c.startsWith(p))||(c=`/spot/${u}/${rf(c)}`),c}catch(i){return Gf.warn("Failed to parse deeplink URL",i),null}},Kf=[/(^|\.)meltingspot\.io$/i],Zf=s=>{let u;try{const v=zu(s);u=new URL(v)}catch{throw new Error(`Invalid baseURL: ${s}`)}const i=u.hostname==="localhost"||u.hostname==="127.0.0.1",c=u.protocol==="https:",p=Kf.some(v=>v.test(u.hostname));if(!i&&(!c||!p))throw new Error(`Untrusted baseURL origin: ${u.origin}`);return u.origin},Jf={msApiBaseUrl:"https://openapi.meltingspot.io/",msCommunityWebBaseUrl:"https://go.meltingspot.io/",ssoToken:void 0,spotId:"",rootDocument:globalThis.document};class ue{constructor(){this.configuration=Jf}static getInstance(){return ue.instance||(ue.instance=new ue),ue.instance}setConfiguration(u){this.configuration={...this.configuration,...u}}static getConfiguration(u={}){return{...ue.getInstance().configuration,...u}}}const ss="%[a-f0-9]{2}",os=new RegExp("("+ss+")|([^%]+?)","gi"),as=new RegExp("("+ss+")+","gi");function di(s,u){try{return[decodeURIComponent(s.join(""))]}catch{}if(s.length===1)return s;u=u||1;const i=s.slice(0,u),c=s.slice(u);return Array.prototype.concat.call([],di(i),di(c))}function Xf(s){try{return decodeURIComponent(s)}catch{let u=s.match(os)||[];for(let i=1;i<u.length;i++)s=di(u,i).join(""),u=s.match(os)||[];return s}}function Vf(s){const u={"%FE%FF":"��","%FF%FE":"��"};let i=as.exec(s);for(;i;){try{u[i[0]]=decodeURIComponent(i[0])}catch{const p=Xf(i[0]);p!==i[0]&&(u[i[0]]=p)}i=as.exec(s)}u["%C2"]="�";const c=Object.keys(u);for(const p of c)s=s.replace(new RegExp(p,"g"),u[p]);return s}function jf(s){if(typeof s!="string")throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof s+"`");try{return decodeURIComponent(s)}catch{return Vf(s)}}function nc(s,u){const i={};if(Array.isArray(u))for(const c of u){const p=Object.getOwnPropertyDescriptor(s,c);p?.enumerable&&Object.defineProperty(i,c,p)}else for(const c of Reflect.ownKeys(s)){const p=Object.getOwnPropertyDescriptor(s,c);if(p.enumerable){const v=s[c];u(c,v,s)&&Object.defineProperty(i,c,p)}}return i}function fs(s,u){if(!(typeof s=="string"&&typeof u=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(s===""||u==="")return[];const i=s.indexOf(u);return i===-1?[]:[s.slice(0,i),s.slice(i+u.length)]}const ec=s=>s==null,tc=s=>encodeURIComponent(s).replaceAll(/[!'()*]/g,u=>`%${u.charCodeAt(0).toString(16).toUpperCase()}`),pi=Symbol("encodeFragmentIdentifier");function rc(s){switch(s.arrayFormat){case"index":return u=>(i,c)=>{const p=i.length;return c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,[In(u,s),"[",p,"]"].join("")]:[...i,[In(u,s),"[",In(p,s),"]=",In(c,s)].join("")]};case"bracket":return u=>(i,c)=>c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,[In(u,s),"[]"].join("")]:[...i,[In(u,s),"[]=",In(c,s)].join("")];case"colon-list-separator":return u=>(i,c)=>c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,[In(u,s),":list="].join("")]:[...i,[In(u,s),":list=",In(c,s)].join("")];case"comma":case"separator":case"bracket-separator":{const u=s.arrayFormat==="bracket-separator"?"[]=":"=";return i=>(c,p)=>p===void 0||s.skipNull&&p===null||s.skipEmptyString&&p===""?c:(p=p===null?"":p,c.length===0?[[In(i,s),u,In(p,s)].join("")]:[[c,In(p,s)].join(s.arrayFormatSeparator)])}default:return u=>(i,c)=>c===void 0||s.skipNull&&c===null||s.skipEmptyString&&c===""?i:c===null?[...i,In(u,s)]:[...i,[In(u,s),"=",In(c,s)].join("")]}}function ic(s){let u;switch(s.arrayFormat){case"index":return(i,c,p)=>{if(u=/\[(\d*)]$/.exec(i),i=i.replace(/\[\d*]$/,""),!u){p[i]=c;return}p[i]===void 0&&(p[i]={}),p[i][u[1]]=c};case"bracket":return(i,c,p)=>{if(u=/(\[])$/.exec(i),i=i.replace(/\[]$/,""),!u){p[i]=c;return}if(p[i]===void 0){p[i]=[c];return}p[i]=[...p[i],c]};case"colon-list-separator":return(i,c,p)=>{if(u=/(:list)$/.exec(i),i=i.replace(/:list$/,""),!u){p[i]=c;return}if(p[i]===void 0){p[i]=[c];return}p[i]=[...p[i],c]};case"comma":case"separator":return(i,c,p)=>{const v=typeof c=="string"&&c.includes(s.arrayFormatSeparator),_=typeof c=="string"&&!v&&xe(c,s).includes(s.arrayFormatSeparator);c=_?xe(c,s):c;const A=v||_?c.split(s.arrayFormatSeparator).map(x=>xe(x,s)):c===null?c:xe(c,s);p[i]=A};case"bracket-separator":return(i,c,p)=>{const v=/(\[])$/.test(i);if(i=i.replace(/\[]$/,""),!v){p[i]=c&&xe(c,s);return}const _=c===null?[]:xe(c,s).split(s.arrayFormatSeparator);if(p[i]===void 0){p[i]=_;return}p[i]=[...p[i],..._]};default:return(i,c,p)=>{if(p[i]===void 0){p[i]=c;return}p[i]=[...[p[i]].flat(),c]}}}function cs(s){if(typeof s!="string"||s.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function In(s,u){return u.encode?u.strict?tc(s):encodeURIComponent(s):s}function xe(s,u){return u.decode?jf(s):s}function ls(s){return Array.isArray(s)?s.sort():typeof s=="object"?ls(Object.keys(s)).sort((u,i)=>Number(u)-Number(i)).map(u=>s[u]):s}function hs(s){const u=s.indexOf("#");return u!==-1&&(s=s.slice(0,u)),s}function uc(s){let u="";const i=s.indexOf("#");return i!==-1&&(u=s.slice(i)),u}function ds(s,u,i){return i==="string"&&typeof s=="string"?s:typeof i=="function"&&typeof s=="string"?i(s):i==="boolean"&&s===null?!0:i==="boolean"&&s!==null&&(s.toLowerCase()==="true"||s.toLowerCase()==="false")?s.toLowerCase()==="true":i==="boolean"&&s!==null&&(s.toLowerCase()==="1"||s.toLowerCase()==="0")?s.toLowerCase()==="1":i==="string[]"&&u.arrayFormat!=="none"&&typeof s=="string"?[s]:i==="number[]"&&u.arrayFormat!=="none"&&!Number.isNaN(Number(s))&&typeof s=="string"&&s.trim()!==""?[Number(s)]:i==="number"&&!Number.isNaN(Number(s))&&typeof s=="string"&&s.trim()!==""?Number(s):u.parseBooleans&&s!==null&&(s.toLowerCase()==="true"||s.toLowerCase()==="false")?s.toLowerCase()==="true":u.parseNumbers&&!Number.isNaN(Number(s))&&typeof s=="string"&&s.trim()!==""?Number(s):s}function _i(s){s=hs(s);const u=s.indexOf("?");return u===-1?"":s.slice(u+1)}function gi(s,u){u={decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1,types:Object.create(null),...u},cs(u.arrayFormatSeparator);const i=ic(u),c=Object.create(null);if(typeof s!="string"||(s=s.trim().replace(/^[?#&]/,""),!s))return c;for(const p of s.split("&")){if(p==="")continue;const v=u.decode?p.replaceAll("+"," "):p;let[_,A]=fs(v,"=");_===void 0&&(_=v),A=A===void 0?null:["comma","separator","bracket-separator"].includes(u.arrayFormat)?A:xe(A,u),i(xe(_,u),A,c)}for(const[p,v]of Object.entries(c))if(typeof v=="object"&&v!==null&&u.types[p]!=="string")for(const[_,A]of Object.entries(v)){const x=u.types[p]?u.types[p].replace("[]",""):void 0;v[_]=ds(A,u,x)}else typeof v=="object"&&v!==null&&u.types[p]==="string"?c[p]=Object.values(v).join(u.arrayFormatSeparator):c[p]=ds(v,u,u.types[p]);return u.sort===!1?c:(u.sort===!0?Object.keys(c).sort():Object.keys(c).sort(u.sort)).reduce((p,v)=>{const _=c[v];return p[v]=_&&typeof _=="object"&&!Array.isArray(_)?ls(_):_,p},Object.create(null))}function ps(s,u){if(!s)return"";u={encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:",",...u},cs(u.arrayFormatSeparator);const i=_=>u.skipNull&&ec(s[_])||u.skipEmptyString&&s[_]==="",c=rc(u),p={};for(const[_,A]of Object.entries(s))i(_)||(p[_]=A);const v=Object.keys(p);return u.sort!==!1&&v.sort(u.sort),v.map(_=>{const A=s[_];return A===void 0?"":A===null?In(_,u):Array.isArray(A)?A.length===0&&u.arrayFormat==="bracket-separator"?In(_,u)+"[]":A.reduce(c(_),[]).join("&"):In(_,u)+"="+In(A,u)}).filter(_=>_.length>0).join("&")}function _s(s,u){u={decode:!0,...u};let[i,c]=fs(s,"#");return i===void 0&&(i=s),{url:i?.split("?")?.[0]??"",query:gi(_i(s),u),...u&&u.parseFragmentIdentifier&&c?{fragmentIdentifier:xe(c,u)}:{}}}function gs(s,u){u={encode:!0,strict:!0,[pi]:!0,...u};const i=hs(s.url).split("?")[0]||"",c=_i(s.url),p={...gi(c,{sort:!1,...u}),...s.query};let v=ps(p,u);v&&=`?${v}`;let _=uc(s.url);if(typeof s.fragmentIdentifier=="string"){const A=new URL(i);A.hash=s.fragmentIdentifier,_=u[pi]?A.hash:`#${s.fragmentIdentifier}`}return`${i}${v}${_}`}function ms(s,u,i){i={parseFragmentIdentifier:!0,[pi]:!1,...i};const{url:c,query:p,fragmentIdentifier:v}=_s(s,i);return gs({url:c,query:nc(p,u),fragmentIdentifier:v},i)}function sc(s,u,i){const c=Array.isArray(u)?p=>!u.includes(p):(p,v)=>!u(p,v);return ms(s,c,i)}const oc=Object.freeze(Object.defineProperty({__proto__:null,exclude:sc,extract:_i,parse:gi,parseUrl:_s,pick:ms,stringify:ps,stringifyUrl:gs},Symbol.toStringTag,{value:"Module"}));class Gn extends Error{constructor(u,i){super(`HTTP Error ${u}${i?`: ${i}`:""}`),this.code=u,this.name="HttpError",Object.setPrototypeOf(this,Gn.prototype)}}var Nn=(s=>(s.GET="GET",s.PATCH="PATCH",s.POST="POST",s))(Nn||{});class ac{constructor(){this.headers={}}setHeaders(u){this.headers=u}async get(u){try{const i=u.query?`${u.url}?${this.serializeQuery(u.query)}`:u.url,c=await fetch(i,{headers:{...this.headers,...u.headers,"Content-Type":"application/json"}});return c.ok?an(await c.json()):K(new Gn(c.status,await c.text()))}catch(i){const c=i instanceof Error?i.message:"Unknown error";return K(new Gn(ie.INTERNAL_SERVER_ERROR,c))}}async post(u){try{const i=await fetch(u.url,{method:"POST",headers:{...this.headers,...u.headers,"Content-Type":"application/json"},body:JSON.stringify(u.payload)});return i.ok?an(await i.json()):K(new Gn(i.status,await i.text()))}catch(i){const c=i instanceof Error?i.message:"Unknown error";return K(new Gn(ie.INTERNAL_SERVER_ERROR,c))}}async patch(u){try{const i=await fetch(u.url,{method:"PATCH",headers:{...this.headers,...u.headers,"Content-Type":"application/json"},body:JSON.stringify(u.payload)});return i.ok?an(await i.json()):K(new Gn(i.status,await i.text()))}catch(i){const c=i instanceof Error?i.message:"Unknown error";return K(new Gn(ie.INTERNAL_SERVER_ERROR,c))}}serializeQuery(u){if(typeof u=="string")return u;if(typeof u=="object")for(const i in u)u[i]===void 0&&delete u[i];return u=oc.stringify(u,{arrayFormat:"none"}),u}}const mr={accessToken:{email:"/v1/auth/accessToken/email",sso:{jwt:"/v1/auth/accessToken/sso/jwt"}},refreshAccessToken:"/v1/auth/accessToken~refresh",password:{reset:"/v1/auth/password~reset"}};class ke extends EventTarget{constructor(){super(),this.accessToken=null,this.refreshToken=null}static getInstance(){return ke.instance||(ke.instance=new ke),ke.instance}async loginWithPassword(u,i){const c=await this.callApi({endpoint:mr.accessToken.email,method:"POST",body:{email:u,password:i},withSpotId:!0});if(c.isErr())return K(c.error);const{accessToken:p,refreshToken:v}=c.value;return this.setTokens(p.token,v.token),an({accessToken:p.token,refreshToken:v.token})}async loginWithSsoToken(u){const i=await this.callApi({endpoint:mr.accessToken.sso.jwt,method:"POST",body:{token:u},withSpotId:!0});if(i.isErr())return K(i.error);const{accessToken:c,refreshToken:p}=i.value;return this.setTokens(c.token,p.token),an({accessToken:c.token,refreshToken:p.token})}loginWithAuthTokens(u,i){return this.setTokens(u,i),{accessToken:u,refreshToken:i}}resetPassword(u){return this.callApi({endpoint:mr.password.reset,method:"POST",body:{email:u}})}async refresh(){const u=await this.callApi({endpoint:mr.refreshAccessToken,method:"POST",body:{refreshToken:this.refreshToken}});if(u.isErr())return K(u.error);const{accessToken:i,refreshToken:c}=u.value;return this.setTokens(i.token,c.token),an({accessToken:i.token,refreshToken:c.token})}async logout(){this.setTokens(null,null)}getAccessToken(){return this.accessToken}getRefreshToken(){return this.refreshToken}setTokens(u,i){if(this.accessToken!==u||this.refreshToken!==i){this.accessToken=u,this.refreshToken=i;const c=new CustomEvent("auth:tokens-updated",{detail:{accessToken:u,refreshToken:i}});this.dispatchEvent(c)}}async callApi(u){try{const{spotId:i,msApiBaseUrl:c}=ue.getConfiguration(),p=hi(u.endpoint,c),v={"Content-Type":"application/json",...u.headers};u.withSpotId&&i&&(v[vs.SpotId]=i);const _=await fetch(p,{method:u.method,body:u.body?JSON.stringify(u.body):void 0,headers:v});if(!_.ok)return K(new Gn(_.status,_.statusText));if(_.status===ie.NO_CONTENT)return an(void 0);const A=await _.json();return an(A)}catch(i){return K(new Gn(ie.INTERNAL_SERVER_ERROR,i instanceof Error?i.message:String(i)))}}}var vs=(s=>(s.Authorization="Authorization",s.SpotId="x-spotid",s))(vs||{});class ye{constructor(){this.queue=[],this.isProcessing=!1,this.isPaused=!1,this.authService=ke.getInstance(),this.httpService=new ac}static getInstance(){return ye.instance||(ye.instance=new ye),ye.instance}static buildAuthenticatedRequest(u){const{msApiBaseUrl:i,spotId:c}=ue.getConfiguration(),p=hi(u,i),v=ke.getInstance().getAccessToken();if(!v)return K(new Error("Not authenticated"));const _={"Content-Type":"application/json",Authorization:`Bearer ${v}`};return c&&(_["x-spotid"]=c),an({url:p,headers:_})}static async stream(u,i,c){const p=ye.buildAuthenticatedRequest(u);if(p.isErr())return K(p.error);const{url:v,headers:_}=p.value;try{const A=await fetch(v,{method:"POST",headers:_,...i!==void 0?{body:JSON.stringify(i)}:{},...c?{signal:c}:{}});if(!A.ok){const x=await A.text();return K(new Error(`HTTP ${A.status}: ${x}`))}return A.body?an(A.body):K(new Error("Response body is empty"))}catch(A){const x=A instanceof Error?A.message:"Unknown error";return K(A instanceof Error?A:new Error(x))}}get pendingCount(){return this.queue.length}enqueue(u){return new Promise(i=>{const c=async()=>{try{const p=await u();i(p)}catch(p){i(K(new Gn(ie.INTERNAL_SERVER_ERROR,p instanceof Error?p.message:"Unknown error")))}};this.queue.push(c),this.processQueue()})}async processQueue(){if(!this.isProcessing){this.isProcessing=!0;try{for(;!this.isPaused&&this.queue.length>0;){const u=this.queue.shift();if(!u)break;await u()}}finally{this.isProcessing=!1,!this.isPaused&&this.queue.length>0&&Promise.resolve().then(()=>this.processQueue())}}}pauseQueue(){this.isPaused=!0}resumeQueue(){const u=this.isPaused;this.isPaused=!1,u&&this.processQueue()}async call(u){return this.enqueue(async()=>{const i=async()=>{const{spotId:p,msApiBaseUrl:v}=ue.getConfiguration(),_={...u.options?.headers??{}};p&&(_["x-spotid"]=p);const A=this.authService.getAccessToken(),{requiresAuth:x=!0}=u;if(!A&&x)return K(new Gn(ie.UNAUTHORIZED));A&&(_.Authorization=`Bearer ${A}`);const q=hi(u.endpoint,v);switch(u.method){case Nn.GET:return this.httpService.get({...u.options??{},headers:_,url:q});case Nn.PATCH:return this.httpService.patch({...u.options??{},headers:_,url:q});case Nn.POST:return this.httpService.post({...u.options??{},headers:_,url:q});default:return K(new Gn(ie.METHOD_NOT_ALLOWED,"Method not allowed"))}};let c=await i();if(c.isErr()&&c.error.code===ie.UNAUTHORIZED){const p=await this.authService.refresh();if(p.isErr())return K(new Gn(ie.UNAUTHORIZED,p.error.message));c=await i()}return c})}}const Ae={playbooks:"/v1/playbooks",pages:s=>`/v1/playbooks/${s}/pages`,hotspots:(s,u)=>`/v1/playbooks/${s}/pages/${u}/hotspots`,hotspot:(s,u,i)=>`/v1/playbooks/${s}/pages/${u}/hotspots/${i}`,accessibleIntents:(s,u)=>`/v1/playbooks/${s}/pages/${u}/accessibleIntents`,intents:(s,u,i)=>`/v1/playbooks/${s}/pages/${u}/hotspots/${i}/intents`,intent:(s,u,i,c)=>`/v1/playbooks/${s}/pages/${u}/hotspots/${i}/intents/${c}`},vr=50;class lt{static getInstance(){return lt.instance||(lt.instance=new lt),lt.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async listPlaybooks(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.playbooks,options:{query:{page:u?.page??1,limit:u?.limit??vr,...u?.domain?{"domain[eq]":u.domain}:{}}}});return i.isErr()?K(i.error):an(i.value)}async listPlaybookPages(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.pages(u.playbookId),options:{query:{page:u.page??1,limit:u.limit??vr,...u.url?{"url[eq]":u.url}:{}}}});return i.isErr()?K(i.error):an(i.value)}async createPlaybookPage(u,i){const c=await this.meltingSpotApi.call({method:Nn.POST,endpoint:Ae.pages(u.playbookId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async listAccessiblePlaybookIntents(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.accessibleIntents(u.playbookId,u.pageId),options:{query:{...u.domain?{"domain[eq]":u.domain}:{}}}});return i.isErr()?K(i.error):an(i.value)}async listPlaybookHotspots(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.hotspots(u.playbookId,u.pageId),options:{query:{page:u.page??1,limit:u.limit??vr,...u.intentStatus?{"intentStatus[eq]":u.intentStatus}:{},...u.widgetType?{"widgetType[eq]":u.widgetType}:{}}}});return i.isErr()?K(i.error):an(i.value)}async createPlaybookHotspot(u,i){const c=await this.meltingSpotApi.call({method:Nn.POST,endpoint:Ae.hotspots(u.playbookId,u.pageId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async updatePlaybookHotspot(u,i){const c=await this.meltingSpotApi.call({method:Nn.PATCH,endpoint:Ae.hotspot(u.playbookId,u.pageId,u.hotspotId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async listPlaybookIntents(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:Ae.intents(u.playbookId,u.pageId,u.hotspotId),options:{query:{page:u.page??1,limit:u.limit??vr,...u.status?{"status[eq]":u.status}:{}}}});return i.isErr()?K(i.error):an(i.value)}async createPlaybookIntent(u,i){const c=await this.meltingSpotApi.call({method:Nn.POST,endpoint:Ae.intents(u.playbookId,u.pageId,u.hotspotId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}async updatePlaybookIntent(u,i){const c=await this.meltingSpotApi.call({method:Nn.PATCH,endpoint:Ae.intent(u.playbookId,u.pageId,u.hotspotId,u.intentId),options:{payload:i}});return c.isErr()?K(c.error):an(c.value)}}const fc={me:"/v1/spots/me"},cc=50;class ht{static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async listSpotsForMe(u){const i=await this.meltingSpotApi.call({method:Nn.GET,endpoint:fc.me,options:{query:{page:1,limit:cc,...u?.spotMemberRole?{"spotMemberRole[eq]":u.spotMemberRole}:{}}}});return i.isErr()?K(i.error):an(i.value)}}const lc={spotMember:{me:"/v1/spotMembers/me"}};class dt{static getInstance(){return dt.instance||(dt.instance=new dt),dt.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async getSpotMemberForMe(){const u=await this.meltingSpotApi.call({method:Nn.GET,endpoint:lc.spotMember.me});return u.isErr()?K(u.error):an(u.value)}}const hc={spotMemberSsoToken:"/v1/spotMembers/auth/sso/jwt"};class pt{static getInstance(){return pt.instance||(pt.instance=new pt),pt.instance}constructor(){this.meltingSpotApi=ye.getInstance()}async generateSsoToken(){const u=await this.meltingSpotApi.call({method:Nn.POST,endpoint:hc.spotMemberSsoToken,options:{payload:{}}});return u.isErr()?K(u.error):an(u.value.token)}}class _t{static getInstance(){return _t.instance||(_t.instance=new _t),_t.instance}constructor(){this.spotMemberAuthApiService=pt.getInstance()}async generateSsoToken(){return this.spotMemberAuthApiService.generateSsoToken()}}const dc=s=>{const u=s.get("utm_source");if(u)return{source:u,medium:s.get("utm_medium")??void 0,campaign:s.get("utm_campaign")??void 0,term:s.get("utm_term")??void 0,content:s.get("utm_content")??void 0}},pc=s=>s?Object.entries(s).reduce((u,[i,c])=>(c!=null&&(u[`utm_${i}`]=c),u),{}):{},_c=ue.getInstance(),gc=ke.getInstance(),mc=_t.getInstance(),vc={Playbook:lt.getInstance(),Spot:ht.getInstance(),SpotMember:dt.getInstance()},gt=globalThis;gt.MeltingSpot||(gt.MeltingSpot={}),gt.MeltingSpot.Configuration=_c,gt.MeltingSpot.Auth=gc,gt.MeltingSpot.Sso=mc,gt.MeltingSpot.Api=vc;const Ec="1.0.0",mi=new us({appName:"Embed SDK",appVersion:Ec});class Es{constructor(u){this.content=u}#n=null;#e=null;set onRemove(u){this.#e=u}inject(u){this.remove();const i=sf({input:u,rootDocument:this.content.rootDocument});this.#n=this.content.iframe,this.#n.classList.add("ms-embed"),i.appendChild(this.#n)}remove(){this.#n&&(this.#n.contentWindow&&this.#e?.(this.#n.contentWindow),this.#n.remove(),this.#n=null)}}class wc{constructor(u){this.baseURL=Zf(u.baseURL),this.spotId=zf(u.spotId),this.authToken=u.authToken??null,this.themeMode=u.themeMode??"auto",this.domain=u.domain??null,this.deeplink=u.deeplink?Qf({deeplink:u.deeplink,spotId:this.spotId}):null,this.utmParameters=u.utmParameters??null,this.rootDocument=u.rootDocument}get iframe(){const u=this.authToken&&this.authToken.trim().length>0?"/sso/jwt":"",i=new URL(`/spot/${this.spotId}${u}`,zu(this.baseURL)),c=af({url:i,searchParams:{embed:this.spotId,themeMode:this.themeMode,ms_token:this.authToken,domain:this.domain,deeplink:this.deeplink,...pc(this.utmParameters)},rootDocument:this.rootDocument});return c.classList.add("ms-spot"),c}}const Er={READY:"meltingspot:ready",ERROR:"meltingspot:error"},Mn=class Mn{static injectSpotInto(u,i){const{onReady:c,onError:p,...v}=i,{spotId:_,rootDocument:A,msCommunityWebBaseUrl:x}=ue.getConfiguration({spotId:v.spotId,rootDocument:v.rootDocument,msCommunityWebBaseUrl:v.baseURL});if(!_)throw mi.error("Spot ID is required"),new Error("Spot ID is not configured. Please set the spotId in the configuration.");const q=new URLSearchParams(window.location.search),nn={spotId:_,authToken:v.authToken??q.get("ms_token"),domain:v.domain,deeplink:v.deeplink??q.get("ms_url"),themeMode:v.themeMode,utmParameters:v.utmParameters??dc(q),baseURL:x,rootDocument:A},N=new Es(new wc(nn));if(N.inject(u),Mn.embeds.push(N),c||p){const $=N.content.iframe.contentWindow;$&&(Mn.iframeCallbacks.set($,{onReady:c,onError:p}),N.onRemove=G=>{Mn.iframeCallbacks.delete(G)}),Mn.ensureMessageListener()}return mi.log("Spot injected",nn,u),N}static clear(){Mn.embeds.forEach(u=>{u.remove()}),Mn.embeds=[],Mn.iframeCallbacks.clear(),Mn.messageListened&&(window.removeEventListener("message",Mn.handleMessageEvent),Mn.messageListened=!1),mi.log("All MeltingSpot embeds cleared")}static handleMessageEvent(u){if(!u.data||typeof u.data!="object"||u.data.type!==Er.READY&&u.data.type!==Er.ERROR)return;const i=u.source,c=Mn.iframeCallbacks.get(i);if(!c)return;const{msCommunityWebBaseUrl:p}=ue.getConfiguration({});if(p)try{const v=new URL(p).origin;if(u.origin!==v)return}catch{}u.data.type===Er.READY?c.onReady?.():c.onError?.(u.data.error)}static ensureMessageListener(){Mn.messageListened||(window.addEventListener("message",Mn.handleMessageEvent),Mn.messageListened=!0)}};Mn.embeds=[],Mn.messageListened=!1,Mn.iframeCallbacks=new Map;let wr=Mn;const vi=globalThis;vi.MeltingSpot||(vi.MeltingSpot={}),vi.MeltingSpot.Embed=wr,He.EMBED_POST_MESSAGE_TYPE=Er,He.Embed=wr,He.EmbedFrame=Es,Object.defineProperty(He,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "MeltingSpot Embed SDK",
4
4
  "homepage": "https://meltingspot.io",
5
5
  "license": "BSD-3-Clause",
6
- "version": "0.1.0",
6
+ "version": "1.0.0",
7
7
  "main": "./index.cjs",
8
8
  "module": "./index.mjs",
9
9
  "typings": "./index.d.ts",
@@ -17,7 +17,7 @@
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "@meltingspot/core": "0.1.0"
20
+ "@meltingspot/core": "1.0.0"
21
21
  },
22
22
  "publishConfig": {
23
23
  "provenance": false