@vkontakte/videoplayer-interactive 1.0.6-dev.5a11a96.0 → 1.0.6-dev.9aa76b8.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.cjs.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.6-dev.5a11a96.0
3
- * Tue, 12 Dec 2023 11:20:59 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.6-dev.9aa76b8.0
3
+ * Tue, 12 Dec 2023 10:50:05 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-6/doc/
5
5
  */
6
- "use strict";var ot=Object.create;var ge=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ut=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lt(e))!dt.call(i,s)&&s!==t&&ge(i,s,{get:()=>e[s],enumerable:!(n=ct(e,s))||n.enumerable});return i};var ft=(i,e,t)=>(t=i!=null?ot(ht(i)):{},ut(e||!i||!i.__esModule?ge(t,"default",{value:i,enumerable:!0}):t,i));var j=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),ce=require("uuid"),pt=require("@vkontakte/videoplayer-core/esnext.cjs.js");const mt="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 _="SDK_NAME",yt="SDK_NAME-controls-container",$e=()=>document.querySelector(`.${yt}`),V={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"},Ce={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=Ce[e?.text?.alignment]??Ce.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})`},le=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class he{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${_}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.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(`.${_}-control-container-${this.control.id}`)}}const Ge=i=>{if(i.type.trim().toLowerCase()==="area")return new gt(i)};class gt extends he{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(`${_}-${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:{...V,backgroundColor:"transparent"}}),ze({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),le({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new vt(i)};class vt extends he{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(`${_}-${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",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),Ue({target:r,props:this.control.props,fallback:V}),ze({target:r,props:this.control.props,fallback:V,dependsOn:n}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const bt=i=>{if(i.type.trim().toLowerCase()==="text")return new Ct(i)};class Ct extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${_}-${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",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}class Et{constructor(e){this.layout=e}}const wt=i=>{if(i.type.trim().toLowerCase()==="relative")return new qe(i)};class qe extends Et{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 Ke=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new It(i,e)};class It 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",bt),this.addControlFactory("area",Ge)}createView(e){const t=document.createElement("div");return t.classList.add(`${_}-${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(`.${_}-${this.container.id}`)}}function Xe(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const q={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,de=i=>z(i,q.Object),re=i=>z(i,q.String),U=i=>z(i,q.Array),Ze=i=>z(i,q.Number),St=i=>z(i,q.Function),Ee=i=>Ze(i)&&!isNaN(i),Tt=i=>i==null,G=i=>de(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(),Rt=/mobi/i.test(Je);Je.indexOf("android")>-1;const At="video_interactive",xt="videoint",Ot=250;class Lt{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=Nt(e),this.resizeObserver=new ResizeObserver(Xe(this.onResize,Ot)),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(!Ze(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 j.loadVKLangPack(this.lang,At,xt)}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 Nt(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 _t=(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),[]),Ie="chapterId";class ${constructor(e){this.id=e?.id??ce.v4(),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),Ie):[],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],Ie)),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??ce.v4(),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;Tt(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 Vt(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 W=(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},Mt="3.1",Se={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},kt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ft=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=[kt];switch(a){case"await":l?p=[]:r=[];break;case"default":{const u={type:"onSuspense",action:{type:Se.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:Se[a],args:{}}};l?p=[u]:r=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:ce.v4(),events:p})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=Mt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Pt="3.2",Bt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Pt},media:e}}return i},$t="3.3",Dt=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ht=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:Dt(t),metadata:{...i.metadata,version:$t}}},Ut=[{version:"3.0",migrate:Ft},{version:"3.1",migrate:Bt},{version:"3.2",migrate:Ht}],zt=i=>Ut.reduce((e,t)=>W(e.metadata.version,t.version)?e:t.migrate(e),i),Gt=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});exports.INTERACTIVE_CLICK_ACTIONS=void 0;(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"})(exports.INTERACTIVE_CLICK_ACTIONS||(exports.INTERACTIVE_CLICK_ACTIONS={}));const Re={metadata:"Object",chapters:"Array"},Wt="3.0.0",qt="3.3.0",ue=i=>{const e=W(i,Wt);return e===-1?!1:e===0?!0:W(i,qt)!==1},Qt=i=>{if(!de(i))return!1;for(const e in Re)if(!i[e]||!z(i[e],Re[e]))return!1;return ue(i.metadata.version)},Kt=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 et{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 Xt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{St(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 Zt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Yt(...this.loaders[e])(t)}}function Yt(...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 tt 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 Jt{constructor(){Object.defineProperty(this,"signal",{value:new tt,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&&(Jt.prototype[Symbol.toStringTag]="AbortController",tt.prototype[Symbol.toStringTag]="AbortSignal");function it(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 ei(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!it({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((C,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=it({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),nt=fe?ei({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xe=fe?nt.fetch:window.fetch;fe?nt.Request:window.Request;const ti=async i=>{try{let e,t;if(de(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(!Qt(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 ri(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ii(i){const{manifest:e,manifestURL:t}=await ti(i),n=zt(e);return n.media=ni(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 ni(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=si(n.url,e);return{...n,url:s||n.url}})}))}}function si(i,e){try{return new URL(i,e).href}catch{return""}}function ri(i){return W(i,"3.2.0")>=0}class st extends Zt{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 ii(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"},Ne={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ai(){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 _e(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 Y=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},oi=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[]},ee={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ci=2;function li(i){const e=ai();let t,n;const s=new et;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 E=(e.map.get(d)??{})[g];if(E){r={chapterId:m,listId:d,itemId:g,...E};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:N})=>{v.info.isAutoQualityEnabled$.getValue()||Y(N,w)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),s.emit(ee.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 E=a.getChapterBranches();o=!0;const v=new Set;for(const w of E)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 C({chapter:{id:d},media:g}){if(G(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),S=r.player.info.currentQuality$.getValue(),E=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),w=r.player.info.currentPlaybackRate$.getValue(),L=!E;let N=!1;for(const O of e.map)if(O[0]===g.id){const Q=Object.keys(O[1]);for(const F of Q)F===r.itemId?(Q.length<ci||(N=!0),e.removePlayer(O[0],F)):(N=!0,u(O[0],F,d),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m),r.player.setPlaybackRate(w))}else e.removePlayer(O[0]);N||(await x({media:g,chapterId:d,setAsActive:!0,playbackRate:w}),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m))}async function x({media:d,chapterId:g,prefetch:m=!0,setAsActive:S=!0,autoplay:E=!1,preferredExt:v,title:w,playbackRate:L}){const N=Math.random().toString(),O=document.createElement("div");l.append(O);const Q=r?.player?.info.isAutoQualityEnabled$.getValue();let F;if(a?.options?.vkVideoLoader){const K=oi(d);K.length&&(F=await a.options.vkVideoLoader(...K))}const me={container:O,...F?.videos?.[0]||{sources:_e(d,v).sources},title:w},P=new pt.Player;P.initVideo(me);const at=O.lastChild,ye=new j.Subscription;ye.add(P.info.position$.subscribe(function(K){b(N,P.info.duration$.getValue(),K)})).add(P.events.canplay$.subscribe(function(){Q||Y(P,t),L&&P.setPlaybackRate(L)})),at&&(O.style.display="none",O.classList.add(g));const B=e.createPlayer({listId:d.id,itemId:N,player:P,container:O,sources:_e(d,v).sources,config:me,subscription:ye});return S&&u(d.id,B.itemId,g),E&&B.player.play(),m&&!E&&B.player.prepare(),s.emit(ee.playerCreated,B.player),{player:B.player,config:B.config}}function k(){h(),a=null}function h(){a?.off(y.chapterChanged,C),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:S,chapter:E}=await a.setChapter({chapterId:g});if(S){a.on(y.chapterChanged,C);const{player:v,config:w}=await x({media:S,chapterId:E.id,title:E.label});return s.emit(ee.initiated,{container:m,media:S,chapterId:E.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:k,getActivePlayer:function(){return r}}}const hi=3e3,di=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=hi)=>{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=di(),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",ui=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t<(e.startTime??0)},je=(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"),Ve=i=>i.find(e=>e.action.type==="expect"),fi=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),pi=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!Kt(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 C=e[b];if(u.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=r[0]&&C.range[1]>=r[1])return e[b].subjects.push(o),e;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[1]=C.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]),mi=(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 yi{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 j.Subscription,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=fi({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(ui(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(je(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=je(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 gi(){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(Ee(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(Ee(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 vi=[I.expect,I.setNextBranch],bi=1/0;function Me(i){let e=i,t;const n=Ci(),s=new gi;let r;const o=()=>{u(),k()},a=h=>{s.add.call(void 0,h),b()},c=(h=[])=>{for(const f of h)if(f.action(),vi.includes(f.actionType))break},l=h=>{if(!n.isReady(h))return;const f=J(s.get({timestamp:h,priority:"control"})??{}),d=J(s.get({timestamp:h,priority:"container"})??{}),g=J(s.get({timestamp:h,priority:"chapter"})??{});c([...f,...d,...g])},p=()=>{c([...J(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))},C=h=>{u(),e=h},x=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},k=()=>{n.release(),s.removeAll()};return{setPlayer:C,add:a,remove:x,exec:l,execEndOfVideo:p,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function Ci(){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??bi,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 J(i){return Object.values(i).flat().sort(e=>e.actionType===I.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}},wi=250;function Ii(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=Xe(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},wi);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 Ti=i=>Math.floor(Math.random()*i),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=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},xi=i=>{const e=i.length,t=Ti(e);return i[t]},ke=1,Oi=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:S,isEOV:E=()=>!1})=>{const v=se(h,E()),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 I.setNextBranch.trim().toLowerCase():{const N=m.find(O=>O.id===v.args.branchId);if(!N)return;S(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:N.chapterId,autoSelect:!1}}):(t.add({...w,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:f,action:h}):t.add({...w,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:h})});return}case I.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?k({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}}):(t.add({...w,action:k.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:S=!1})=>{const E=se(h,m),v={timestamp:!E.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:f,actionType:E.type},w=i.emit.bind(i,y.interactives,{subjectId:f,subjectName:"container",type:R.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const L=g.find(N=>N.id===E.args.branchId);if(!L)return;w(),t.add({...v,action:x.bind(null,{subjectId:f,subjectName:"container",action:E,payload:{chapterId:L.chapterId,autoSelect:S}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{w(),t.add({...v,action:C.bind(null,{subjectId:f,subjectName:"container",action:E})});return}case I.openURI.trim().toLowerCase():{w(),t.add({...v,action:k.bind(null,{subjectId:f,subjectName:"container",action:E,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=Ve(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:I.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 I.setNextBranch.trim().toLowerCase():{const m=d.find(S=>S.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 I.setWeightlessRandomBranch.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 I.setRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.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 I.setMinWeightBranch.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 I.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:h,subjectName:"chapter",action:f});case I.openURI.trim().toLowerCase():return g(),k.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=Ve(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:I.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??I.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"})},C=({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})},k=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const S=window.open(m.URI,"_blank","noopener,noreferrer");S&&(S.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 Li{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 Ni{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 _i{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
+ "use strict";var ot=Object.create;var ge=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ut=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lt(e))!dt.call(i,s)&&s!==t&&ge(i,s,{get:()=>e[s],enumerable:!(n=ct(e,s))||n.enumerable});return i};var ft=(i,e,t)=>(t=i!=null?ot(ht(i)):{},ut(e||!i||!i.__esModule?ge(t,"default",{value:i,enumerable:!0}):t,i));var j=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),ce=require("uuid"),pt=require("@vkontakte/videoplayer-core/esnext.cjs.js");const mt="1.0.6-dev.9aa76b8.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 _="SDK_NAME",yt="SDK_NAME-controls-container",$e=()=>document.querySelector(`.${yt}`),V={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"},Ce={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=Ce[e?.text?.alignment]??Ce.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})`},le=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class he{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${_}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.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(`.${_}-control-container-${this.control.id}`)}}const Ge=i=>{if(i.type.trim().toLowerCase()==="area")return new gt(i)};class gt extends he{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(`${_}-${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:{...V,backgroundColor:"transparent"}}),ze({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),le({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new vt(i)};class vt extends he{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(`${_}-${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",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),Ue({target:r,props:this.control.props,fallback:V}),ze({target:r,props:this.control.props,fallback:V,dependsOn:n}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const bt=i=>{if(i.type.trim().toLowerCase()==="text")return new Ct(i)};class Ct extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${_}-${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",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}class Et{constructor(e){this.layout=e}}const wt=i=>{if(i.type.trim().toLowerCase()==="relative")return new qe(i)};class qe extends Et{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 Ke=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new It(i,e)};class It 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",bt),this.addControlFactory("area",Ge)}createView(e){const t=document.createElement("div");return t.classList.add(`${_}-${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(`.${_}-${this.container.id}`)}}function Xe(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const q={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,de=i=>z(i,q.Object),re=i=>z(i,q.String),U=i=>z(i,q.Array),Ze=i=>z(i,q.Number),St=i=>z(i,q.Function),Ee=i=>Ze(i)&&!isNaN(i),Tt=i=>i==null,G=i=>de(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(),Rt=/mobi/i.test(Je);Je.indexOf("android")>-1;const At="video_interactive",xt="videoint",Ot=250;class Lt{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=Nt(e),this.resizeObserver=new ResizeObserver(Xe(this.onResize,Ot)),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(!Ze(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 j.loadVKLangPack(this.lang,At,xt)}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 Nt(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 _t=(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),[]),Ie="chapterId";class ${constructor(e){this.id=e?.id??ce.v4(),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),Ie):[],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],Ie)),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??ce.v4(),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;Tt(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 Vt(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 W=(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},Mt="3.1",Se={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},kt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ft=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=[kt];switch(a){case"await":l?p=[]:r=[];break;case"default":{const u={type:"onSuspense",action:{type:Se.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:Se[a],args:{}}};l?p=[u]:r=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:ce.v4(),events:p})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=Mt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Pt="3.2",Bt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Pt},media:e}}return i},$t="3.3",Dt=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ht=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:Dt(t),metadata:{...i.metadata,version:$t}}},Ut=[{version:"3.0",migrate:Ft},{version:"3.1",migrate:Bt},{version:"3.2",migrate:Ht}],zt=i=>Ut.reduce((e,t)=>W(e.metadata.version,t.version)?e:t.migrate(e),i),Gt=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});exports.INTERACTIVE_CLICK_ACTIONS=void 0;(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"})(exports.INTERACTIVE_CLICK_ACTIONS||(exports.INTERACTIVE_CLICK_ACTIONS={}));const Re={metadata:"Object",chapters:"Array"},Wt="3.0.0",qt="3.3.0",ue=i=>{const e=W(i,Wt);return e===-1?!1:e===0?!0:W(i,qt)!==1},Qt=i=>{if(!de(i))return!1;for(const e in Re)if(!i[e]||!z(i[e],Re[e]))return!1;return ue(i.metadata.version)},Kt=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 et{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 Xt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{St(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 Zt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Yt(...this.loaders[e])(t)}}function Yt(...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 tt 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 Jt{constructor(){Object.defineProperty(this,"signal",{value:new tt,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&&(Jt.prototype[Symbol.toStringTag]="AbortController",tt.prototype[Symbol.toStringTag]="AbortSignal");function it(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 ei(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!it({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((C,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=it({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),nt=fe?ei({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xe=fe?nt.fetch:window.fetch;fe?nt.Request:window.Request;const ti=async i=>{try{let e,t;if(de(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(!Qt(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 ri(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ii(i){const{manifest:e,manifestURL:t}=await ti(i),n=zt(e);return n.media=ni(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 ni(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=si(n.url,e);return{...n,url:s||n.url}})}))}}function si(i,e){try{return new URL(i,e).href}catch{return""}}function ri(i){return W(i,"3.2.0")>=0}class st extends Zt{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 ii(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"},Ne={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ai(){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 _e(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 Y=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},oi=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[]},ee={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ci=2;function li(i){const e=ai();let t,n;const s=new et;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 E=(e.map.get(d)??{})[g];if(E){r={chapterId:m,listId:d,itemId:g,...E};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:N})=>{v.info.isAutoQualityEnabled$.getValue()||Y(N,w)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),s.emit(ee.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 E=a.getChapterBranches();o=!0;const v=new Set;for(const w of E)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 C({chapter:{id:d},media:g}){if(G(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),S=r.player.info.currentQuality$.getValue(),E=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),w=r.player.info.currentPlaybackRate$.getValue(),L=!E;let N=!1;for(const O of e.map)if(O[0]===g.id){const Q=Object.keys(O[1]);for(const F of Q)F===r.itemId?(Q.length<ci||(N=!0),e.removePlayer(O[0],F)):(N=!0,u(O[0],F,d),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m),r.player.setPlaybackRate(w))}else e.removePlayer(O[0]);N||(await x({media:g,chapterId:d,setAsActive:!0,playbackRate:w}),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m))}async function x({media:d,chapterId:g,prefetch:m=!0,setAsActive:S=!0,autoplay:E=!1,preferredExt:v,title:w,playbackRate:L}){const N=Math.random().toString(),O=document.createElement("div");l.append(O);const Q=r?.player?.info.isAutoQualityEnabled$.getValue();let F;if(a?.options?.vkVideoLoader){const K=oi(d);K.length&&(F=await a.options.vkVideoLoader(...K))}const me={container:O,...F?.videos?.[0]||{sources:_e(d,v).sources},title:w},P=new pt.Player;P.initVideo(me);const at=O.lastChild,ye=new j.Subscription;ye.add(P.info.position$.subscribe(function(K){b(N,P.info.duration$.getValue(),K)})).add(P.events.canplay$.subscribe(function(){Q||Y(P,t),L&&P.setPlaybackRate(L)})),at&&(O.style.display="none",O.classList.add(g));const B=e.createPlayer({listId:d.id,itemId:N,player:P,container:O,sources:_e(d,v).sources,config:me,subscription:ye});return S&&u(d.id,B.itemId,g),E&&B.player.play(),m&&!E&&B.player.prepare(),s.emit(ee.playerCreated,B.player),{player:B.player,config:B.config}}function k(){h(),a=null}function h(){a?.off(y.chapterChanged,C),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:S,chapter:E}=await a.setChapter({chapterId:g});if(S){a.on(y.chapterChanged,C);const{player:v,config:w}=await x({media:S,chapterId:E.id,title:E.label});return s.emit(ee.initiated,{container:m,media:S,chapterId:E.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:k,getActivePlayer:function(){return r}}}const hi=3e3,di=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=hi)=>{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=di(),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",ui=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t<(e.startTime??0)},je=(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"),Ve=i=>i.find(e=>e.action.type==="expect"),fi=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),pi=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!Kt(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 C=e[b];if(u.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=r[0]&&C.range[1]>=r[1])return e[b].subjects.push(o),e;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[1]=C.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]),mi=(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 yi{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 j.Subscription,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=fi({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(ui(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(je(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=je(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 gi(){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(Ee(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(Ee(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 vi=[I.expect,I.setNextBranch],bi=1/0;function Me(i){let e=i,t;const n=Ci(),s=new gi;let r;const o=()=>{u(),k()},a=h=>{s.add.call(void 0,h),b()},c=(h=[])=>{for(const f of h)if(f.action(),vi.includes(f.actionType))break},l=h=>{if(!n.isReady(h))return;const f=J(s.get({timestamp:h,priority:"control"})??{}),d=J(s.get({timestamp:h,priority:"container"})??{}),g=J(s.get({timestamp:h,priority:"chapter"})??{});c([...f,...d,...g])},p=()=>{c([...J(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))},C=h=>{u(),e=h},x=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},k=()=>{n.release(),s.removeAll()};return{setPlayer:C,add:a,remove:x,exec:l,execEndOfVideo:p,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function Ci(){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??bi,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 J(i){return Object.values(i).flat().sort(e=>e.actionType===I.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}},wi=250;function Ii(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=Xe(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},wi);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 Ti=i=>Math.floor(Math.random()*i),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=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},xi=i=>{const e=i.length,t=Ti(e);return i[t]},ke=1,Oi=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:S,isEOV:E=()=>!1})=>{const v=se(h,E()),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 I.setNextBranch.trim().toLowerCase():{const N=m.find(O=>O.id===v.args.branchId);if(!N)return;S(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:N.chapterId,autoSelect:!1}}):(t.add({...w,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:f,action:h}):t.add({...w,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:h})});return}case I.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?k({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}}):(t.add({...w,action:k.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:S=!1})=>{const E=se(h,m),v={timestamp:!E.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:f,actionType:E.type},w=i.emit.bind(i,y.interactives,{subjectId:f,subjectName:"container",type:R.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const L=g.find(N=>N.id===E.args.branchId);if(!L)return;w(),t.add({...v,action:x.bind(null,{subjectId:f,subjectName:"container",action:E,payload:{chapterId:L.chapterId,autoSelect:S}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{w(),t.add({...v,action:C.bind(null,{subjectId:f,subjectName:"container",action:E})});return}case I.openURI.trim().toLowerCase():{w(),t.add({...v,action:k.bind(null,{subjectId:f,subjectName:"container",action:E,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=Ve(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:I.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 I.setNextBranch.trim().toLowerCase():{const m=d.find(S=>S.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 I.setWeightlessRandomBranch.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 I.setRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.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 I.setMinWeightBranch.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 I.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:h,subjectName:"chapter",action:f});case I.openURI.trim().toLowerCase():return g(),k.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=Ve(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:I.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??I.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"})},C=({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})},k=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const S=window.open(m.URI,"_blank","noopener,noreferrer");S&&(S.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 Li{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 Ni{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 _i{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;
package/esnext.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.6-dev.5a11a96.0
3
- * Tue, 12 Dec 2023 11:20:59 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.6-dev.9aa76b8.0
3
+ * Tue, 12 Dec 2023 10:50:05 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-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=`
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.9aa76b8.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;