@vkontakte/videoplayer-interactive 1.0.6-beta.0 → 1.0.6-dev.5a11a96.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/esnext.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.6-beta.0
3
- * Wed, 29 Nov 2023 17:13:44 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.6-dev.5a11a96.0
3
+ * Tue, 12 Dec 2023 11:20:59 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-6/doc/
5
5
  */
6
- import{loadVKLangPack as ot,Subscription as ce,ValueSubject as ct,Observable as ge,getCurrentBrowser as lt,CurrentClientBrowser as ht,once as dt}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as le}from"uuid";import{Player as ut}from"@vkontakte/videoplayer-core/esnext.esm.js";const ft="1.0.6-beta.0";function Be(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}const N="SDK_NAME",pt="SDK_NAME-controls-container",$e=()=>document.querySelector(`.${pt}`),_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ve={top:"flex-start",bottom:"flex-end",center:"center"},be={start:"flex-start",end:"flex-end",center:"center"},Ee={start:"left",end:"right",center:"center"},De=({target:i,props:e})=>{i.style.alignItems=ve[e?.text?.gravityVertical]??ve.center,i.style.justifyContent=be[e?.text?.gravityHorizontal]??be.center,i.style.textAlign=Ee[e?.text?.alignment]??Ee.start},He=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},Ge=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},Ue=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Be(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},he=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class de{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${N}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??_.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",s=>{s.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const ze=i=>{if(i.type.trim().toLowerCase()==="area")return new mt(i)};class mt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");return s.classList.add(`${N}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",Ge({target:s,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Ue({target:s,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),he({target:s,layoutParams:this.control.layoutParams,fallback:_}),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new yt(i)};class yt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");s.type="button",s.classList.add(`${N}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",he({target:s,layoutParams:this.control.layoutParams,fallback:_}),Ge({target:s,props:this.control.props,fallback:_}),Ue({target:s,props:this.control.props,fallback:_,dependsOn:n}),De({target:s,props:this.control.props}),He({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const gt=i=>{if(i.type.trim().toLowerCase()==="text")return new vt(i)};class vt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("div");s.classList.add(`${N}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",he({target:s,layoutParams:this.control.layoutParams,fallback:_}),De({target:s,props:this.control.props}),He({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class bt{constructor(e){this.layout=e}}const Et=i=>{if(i.type.trim().toLowerCase()==="relative")return new qe(i)};class qe extends bt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Qe{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...e,r(t)]:[...e]},[])}}const Xe=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new Ct(i,e)};class Ct extends Qe{constructor(e,t){super(e),this.rootElement=t??$e(),this.layout=new qe(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",We),this.addControlFactory("text",gt),this.addControlFactory("area",ze)}createView(e){const t=document.createElement("div");return t.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const r=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(r,e)}),this.rootElement.append(t),t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Ze(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const W={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},U=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ue=i=>U(i,W.Object),re=i=>U(i,W.String),G=i=>U(i,W.Array),Ke=i=>U(i,W.Number),wt=i=>U(i,W.Function),Ce=i=>Ke(i)&&!isNaN(i),St=i=>i==null,z=i=>ue(i)&&Object.keys(i).length===0,Ye=i=>G(i)&&!i.length,X=(i,e)=>re(i)&&(e?i.trim():i).length,Je=window.navigator.userAgent.toLowerCase(),It=/mobi/i.test(Je);Je.indexOf("android")>-1;const Tt="video_interactive",Rt="videoint",At=250;class xt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=t,this.onError=n,this.lang=r??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Ot(e),this.resizeObserver=new ResizeObserver(Ze(this.onResize,At)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!Ke(e.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await ot(this.lang,Tt,Rt)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:r}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new r(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:s,chapterId:o})=>{s==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",s=>{this.lastZoomInfo={...s}})}this.visitedChapterIds=new Set(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function Ot(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const Lt=(i={})=>Array.from(new Set(i.sessions?.map(e=>e.visitedChapters.map(t=>t.chapterId)??[]).flat())),we=(i=[],e="")=>i.reduce((t,n)=>(t.find(r=>r[e]===n[e])||t.push(n),t),[]),Se="chapterId";class ${constructor(e){this.id=e?.id??le(),this.startDate=e?.startDate?new Date(e.startDate).toISOString():new Date(Date.now()).toISOString(),this.updateOn=e?.updateOn?new Date(e.updateOn).toISOString():null,this.visitedChapters=e?.visitedChapters?we(Array.from(e.visitedChapters),Se):[],this.branches=G(e?.branches)?e.branches:[]}update(e){e?.startDate&&(this.startDate=new Date(e.startDate).toISOString()),e?.updateOn&&(this.updateOn=new Date(e.updateOn).toISOString()),G(e?.visitedChapters)&&(this.visitedChapters=we([...this.visitedChapters,...e.visitedChapters],Se)),G(e?.branches)&&(this.branches=this.branches.concat(e.branches))}getSession(){return{...this}}static createVisitedChapter(e){return[{chapterId:e}]}static createBranch(e,t,n){return[{chapterId:e,branchId:t,autoSelect:n}]}}class Z{constructor(e){this.id=e?.id??le(),this.manifestId=e?.manifestId,this.manifestVersion=e?.manifestVersion,this.manifestBuild=e?.manifestBuild,this.sessions=G(e?.sessions)?e?.sessions.map(t=>new $(t)):[],this.isCompleted=e?.isCompleted??!1}update(e){this.id=e?.id??this.id,this.manifestId=e?.manifestId??this.manifestId,this.manifestVersion=e?.manifestVersion??this.manifestVersion,this.manifestBuild=e?.manifestBuild??this.manifestBuild,this.isCompleted=e?.isCompleted??this.isCompleted}addSession(e){this.sessions.push(new $(e))}updateSession(e,t){let n;St(e)?n=this.sessions[this.sessions.length-1]:n=this.sessions.find(r=>r.id===e),n&&n.update(t)}resetSession(){this.sessions=[]}getHistory(){return{...this,sessions:this.sessions.map(e=>e.getSession())}}}const ae="SDK_NAME-history-changed";class jt extends EventTarget{constructor(){super(),this.history=new Z,this.sendEvent()}onChapterChange({chapterId:e,mediaId:t,autoSelect:n=!1,isLastChapter:r=!1}){this.history.isCompleted?this.history=new Z({manifestId:this.history.manifestId,manifestVersion:this.history.manifestVersion,manifestBuild:this.history.manifestBuild}):r&&this.history.update({isCompleted:!0}),this.history.sessions.length?this.history.updateSession(null,{updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,n)}):this.history.addSession({updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,!1)}),this.sendEvent()}onManifestChange(e,t){t?this.history=new Z(t):this.history=new Z({manifestId:e.id,manifestVersion:e.version,manifestBuild:e.build}),this.history.addSession({updateOn:Date.now()}),this.sendEvent()}getHistory(){if(history)return this.history.getHistory()}sendEvent(){this.dispatchEvent(new CustomEvent(ae,{bubbles:!1,detail:this.getHistory()}))}destroy(){this.history=void 0}}function Nt(i,e){if(!e||!i||!e.sessions.length)return;const t=e.sessions.reverse().find(n=>n.branches.length);return t.branches[t.branches.length-1].chapterId??void 0}const ee=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},_t="3.1",Ie={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Mt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Vt=i=>{const e=[];for(const t of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let p=[Mt];switch(a){case"await":l?p=[]:s=[];break;case"default":{const u={type:"onSuspense",action:{type:Ie.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?p=[u]:s=[u];break}case"random":case"weightlessRandom":case"max":case"min":{const u={type:"onSuspense",action:{type:Ie[a],args:{}}};l?p=[u]:s=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:le(),events:p})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=_t,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Pt="3.2",kt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Pt},media:e}}return i},Ft="3.3",Bt=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},$t=i=>{const e=[],t=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:p,type:u,...b})=>({...b,type:p??u})),events:l.events?.length?l.events:[Te]}));e.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Te]}),t.push({id:r,x:s,y:o})}return{...i,chapters:e,graph:Bt(t),metadata:{...i.metadata,version:Ft}}},Dt=[{version:"3.0",migrate:Vt},{version:"3.1",migrate:kt},{version:"3.2",migrate:$t}],Ht=i=>Dt.reduce((e,t)=>ee(e.metadata.version,t.version)?e:t.migrate(e),i),Gt=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(F||(F={}));const Re={metadata:"Object",chapters:"Array"},Ut="3.0.0",zt="3.3.0",et=i=>{const e=ee(i,Ut);return e===-1?!1:e===0?!0:ee(i,zt)!==1},Wt=i=>{if(!ue(i))return!1;for(const e in Re)if(!i[e]||!U(i[e],Re[e]))return!1;return et(i.metadata.version)},qt=i=>i.type===Gt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class tt{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Qt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{wt(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Xt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Zt(...this.loaders[e])(t)}}function Zt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function te(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function oe({actions:i,errors:e,chapterId:t,...n}){if(t){const r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:e,result:{chapter:s,media:o,graph:a}}:{...n,errors:te(e,oe.name,"Could not find media"),actions:i}}}return{...n,errors:te(e,oe.name,"Could not find chapter"),actions:i}}class Ae{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,n){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:n})}removeEventListener(e,t){if(!(e in this.listeners))return;const n=this.listeners[e];for(let r=0,s=n.length;r<s;r++)if(n[r].callback===t){n.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const n=this.listeners[e.type].slice();for(let r=0,s=n.length;r<s;r++){const o=n[r];try{o.callback.call(this,e)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class it extends Ae{constructor(){super(),this.listeners||Ae.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Kt{constructor(){Object.defineProperty(this,"signal",{value:new it,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let n=e;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Kt.prototype[Symbol.toStringTag]="AbortController",it.prototype[Symbol.toStringTag]="AbortSignal");function nt(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Yt(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!nt({fetch:e,Request:t,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,p){let u;p&&p.signal&&(u=p.signal,delete p.signal);const b=new t(l,p);return u&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),b},s.prototype=t.prototype);const o=e;return{fetch:(c,l)=>{const p=s&&s.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(p){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(p.aborted)return Promise.reject(u);const b=new Promise((E,x)=>{p.addEventListener("abort",()=>x(u),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:s}}const fe=nt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),st=fe?Yt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xe=fe?st.fetch:window.fetch;fe?st.Request:window.Request;const Jt=async i=>{try{let e,t;if(ue(i))e=i;else if(re(i)){t=new URL(i).href;const r=await xe(t);if(!r.ok)return{};e=await r.json()}else return{};if(!Wt(e))return{};const n=e.metadata.media;if(re(n)&&!e.media)try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);const s=await xe(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return ni(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ei(i){const{manifest:e,manifestURL:t}=await Jt(i),n=Ht(e);return n.media=ti(n.media,t),delete n.metadata.media,n}function ne(i,e){return i.find(t=>t.id===e)}function Oe(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Le(i,e){return i.videos.find(t=>t.id===e)}function ti(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=ii(n.url,e);return{...n,url:r||n.url}})}))}}function ii(i,e){try{return new URL(i,e).href}catch{return""}}function ni(i){return ee(i,"3.2.0")>=0}class si extends Xt{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:te},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await ei(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",oe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Oe,getChapter:ne,getMedia:Le,getByBranches:this.getByBranches.bind(this),addErrorMessage:te},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=ne(this.manifest.chapters,e);if(t){const n=Le(this.manifest.media,t.videoId),r=Oe(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:r}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=ne(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const r=this.getByChapterId(n.chapterId);return r&&t.push(r),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},je={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ri(){const i=new Map;function e({listId:r=Math.random().toString(),itemId:s=Math.random().toString(),...o}){const a=i.get(r),c={...o};return a?a[s]=c:i.set(r,{[s]:c}),{listId:r,itemId:s,...o}}function t(r,s){const o=i.get(r);if(o){if(s)return o[s]?.player.destroy(),o[s]?.container.remove(),o[s]?.subscription.unsubscribe(),delete o[s],Object.keys(o).length||i.delete(r),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(r),!0}else throw Error("Can't remove. Not find.")}function n(){for(const r of i)t(r[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function Ne(i,e=[]){let t={},n;const r=!e.length;for(const s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:t,thumbUrl:n,title:i.title??""}}const K=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},ai=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},J={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},oi=2;function ci(i){const e=ri();let t,n;const r=new tt;let s={},o=!1,a=null,c=!1,l;i&&p(i);function p(d){a=d}function u(d,g,m){if(!a)throw Error("need to set interactive controller");const C=(e.map.get(d)??{})[g];if(C){s={chapterId:m,listId:d,itemId:g,...C};const v=s.player;n=v.info.currentQuality$.subscribe(w=>{if(!(!w||!v.info.position$.getValue())){t=w;for(const L of e.map)Object.values(L[1]).forEach(({player:j})=>{v.info.isAutoQualityEnabled$.getValue()||K(j,w)})}}),C.container.remove(),o=!1,a.setPlayer(C.player),c||(a.init(),c=!0),r.emit(J.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(z(s)||d!==s.itemId)return;if(m>=0&&!o){const C=a.getChapterBranches();o=!0;const v=new Set;for(const w of C)v.has(w.media.id)||(await x({media:w.media,chapterId:w.chapter.id,setAsActive:!1,title:w.chapter.label}),v.add(w.media.id))}}async function E({chapter:{id:d},media:g}){if(z(s))return;n?.unsubscribe();const m=s.player.info.muted$.getValue(),I=s.player.info.currentQuality$.getValue(),C=s.player.info.isAutoQualityEnabled$.getValue(),v=s.player.info.volume$.getValue(),w=s.player.info.currentPlaybackRate$.getValue(),L=!C;let j=!1;for(const O of e.map)if(O[0]===g.id){const q=Object.keys(O[1]);for(const P of q)P===s.itemId?(q.length<oi||(j=!0),e.removePlayer(O[0],P)):(j=!0,u(O[0],P,d),L?K(s.player,I):s.player.setAutoQuality(!0),s.player.setVolume(v),s.player.setMuted(m),s.player.setPlaybackRate(w))}else e.removePlayer(O[0]);j||(await x({media:g,chapterId:d,setAsActive:!0,playbackRate:w}),L?K(s.player,I):s.player.setAutoQuality(!0),s.player.setVolume(v),s.player.setMuted(m))}async function x({media:d,chapterId:g,prefetch:m=!0,setAsActive:I=!0,autoplay:C=!1,preferredExt:v,title:w,playbackRate:L}){const j=Math.random().toString(),O=document.createElement("div");l.append(O);const q=s?.player?.info.isAutoQualityEnabled$.getValue();let P;if(a?.options?.vkVideoLoader){const Q=ai(d);Q.length&&(P=await a.options.vkVideoLoader(...Q))}const me={container:O,...P?.videos?.[0]||{sources:Ne(d,v).sources},title:w},k=new ut;k.initVideo(me);const at=O.lastChild,ye=new ce;ye.add(k.info.position$.subscribe(function(Q){b(j,k.info.duration$.getValue(),Q)})).add(k.events.canplay$.subscribe(function(){q||K(k,t),L&&k.setPlaybackRate(L)})),at&&(O.style.display="none",O.classList.add(g));const B=e.createPlayer({listId:d.id,itemId:j,player:k,container:O,sources:Ne(d,v).sources,config:me,subscription:ye});return I&&u(d.id,B.itemId,g),C&&B.player.play(),m&&!C&&B.player.prepare(),r.emit(J.playerCreated,B.player),{player:B.player,config:B.config}}function V(){h(),a=null}function h(){a?.off(y.chapterChanged,E),e.removeAll(),s={},c=!1,o=!1}async function f({source:d,initialChapter:g,container:m}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=m;const{media:I,chapter:C}=await a.setChapter({chapterId:g});if(I){a.on(y.chapterChanged,E);const{player:v,config:w}=await x({media:I,chapterId:C.id,title:C.label});return r.emit(J.initiated,{container:m,media:I,chapterId:C.id}),{player:v,config:w}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:f,setInteractiveController:p,createPlayer:x,removeAll:V,getActivePlayer:function(){return s}}}const li=3e3,hi=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=li)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const p of i){const u=p.startTime-o;if(u<=l&&(l<=p.endTime||p.endTime===null)){c=!0;break}l<u&&(a=a===-1?u:Math.min(a,u))}return!c&&a!==-1?a:null}}},D=hi(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pe=i=>G(i)&&!Ye(i),rt=i=>Ye(i.branches)||i.order==="end",di=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t<(e.startTime??0)},_e=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ie=i=>i.some(e=>e.action.type==="expect"),Me=i=>i.find(e=>e.action.type==="expect"),ui=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),fi=(i=[])=>i.reduce((e,t,n)=>{const r=(t?.controls??[]).filter(s=>!qt(s));if(pe(r)){const s=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,p=[];const u=[];for(let b=0;b<e.length;b++){const E=e[b];if(u.push(...E.subjects),E.range[0]<l&&(l=E.range[0]),E.range[1]>c&&(c=E.range[1]),E.range[0]<=s[0]&&E.range[1]>=s[1])return e[b].subjects.push(o),e;s[0]>=E.range[0]&&s[0]<=E.range[1]&&(a.push(b),p=p.concat(E.subjects),s[0]=E.range[0]),s[1]>=E.range[0]&&s[1]<=E.range[1]&&(a.push(b),p=p.concat(E.subjects),s[1]=E.range[1])}if(u.push(o),s[0]<=l&&s[1]>=c)return[{subjects:u,range:s}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:p.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),pi=(i,e)=>ie(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ie(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class mi{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a}){this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new ce,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.globalEventEmitter=o,this.gameState=T.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo))}hide=()=>{setTimeout(()=>{this.gameState!==T.end&&(ie(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!1});else{const t=ui({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!this.isSelectedControlEvent&&(this.isSelectedContainerEvent||(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime)))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ie(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState))return;const t=this.player.getExactTime();if(di(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(_e(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const s=this.gameState;this.gameState=T.afterInteractive,s===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=_e(t,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function yi(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function r({timestamp:a,priority:c,initiator:l}){if(Ce(a)){const p=i[a]??null;if(p&&X(c,!0)){let u={};const b=p[c];return b&&(u={...u,...b}),u=z(u)?null:u,u&&X(l,!0)?u[l]??null:u}return p}return null}function s({timestamp:a,priority:c,initiator:l}){if(Ce(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!z(i[a][c]))return!0}else return!1;if(delete i[a][c],!z(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...p}){i[a]?.[c]?.[l]?i[a][c][l].push({...p}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...p}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...p}]}}:i[a]={[c]:{[l]:[{...p}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const gi=[S.expect,S.setNextBranch],vi=1/0;function Ve(i){let e=i,t;const n=bi(),r=new yi;let s;const o=()=>{u(),V()},a=h=>{r.add.call(void 0,h),b()},c=(h=[])=>{for(const f of h)if(f.action(),gi.includes(f.actionType))break},l=h=>{if(!n.isReady(h))return;const f=Y(r.get({timestamp:h,priority:"control"})??{}),d=Y(r.get({timestamp:h,priority:"container"})??{}),g=Y(r.get({timestamp:h,priority:"chapter"})??{});c([...f,...d,...g])},p=()=>{c([...Y(r.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{t&&(s?.unsubscribe(),t=void 0)},b=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),s=e.events.ended$.subscribe(t))},E=h=>{u(),e=h},x=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},V=()=>{n.release(),r.removeAll()};return{setPlayer:E,add:a,remove:x,exec:l,execEndOfVideo:p,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function bi(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??vi,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function Y(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}const Ei=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=e.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=r/s;let c,l;return a>o?(l=s,c=s*o):a<o?(l=r/o,c=r):(l=s,c=r),{videoContentWidth:l,videoContentHeight:c}},Ci=250;function wi(i){let e=()=>{};const t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:p,videoContentHeight:u}=Ei(c,l);c.style.setProperty("--interactive-content-width",`${p}px`),c.style.setProperty("--interactive-content-height",`${u}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){const{parentElement:a}=i();a.removeAttribute("style")}const s=Ze(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},Ci);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class Si{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const Ii=i=>Math.floor(Math.random()*i),Ti=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},Ri=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},Ai=i=>{const e=i.length,t=Ii(e);return i[t]},Pe=1,xi=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Pe;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Pe,e>=t)return i[n];return i[i.length-1]},ke=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),se=(i,e=!1)=>({...i,args:e?{...i.args,...ke}:{...ke,...i.args}}),Fe=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:h,controlType:f,controlId:d,containerId:g,branches:m=[],onEvent:I,isEOV:C=()=>!1})=>{const v=se(h,C()),w={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},L=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:f,subjectName:"control",type:R.actionChoice,actionType:h.type,payload:{containerId:g,...v.args}});switch(v.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const j=m.find(O=>O.id===v.args.branchId);if(!j)return;I(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:j.chapterId,autoSelect:!1}}):(t.add({...w,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:j.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{I(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?E({subjectId:d,subjectName:"control",subjectType:f,action:h}):t.add({...w,action:E.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:h})});return}case S.openURI.trim().toLowerCase():{I(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}}):(t.add({...w,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:f,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:I=!1})=>{const C=se(h,m),v={timestamp:!C.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:f,actionType:C.type},w=i.emit.bind(i,y.interactives,{subjectId:f,subjectName:"container",type:R.actionChoice,actionType:C.type,payload:C.args});switch(C.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const L=g.find(j=>j.id===C.args.branchId);if(!L)return;w(),t.add({...v,action:x.bind(null,{subjectId:f,subjectName:"container",action:C,payload:{chapterId:L.chapterId,autoSelect:I}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{w(),t.add({...v,action:E.bind(null,{subjectId:f,subjectName:"container",action:C})});return}case S.openURI.trim().toLowerCase():{w(),t.add({...v,action:V.bind(null,{subjectId:f,subjectName:"container",action:C,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:f,isEOV:d=!1}){const g=Me(h.events);if(g){const m=se(g.action,d);i.emit(y.interactives,{subjectId:h.id,subjectName:"container",type:R.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:S.expect,action:u.bind(null,{subjectId:h.id,subjectName:"container"})}),r.isExpect=!0}else for(const m of h.events)a({action:m.action,container:h,branches:f,isEOV:d})}const l=({chapterId:h,action:f,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"chapter",type:R.actionChoice,actionType:f.type,payload:f.args});switch(f.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const m=d.find(I=>I.id===f.args.branchId);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const m=Ai(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const m=xi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const m=Ri(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const m=Ti(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return g(),E.bind(null,{subjectId:h,subjectName:"chapter",action:f});case S.openURI.trim().toLowerCase():return g(),V.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{URI:f.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function p(h){const f=Me(h.events);if(f){if(rt(h))return;i.emit(y.interactives,{subjectId:h.id,subjectName:"chapter",type:R.actionChoice,actionType:f.action.type,payload:f.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:S.expect,action:u.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const g=l({chapterId:h.id,action:d.action,branches:h.branches});g&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:g})})}const u=({subjectId:h,subjectName:f,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:d?.type??S.expect})},b=({subjectId:h,subjectName:f})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:"after-expect"})},E=({subjectId:h,subjectName:f,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})},x=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type,payload:m})},V=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const I=window.open(m.URI,"_blank","noopener,noreferrer");I&&(I.opener=null),i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:u,expectEventHandler:b,setManifestChapterEvents:p,setManifestContainerEvents:c,stopExpect:s,state:r}};class H{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=H.#a(e,r),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),r=Object.keys(t).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),H.#l(e)?t:t.capture||!1}}static#s=void 0;static#l(e){let t=H.#s;if(t===void 0){t=!1;try{const n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}H.#s=t}return t||!1}}class Oi{constructor(){this.bindingMap=new Si}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new H(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){const s=o=>{this.unlisten(e,t,s),n(o)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;const r=this.bindingMap.get(t)||[];for(const s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class Li{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let r=3;r<n;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class ji{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
6
+ import{loadVKLangPack as ot,Subscription as ce,ValueSubject as ct,Observable as ge,getCurrentBrowser as lt,CurrentClientBrowser as ht,once as dt}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as le}from"uuid";import{Player as ut}from"@vkontakte/videoplayer-core/esnext.esm.js";const ft="1.0.6-dev.5a11a96.0";function Be(i,e=1){let t="0",n="0",s="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+s},${e})`}const N="SDK_NAME",pt="SDK_NAME-controls-container",$e=()=>document.querySelector(`.${pt}`),_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ve={top:"flex-start",bottom:"flex-end",center:"center"},be={start:"flex-start",end:"flex-end",center:"center"},Ee={start:"left",end:"right",center:"center"},De=({target:i,props:e})=>{i.style.alignItems=ve[e?.text?.gravityVertical]??ve.center,i.style.justifyContent=be[e?.text?.gravityHorizontal]??be.center,i.style.textAlign=Ee[e?.text?.alignment]??Ee.start},He=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},Ue=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},ze=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Be(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},he=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class de{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${N}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??_.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",r=>{r.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Ge=i=>{if(i.type.trim().toLowerCase()==="area")return new mt(i)};class mt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");return r.classList.add(`${N}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ue({target:r,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),ze({target:r,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),he({target:r,layoutParams:this.control.layoutParams,fallback:_}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new yt(i)};class yt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");r.type="button",r.classList.add(`${N}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",he({target:r,layoutParams:this.control.layoutParams,fallback:_}),Ue({target:r,props:this.control.props,fallback:_}),ze({target:r,props:this.control.props,fallback:_,dependsOn:n}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:_,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const gt=i=>{if(i.type.trim().toLowerCase()==="text")return new vt(i)};class vt extends de{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${N}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",he({target:r,layoutParams:this.control.layoutParams,fallback:_}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:_,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class bt{constructor(e){this.layout=e}}const Et=i=>{if(i.type.trim().toLowerCase()==="relative")return new qe(i)};class qe extends bt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Qe{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...e,s(t)]:[...e]},[])}}const Xe=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new Ct(i,e)};class Ct extends Qe{constructor(e,t){super(e),this.rootElement=t??$e(),this.layout=new qe(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",We),this.addControlFactory("text",gt),this.addControlFactory("area",Ge)}createView(e){const t=document.createElement("div");return t.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const s=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(s,e)}),this.rootElement.append(t),t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Ze(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const W={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ue=i=>z(i,W.Object),re=i=>z(i,W.String),U=i=>z(i,W.Array),Ke=i=>z(i,W.Number),wt=i=>z(i,W.Function),Ce=i=>Ke(i)&&!isNaN(i),St=i=>i==null,G=i=>ue(i)&&Object.keys(i).length===0,Ye=i=>U(i)&&!i.length,X=(i,e)=>re(i)&&(e?i.trim():i).length,Je=window.navigator.userAgent.toLowerCase(),It=/mobi/i.test(Je);Je.indexOf("android")>-1;const Tt="video_interactive",Rt="videoint",At=250;class xt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=t,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Ot(e),this.resizeObserver=new ResizeObserver(Ze(this.onResize,At)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!Ke(e.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await ot(this.lang,Tt,Rt)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function Ot(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const Lt=(i={})=>Array.from(new Set(i.sessions?.map(e=>e.visitedChapters.map(t=>t.chapterId)??[]).flat())),we=(i=[],e="")=>i.reduce((t,n)=>(t.find(s=>s[e]===n[e])||t.push(n),t),[]),Se="chapterId";class ${constructor(e){this.id=e?.id??le(),this.startDate=e?.startDate?new Date(e.startDate).toISOString():new Date(Date.now()).toISOString(),this.updateOn=e?.updateOn?new Date(e.updateOn).toISOString():null,this.visitedChapters=e?.visitedChapters?we(Array.from(e.visitedChapters),Se):[],this.branches=U(e?.branches)?e.branches:[]}update(e){e?.startDate&&(this.startDate=new Date(e.startDate).toISOString()),e?.updateOn&&(this.updateOn=new Date(e.updateOn).toISOString()),U(e?.visitedChapters)&&(this.visitedChapters=we([...this.visitedChapters,...e.visitedChapters],Se)),U(e?.branches)&&(this.branches=this.branches.concat(e.branches))}getSession(){return{...this}}static createVisitedChapter(e){return[{chapterId:e}]}static createBranch(e,t,n){return[{chapterId:e,branchId:t,autoSelect:n}]}}class Z{constructor(e){this.id=e?.id??le(),this.manifestId=e?.manifestId,this.manifestVersion=e?.manifestVersion,this.manifestBuild=e?.manifestBuild,this.sessions=U(e?.sessions)?e?.sessions.map(t=>new $(t)):[],this.isCompleted=e?.isCompleted??!1}update(e){this.id=e?.id??this.id,this.manifestId=e?.manifestId??this.manifestId,this.manifestVersion=e?.manifestVersion??this.manifestVersion,this.manifestBuild=e?.manifestBuild??this.manifestBuild,this.isCompleted=e?.isCompleted??this.isCompleted}addSession(e){this.sessions.push(new $(e))}updateSession(e,t){let n;St(e)?n=this.sessions[this.sessions.length-1]:n=this.sessions.find(s=>s.id===e),n&&n.update(t)}resetSession(){this.sessions=[]}getHistory(){return{...this,sessions:this.sessions.map(e=>e.getSession())}}}const ae="SDK_NAME-history-changed";class jt extends EventTarget{constructor(){super(),this.history=new Z,this.sendEvent()}onChapterChange({chapterId:e,mediaId:t,autoSelect:n=!1,isLastChapter:s=!1}){this.history.isCompleted?this.history=new Z({manifestId:this.history.manifestId,manifestVersion:this.history.manifestVersion,manifestBuild:this.history.manifestBuild}):s&&this.history.update({isCompleted:!0}),this.history.sessions.length?this.history.updateSession(null,{updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,n)}):this.history.addSession({updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,!1)}),this.sendEvent()}onManifestChange(e,t){t?this.history=new Z(t):this.history=new Z({manifestId:e.id,manifestVersion:e.version,manifestBuild:e.build}),this.history.addSession({updateOn:Date.now()}),this.sendEvent()}getHistory(){if(history)return this.history.getHistory()}sendEvent(){this.dispatchEvent(new CustomEvent(ae,{bubbles:!1,detail:this.getHistory()}))}destroy(){this.history=void 0}}function Nt(i,e){if(!e||!i||!e.sessions.length)return;const t=e.sessions.reverse().find(n=>n.branches.length);return t.branches[t.branches.length-1].chapterId??void 0}const ee=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},_t="3.1",Ie={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Mt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Vt=i=>{const e=[];for(const t of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let p=[Mt];switch(a){case"await":l?p=[]:r=[];break;case"default":{const u={type:"onSuspense",action:{type:Ie.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?p=[u]:r=[u];break}case"random":case"weightlessRandom":case"max":case"min":{const u={type:"onSuspense",action:{type:Ie[a],args:{}}};l?p=[u]:r=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:le(),events:p})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=_t,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},kt="3.2",Ft=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:kt},media:e}}return i},Pt="3.3",Bt=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},$t=i=>{const e=[],t=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:p,type:u,...b})=>({...b,type:p??u})),events:l.events?.length?l.events:[Te]}));e.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Te]}),t.push({id:s,x:r,y:o})}return{...i,chapters:e,graph:Bt(t),metadata:{...i.metadata,version:Pt}}},Dt=[{version:"3.0",migrate:Vt},{version:"3.1",migrate:Ft},{version:"3.2",migrate:$t}],Ht=i=>Dt.reduce((e,t)=>ee(e.metadata.version,t.version)?e:t.migrate(e),i),Ut=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var P;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(P||(P={}));const Re={metadata:"Object",chapters:"Array"},zt="3.0.0",Gt="3.3.0",et=i=>{const e=ee(i,zt);return e===-1?!1:e===0?!0:ee(i,Gt)!==1},Wt=i=>{if(!ue(i))return!1;for(const e in Re)if(!i[e]||!z(i[e],Re[e]))return!1;return et(i.metadata.version)},qt=i=>i.type===Ut.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class tt{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let s=n.length;s>0;s--)if(n[s]===t){n.splice(s,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(s=>{s(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Qt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{wt(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Xt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Zt(...this.loaders[e])(t)}}function Zt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function te(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function oe({actions:i,errors:e,chapterId:t,...n}){if(t){const s=i.getManifest(),r=i.getChapter(s.chapters,t);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:e,result:{chapter:r,media:o,graph:a}}:{...n,errors:te(e,oe.name,"Could not find media"),actions:i}}}return{...n,errors:te(e,oe.name,"Could not find chapter"),actions:i}}class Ae{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,n){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:n})}removeEventListener(e,t){if(!(e in this.listeners))return;const n=this.listeners[e];for(let s=0,r=n.length;s<r;s++)if(n[s].callback===t){n.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const n=this.listeners[e.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];try{o.callback.call(this,e)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class it extends Ae{constructor(){super(),this.listeners||Ae.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Kt{constructor(){Object.defineProperty(this,"signal",{value:new it,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let n=e;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Kt.prototype[Symbol.toStringTag]="AbortController",it.prototype[Symbol.toStringTag]="AbortSignal");function nt(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Yt(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!nt({fetch:e,Request:t,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=function(l,p){let u;p&&p.signal&&(u=p.signal,delete p.signal);const b=new t(l,p);return u&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),b},r.prototype=t.prototype);const o=e;return{fetch:(c,l)=>{const p=r&&r.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(p){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(p.aborted)return Promise.reject(u);const b=new Promise((E,x)=>{p.addEventListener("abort",()=>x(u),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const fe=nt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),st=fe?Yt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xe=fe?st.fetch:window.fetch;fe?st.Request:window.Request;const Jt=async i=>{try{let e,t;if(ue(i))e=i;else if(re(i)){t=new URL(i).href;const s=await xe(t);if(!s.ok)return{};e=await s.json()}else return{};if(!Wt(e))return{};const n=e.metadata.media;if(re(n)&&!e.media)try{let s;t?s=new URL(n,t).href:(s=new URL(n).href,t=s);const r=await xe(s);if(!r.ok)throw new Error;e.metadata.media=await r.json()}catch{return ni(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ei(i){const{manifest:e,manifestURL:t}=await Jt(i),n=Ht(e);return n.media=ti(n.media,t),delete n.metadata.media,n}function ne(i,e){return i.find(t=>t.id===e)}function Oe(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Le(i,e){return i.videos.find(t=>t.id===e)}function ti(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=ii(n.url,e);return{...n,url:s||n.url}})}))}}function ii(i,e){try{return new URL(i,e).href}catch{return""}}function ni(i){return ee(i,"3.2.0")>=0}class si extends Xt{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:te},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await ei(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",oe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Oe,getChapter:ne,getMedia:Le,getByBranches:this.getByBranches.bind(this),addErrorMessage:te},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=ne(this.manifest.chapters,e);if(t){const n=Le(this.manifest.media,t.videoId),s=Oe(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:s}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=ne(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const s=this.getByChapterId(n.chapterId);return s&&t.push(s),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},je={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ri(){const i=new Map;function e({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function t(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)t(s[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function Ne(i,e=[]){let t={},n;const s=!e.length;for(const r of i.variants)switch(!n&&"cover"in r&&(n=r.cover),r.type){case"mp4":(s||e.includes("mp4"))&&(t={...t,MPEG:{"Invariant quality":r.url}});break;case"hls":(s||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:r.url}});break;case"dash":(s||e.includes("dash"))&&(t={...t,DASH:{type:"url",url:r.url}});break}return{sources:t,thumbUrl:n,title:i.id}}const K=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},ai=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},J={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},oi=2;function ci(i){const e=ri();let t,n;const s=new tt;let r={},o=!1,a=null,c=!1,l;i&&p(i);function p(d){a=d}function u(d,g,m){if(!a)throw Error("need to set interactive controller");const C=(e.map.get(d)??{})[g];if(C){r={chapterId:m,listId:d,itemId:g,...C};const v=r.player;n=v.info.currentQuality$.subscribe(w=>{if(!(!w||!v.info.position$.getValue())){t=w;for(const L of e.map)Object.values(L[1]).forEach(({player:j})=>{v.info.isAutoQualityEnabled$.getValue()||K(j,w)})}}),C.container.remove(),o=!1,a.setPlayer(C.player),c||(a.init(),c=!0),s.emit(J.activePlayerChanged,{player:r.player,config:r.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(G(r)||d!==r.itemId)return;if(m>=0&&!o){const C=a.getChapterBranches();o=!0;const v=new Set;for(const w of C)v.has(w.media.id)||(await x({media:w.media,chapterId:w.chapter.id,setAsActive:!1,title:w.chapter.label}),v.add(w.media.id))}}async function E({chapter:{id:d},media:g}){if(G(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),I=r.player.info.currentQuality$.getValue(),C=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),w=r.player.info.currentPlaybackRate$.getValue(),L=!C;let j=!1;for(const O of e.map)if(O[0]===g.id){const q=Object.keys(O[1]);for(const k of q)k===r.itemId?(q.length<oi||(j=!0),e.removePlayer(O[0],k)):(j=!0,u(O[0],k,d),L?K(r.player,I):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m),r.player.setPlaybackRate(w))}else e.removePlayer(O[0]);j||(await x({media:g,chapterId:d,setAsActive:!0,playbackRate:w}),L?K(r.player,I):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m))}async function x({media:d,chapterId:g,prefetch:m=!0,setAsActive:I=!0,autoplay:C=!1,preferredExt:v,title:w,playbackRate:L}){const j=Math.random().toString(),O=document.createElement("div");l.append(O);const q=r?.player?.info.isAutoQualityEnabled$.getValue();let k;if(a?.options?.vkVideoLoader){const Q=ai(d);Q.length&&(k=await a.options.vkVideoLoader(...Q))}const me={container:O,...k?.videos?.[0]||{sources:Ne(d,v).sources},title:w},F=new ut;F.initVideo(me);const at=O.lastChild,ye=new ce;ye.add(F.info.position$.subscribe(function(Q){b(j,F.info.duration$.getValue(),Q)})).add(F.events.canplay$.subscribe(function(){q||K(F,t),L&&F.setPlaybackRate(L)})),at&&(O.style.display="none",O.classList.add(g));const B=e.createPlayer({listId:d.id,itemId:j,player:F,container:O,sources:Ne(d,v).sources,config:me,subscription:ye});return I&&u(d.id,B.itemId,g),C&&B.player.play(),m&&!C&&B.player.prepare(),s.emit(J.playerCreated,B.player),{player:B.player,config:B.config}}function V(){h(),a=null}function h(){a?.off(y.chapterChanged,E),e.removeAll(),r={},c=!1,o=!1}async function f({source:d,initialChapter:g,container:m}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=m;const{media:I,chapter:C}=await a.setChapter({chapterId:g});if(I){a.on(y.chapterChanged,E);const{player:v,config:w}=await x({media:I,chapterId:C.id,title:C.label});return s.emit(J.initiated,{container:m,media:I,chapterId:C.id}),{player:v,config:w}}else console.error("not found")}return{...e,on:s.on.bind(s),off:s.off.bind(s),init:f,setInteractiveController:p,createPlayer:x,removeAll:V,getActivePlayer:function(){return r}}}const li=3e3,hi=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=li)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const p of i){const u=p.startTime-o;if(u<=l&&(l<=p.endTime||p.endTime===null)){c=!0;break}l<u&&(a=a===-1?u:Math.min(a,u))}return!c&&a!==-1?a:null}}},D=hi(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pe=i=>U(i)&&!Ye(i),rt=i=>Ye(i.branches)||i.order==="end",di=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t<(e.startTime??0)},_e=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ie=i=>i.some(e=>e.action.type==="expect"),Me=i=>i.find(e=>e.action.type==="expect"),ui=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),fi=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!qt(r));if(pe(s)){const r=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:r});else{const a=[];let c=-1/0,l=1/0,p=[];const u=[];for(let b=0;b<e.length;b++){const E=e[b];if(u.push(...E.subjects),E.range[0]<l&&(l=E.range[0]),E.range[1]>c&&(c=E.range[1]),E.range[0]<=r[0]&&E.range[1]>=r[1])return e[b].subjects.push(o),e;r[0]>=E.range[0]&&r[0]<=E.range[1]&&(a.push(b),p=p.concat(E.subjects),r[0]=E.range[0]),r[1]>=E.range[0]&&r[1]<=E.range[1]&&(a.push(b),p=p.concat(E.subjects),r[1]=E.range[1])}if(u.push(o),r[0]<=l&&r[1]>=c)return[{subjects:u,range:r}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:p.concat([o]),range:r})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),pi=(i,e)=>ie(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ie(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class mi{constructor({player:e,container:t,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a}){this.container=t,this.branches=n,this.selectBranches=s,this.subscription=new ce,this.player=e,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.globalEventEmitter=o,this.gameState=T.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo))}hide=()=>{setTimeout(()=>{this.gameState!==T.end&&(ie(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!1});else{const t=ui({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})},onEvent:(n,s)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!this.isSelectedControlEvent&&(this.isSelectedContainerEvent||(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime)))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ie(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState))return;const t=this.player.info.position$.getValue();if(di(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(_e(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const r=this.gameState;this.gameState=T.afterInteractive,r===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=_e(t,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function yi(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function s({timestamp:a,priority:c,initiator:l}){if(Ce(a)){const p=i[a]??null;if(p&&X(c,!0)){let u={};const b=p[c];return b&&(u={...u,...b}),u=G(u)?null:u,u&&X(l,!0)?u[l]??null:u}return p}return null}function r({timestamp:a,priority:c,initiator:l}){if(Ce(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!G(i[a][c]))return!0}else return!1;if(delete i[a][c],!G(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...p}){i[a]?.[c]?.[l]?i[a][c][l].push({...p}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...p}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...p}]}}:i[a]={[c]:{[l]:[{...p}]}}}return{map:i,remove:r,add:o,removeAll:e,get:s,getLte:t,getGte:n}}const gi=[S.expect,S.setNextBranch],vi=1/0;function Ve(i){let e=i,t;const n=bi(),s=new yi;let r;const o=()=>{u(),V()},a=h=>{s.add.call(void 0,h),b()},c=(h=[])=>{for(const f of h)if(f.action(),gi.includes(f.actionType))break},l=h=>{if(!n.isReady(h))return;const f=Y(s.get({timestamp:h,priority:"control"})??{}),d=Y(s.get({timestamp:h,priority:"container"})??{}),g=Y(s.get({timestamp:h,priority:"chapter"})??{});c([...f,...d,...g])},p=()=>{c([...Y(s.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{t&&(r?.unsubscribe(),t=void 0)},b=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),r=e.events.ended$.subscribe(t))},E=h=>{u(),e=h},x=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},V=()=>{n.release(),s.removeAll()};return{setPlayer:E,add:a,remove:x,exec:l,execEndOfVideo:p,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function bi(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??vi,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function Y(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}const Ei=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=e.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},Ci=250;function wi(i){let e=()=>{};const t=new ResizeObserver(a=>{r(a),e=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:p,videoContentHeight:u}=Ei(c,l);c.style.setProperty("--interactive-content-width",`${p}px`),c.style.setProperty("--interactive-content-height",`${u}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Ze(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},Ci);function o(){e=void 0,t.disconnect(),s()}return{resizeObserver:t,calc:()=>{e()},release:o}}class Si{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const Ii=i=>Math.floor(Math.random()*i),Ti=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},Ri=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},Ai=i=>{const e=i.length,t=Ii(e);return i[t]},ke=1,xi=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??ke;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??ke,e>=t)return i[n];return i[i.length-1]},Fe=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),se=(i,e=!1)=>({...i,args:e?{...i.args,...Fe}:{...Fe,...i.args}}),Pe=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:h,controlType:f,controlId:d,containerId:g,branches:m=[],onEvent:I,isEOV:C=()=>!1})=>{const v=se(h,C()),w={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},L=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:f,subjectName:"control",type:R.actionChoice,actionType:h.type,payload:{containerId:g,...v.args}});switch(v.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const j=m.find(O=>O.id===v.args.branchId);if(!j)return;I(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:j.chapterId,autoSelect:!1}}):(t.add({...w,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:j.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{I(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?E({subjectId:d,subjectName:"control",subjectType:f,action:h}):t.add({...w,action:E.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:h})});return}case S.openURI.trim().toLowerCase():{I(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}}):(t.add({...w,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:f,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:I=!1})=>{const C=se(h,m),v={timestamp:!C.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:f,actionType:C.type},w=i.emit.bind(i,y.interactives,{subjectId:f,subjectName:"container",type:R.actionChoice,actionType:C.type,payload:C.args});switch(C.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const L=g.find(j=>j.id===C.args.branchId);if(!L)return;w(),t.add({...v,action:x.bind(null,{subjectId:f,subjectName:"container",action:C,payload:{chapterId:L.chapterId,autoSelect:I}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{w(),t.add({...v,action:E.bind(null,{subjectId:f,subjectName:"container",action:C})});return}case S.openURI.trim().toLowerCase():{w(),t.add({...v,action:V.bind(null,{subjectId:f,subjectName:"container",action:C,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:f,isEOV:d=!1}){const g=Me(h.events);if(g){const m=se(g.action,d);i.emit(y.interactives,{subjectId:h.id,subjectName:"container",type:R.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:S.expect,action:u.bind(null,{subjectId:h.id,subjectName:"container"})}),s.isExpect=!0}else for(const m of h.events)a({action:m.action,container:h,branches:f,isEOV:d})}const l=({chapterId:h,action:f,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"chapter",type:R.actionChoice,actionType:f.type,payload:f.args});switch(f.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const m=d.find(I=>I.id===f.args.branchId);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const m=Ai(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const m=xi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const m=Ri(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const m=Ti(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return g(),E.bind(null,{subjectId:h,subjectName:"chapter",action:f});case S.openURI.trim().toLowerCase():return g(),V.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{URI:f.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function p(h){const f=Me(h.events);if(f){if(rt(h))return;i.emit(y.interactives,{subjectId:h.id,subjectName:"chapter",type:R.actionChoice,actionType:f.action.type,payload:f.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:S.expect,action:u.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const g=l({chapterId:h.id,action:d.action,branches:h.branches});g&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:g})})}const u=({subjectId:h,subjectName:f,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:d?.type??S.expect})},b=({subjectId:h,subjectName:f})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:"after-expect"})},E=({subjectId:h,subjectName:f,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})},x=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type,payload:m})},V=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const I=window.open(m.URI,"_blank","noopener,noreferrer");I&&(I.opener=null),i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:u,expectEventHandler:b,setManifestChapterEvents:p,setManifestContainerEvents:c,stopExpect:r,state:s}};class H{constructor(e,t,n,s){this.target=e,this.type=t,this.listener=n,this.options=H.#a(e,s),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),s=Object.keys(t).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),H.#l(e)?t:t.capture||!1}}static#s=void 0;static#l(e){let t=H.#s;if(t===void 0){t=!1;try{const n={},s={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};e.addEventListener("test",r,n),e.removeEventListener("test",r,n)}catch{t=!1}H.#s=t}return t||!1}}class Oi{constructor(){this.bindingMap=new Si}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,s){if(!this.bindingMap)return;const r=new H(e,t,n,s);this.bindingMap.push(t,r)}listenOnce(e,t,n,s){const r=o=>{this.unlisten(e,t,r),n(o)};this.listen(e,t,r,s)}unlisten(e,t,n){if(!this.bindingMap)return;const s=this.bindingMap.get(t)||[];for(const r of s)r.target===e&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(t,r))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class Li{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let s=3;s<n;s+=40)if(t[s]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let s;t&&(s=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&s&&this.restore(s),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class ji{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
@@ -16,8 +16,8 @@ import{loadVKLangPack as ot,Subscription as ce,ValueSubject as ct,Observable as
16
16
  top: 50%;
17
17
  left: 50%;
18
18
  transform: translate(-50%, -50%);
19
- `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);const t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{const t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function Ni(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}const _i=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,lastFrame:!1}),M=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function Mi(){const i=document.createElement("div");return i.style.cssText=`
19
+ `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);const t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(s){this._onError(s)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{const t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function Ni(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}const _i=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,lastFrame:!1}),M=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function Mi(){const i=document.createElement("div");return i.style.cssText=`
20
20
  position: absolute;
21
21
  top: 0;
22
22
  left: 0;
23
- `,i}class Fi{#a=null;#s=null;#l=null;#h=null;#r=null;#o=null;#d=null;#t=null;#u=new ct(!1);#m=new Set;#n=null;#c=null;#y=null;#i=null;#e=null;constructor(e){this.options={..._i,...e},this.#s=[],this.factories=new Map([["choice",Xe]]),this.rootElement=Mi(),this.options.parentElement.append(this.rootElement),this.#e=new tt,this.#h=new ce,this.#l=new Oi,this.options.lastFrame&&(this.#i=new ji({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.SEAMLESS,t))})),this.#l.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.#l.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.#t=new si(this.options.loaders,t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.MANIFEST,t))),this.#r=Ve(this.options.player),this.#o=new Qt,this.#d=Fe({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#f}),this.#a=wi(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#i.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#n=new xt({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.#e.emit(y.graph,{type:je.watchAgainClicked,chapterId:t})},onError:t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.LOADERS,{message:t}))})),this.#c=new jt,this.#c.addEventListener(ae,this.#E),this.#e.on(y.interactives,t=>{if(t.type===R.actionExecution){if(t.payload?.behaviour==="change-chapter"){const{chapterId:n,autoSelect:r}=t.payload;this.setChapter({chapterId:n,autoSelect:r})}if(t.payload?.behaviour==="change-manifest"){const{manifestURL:n}=t.payload;this.setManifest(n)}}}),this.isFirstChapterFetched=!1,this.state=M.created}emitPlayerChanged=e=>{this.#e.emit(y.playerChanged,e)};async initSeamless({source:e,initialChapter:t,visitedChapters:n=[],videosInfo:r}){this.#y=ci(this);const s=document.createElement("div");this.#y.on(J.activePlayerChanged,this.emitPlayerChanged);const{player:o,config:a}=await this.#y.init({source:e,initialChapter:t,container:s});return this.setVisitedChapters(n),this.updateGraphVideosInfo(r),{player:o,config:a}}getStatEvents(){return{click$:new ge(e=>{this.#e.on(y.graph,({type:t,visibility:n})=>{t==="visibility"&&e.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),t==="watchAgainClicked"&&e.next(F.WATCH_AGAIN)}),this.#e.on(y.interactives,({type:t,subjectName:n,subjectType:r})=>{t!=="action-choice"||n!=="control"||(r==="Button"&&e.next(F.GO_NEXT_BUTTON),r==="Area"&&e.next(F.GO_NEXT_AREA))})}),nextMovie$:new ge(e=>{this.#e.on(y.playerChanged,({config:t})=>{t?.unitedVideoId&&e.next(t.unitedVideoId)})})}}setPlayer(e){this.#g(),this.options.player=e,D.setPlayer(this.options.player),this.#r?this.#r.setPlayer(this.options.player):this.#r=Ve(this.options.player),this.#d=Fe({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#f}),this.state===M.initiated&&(this.#v(),this.#p(this.#t.chapter))}async setManifest(e,t){this.#g(),this.isFirstChapterFetched=!1;const n=await this.#t.setManifest(e),r=t&&t.manifestId===n.manifest.metadata.id?{...t}:void 0;return this.#c.onManifestChange(n.manifest.metadata,r),this.#n&&await this.#n.handleManifestChange(n.manifest,r?Lt(r):[]),this.#e.emit(y.manifestChanged,{manifest:n.manifest}),this.#p(this.#t.chapter),n.manifest}setVisitedChapters(e){Array.isArray(e)&&this.#n?.setVisitedChapters(e)}updateGraphVideosInfo(e){Array.isArray(e)&&this.#n?.updateVideosInfo(e)}async setChapter({chapterId:e,autoSelect:t,tryContinueFromHistory:n=!1}={}){this.#g(),this.#i&&this.isFirstChapterFetched&&(this.#i.draw(),this.#i.show()),lt().browser===ht.Safari&&await Ni(35);let s;e?s=await this.#t.setNext(e):s=await(n?this.#t.setNext(Nt(this.#t.manifest,this.getHistory())):this.#t.setInitial());const{chapter:o,media:a,graph:c}=s;return this.#c.onChapterChange({chapterId:o.id,mediaId:a.id,autoSelect:t,isLastChapter:rt(o)}),this.#n&&this.#n.handleChapterChange(c),this.#i?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(y.chapterChanged,{chapter:o,media:a,graph:c}),this.#p(this.#t.chapter),this.#m=new Set,this.isFirstChapterFetched=!0,{chapter:o,media:a,graph:c}}toggleGraphView(e=!0){this.#n&&(e?(this.#n.show(),this.#u.next(!1)):(this.#n.hide(),this.#b()),this.#e.emit(y.graph,{type:je.visibility,visibility:e}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.state===M.created&&(this.#a.resizeObserver.observe(this.options.fullscreenTargetElement),this.#v(),this.state=M.initiated,this.#p(this.#t.chapter))}#g(){this.state===M.ready&&(this.#f(),this.#s=[],this.#o.release(),this.#r?.release(),this.state=M.initiated,this.#u.next(!1))}#I=()=>{this.#o.fns.forEach(n=>n());const e=this.options.player.info.position$.getValue()*1e3,t=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(e));for(const n of t){this.#r.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#r.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#s.find(r=>r.container.container.id===n.id).reset()}};#C=()=>{this.#a.calc(),this.#o.requestAnimation()};#w(e){(!this.#n||this.#n.isHidden)&&this.#b();const t=e*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>t>=s[1]);if(r){const s=r.range.join("-");this.#m.has(s)||(this.#m.add(s),this.#e.emit(y.interactives,{type:R.rangeEnded,payload:r,visibility:!0}))}}#v(){this.#h.unsubscribe(),this.#h.add(this.options.player.events.started$.pipe(dt()).subscribe(this.#C)).add(this.options.player.events.playing$.subscribe(this.#o.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#o.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#w.bind(this))),this.options.lastFrame&&this.#h.add(this.options.player.info.duration$.subscribe(e=>{this.#i.setVideoDuration(e*1e3)})).add(this.options.player.experimental.element$.subscribe(e=>{e&&this.#i.setVideoElement(e)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#i.reset(),setTimeout(()=>{this.#i.hide(),this.#i.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#i.onSeek))}#f=()=>{this.#s.forEach(e=>{this.#o.removeFn(e.whilePlaying),e.destroy()})};#p(e){this.#t.chapter&&this.state===M.initiated&&(this.#d.setManifestChapterEvents(e),this.#s=this.#S(e),this.#r.containersEventsCallState.setData(e.containers),D.setContainers(this.#s.map(t=>t.container.container)),this.options.lastFrame&&this.#o.addFn(()=>{this.#i.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.state=M.ready)}#S(e){return e?.containers?.reduce((t,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new mi({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#d,interactiveEvents:this.#r,globalEventEmitter:this.#e,ignoreContainerEvent:()=>pi(n,this.#s)});return this.#o.addFn(o.whilePlaying,!0),[...t,o]}return[...t]},[])??[]}#b(){const e=this.#u.getValue(),t=!!D.getNextInteractiveTime();(t&&!e||!t&&e)&&this.#u.next(!e)}isSupport(e=this.#t.manifest){return et(e.metadata.version)}getIsSeekable(){return this.#u}getHistory(){return this.#c.getHistory()}#E=({detail:e})=>{this.#e.emit(y.historyChanged,e)};getInteractiveRanges(){return fi(this.#t.chapter?.containers)}getNextInteractiveStartTime(e){return D.getNextInteractiveTime(e)}getChapterBranches(e){return this.#t.getBranches(e)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(e,t){this.factories.set(e.trim().toLowerCase(),t)}removeFactory(e){this.factories.delete(e.trim().toLowerCase())}on(...e){return this.#e.on(...e),this}off(...e){return this.#e.off(...e),this}once(...e){return this.#e.once(...e),this}destroy(){this.#f(),this.#s=void 0,this.#c.removeEventListener(ae,this.#E),this.#c.destroy(),this.#c=void 0,this.#n?.destroy(),this.#n=void 0,this.#a.release(),this.#a=void 0,this.#d=void 0,this.#o.release(),this.#o=void 0,this.#r.release(),this.#r=void 0,this.#t.release(),this.#d=void 0,this.#l.release(),this.#l=void 0,this.#h.unsubscribe(),this.#h=void 0,this.#e.reset(),this.#e=void 0,this.#i?.destroy(),this.#i=void 0,this.rootElement.remove(),this.rootElement=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.state=M.destroyed}}const Bi={Container:Qe,createChoiceContainer:Xe,createAreaControl:ze,createButtonControl:We,createRelativeLayout:Et,getRootEl:$e,classnamesPrefix:N},$i={version:ft};export{A as CustomError,y as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Fi as Interactives,si as ManifestController,$i as SDKInfo,ee as compareVersions,et as isSupportedManifest,Bi as utils};
23
+ `,i}class Pi{#a=null;#s=null;#l=null;#h=null;#r=null;#o=null;#d=null;#t=null;#u=new ct(!1);#m=new Set;#n=null;#c=null;#y=null;#i=null;#e=null;constructor(e){this.options={..._i,...e},this.#s=[],this.factories=new Map([["choice",Xe]]),this.rootElement=Mi(),this.options.parentElement.append(this.rootElement),this.#e=new tt,this.#h=new ce,this.#l=new Oi,this.options.lastFrame&&(this.#i=new ji({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.SEAMLESS,t))})),this.#l.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.#l.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.#t=new si(this.options.loaders,t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.MANIFEST,t))),this.#r=Ve(this.options.player),this.#o=new Qt,this.#d=Pe({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#f}),this.#a=wi(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#i.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#n=new xt({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.#e.emit(y.graph,{type:je.watchAgainClicked,chapterId:t})},onError:t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.LOADERS,{message:t}))})),this.#c=new jt,this.#c.addEventListener(ae,this.#E),this.#e.on(y.interactives,t=>{if(t.type===R.actionExecution){if(t.payload?.behaviour==="change-chapter"){const{chapterId:n,autoSelect:s}=t.payload;this.setChapter({chapterId:n,autoSelect:s})}if(t.payload?.behaviour==="change-manifest"){const{manifestURL:n}=t.payload;this.setManifest(n)}}}),this.isFirstChapterFetched=!1,this.state=M.created}emitPlayerChanged=e=>{this.#e.emit(y.playerChanged,e)};async initSeamless({source:e,initialChapter:t,visitedChapters:n=[],videosInfo:s}){this.#y=ci(this);const r=document.createElement("div");this.#y.on(J.activePlayerChanged,this.emitPlayerChanged);const{player:o,config:a}=await this.#y.init({source:e,initialChapter:t,container:r});return this.setVisitedChapters(n),this.updateGraphVideosInfo(s),{player:o,config:a}}getStatEvents(){return{click$:new ge(e=>{this.#e.on(y.graph,({type:t,visibility:n})=>{t==="visibility"&&e.next(n?P.OPEN_GRAPH:P.CLOSE_GRAPH),t==="watchAgainClicked"&&e.next(P.WATCH_AGAIN)}),this.#e.on(y.interactives,({type:t,subjectName:n,subjectType:s})=>{t!=="action-choice"||n!=="control"||(s==="Button"&&e.next(P.GO_NEXT_BUTTON),s==="Area"&&e.next(P.GO_NEXT_AREA))})}),nextMovie$:new ge(e=>{this.#e.on(y.playerChanged,({config:t})=>{t?.unitedVideoId&&e.next(t.unitedVideoId)})})}}setPlayer(e){this.#g(),this.options.player=e,D.setPlayer(this.options.player),this.#r?this.#r.setPlayer(this.options.player):this.#r=Ve(this.options.player),this.#d=Pe({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#f}),this.state===M.initiated&&(this.#v(),this.#p(this.#t.chapter))}async setManifest(e,t){this.#g(),this.isFirstChapterFetched=!1;const n=await this.#t.setManifest(e),s=t&&t.manifestId===n.manifest.metadata.id?{...t}:void 0;return this.#c.onManifestChange(n.manifest.metadata,s),this.#n&&await this.#n.handleManifestChange(n.manifest,s?Lt(s):[]),this.#e.emit(y.manifestChanged,{manifest:n.manifest}),this.#p(this.#t.chapter),n.manifest}setVisitedChapters(e){Array.isArray(e)&&this.#n?.setVisitedChapters(e)}updateGraphVideosInfo(e){Array.isArray(e)&&this.#n?.updateVideosInfo(e)}async setChapter({chapterId:e,autoSelect:t,tryContinueFromHistory:n=!1}={}){this.#g(),this.#i&&this.isFirstChapterFetched&&(this.#i.draw(),this.#i.show()),lt().browser===ht.Safari&&await Ni(35);let r;e?r=await this.#t.setNext(e):r=await(n?this.#t.setNext(Nt(this.#t.manifest,this.getHistory())):this.#t.setInitial());const{chapter:o,media:a,graph:c}=r;return this.#c.onChapterChange({chapterId:o.id,mediaId:a.id,autoSelect:t,isLastChapter:rt(o)}),this.#n&&this.#n.handleChapterChange(c),this.#i?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(y.chapterChanged,{chapter:o,media:a,graph:c}),this.#p(this.#t.chapter),this.#m=new Set,this.isFirstChapterFetched=!0,{chapter:o,media:a,graph:c}}toggleGraphView(e=!0){this.#n&&(e?(this.#n.show(),this.#u.next(!1)):(this.#n.hide(),this.#b()),this.#e.emit(y.graph,{type:je.visibility,visibility:e}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.state===M.created&&(this.#a.resizeObserver.observe(this.options.fullscreenTargetElement),this.#v(),this.state=M.initiated,this.#p(this.#t.chapter))}#g(){this.state===M.ready&&(this.#f(),this.#s=[],this.#o.release(),this.#r?.release(),this.state=M.initiated,this.#u.next(!1))}#I=()=>{this.#o.fns.forEach(n=>n());const e=this.options.player.info.position$.getValue()*1e3,t=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(e));for(const n of t){this.#r.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const s of n.controls)this.#r.remove({timestamp:1/0,priority:"control",initiator:s.id});this.#s.find(s=>s.container.container.id===n.id).reset()}};#C=()=>{this.#a.calc(),this.#o.requestAnimation()};#w(e){(!this.#n||this.#n.isHidden)&&this.#b();const t=e*1e3,s=this.getInteractiveRanges().findLast(({range:r})=>t>=r[1]);if(s){const r=s.range.join("-");this.#m.has(r)||(this.#m.add(r),this.#e.emit(y.interactives,{type:R.rangeEnded,payload:s,visibility:!0}))}}#v(){this.#h.unsubscribe(),this.#h.add(this.options.player.events.started$.pipe(dt()).subscribe(this.#C)).add(this.options.player.events.playing$.subscribe(this.#o.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#o.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#w.bind(this))),this.options.lastFrame&&this.#h.add(this.options.player.info.duration$.subscribe(e=>{this.#i.setVideoDuration(e*1e3)})).add(this.options.player.experimental.element$.subscribe(e=>{e&&this.#i.setVideoElement(e)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#i.reset(),setTimeout(()=>{this.#i.hide(),this.#i.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#i.onSeek))}#f=()=>{this.#s.forEach(e=>{this.#o.removeFn(e.whilePlaying),e.destroy()})};#p(e){this.#t.chapter&&this.state===M.initiated&&(this.#d.setManifestChapterEvents(e),this.#s=this.#S(e),this.#r.containersEventsCallState.setData(e.containers),D.setContainers(this.#s.map(t=>t.container.container)),this.options.lastFrame&&this.#o.addFn(()=>{this.#i.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.state=M.ready)}#S(e){return e?.containers?.reduce((t,n)=>{const s=n.type.trim().toLowerCase(),r=this.factories.get(s);if(r){const o=new mi({player:this.options.player,container:r(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#d,interactiveEvents:this.#r,globalEventEmitter:this.#e,ignoreContainerEvent:()=>pi(n,this.#s)});return this.#o.addFn(o.whilePlaying,!0),[...t,o]}return[...t]},[])??[]}#b(){const e=this.#u.getValue(),t=!!D.getNextInteractiveTime();(t&&!e||!t&&e)&&this.#u.next(!e)}isSupport(e=this.#t.manifest){return et(e.metadata.version)}getIsSeekable(){return this.#u}getHistory(){return this.#c.getHistory()}#E=({detail:e})=>{this.#e.emit(y.historyChanged,e)};getInteractiveRanges(){return fi(this.#t.chapter?.containers)}getNextInteractiveStartTime(e){return D.getNextInteractiveTime(e)}getChapterBranches(e){return this.#t.getBranches(e)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(e,t){this.factories.set(e.trim().toLowerCase(),t)}removeFactory(e){this.factories.delete(e.trim().toLowerCase())}on(...e){return this.#e.on(...e),this}off(...e){return this.#e.off(...e),this}once(...e){return this.#e.once(...e),this}destroy(){this.#f(),this.#s=void 0,this.#c.removeEventListener(ae,this.#E),this.#c.destroy(),this.#c=void 0,this.#n?.destroy(),this.#n=void 0,this.#a.release(),this.#a=void 0,this.#d=void 0,this.#o.release(),this.#o=void 0,this.#r.release(),this.#r=void 0,this.#t.release(),this.#d=void 0,this.#l.release(),this.#l=void 0,this.#h.unsubscribe(),this.#h=void 0,this.#e.reset(),this.#e=void 0,this.#i?.destroy(),this.#i=void 0,this.rootElement.remove(),this.rootElement=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.state=M.destroyed}}const Bi={Container:Qe,createChoiceContainer:Xe,createAreaControl:Ge,createButtonControl:We,createRelativeLayout:Et,getRootEl:$e,classnamesPrefix:N},$i={version:ft};export{A as CustomError,y as EVENT_NAMES,P as INTERACTIVE_CLICK_ACTIONS,Pi as Interactives,si as ManifestController,$i as SDKInfo,ee as compareVersions,et as isSupportedManifest,Bi as utils};