@oddin-gg/havik-player 1.0.2

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/dist/index.cjs ADDED
@@ -0,0 +1,108 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("hls.js");c=s(c,1);var l=class extends Error{code;httpStatus;retryAfterMs;requestId;serverCode;liveStartsAtMs;constructor(e,t,n,r){super(n),this.name=`PlaybackError`,this.code=e,this.httpStatus=t,this.retryAfterMs=r?.retryAfterMs,this.requestId=r?.requestId,this.serverCode=r?.serverCode,this.liveStartsAtMs=r?.liveStartsAtMs,r?.cause!==void 0&&(this.cause=r.cause)}};function u(e){switch(e){case 400:return`INVALID_URN`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 410:return`GONE`;case 425:return`TOO_EARLY`;case 429:return`RATE_LIMITED`;case 503:return`UNAVAILABLE`;default:return`INTERNAL`}}var d=new Set([`TOO_EARLY`,`UNAVAILABLE`,`RATE_LIMITED`,`NETWORK`]);function f(e){return d.has(e)}async function p(e){let t=typeof e==`function`?await e():e;if(!t||!t.apiKey)throw Error(`havik-player: credential is missing an apiKey`);return t}function m(e,t){let n=e.replace(/\/+$/,``),r;try{r=new URL(n+t)}catch{throw new l(`INTERNAL`,0,`invalid baseUrl: ${JSON.stringify(e)}`)}if(r.protocol!==`https:`&&r.protocol!==`http:`)throw new l(`INTERNAL`,0,`baseUrl must be http(s), got: ${JSON.stringify(e)}`);return r.toString()}function ee(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.round(t*1e3));let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}async function h(e,t){let n=await p(t.credential),r=t.headers??new Headers;r.set(`x-api-key`,n.apiKey);try{return await fetch(e,{method:t.method??`GET`,headers:r,body:t.body,signal:t.signal,cache:`no-store`,credentials:`omit`,mode:`cors`})}catch(e){throw t.signal?.aborted?new l(`ABORTED`,0,`request aborted`,{cause:e}):new l(`NETWORK`,0,`network request failed: ${te(e)}`,{cause:e})}}function te(e){return e instanceof Error?e.message:String(e)}var ne=1e3,re=3e4,g=600*1e3,_=300*1e3,v=1e3,y={TOO_EARLY:`tooEarly`,UNAVAILABLE:`unavailable`,RATE_LIMITED:`rateLimited`,NETWORK:`network`};function b(e){let t=e===!0||e===!1?{}:e,n=Math.max(v,t.floorMs??ne),r=Math.max(n,t.ceilMs??re),i=Math.max(0,t.imminentMs??g),a=Math.max(r,t.sanityFloorMs??_);return{timeoutMs:t.timeoutMs,floorMs:n,ceilMs:r,imminentMs:i,sanityFloorMs:a,kickoffMs:x(t.kickoffAt),jitter:t.jitter??!0,onState:t.onState}}function x(e){if(e==null)return;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function ie(e,t,n){return Math.min(n,Math.max(t,e))}function ae(e){return Math.round(e*(1+.15*Math.random()))}function oe(e,t,n,r){let i=r??n.kickoffMs,a=i==null?void 0:Math.max(0,i-t),o=Math.max(n.floorMs,e??0);if(a==null||a<=n.imminentMs)return{delay:ie(e??n.floorMs,o,n.ceilMs),ttkMs:a};let s=Math.min(Math.floor(a/10),n.sanityFloorMs,a);return{delay:Math.max(o,s),ttkMs:a}}function se(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new l(`ABORTED`,0,`wait-for-live aborted`));return}let i=()=>{clearTimeout(a),r(new l(`ABORTED`,0,`wait-for-live aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function S(e,t,n){let r=b(t),i=Date.now(),a=r.timeoutMs==null?1/0:i+r.timeoutMs,o=0,s;for(;;){if(n?.aborted)throw new l(`ABORTED`,0,`wait-for-live aborted`);try{return await e()}catch(e){if(!(e instanceof l)||!f(e.code))throw e;o+=1,e.liveStartsAtMs!=null&&Number.isFinite(e.liveStartsAtMs)&&(s=e.liveStartsAtMs);let t=Date.now(),c=oe(e.retryAfterMs,t,r,s),u=c.ttkMs,d=c.delay;if(r.jitter&&(d=ae(d)),t+d>a)throw new l(`TIMEOUT`,e.httpStatus,`timed out after ${r.timeoutMs}ms waiting for the stream to go live`,{retryAfterMs:e.retryAfterMs,cause:e});r.onState?.({phase:y[e.code]??`unavailable`,retryInMs:d,attempt:o,elapsedMs:t-i,ttkMs:u}),await se(d,n)}}}async function C(e){if(!e.matchUrn||typeof e.matchUrn!=`string`)throw new l(`INVALID_URN`,0,`resolveStream: a non-empty matchUrn is required`);let t=await h(m(e.baseUrl,`/v1/playback/${encodeURIComponent(e.matchUrn)}`),{credential:e.credential,signal:e.signal});if(!t.ok)throw await ce(t);return ue(await t.json(),e.matchUrn)}function w(e){let t=()=>C(e);return e.waitForLive?S(t,e.waitForLive,e.signal):t()}async function ce(e){let t=ee(e.headers.get(`retry-after`)),n=e.headers.get(`x-request-id`)??e.headers.get(`x-amzn-requestid`)??void 0,r=e.statusText||`HTTP ${e.status}`,i,a;try{let t=await e.json();if(t?.error?.message&&(r=t.error.message),t?.error?.code&&(i=t.error.code),typeof t?.liveStartsAt==`string`){let e=Date.parse(t.liveStartsAt);Number.isFinite(e)&&(a=e)}}catch{}return new l(u(e.status),e.status,r,{retryAfterMs:t,requestId:n,serverCode:i,liveStartsAtMs:a})}var le=new Set([`matchUrn`,`protocol`,`drmEnabled`,`manifestUrl`,`drm`,`serverTime`,`liveStartsAt`,`expiresAt`]);function T(e,t){let n;try{n=new URL(t)}catch{throw new l(`INTERNAL`,0,`playback ${e} is not a valid URL`)}if(n.protocol!==`https:`&&n.protocol!==`http:`)throw new l(`INTERNAL`,0,`playback ${e} has a disallowed scheme: ${n.protocol}`);return t}function ue(e,t){if(!e.manifestUrl)throw new l(`INTERNAL`,0,`playback response is missing manifestUrl`);let n=e.drmEnabled??!!e.drm,r={matchUrn:e.matchUrn??t,protocol:`hls`,drmEnabled:n,manifestUrl:T(`manifestUrl`,e.manifestUrl),serverTime:e.serverTime??``};if(e.liveStartsAt&&(r.liveStartsAt=e.liveStartsAt),n&&e.drm){let t={};e.drm.widevine?.licenseUrl&&(t.widevine={licenseUrl:T(`widevine licenseUrl`,e.drm.widevine.licenseUrl)}),e.drm.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&(t.fairplay={licenseUrl:T(`fairplay licenseUrl`,e.drm.fairplay.licenseUrl),certificateUrl:T(`fairplay certificateUrl`,e.drm.fairplay.certificateUrl)}),(t.widevine||t.fairplay)&&(r.drm=t)}let i={};for(let[t,n]of Object.entries(e))le.has(t)||(i[t]=n);return Object.keys(i).length>0&&(r.extensions=i),r}async function E(e){let t=new URLSearchParams;e.status&&t.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e.sport&&t.set(`sport`,e.sport);let n=t.toString(),r=m(e.baseUrl,`/v1/catalog`+(n?`?${n}`:``)),i=new Headers;e.etag&&i.set(`If-None-Match`,e.etag);let a=await h(r,{credential:e.credential,signal:e.signal,headers:i});if(a.status===304)return{tournaments:[],etag:e.etag,notModified:!0};if(!a.ok)throw new l(u(a.status),a.status,`catalog request failed (HTTP ${a.status})`);return{tournaments:D(await a.json()),etag:a.headers.get(`etag`)??void 0,notModified:!1}}function D(e){return(e.tournaments??[]).map(e=>{let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:e.status??`upcoming`,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r}))}})}async function O(e){let t=m(e.baseUrl,`/v1/tournaments/${encodeURIComponent(e.urn)}`),n=new Headers;e.etag&&n.set(`If-None-Match`,e.etag);let r=await h(t,{credential:e.credential,signal:e.signal,headers:n});if(r.status===304)return{etag:e.etag,notModified:!0,notFound:!1};if(r.status===404)return{notModified:!1,notFound:!0};if(!r.ok)throw new l(u(r.status),r.status,`tournament request failed (HTTP ${r.status})`);return{tournament:k(await r.json()),etag:r.headers.get(`etag`)??void 0,notModified:!1,notFound:!1}}function k(e){let t=e.urn??``,n=e.name??``,r=e.sport??``;return{urn:t,name:n,sport:r,isOffline:!!e.isOffline,matches:(e.matches??[]).map(e=>({matchUrn:e.matchUrn??``,matchName:e.matchName??``,status:e.status??`upcoming`,datePlannedStart:e.datePlannedStart,tournamentUrn:t,tournamentName:n,sport:r}))}}function A(e){return e.tournaments.flatMap(e=>e.matches)}function j(e){let t=Math.max(2e3,e.intervalMs??1e4),n=new AbortController,r,i,a,o=!1,s=()=>{o||(r=setTimeout(c,t))},c=async()=>{try{let t=m(e.baseUrl,`/v1/matches/${encodeURIComponent(e.matchUrn)}`),r=new Headers;i&&r.set(`If-None-Match`,i);let o=await h(t,{credential:e.credential,signal:n.signal,headers:r});if(o.status!==304){if(!o.ok)throw new l(u(o.status),o.status,`match status request failed (HTTP ${o.status})`);i=o.headers.get(`etag`)??i;let t=await o.json(),n=t.status??`upcoming`;n!==a&&(a=n,e.onChange({matchUrn:t.matchUrn??e.matchUrn,matchName:t.matchName,status:n,datePlannedStart:t.datePlannedStart}))}}catch(t){n.signal.aborted||e.onError?.(t instanceof l?t:new l(`NETWORK`,0,String(t)))}finally{s()}};return c(),{stop(){o=!0,n.abort(),r&&clearTimeout(r)}}}function M(e){let t=Math.max(250,e.minBackoffMs??1e3),n=Math.max(t,e.maxBackoffMs??15e3),r=new AbortController,i=!1,a=e=>new Promise(t=>{if(r.signal.aborted)return t();let n=setTimeout(t,e);r.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),o=t=>{e.onAlive?.();let n=`message`,r=[];for(let e of t.split(`
2
+ `)){let t=e.endsWith(`\r`)?e.slice(0,-1):e;if(t===``||t.startsWith(`:`))continue;let i=t.indexOf(`:`),a=i<0?t:t.slice(0,i),o=i<0?``:t.slice(i+1);o.startsWith(` `)&&(o=o.slice(1)),a===`event`?n=o:a===`data`&&r.push(o)}if(!(n!==`state`||r.length===0))try{let t=JSON.parse(r.join(`
3
+ `));t&&typeof t.state==`string`&&e.onState(t)}catch{}},s=/\r\n\r\n|\n\n|\r\r/,c=async(e,t)=>{let n=e.getReader(),r=new TextDecoder,a=``,c=!1;try{for(;;){let{value:e,done:l}=await n.read();if(l)return;!c&&e&&e.length>0&&(c=!0,t()),a+=r.decode(e,{stream:!0});let u;for(;(u=s.exec(a))!==null;)o(a.slice(0,u.index)),a=a.slice(u.index+u[0].length);if(i)return}}finally{await n.cancel().catch(()=>{})}};return(async()=>{let o=t;for(;!i;){try{let n=await p(e.credential);if(i)return;let a=m(e.eventsBaseUrl,`/v1/events/${encodeURIComponent(e.matchUrn)}`),s=await fetch(a,{method:`GET`,headers:{"x-api-key":n.apiKey,accept:`text/event-stream`},signal:r.signal,cache:`no-store`,credentials:`omit`,mode:`cors`});if(i)return;!s.ok||!s.body?e.onError?.(Error(`live-state subscribe failed: HTTP ${s.status}`)):await c(s.body,()=>{o=t})}catch(t){if(i||r.signal.aborted)return;e.onError?.(t)}if(i)return;await a(o),o=Math.min(n,o*2)}})(),{close(){i||(i=!0,r.abort())}}}function N(e){try{let t=new URL(e);return t.hostname=`events.${t.hostname}`,t.pathname=``,t.search=``,t.origin}catch{return}}var P=`havik.player.deviceId`,F;function I(){if(F)return F;try{let e=globalThis.localStorage?.getItem(P);if(e)return F=e,e}catch{}let e=R();F=e;try{globalThis.localStorage?.setItem(P,e)}catch{}return e}function L(){F=void 0;try{globalThis.localStorage?.removeItem(P)}catch{}}function R(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<16;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}function z(e,t,n={}){let r={"x-api-key":t.apiKey,"X-Match-Urn":e.matchUrn,"X-Device-Id":n.deviceId??I(),"Content-Type":`application/octet-stream`};return n.userId&&(r[`X-User-Id`]=n.userId),r}var B=/^#EXT-X-(PART-INF|PART|PRELOAD-HINT)[:\s]/m;function V(e){return B.test(e)}var H={droppedFrames:0};function U(e){return e.getVideoPlaybackQuality?.()?.droppedVideoFrames??0}function de(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}function fe(){return c.default.isSupported()}var pe=3,me=5,he=3,ge=3e4,_e=12e3,ve=3e3,ye=3,be=9;function xe(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=ye;let t=Math.max(12,e.liveSyncDuration+be);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t)}var Se=class{name=`hls`;hls=null;deps;licenseUrl;detectedLowLatency=!1;mediaRecoveries=0;networkRecoveries=0;licenseRecoveries=0;recoveryResetTimer=null;networkRetryTimer=null;licenseRetryTimer=null;onVisibility=null;sawLive=!1;lastEndSN=-1;lastAdvanceMs=0;endWatchdog=null;endedEmitted=!1;constructor(e){this.deps=e,this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl}async load(){let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps;if(e.drmEnabled&&!e.drm?.widevine?.licenseUrl){r({type:`error`,error:new l(`INTERNAL`,0,`DRM is required but no Widevine license is available for this stream on this browser`),fatal:!0});return}this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility))}startHls(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,lowLatency:a,hlsConfig:o,emit:s}=this.deps,l=t.drmEnabled&&!!t.drm?.widevine?.licenseUrl,u={enableWorker:!a,lowLatencyMode:a,backBufferLength:90,maxBufferHole:.5,maxLiveSyncPlaybackRate:1.5,abrEwmaDefaultEstimate:1e6,capLevelToPlayerSize:!0,...l?{emeEnabled:!0,drmSystems:{"com.widevine.alpha":{licenseUrl:this.licenseUrl}},drmSystemOptions:{videoRobustness:`SW_SECURE_DECODE`,audioRobustness:`SW_SECURE_CRYPTO`,videoEncryptionScheme:`cbcs`,audioEncryptionScheme:`cbcs`},licenseXhrSetup:(e,a)=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i)}}:{},...o};xe(u);let d=new c.default(u);this.hls=d,d.on(c.default.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,s({type:`ready`})}),d.on(c.default.Events.FRAG_BUFFERED,()=>{(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.recoveryResetTimer=null},ge))}),d.on(c.default.Events.LEVEL_LOADED,(e,t)=>{if(this.detectedLowLatency)return;let n=t.details;(n?.partList?.length||(n?.partTarget??0)>0)&&(this.detectedLowLatency=!0,s({type:`lowLatencyDetected`,value:!0}))}),d.on(c.default.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.endWatchdog=setInterval(()=>this.checkEndStale(),ve),d.on(c.default.Events.LEVEL_SWITCHED,(e,t)=>s({type:`qualitychange`,index:t.level})),d.on(c.default.Events.AUDIO_TRACK_SWITCHED,(e,t)=>s({type:`audiotrackchange`,id:t.id})),d.on(c.default.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>s({type:`texttrackchange`,id:t.id})),d.on(c.default.Events.ERROR,(e,t)=>this.onError(t)),d.loadSource(t.manifestUrl),d.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(!t)return;if(e==null){t.autoLevelCapping=-1;return}let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),t.autoLevelCapping=n}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrl(e){this.licenseUrl=e}getStats(){let e=this.hls,t={droppedFrames:U(this.deps.video),lowLatency:this.detectedLowLatency};if(e){typeof e.latency==`number`&&(t.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(t.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(t.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let n=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;n&&(t.levelHeight=n.height),typeof n?.details?.live==`boolean`&&(t.isLive=n.details.live,typeof e.liveSyncPosition==`number`&&(t.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return t}trackEnd(e){let t=e.details;if(t){if(t.live===!0){this.sawLive=!0;let e=t.endSN??-1;e!==this.lastEndSN&&(this.lastEndSN=e,this.lastAdvanceMs=Date.now());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(!(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)){if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}Date.now()-this.lastAdvanceMs>_e&&this.emitEnded(`stalled`)}}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}destroy(){if(this.clearRecoveryReset(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(!(e.details===c.default.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED||e.details===c.default.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED))return!1;let t=e.response?.code??0;if(!(t===0||t===408||t===429||t>=500)||this.licenseRecoveries>=he)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{if(this.licenseRetryTimer=null,this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during license retry`,e)}this.hls=null,this.startHls()}},n),!0}onError(e){if(!e.fatal)return;let t=this.hls;if(t){if(this.clearRecoveryReset(),e.type===c.default.ErrorTypes.KEY_SYSTEM_ERROR){if(this.scheduleLicenseRetry(e))return;this.deps.emit({type:`error`,error:this.toError(e,`DRM`),fatal:!0});return}if(e.type===c.default.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<me){this.networkRecoveries+=1;let e=Math.min(8e3,1e3*2**(this.networkRecoveries-1));this.networkRetryTimer=setTimeout(()=>{this.networkRetryTimer=null,this.hls&&this.hls.startLoad()},e);return}this.deps.emit({type:`error`,error:this.toError(e,`NETWORK`),fatal:!0});return}if(e.type===c.default.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<pe){this.mediaRecoveries+=1,t.recoverMediaError();return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``;return new l(n===401?`UNAUTHORIZED`:n===403||t===`DRM`?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`)}};function Ce(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}var W=class{name=`native`;deps;onLoaded;onError;constructor(e){this.deps=e}async load(){let{video:e,descriptor:t,emit:n}=this.deps;if(t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new l(`INTERNAL`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}n({type:`error`,error:new l(`INTERNAL`,0,`FairPlay EME is not implemented in this SDK version; relying on native passthrough`),fatal:!1})}this.onLoaded=()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new l(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=t.manifestUrl,e.load()}setLicenseUrl(e){}getQualityLevels(){return[]}getCurrentQuality(){return-1}setQuality(e){}setMaxBitrate(e){}getAudioTracks(){let e=this.deps.video.audioTracks;return e?Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Audio ${n+1}`,lang:r.language||void 0,default:r.enabled}}):[]}setAudioTrack(e){let t=this.deps.video.audioTracks;if(t)for(let n=0;n<t.length;n+=1)t[n].enabled=n===e}getTextTracks(){let e=this.deps.video.textTracks;return Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Text ${n+1}`,lang:r.language||void 0}})}setTextTrack(e){let t=this.deps.video.textTracks;for(let n=0;n<t.length;n+=1)t[n].mode=n===e?`showing`:`disabled`}seekToLive(){let e=this.deps.video;e.seekable.length>0&&(e.currentTime=e.seekable.end(e.seekable.length-1))}getStats(){let e=this.deps.video,t={droppedFrames:U(e)};return e.duration===1/0&&(t.isLive=!0,e.seekable.length>0&&(t.atLiveEdge=e.currentTime>=e.seekable.end(e.seekable.length-1)-2)),t}stop(){try{this.deps.video.pause()}catch{}}destroy(){let{video:e}=this.deps;this.onLoaded&&e.removeEventListener(`loadedmetadata`,this.onLoaded),this.onError&&e.removeEventListener(`error`,this.onError);try{e.pause()}catch{}e.removeAttribute(`src`);try{e.load()}catch{}}},G={accent:`#E1B600`,accentText:`#1B1C23`,background:`#0e0f13`,surface:`#1B1C23`,surfaceMuted:`#2a2c36`,text:`#ffffff`,textMuted:`#9aa0ad`,border:`rgba(255, 255, 255, 0.1)`,radius:`8px`,fontFamily:`ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`},K={accent:`--havik-accent`,accentText:`--havik-accent-text`,background:`--havik-bg`,surface:`--havik-surface`,surfaceMuted:`--havik-surface-muted`,text:`--havik-text`,textMuted:`--havik-text-muted`,border:`--havik-border`,radius:`--havik-radius`,fontFamily:`--havik-font`};function q(e,t){let n={...G,...t};for(let t of Object.keys(K))e.style.setProperty(K[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var J=`havik-player-styles`,we=`
4
+ .havik-player{position:relative;display:block;width:100%;background:var(--havik-bg,#0e0f13);
5
+ color:var(--havik-text,#fff);font-family:var(--havik-font,system-ui,sans-serif);
6
+ overflow:hidden;line-height:1.4;-webkit-tap-highlight-color:transparent}
7
+ .havik-player video{display:block;width:100%;height:auto;aspect-ratio:16/9;
8
+ object-fit:contain;background:#000;outline:none}
9
+ .havik-player:focus{outline:none}
10
+ .havik-player *{box-sizing:border-box}
11
+
12
+ .havik-player:fullscreen,.havik-player:-webkit-full-screen{display:flex;align-items:center;
13
+ justify-content:center;width:100vw;height:100vh;aspect-ratio:auto}
14
+ .havik-player:fullscreen video,.havik-player:-webkit-full-screen video{width:100%;height:100%;
15
+ aspect-ratio:auto;object-fit:contain}
16
+
17
+ .havik-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;cursor:pointer}
18
+ .havik-gradient{position:absolute;left:0;right:0;bottom:0;height:120px;pointer-events:none;
19
+ background:linear-gradient(to top,rgba(0,0,0,.78),transparent);
20
+ opacity:1;transition:opacity .25s}
21
+ .havik-player.havik-hide .havik-gradient,
22
+ .havik-player.havik-hide .havik-bar{opacity:0;pointer-events:none}
23
+ .havik-player.havik-hide{cursor:none}
24
+
25
+ .havik-center{width:74px;height:74px;border-radius:50%;border:0;cursor:pointer;
26
+ background:var(--havik-accent,#E1B600);color:var(--havik-accent-text,#1B1C23);
27
+ display:flex;align-items:center;justify-content:center;
28
+ box-shadow:0 6px 24px rgba(0,0,0,.45);transition:transform .15s,opacity .15s}
29
+ .havik-center:hover{transform:scale(1.06)}
30
+ .havik-center svg{width:38px;height:38px;margin-left:2px}
31
+ .havik-center.havik-gone{opacity:0;pointer-events:none;transform:scale(.8)}
32
+
33
+ .havik-spinner{width:56px;height:56px;border-radius:50%;
34
+ border:4px solid rgba(255,255,255,.2);border-top-color:var(--havik-accent,#E1B600);
35
+ animation:havik-spin .8s linear infinite}
36
+ @keyframes havik-spin{to{transform:rotate(360deg)}}
37
+
38
+ /* Status card — branded full-bleed overlay for the stopped/pre-play states
39
+ (ended / fatal error / pre-play / armed-waiting). */
40
+ .havik-status{position:absolute;inset:0;display:flex;flex-direction:column;gap:16px;
41
+ align-items:center;justify-content:center;background:rgba(14,15,19,.82);text-align:center;padding:24px}
42
+ .havik-status__logo{width:128px;height:46px;background:var(--havik-logo) center/contain no-repeat;opacity:.95}
43
+ .havik-status__msg{color:var(--havik-text,#fff);font-size:15px;font-weight:600;max-width:480px}
44
+ .havik-status__btn{display:inline-flex;align-items:center;gap:8px;border:0;cursor:pointer;
45
+ padding:10px 18px;border-radius:var(--havik-radius,8px);font-weight:700;font-size:14px;
46
+ background:var(--havik-accent,#E1B600);color:var(--havik-accent-text,#1B1C23);transition:transform .15s}
47
+ .havik-status__btn:hover{transform:scale(1.04)}
48
+ .havik-status__btn svg{width:18px;height:18px}
49
+ /* Pre-play: lighter scrim so the poster shows through, and a round play CTA. */
50
+ .havik-status--preplay{background:rgba(14,15,19,.4)}
51
+ .havik-status--preplay .havik-status__btn--play{width:74px;height:74px;border-radius:50%;padding:0;
52
+ justify-content:center;box-shadow:0 6px 24px rgba(0,0,0,.45)}
53
+ .havik-status--preplay .havik-status__btn--play svg{width:38px;height:38px;margin-left:3px}
54
+
55
+ .havik-watermark{position:absolute;top:12px;right:14px;height:22px;opacity:.85;pointer-events:none;
56
+ content:'';background:var(--havik-logo) center/contain no-repeat;width:90px}
57
+
58
+ .havik-bar{position:absolute;left:0;right:0;bottom:0;padding:0 12px 8px;
59
+ opacity:1;transition:opacity .25s;z-index:2}
60
+ .havik-seek{position:relative;height:16px;display:flex;align-items:center;cursor:pointer;margin-bottom:2px}
61
+ .havik-seek__track{position:relative;width:100%;height:4px;border-radius:3px;background:rgba(255,255,255,.25)}
62
+ .havik-seek__buffered{position:absolute;left:0;top:0;height:100%;border-radius:3px;background:rgba(255,255,255,.4)}
63
+ .havik-seek__played{position:absolute;left:0;top:0;height:100%;border-radius:3px;background:var(--havik-accent,#E1B600)}
64
+ .havik-seek__thumb{position:absolute;top:50%;width:13px;height:13px;border-radius:50%;
65
+ background:var(--havik-accent,#E1B600);transform:translate(-50%,-50%) scale(0);transition:transform .1s}
66
+ .havik-seek:hover .havik-seek__thumb{transform:translate(-50%,-50%) scale(1)}
67
+
68
+ .havik-controls{display:flex;align-items:center;gap:6px;height:40px}
69
+ .havik-spacer{flex:1}
70
+ .havik-btn{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;
71
+ border:0;background:transparent;color:var(--havik-text,#fff);cursor:pointer;border-radius:var(--havik-radius,8px);
72
+ padding:0;transition:background .12s,color .12s}
73
+ .havik-btn:hover{background:rgba(255,255,255,.12)}
74
+ .havik-btn:focus-visible{outline:2px solid var(--havik-accent,#E1B600);outline-offset:1px}
75
+ .havik-btn svg{width:22px;height:22px}
76
+
77
+ .havik-vol{display:flex;align-items:center}
78
+ .havik-vol__slider{width:0;opacity:0;transition:width .18s,opacity .18s;height:4px;cursor:pointer;
79
+ appearance:none;-webkit-appearance:none;background:rgba(255,255,255,.3);border-radius:3px;margin:0 4px}
80
+ .havik-vol:hover .havik-vol__slider,.havik-vol:focus-within .havik-vol__slider{width:70px;opacity:1}
81
+ .havik-vol__slider::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;border-radius:50%;background:var(--havik-accent,#E1B600)}
82
+ .havik-vol__slider::-moz-range-thumb{width:12px;height:12px;border:0;border-radius:50%;background:var(--havik-accent,#E1B600)}
83
+
84
+ .havik-time{font-size:12px;color:var(--havik-text-muted,#9aa0ad);
85
+ font-variant-numeric:tabular-nums;padding:0 6px;white-space:nowrap}
86
+ .havik-live{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:700;
87
+ letter-spacing:.4px;padding:0 8px;color:var(--havik-text,#fff)}
88
+ .havik-live svg{width:9px;height:9px;color:var(--havik-text-muted,#9aa0ad)}
89
+ .havik-live.is-live svg{color:var(--havik-accent,#E1B600)}
90
+ .havik-live__go{margin-left:2px;border:0;cursor:pointer;background:transparent;color:var(--havik-text-muted,#9aa0ad);
91
+ font:inherit;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;padding:2px 6px;border-radius:6px}
92
+ .havik-live.is-live .havik-live__go{display:none}
93
+ .havik-live__go:hover{color:var(--havik-accent,#E1B600)}
94
+
95
+ .havik-menu{position:absolute;bottom:54px;right:12px;min-width:170px;max-height:230px;overflow:auto;
96
+ background:var(--havik-surface,#1B1C23);border:1px solid var(--havik-border,rgba(255,255,255,.1));
97
+ border-radius:var(--havik-radius,8px);box-shadow:0 10px 30px rgba(0,0,0,.5);padding:6px;z-index:3}
98
+ .havik-menu[hidden]{display:none}
99
+ .havik-menu__title{font-size:11px;text-transform:uppercase;letter-spacing:.6px;
100
+ color:var(--havik-text-muted,#9aa0ad);padding:6px 8px 4px}
101
+ .havik-menu__item{display:flex;align-items:center;justify-content:space-between;gap:10px;width:100%;
102
+ border:0;background:transparent;color:var(--havik-text,#fff);cursor:pointer;font:inherit;font-size:13px;
103
+ text-align:left;padding:7px 8px;border-radius:6px}
104
+ .havik-menu__item:hover{background:var(--havik-surface-muted,#2a2c36)}
105
+ .havik-menu__item[aria-checked="true"]{color:var(--havik-accent,#E1B600);font-weight:600}
106
+ .havik-menu__item[aria-checked="true"]::after{content:'✓'}
107
+ `;function Te(e=document){if(e.getElementById(J))return;let t=e.createElement(`style`);t.id=J,t.textContent=we,e.head.appendChild(t)}var Ee={play:`<path d="M8 5v14l11-7z"/>`,pause:`<path d="M6 5h4v14H6zM14 5h4v14h-4z"/>`,volumeHigh:`<path d="M3 10v4h4l5 5V5L7 10H3zm13.5 2a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zm-2.5-9v2.06A7 7 0 0 1 14 19v2a9 9 0 0 0 0-18z"/>`,volumeMute:`<path d="M3 10v4h4l5 5V5L7 10H3zm16.5 2 2.5-2.5-1.4-1.4L18 10.6 15.4 8 14 9.4l2.6 2.6L14 14.6l1.4 1.4 2.6-2.6 2.6 2.6 1.4-1.4z"/>`,cc:`<path d="M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM10 11H8.5v-.5h-2v3h2V13H10v1a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H17v1a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1z"/>`,settings:`<path d="m19.4 13 .1-1-.1-1 2-1.6-2-3.4-2.4 1a7 7 0 0 0-1.7-1l-.4-2.5H9.1L8.7 6a7 7 0 0 0-1.7 1l-2.4-1-2 3.4L2.6 11l-.1 1 .1 1-2 1.6 2 3.4 2.4-1c.5.4 1 .7 1.7 1l.4 2.5h5.8l.4-2.5c.6-.3 1.2-.6 1.7-1l2.4 1 2-3.4-2-1.6zM12 15.5a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7z"/>`,pip:`<path d="M19 7h-8v6h8V7zm4 12V5a2 2 0 0 0-2-2H3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2zm-2 .02H3V4.98h18v14.04z"/>`,fullscreen:`<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>`,fullscreenExit:`<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>`,liveDot:`<circle cx="12" cy="12" r="6"/>`,retry:`<path d="M17.65 6.35A8 8 0 1 0 19.73 13h-2.08A6 6 0 1 1 12 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>`};function Y(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Ee[e]}</svg>`}var De=3e3,Oe=new Set([`GONE`,`NOT_FOUND`,`INVALID_URN`,`UNAUTHORIZED`]);function ke(e){return new Ae(e)}var Ae=class{root;video;player;doc;autoHideMs;overlay;center;spinner;bar;gradient;seek;seekBuffered;seekPlayed;seekThumb;playBtn;muteBtn;volSlider;live;liveGo;time;ccBtn;audioBtn;qualityBtn;pipBtn;fsBtn;menu;statusBox=null;statusKind=null;hasPlayed=!1;lastError=null;logoUrl;statusOverlays;endedMessage;errorMessage;hideTimer;openMenu=null;scrubbing=!1;offFns=[];constructor(e){this.root=e.root,this.video=e.video,this.player=e.player,this.doc=e.root.ownerDocument??document,this.autoHideMs=e.autoHideMs??De,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.endedMessage=e.endedMessage??`This stream has ended`,this.errorMessage=e.errorMessage,Te(this.doc),this.root.classList.add(`havik-player`),this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=0),this.root.setAttribute(`role`,`region`),this.root.setAttribute(`aria-label`,`Video player`);let t=(e,t,n)=>{let r=this.doc.createElement(e);if(r.className=t,n)for(let[e,t]of Object.entries(n))r.setAttribute(e,t);return r},n=(e,n,r)=>{let i=t(`button`,e,{type:`button`,"aria-label":r,title:r});return i.innerHTML=Y(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Y(`play`),this.spinner=t(`div`,`havik-spinner`),this.spinner.style.display=`none`,this.overlay.append(this.center,this.spinner),this.gradient=t(`div`,`havik-gradient`),this.bar=t(`div`,`havik-bar`),this.seek=t(`div`,`havik-seek`,{role:`slider`,"aria-label":`Seek`,"aria-valuemin":`0`,"aria-valuemax":`100`,tabindex:`0`});let r=t(`div`,`havik-seek__track`);this.seekBuffered=t(`div`,`havik-seek__buffered`),this.seekPlayed=t(`div`,`havik-seek__played`),this.seekThumb=t(`div`,`havik-seek__thumb`),r.append(this.seekBuffered,this.seekPlayed,this.seekThumb),this.seek.append(r);let i=t(`div`,`havik-controls`);this.playBtn=n(`havik-btn`,`play`,`Play`),this.muteBtn=n(`havik-btn`,`volumeHigh`,`Mute`),this.volSlider=t(`input`,`havik-vol__slider`,{type:`range`,min:`0`,max:`1`,step:`0.05`,"aria-label":`Volume`});let a=t(`div`,`havik-vol`);a.append(this.muteBtn,this.volSlider),this.live=t(`div`,`havik-live`),this.live.innerHTML=Y(`liveDot`);let o=this.doc.createElement(`span`);o.textContent=`LIVE`,this.liveGo=t(`button`,`havik-live__go`,{type:`button`}),this.liveGo.textContent=`Go live`,this.live.append(o,this.liveGo),this.time=t(`div`,`havik-time`),this.time.textContent=`0:00`,this.time.style.display=`none`;let s=t(`div`,`havik-spacer`);if(this.ccBtn=n(`havik-btn`,`cc`,`Subtitles`),this.audioBtn=n(`havik-btn`,`settings`,`Audio track`),this.qualityBtn=n(`havik-btn`,`settings`,`Quality`),this.pipBtn=n(`havik-btn`,`pip`,`Picture in picture`),this.fsBtn=n(`havik-btn`,`fullscreen`,`Fullscreen`),this.ccBtn.style.display=`none`,this.audioBtn.style.display=`none`,this.qualityBtn.style.display=`none`,this.pipSupported()||(this.pipBtn.style.display=`none`),i.append(this.playBtn,a,this.live,this.time,s,this.ccBtn,this.audioBtn,this.qualityBtn,this.pipBtn,this.fsBtn),this.bar.append(this.seek,i),this.menu=t(`div`,`havik-menu`,{role:`menu`}),this.menu.hidden=!0,this.root.append(this.gradient,this.overlay,this.bar,this.menu),e.logoUrl){let n=t(`div`,`havik-watermark`);n.style.backgroundImage=`url("${e.logoUrl}")`,this.root.append(n)}this.wire(),this.syncPlayPause(),this.syncVolume(),this.scheduleHide()}on(e,t,n,r){e.addEventListener(t,n,r),this.offFns.push(()=>e.removeEventListener(t,n,r))}wire(){let e=this.video;this.on(this.playBtn,`click`,()=>this.togglePlay()),this.on(this.center,`click`,()=>this.togglePlay()),this.on(this.overlay,`click`,e=>{e.target===this.overlay&&this.togglePlay()}),this.on(this.muteBtn,`click`,()=>this.player.setMuted(!e.muted)),this.on(this.volSlider,`input`,()=>{let t=Number(this.volSlider.value);this.player.setVolume(t),t>0&&e.muted&&this.player.setMuted(!1)}),this.on(this.liveGo,`click`,()=>this.player.seekToLive()),this.on(this.pipBtn,`click`,()=>void this.togglePip()),this.on(this.fsBtn,`click`,()=>void this.toggleFullscreen()),this.on(this.ccBtn,`click`,()=>this.toggleMenu(`cc`)),this.on(this.audioBtn,`click`,()=>this.toggleMenu(`audio`)),this.on(this.qualityBtn,`click`,()=>this.toggleMenu(`quality`)),this.on(this.seek,`pointerdown`,e=>this.onSeekDown(e)),this.on(this.seek,`keydown`,e=>this.onSeekKey(e)),this.on(e,`play`,()=>this.syncPlayPause()),this.on(e,`pause`,()=>this.syncPlayPause()),this.on(e,`volumechange`,()=>this.syncVolume()),this.on(e,`timeupdate`,()=>this.syncProgress()),this.on(e,`progress`,()=>this.syncProgress()),this.on(e,`durationchange`,()=>this.syncProgress()),this.offFns.push(this.player.on(`statechange`,()=>this.syncState())),this.offFns.push(this.player.on(`ready`,()=>this.refreshTracks())),this.offFns.push(this.player.on(`qualitychange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`audiotrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`texttrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`pipchange`,e=>this.syncPip(e))),this.offFns.push(this.player.on(`stats`,()=>this.syncLive())),this.offFns.push(this.player.on(`error`,e=>{this.lastError=e,this.statusKind=null,this.syncState()})),this.on(this.root,`pointermove`,()=>this.poke()),this.on(this.root,`pointerleave`,()=>this.scheduleHide(0)),this.on(this.root,`focusin`,()=>this.poke()),this.on(this.root,`keydown`,e=>this.onKey(e)),this.on(this.doc,`pointerdown`,e=>this.onDocPointer(e),{capture:!0}),this.on(this.doc,`fullscreenchange`,()=>this.syncFullscreen()),this.syncState()}togglePlay(){this.video.paused||this.video.ended?this.player.play():this.player.pause()}syncPlayPause(){let e=!this.video.paused&&!this.video.ended;this.setIcon(this.playBtn,e?`pause`:`play`),this.playBtn.setAttribute(`aria-label`,e?`Pause`:`Play`),this.setIcon(this.center,e?`pause`:`play`),this.center.classList.toggle(`havik-gone`,e||!!this.statusBox),e?this.scheduleHide():this.show()}syncState(){let e=this.player.state;(e===`playing`||e===`buffering`)&&(this.hasPlayed=!0),this.syncStatus(e);let t=e===`loading`||e===`buffering`;this.spinner.style.display=t&&!this.statusBox?``:`none`,(t||this.statusBox)&&this.center.classList.add(`havik-gone`),this.syncLive()}syncStatus(e){let t=null;this.statusOverlays&&(e===`ended`?t=`ended`:e===`error`?t=`error`:e===`waiting`?t=`waiting`:!this.hasPlayed&&(e===`idle`||e===`paused`)&&(t=`preplay`)),this.renderStatus(t)}renderStatus(e){if(e===this.statusKind||(this.statusKind=e,this.statusBox?.remove(),this.statusBox=null,!e))return;let t=this.doc.createElement(`div`);if(t.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,t.append(e)}if(e===`preplay`){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn havik-status__btn--play`,e.setAttribute(`aria-label`,`Play`),e.innerHTML=Y(`play`),e.addEventListener(`click`,()=>void this.player.play()),t.append(e)}else{let n=this.doc.createElement(`div`);if(n.className=`havik-status__msg`,n.textContent=e===`ended`?this.endedMessage:e===`waiting`?`Starting soon…`:this.errorMessage??this.lastError?.message??`Playback unavailable`,t.append(n),e===`error`&&this.lastError&&!Oe.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Y(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),t.append(e)}}this.root.append(t),this.statusBox=t,this.show()}syncVolume(){let e=this.video,t=e.muted||e.volume===0;this.setIcon(this.muteBtn,t?`volumeMute`:`volumeHigh`),this.muteBtn.setAttribute(`aria-label`,t?`Unmute`:`Mute`),this.volSlider.value=String(t?0:e.volume)}seekableRange(){let e=this.video;if(e.seekable&&e.seekable.length>0){let t=e.seekable.start(0),n=e.seekable.end(e.seekable.length-1);if(n>t)return{start:t,end:n}}return Number.isFinite(e.duration)&&e.duration>0?{start:0,end:e.duration}:null}syncProgress(){if(this.scrubbing)return;let e=this.seekableRange();if(!e){this.seekPlayed.style.width=`100%`;return}let t=e.end-e.start,n=Math.min(1,Math.max(0,(this.video.currentTime-e.start)/t));this.seekPlayed.style.width=`${(n*100).toFixed(2)}%`,this.seekThumb.style.left=`${(n*100).toFixed(2)}%`,this.seek.setAttribute(`aria-valuenow`,String(Math.round(n*100)));let r=this.video.buffered;if(r&&r.length>0){let n=r.end(r.length-1),i=Math.min(1,Math.max(0,(n-e.start)/t));this.seekBuffered.style.width=`${(i*100).toFixed(2)}%`}!this.player.getStats().isLive&&Number.isFinite(this.video.duration)&&(this.time.textContent=`${X(this.video.currentTime)} / ${X(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1;this.live.style.display=t?``:`none`,this.time.style.display=t?`none`:``,this.live.classList.toggle(`is-live`,e.atLiveEdge!==!1&&t)}onSeekDown(e){let t=this.seekableRange();if(!t)return;e.preventDefault(),this.scrubbing=!0;let n=e=>this.seekToPointer(e,t),r=()=>{this.scrubbing=!1,this.doc.removeEventListener(`pointermove`,n),this.doc.removeEventListener(`pointerup`,r)};this.doc.addEventListener(`pointermove`,n),this.doc.addEventListener(`pointerup`,r),this.seekToPointer(e,t)}seekToPointer(e,t){let n=this.seek.getBoundingClientRect(),r=n.width>0?Math.min(1,Math.max(0,(e.clientX-n.left)/n.width)):0;this.seekPlayed.style.width=`${(r*100).toFixed(2)}%`,this.seekThumb.style.left=`${(r*100).toFixed(2)}%`,this.video.currentTime=t.start+r*(t.end-t.start)}onSeekKey(e){e.key===`ArrowLeft`?(this.nudge(-5),e.preventDefault()):e.key===`ArrowRight`&&(this.nudge(5),e.preventDefault())}nudge(e){let t=this.seekableRange();t&&(this.video.currentTime=Math.min(t.end,Math.max(t.start,this.video.currentTime+e)))}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e,this.renderMenu(e),this.menu.hidden=!1,this.show()}closeMenu(){this.openMenu=null,this.menu.hidden=!0,this.menu.replaceChildren()}renderMenu(e){e===`quality`?this.renderQualityMenu():e===`audio`?this.renderAudioMenu():this.renderCcMenu()}menuItem(e,t,n){let r=this.doc.createElement(`button`);r.type=`button`,r.className=`havik-menu__item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,t?`true`:`false`);let i=this.doc.createElement(`span`);return i.textContent=e,r.append(i),r.addEventListener(`click`,()=>{n(),this.closeMenu()}),r}renderQualityMenu(){let e=this.player.getQualityLevels(),t=this.player.getCurrentQuality(),n=this.doc.createElement(`div`);n.className=`havik-menu__title`,n.textContent=`Quality`,this.menu.replaceChildren(n,this.menuItem(`Auto`,t===-1,()=>this.player.setQuality(`auto`)));for(let n of e)this.menu.append(this.menuItem(je(n),t===n.index,()=>this.player.setQuality(n.index)))}renderAudioMenu(){let e=this.player.getAudioTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Audio`,this.menu.replaceChildren(t);for(let t of e)this.menu.append(this.menuItem(Me(t),t.default,()=>this.player.setAudioTrack(t.id)))}renderCcMenu(){let e=this.player.getTextTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Subtitles`,this.menu.replaceChildren(t,this.menuItem(`Off`,!1,()=>this.player.setTextTrack(-1)));for(let t of e)this.menu.append(this.menuItem(Ne(t),!1,()=>this.player.setTextTrack(t.id)))}onTracksChanged(){this.openMenu&&this.renderMenu(this.openMenu)}refreshTracks(){let e=this.player.getQualityLevels(),t=this.player.getAudioTracks(),n=this.player.getTextTracks();this.qualityBtn.style.display=e.length>1?``:`none`,this.audioBtn.style.display=t.length>1?``:`none`,this.ccBtn.style.display=n.length>0?``:`none`,this.onTracksChanged()}pipSupported(){return`pictureInPictureEnabled`in this.doc&&typeof this.video.requestPictureInPicture==`function`}async togglePip(){this.doc.pictureInPictureElement===this.video?await this.player.exitPictureInPicture():await this.player.enterPictureInPicture()}syncPip(e){this.pipBtn.setAttribute(`aria-pressed`,e?`true`:`false`)}async toggleFullscreen(){let e=this.root,t=this.doc;try{t.fullscreenElement?await t.exitFullscreen?.():await e.requestFullscreen?.()}catch{}}syncFullscreen(){let e=this.doc.fullscreenElement===this.root;this.setIcon(this.fsBtn,e?`fullscreenExit`:`fullscreen`),this.fsBtn.setAttribute(`aria-label`,e?`Exit fullscreen`:`Fullscreen`)}poke(){this.show(),this.scheduleHide()}show(){this.root.classList.remove(`havik-hide`)}scheduleHide(e=this.autoHideMs){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{!this.video.paused&&!this.video.ended&&!this.openMenu&&!this.statusBox&&this.root.classList.add(`havik-hide`)},e)}onDocPointer(e){this.openMenu&&!this.menu.contains(e.target)&&([this.qualityBtn,this.audioBtn,this.ccBtn].some(t=>t.contains(e.target))||this.closeMenu())}onKey(e){let t=e.target;if(!(t&&t!==this.root&&t!==this.seek&&t.tagName===`INPUT`)){switch(e.key){case` `:case`k`:this.togglePlay();break;case`m`:this.player.setMuted(!this.video.muted);break;case`f`:this.toggleFullscreen();break;case`c`:this.ccBtn.style.display!==`none`&&this.toggleMenu(`cc`);break;case`l`:this.player.seekToLive();break;case`ArrowUp`:this.player.setVolume(Math.min(1,this.video.volume+.1));break;case`ArrowDown`:this.player.setVolume(Math.max(0,this.video.volume-.1));break;case`ArrowLeft`:this.nudge(-5);break;case`ArrowRight`:this.nudge(5);break;default:return}this.poke(),e.preventDefault()}}setIcon(e,t){e.innerHTML=Y(t)}destroy(){this.hideTimer&&clearTimeout(this.hideTimer);for(let e of this.offFns)try{e()}catch{}this.offFns.length=0,this.closeMenu(),this.statusBox?.remove();for(let e of[this.overlay,this.gradient,this.bar,this.menu])e.remove();this.root.classList.remove(`havik-player`,`havik-hide`)}};function X(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=Math.floor(e%60),n=Math.floor(e/60%60),r=Math.floor(e/3600),i=r>0?String(n).padStart(2,`0`):String(n),a=String(t).padStart(2,`0`);return r>0?`${r}:${i}:${a}`:`${i}:${a}`}function je(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function Me(e){return e.name||e.lang||`Track ${e.id}`}function Ne(e){return e.name||e.lang||`Track ${e.id}`}var Pe=6e3,Fe=45e3,Ie=2e3,Z=3,Le=2e3,Re=480*1e3;async function Q(e){if(!e.video||typeof e.video.play!=`function`)throw new l(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);if(!e.baseUrl)throw new l(`INTERNAL`,0,`createPlayer: baseUrl is required`);if(!e.matchUrn)throw new l(`INVALID_URN`,0,`createPlayer: matchUrn is required`);if(!e.credential)throw new l(`INTERNAL`,0,`createPlayer: credential is required`);let t=new ze(e);return await t.start(),t}var ze=class{opts;abort=new AbortController;listeners={};engine=null;controlBar=null;container=null;detachMedia;detachPip;statsTimer;refreshTimer;_state=`idle`;_descriptor=null;destroyed=!1;loadGen=0;liveStateSub=null;endedHandled=!1;armingSub=null;armSseTimer=null;constructor(e){this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}async start(){this.opts.muted&&(this.opts.video.muted=!0),this.opts.poster&&(this.opts.video.poster=this.opts.poster),this.mountControls(),this.attachPipListeners(),this.setState(`loading`);let e=++this.loadGen,t=this.resolveOptions();try{let n=await C(t);await this.onResolved(n,e)}catch(t){if(this.opts.waitForLive&&t instanceof l&&f(t.code)){this.setState(`waiting`),this.beginArming(e);return}throw t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal}}beginArming(e){let t=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??N(this.opts.baseUrl);t?this.armWithSse(e,t):this.beginArmingByPolling(e)}beginArmingByPolling(e,t){w({...this.resolveOptions(),signal:t??this.abort.signal,waitForLive:this.buildWaitConfig()}).then(t=>this.onResolved(t,e)).catch(n=>{this.destroyed||this.abort.signal.aborted||t?.aborted||e!==this.loadGen||this.fail(n)})}armWithSse(e,t){let n=!1,r=!1,i=new AbortController;this.abort.signal.addEventListener(`abort`,()=>i.abort(),{once:!0}),this.setState(`waiting`);let a=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,o=async t=>{n||a()||(n=!0,this.closeArming(),i.abort(),await this.onResolved(t,e))},s=()=>{n||r||a()||(r=!0,this.beginArmingByPolling(e,i.signal))},c=()=>{n||a()||C(this.resolveOptions()).then(e=>o(e)).catch(e=>{n||a()||e instanceof l&&f(e.code)||(n=!0,this.closeArming(),i.abort(),this.fail(e instanceof l?e:new l(`INTERNAL`,0,String(e))))})},u=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!n&&!a()&&s()},e)};u(Pe),this.armingSub=M({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>u(Fe),onState:e=>{n||a()||(e.state===`live`||e.state===`gone`)&&setTimeout(c,Math.random()*Ie)},onError:()=>s()})}closeArming(){this.armSseTimer&&=(clearTimeout(this.armSseTimer),null),this.armingSub?.close(),this.armingSub=null}buildWaitConfig(){let e=this.opts.waitForLive&&this.opts.waitForLive!==!0?this.opts.waitForLive:{};return{...e,onState:t=>{this.setState(`waiting`),this.emit(`waiting`,t),e.onState?.(t)}}}async onResolved(e,t){if(this.destroyed||t!==this.loadGen)return;this._descriptor=e,this.endedHandled=!1;let n=await p(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.createEngine(e,n),i=de(this.opts.video,e=>this.setState(e));if(await r.load(),this.destroyed||t!==this.loadGen){i(),r.destroy();return}this.engine=r,this.detachMedia=i,this.opts.maxBitrate!=null&&r.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t)}createEngine(e,t){let n={...this.opts.hlsConfig};this.opts.startLevel!=null&&(n.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(n.liveSyncDuration=this.opts.liveLatencyTarget);let r={video:this.opts.video,descriptor:e,credential:t,deviceId:I(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,hlsConfig:n,emit:e=>this.onEngineEvent(e)},i=this.opts.engine??`auto`;if(i===`native`)return new W(r);if(i===`hls`||fe())return new Se(r);if(Ce(this.opts.video))return new W(r);throw new l(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`ready`:this.emit(`ready`),this.opts.autoplay!==!1&&this.play();break;case`lowLatencyDetected`:this._descriptor&&(this._descriptor.isLowLatency=e.value);break;case`qualitychange`:this.emit(`qualitychange`,e.index);break;case`audiotrackchange`:this.emit(`audiotrackchange`,e.id);break;case`texttrackchange`:this.emit(`texttrackchange`,e.id);break;case`ended`:this.onStreamEnded();break;case`error`:e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??N(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=M({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`ended`||t.state===`gone`)&&this.onStreamEnded()},onAlive:()=>{n=0,r=!1},onError:()=>{this.destroyed||e!==this.loadGen||r||(n+=1,n>=Z&&(r=!0,this.emit(`warning`,new l(`NETWORK`,0,`live-state events unreachable at ${t} after ${n} attempts — end-of-stream detection degraded to the HLS staleness watchdog. Check the events host, the api-key's allowed origins, and CSP connect-src.`))))}})}closeLiveState(){this.liveStateSub?.close(),this.liveStateSub=null}onStreamEnded(){this.destroyed||this.endedHandled||(this.endedHandled=!0,this.closeLiveState(),this.stopRefresh(),this.engine?.stop(),this.setState(`ended`))}mountControls(){let e=this.opts.controls??`custom`,t=this.opts.video;if(e===`native`){t.controls=!0;return}if(e===`none`){t.controls=!1;return}t.controls=!1;let n=(t.ownerDocument??document).createElement(`div`),r=t.parentNode;r&&r.insertBefore(n,t),n.appendChild(t),q(n,this.opts.theme),this.container=n,this.controlBar=ke({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,errorMessage:this.opts.errorMessage})}unmountControls(){this.controlBar?.destroy(),this.controlBar=null;let e=this.container;e?.parentNode&&(e.parentNode.insertBefore(this.opts.video,e),e.remove()),this.container=null}attachPipListeners(){let e=this.opts.video,t=()=>this.emit(`pipchange`,!0),n=()=>this.emit(`pipchange`,!1);e.addEventListener(`enterpictureinpicture`,t),e.addEventListener(`leavepictureinpicture`,n),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,t),e.removeEventListener(`leavepictureinpicture`,n)}}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??Le);this.statsTimer=setInterval(()=>{this.engine&&this.emit(`stats`,this.engine.getStats())},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}scheduleLicenseRefresh(){this.stopRefresh();let e=this.opts.licenseRefreshMs??Re;!e||!this._descriptor?.drmEnabled||(this.refreshTimer=setInterval(()=>void this.refreshLicense(),e))}stopRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=void 0}async refreshLicense(){let e=this.engine;if(!(this.destroyed||!e))try{let t=await C(this.resolveOptions());if(this.destroyed||this.engine!==e)return;let n=t.drm?.widevine?.licenseUrl;n&&(e.setLicenseUrl(n),this._descriptor=t)}catch(e){e instanceof l&&!f(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e))}}async play(){if(!this.destroyed)try{await this.opts.video.play()}catch(e){e instanceof DOMException&&e.name===`NotAllowedError`&&this.emit(`autoplayblocked`)}}pause(){this.destroyed||this.opts.video.pause()}setMuted(e){this.destroyed||(this.opts.video.muted=e)}setVolume(e){this.destroyed||(this.opts.video.volume=Math.min(1,Math.max(0,e)))}getStats(){return this.engine?.getStats()??H}getQualityLevels(){return this.engine?.getQualityLevels()??[]}getCurrentQuality(){return this.engine?.getCurrentQuality()??-1}setQuality(e){this.destroyed||this.engine?.setQuality(e===`auto`?-1:e)}setMaxBitrate(e){this.destroyed||this.engine?.setMaxBitrate(e)}getAudioTracks(){return this.engine?.getAudioTracks()??[]}setAudioTrack(e){this.destroyed||this.engine?.setAudioTrack(e)}getTextTracks(){return this.engine?.getTextTracks()??[]}setTextTrack(e){this.destroyed||this.engine?.setTextTrack(e)}seekToLive(){this.destroyed||this.engine?.seekToLive()}async enterPictureInPicture(){if(this.destroyed)return;let e=this.opts.video;typeof e.requestPictureInPicture==`function`&&await e.requestPictureInPicture()}async exitPictureInPicture(){let e=document;e.pictureInPictureElement===this.opts.video&&typeof e.exitPictureInPicture==`function`&&await e.exitPictureInPicture()}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.stopStats(),this.stopRefresh(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null;try{let t=await w({...this.resolveOptions(),waitForLive:this.opts.waitForLive?this.buildWaitConfig():void 0});await this.onResolved(t,e)}catch(t){if(this.destroyed||this.abort.signal.aborted||e!==this.loadGen)return;throw this.fail(t instanceof l?t:new l(`INTERNAL`,0,String(t))),t}}on(e,t){let n=this.listeners[e]??=new Set;return n.add(t),()=>n.delete(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadGen+=1,this.abort.abort(),this.stopStats(),this.stopRefresh(),this.unmountControls(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.detachPip?.(),this.engine?.destroy(),this.engine=null,this.setState(`idle`),this.clearListeners())}clearListeners(){for(let e of Object.keys(this.listeners))this.listeners[e]?.clear()}fail(e){this.setState(`error`),this.emit(`error`,e)}setState(e){if(e!==this._state)switch(this._state=e,this.emit(`statechange`,e),e){case`playing`:this.emit(`playing`);break;case`buffering`:this.emit(`buffering`);break;case`paused`:this.emit(`paused`);break;case`ended`:this.emit(`ended`);break;default:break}}emit(e,t){this.listeners[e]?.forEach(e=>{try{e(t)}catch{}})}};function $(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function Be(e){if(!e.container||typeof e.container.appendChild!=`function`)throw Error(`mountEmbed: opts.container must be a DOM element`);if(!e.src)throw Error(`mountEmbed: opts.src is required`);if(!e.baseUrl||!e.matchUrn)throw Error(`mountEmbed: opts.baseUrl and opts.matchUrn are required`);let t=new URL(e.src,location.href),n=e.allowedFrameOrigin??t.origin;t.searchParams.set(`baseUrl`,e.baseUrl),t.searchParams.set(`matchUrn`,e.matchUrn),t.searchParams.set(`parentOrigin`,location.origin),e.muted!=null&&t.searchParams.set(`muted`,String(e.muted)),e.apiKey&&(t.searchParams.set(`apiKey`,e.apiKey),console.warn(`havik-player: passing apiKey to mountEmbed places it in the iframe URL — DEV/DEMO only. In production inject it server-side into window.HAVIK_EMBED_CONFIG on the embed page.`));let r=document.createElement(`iframe`);r.src=t.toString(),r.allow=`autoplay; encrypted-media; fullscreen`,r.setAttribute(`allowfullscreen`,``),r.referrerPolicy=`no-referrer`,r.setAttribute(`sandbox`,e.sandbox??`allow-scripts allow-same-origin allow-presentation`),r.style.cssText=`border:0;width:100%;height:100%;display:block`,e.container.appendChild(r);let i=new Set,a=t=>{if(t.source!==r.contentWindow||t.origin!==n||!$(t.data))return;let a=t.data;a.type===`oddin:ready`&&a.protocol!==1&&console.warn(`havik-player: embed protocol v${a.protocol} != host v1. Pin the embed page version to the SDK version to avoid skew.`),e.onEvent?.(a),i.forEach(e=>e(a))};window.addEventListener(`message`,a);let o=e=>r.contentWindow?.postMessage(e,n);return{iframe:r,play:()=>o({type:`oddin:play`}),pause:()=>o({type:`oddin:pause`}),setMuted:e=>o({type:`oddin:setMuted`,muted:e}),setVolume:e=>o({type:`oddin:setVolume`,volume:e}),setQuality:e=>o({type:`oddin:setQuality`,index:e}),setMaxBitrate:e=>o({type:`oddin:setMaxBitrate`,bitrate:e}),setAudioTrack:e=>o({type:`oddin:setAudioTrack`,id:e}),setTextTrack:e=>o({type:`oddin:setTextTrack`,id:e}),seekToLive:()=>o({type:`oddin:seekToLive`}),enterPip:()=>o({type:`oddin:enterPip`}),exitPip:()=>o({type:`oddin:exitPip`}),retry:()=>o({type:`oddin:retry`}),load:e=>o({type:`oddin:load`,matchUrn:e}),on:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{o({type:`oddin:destroy`}),window.removeEventListener(`message`,a),r.remove()}}}var Ve=/^[A-Za-z0-9:_.-]{1,128}$/;function He(){let e=window.HAVIK_EMBED_CONFIG;if(e)return{baseUrl:e.baseUrl??``,matchUrn:e.matchUrn??``,apiKey:e.apiKey??``,parentOrigin:e.parentOrigin,autoplay:e.autoplay??!0,muted:e.muted??!0,waitForLive:e.waitForLive??!0};let t=new URLSearchParams(location.search);return{baseUrl:t.get(`baseUrl`)??``,matchUrn:t.get(`matchUrn`)??``,apiKey:t.get(`apiKey`)??``,parentOrigin:t.get(`parentOrigin`)??void 0,autoplay:!0,muted:t.get(`muted`)!==`false`,waitForLive:!0}}async function Ue(){let e=He();Ge();let t=document.createElement(`video`);t.setAttribute(`playsinline`,``),t.muted=e.muted??!0,t.style.cssText=`width:100%;height:100%;object-fit:contain;background:#000;aspect-ratio:auto`,document.body.appendChild(t);let n=e.parentOrigin&&e.parentOrigin!==`null`?e.parentOrigin:null;n||console.warn(`havik-player: embed has no parentOrigin — the postMessage bridge is disabled (no events posted, no commands accepted). mountEmbed sets parentOrigin automatically.`);let r=e=>{if(n)try{window.parent?.postMessage(e,n)}catch{}};if(!e.baseUrl||!e.matchUrn||!e.apiKey){r({type:`oddin:error`,code:`INTERNAL`,message:`embed missing baseUrl/matchUrn/apiKey`});return}let i=null,a=e=>{e.on(`statechange`,e=>r({type:`oddin:state`,state:e})),e.on(`ready`,()=>r({type:`oddin:tracks`,quality:e.getQualityLevels(),audio:e.getAudioTracks(),text:e.getTextTracks()})),e.on(`waiting`,e=>r({type:`oddin:waiting`,retryInMs:e.retryInMs,attempt:e.attempt,phase:e.phase})),e.on(`qualitychange`,e=>r({type:`oddin:qualitychange`,index:e})),e.on(`audiotrackchange`,e=>r({type:`oddin:audiotrackchange`,id:e})),e.on(`texttrackchange`,e=>r({type:`oddin:texttrackchange`,id:e})),e.on(`stats`,e=>r({type:`oddin:stats`,droppedFrames:e.droppedFrames,latencySeconds:e.latencySeconds,bandwidthKbps:e.bandwidthKbps,levelHeight:e.levelHeight,lowLatency:e.lowLatency,isLive:e.isLive,atLiveEdge:e.atLiveEdge})),e.on(`error`,e=>r({type:`oddin:error`,code:e.code,message:e.message})),e.on(`autoplayblocked`,()=>{r({type:`oddin:autoplayblocked`}),We(t,e)})},o=async n=>{i?.destroy(),i=null;try{let r=await Q({video:t,baseUrl:e.baseUrl,matchUrn:n,credential:{apiKey:e.apiKey},autoplay:e.autoplay,muted:e.muted,waitForLive:e.waitForLive});i=r;let o=t.parentElement;o?.classList.contains(`havik-player`)&&(o.style.cssText=`position:absolute;inset:0;width:100%;height:100%;aspect-ratio:auto`),a(r)}catch(e){let t=e instanceof l?e.code:`INTERNAL`,n=e instanceof Error?e.message:String(e);r({type:`oddin:error`,code:t,message:n})}},s=()=>{window.removeEventListener(`message`,u),window.removeEventListener(`pagehide`,s),i?.destroy(),i=null},c=e=>{switch(e.type){case`oddin:play`:i?.play();break;case`oddin:pause`:i?.pause();break;case`oddin:setMuted`:typeof e.muted==`boolean`&&i?.setMuted(e.muted);break;case`oddin:setVolume`:typeof e.volume==`number`&&Number.isFinite(e.volume)&&i?.setVolume(e.volume);break;case`oddin:setQuality`:typeof e.index==`number`&&i?.setQuality(e.index);break;case`oddin:setMaxBitrate`:(e.bitrate===null||typeof e.bitrate==`number`&&Number.isFinite(e.bitrate))&&i?.setMaxBitrate(e.bitrate);break;case`oddin:setAudioTrack`:typeof e.id==`number`&&i?.setAudioTrack(e.id);break;case`oddin:setTextTrack`:typeof e.id==`number`&&i?.setTextTrack(e.id);break;case`oddin:seekToLive`:i?.seekToLive();break;case`oddin:enterPip`:i?.enterPictureInPicture();break;case`oddin:exitPip`:i?.exitPictureInPicture();break;case`oddin:retry`:i?.retry();break;case`oddin:load`:typeof e.matchUrn==`string`&&Ve.test(e.matchUrn)&&o(e.matchUrn);break;case`oddin:destroy`:s();break}},u=e=>{!n||e.origin!==n||$(e.data)&&c(e.data)};n&&window.addEventListener(`message`,u),window.addEventListener(`pagehide`,s,{once:!0}),await o(e.matchUrn),r({type:`oddin:ready`,protocol:1})}function We(e,t){if(document.getElementById(`havik-tap`))return;let n=document.createElement(`button`);n.id=`havik-tap`,n.textContent=`▶ Tap to play`,n.style.cssText=`position:fixed;inset:0;width:100%;height:100%;border:0;background:rgba(0,0,0,.55);color:#fff;font:600 18px system-ui,sans-serif;cursor:pointer;z-index:9`,n.addEventListener(`click`,()=>{n.remove(),t.play()}),document.body.appendChild(n)}function Ge(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}exports.ODDIN_THEME=G,exports.PlaybackError=l,exports.applyTheme=q,exports.bootEmbed=Ue,exports.clearDeviceId=L,exports.createPlayer=Q,exports.deriveEventsBaseUrl=N,exports.fetchCatalog=E,exports.fetchTournament=O,exports.flattenMatches=A,exports.getDeviceId=I,exports.isLowLatencyManifest=V,exports.isOddinMessage=$,exports.licenseRequestHeaders=z,exports.mountEmbed=Be,exports.pollToLive=S,exports.resolveStream=w,exports.subscribeLiveState=M,exports.watchStatus=j;
108
+ //# sourceMappingURL=index.cjs.map