import { AssetSource, AssetType, PERMISSIONS, byte_size_default, getTrad, pluginId, sortOptions, tableHeaders, urlSchema } from "./chunk-ALMC553V.js"; import { useDrag, useDrop } from "./chunk-S3HPKOXW.js"; import { useMutation, useQuery, useQueryClient } from "./chunk-QLEKUQKW.js"; import { useFetchClient } from "./chunk-FCIM6RNO.js"; import { ConfirmDialog } from "./chunk-NP53ZCXD.js"; import { _arrayLikeToArray, _classCallCheck, _createClass, _createSuper, _inherits, _unsupportedIterableToArray, intervalToDuration } from "./chunk-KFLQQE5L.js"; import { require_isEmpty } from "./chunk-YJEURQPS.js"; import { Form, Formik } from "./chunk-PW7XKCYO.js"; import { create4 as create, create5 as create2, create6 as create3 } from "./chunk-XLSIZGJF.js"; import { useTracking } from "./chunk-GSN7U3BK.js"; import { useClipboard } from "./chunk-7PUJSL55.js"; import { useRBAC } from "./chunk-CMLQV3Z2.js"; import { parseISO } from "./chunk-D4WYVNVM.js"; import { Layouts } from "./chunk-TIVRAWTC.js"; import { require_isEqual } from "./chunk-VYSYYPOB.js"; import { ForwardRef$J } from "./chunk-5CAWUBTQ.js"; import { useQueryParams } from "./chunk-W2TBR6J3.js"; import { require_lib } from "./chunk-LCL5TIBZ.js"; import { _defineProperty, _objectSpread2, _typeof } from "./chunk-WOQNBAGN.js"; import { useNotification } from "./chunk-N55RVBRV.js"; import { Avatar, Badge, Box, Breadcrumbs, Button, Card, CardActionImpl, CardAsset, CardBadge, CardBody, CardCheckbox, CardContent, CardHeader, CardSubtitle, CardTimer, CardTitle, CheckboxImpl, Crumb, CrumbLink, CrumbSimpleMenu, DateTimePicker, Dialog, Divider, Field, Flex, FocusTrap, Grid, IconButton, KeyboardNavigable, Loader, Menu, MenuItem, Modal, Popover, ProgressBar, SingleSelect, SingleSelectOption, Table, Tabs, Tag, Tbody, Td, TextInput, Textarea, Th, Thead, TooltipImpl, Tr, Typography, VisuallyHidden, _extends, _objectWithoutPropertiesLoose, autoUpdate, require_hoist_non_react_statics_cjs, useIntl, useNotifyAT } from "./chunk-7XB6XSWQ.js"; import { Link, NavLink, useLocation } from "./chunk-TUXTO2Z5.js"; import { require_react_dom } from "./chunk-FOD4ENRR.js"; import { ForwardRef$1f, ForwardRef$1h, ForwardRef$1v, ForwardRef$2r, ForwardRef$3D, ForwardRef$3V, ForwardRef$3h, ForwardRef$3p, ForwardRef$3v, ForwardRef$45, ForwardRef$47, ForwardRef$4F, ForwardRef$4R, ForwardRef$4T, ForwardRef$4t, ForwardRef$4z, ForwardRef$j } from "./chunk-WRD5KPDH.js"; import { require_jsx_runtime } from "./chunk-NIAJZ5MX.js"; import { dt, nt } from "./chunk-ACIMPXWY.js"; import { require_react } from "./chunk-MADUDGYZ.js"; import { __toESM } from "./chunk-PLDDJCW6.js"; // node_modules/@strapi/upload/dist/admin/hooks/useAssets.mjs var React = __toESM(require_react(), 1); var useAssets = ({ skipWhen = false, query = {} } = {}) => { var _a3; const { formatMessage } = useIntl(); const { toggleNotification } = useNotification(); const { notifyStatus } = useNotifyAT(); const { get } = useFetchClient(); const { folderPath, _q, ...paramsExceptFolderAndQ } = query; let params; if (_q) { params = { ...paramsExceptFolderAndQ, _q: encodeURIComponent(_q) }; } else { params = { ...paramsExceptFolderAndQ, filters: { $and: [ ...((_a3 = paramsExceptFolderAndQ == null ? void 0 : paramsExceptFolderAndQ.filters) == null ? void 0 : _a3.$and) ?? [], { folderPath: { $eq: folderPath ?? "/" } } ] } }; } const { data, error, isLoading } = useQuery([ pluginId, "assets", params ], async () => { const { data: data2 } = await get("/upload/files", { params }); return data2; }, { enabled: !skipWhen, staleTime: 0, cacheTime: 0, select(data2) { if ((data2 == null ? void 0 : data2.results) && Array.isArray(data2.results)) { return { ...data2, results: data2.results.filter((asset) => asset.name).map((asset) => ({ ...asset, /** * Mime and ext cannot be null in the front-end because * we expect them to be strings and use the `includes` method. */ mime: asset.mime ?? "", ext: asset.ext ?? "" })) }; } return data2; } }); React.useEffect(() => { if (data) { notifyStatus(formatMessage({ id: "list.asset.at.finished", defaultMessage: "The assets have finished loading." })); } }, [ data, formatMessage, notifyStatus ]); React.useEffect(() => { if (error) { toggleNotification({ type: "danger", message: formatMessage({ id: "notification.error" }) }); } }, [ error, formatMessage, toggleNotification ]); return { data, error, isLoading }; }; // node_modules/@strapi/upload/dist/admin/hooks/useFolders.mjs var React2 = __toESM(require_react(), 1); var import_qs = __toESM(require_lib(), 1); var useFolders = ({ enabled = true, query = {} } = {}) => { var _a3; const { formatMessage } = useIntl(); const { toggleNotification } = useNotification(); const { notifyStatus } = useNotifyAT(); const { folder, _q, ...paramsExceptFolderAndQ } = query; const { get } = useFetchClient(); let params; if (_q) { params = { ...paramsExceptFolderAndQ, pagination: { pageSize: -1 }, _q }; } else { params = { ...paramsExceptFolderAndQ, pagination: { pageSize: -1 }, filters: { $and: [ ...((_a3 = paramsExceptFolderAndQ == null ? void 0 : paramsExceptFolderAndQ.filters) == null ? void 0 : _a3.$and) ?? [], { parent: { id: folder ?? { $null: true } } } ] } }; } const { data, error, isLoading } = useQuery([ pluginId, "folders", (0, import_qs.stringify)(params) ], async () => { const { data: { data: data2 } } = await get("/upload/folders", { params }); return data2; }, { enabled, staleTime: 0, cacheTime: 0, onError() { toggleNotification({ type: "danger", message: formatMessage({ id: "notification.error" }) }); } }); React2.useEffect(() => { if (data) { notifyStatus(formatMessage({ id: "list.asset.at.finished", defaultMessage: "The folders have finished loading." })); } }, [ data, formatMessage, notifyStatus ]); return { data, error, isLoading }; }; // node_modules/@strapi/upload/dist/admin/hooks/useMediaLibraryPermissions.mjs var { main: _main, ...restPermissions } = PERMISSIONS; var useMediaLibraryPermissions = () => { const { allowedActions, isLoading } = useRBAC(restPermissions); return { ...allowedActions, isLoading }; }; // node_modules/@strapi/upload/dist/admin/hooks/useSelectionState.mjs var React3 = __toESM(require_react(), 1); var useSelectionState = (keys, initialValue) => { const [selections, setSelections] = React3.useState(initialValue); const selectOne = (selection) => { const index2 = selections.findIndex((currentSelection) => keys.every((key) => currentSelection[key] === selection[key])); if (index2 > -1) { setSelections((prevSelected) => [ ...prevSelected.slice(0, index2), ...prevSelected.slice(index2 + 1) ]); } else { setSelections((prevSelected) => [ ...prevSelected, selection ]); } }; const selectAll = (nextSelections) => { if (selections.length > 0) { setSelections([]); } else { setSelections(nextSelections); } }; const selectOnly = (nextSelection) => { const index2 = selections.findIndex((currentSelection) => keys.every((key) => currentSelection[key] === nextSelection[key])); if (index2 > -1) { setSelections([]); } else { setSelections([ nextSelection ]); } }; const selectMultiple = (nextSelections) => { setSelections((currSelections) => [ // already selected items ...currSelections, // filter out already selected items from nextSelections ...nextSelections.filter((nextSelection) => currSelections.findIndex((currentSelection) => keys.every((key) => currentSelection[key] === nextSelection[key])) === -1) ]); }; const deselectMultiple = (nextSelections) => { setSelections((currSelections) => [ // filter out items in currSelections that are in nextSelections ...currSelections.filter((currentSelection) => nextSelections.findIndex((nextSelection) => keys.every((key) => currentSelection[key] === nextSelection[key])) === -1) ]); }; return [ selections, { selectOne, selectAll, selectOnly, selectMultiple, deselectMultiple, setSelections } ]; }; // node_modules/@strapi/upload/dist/admin/utils/containsAssetFilter.mjs var containsMimeTypeFilter = (query) => { var _a3; const filters = (_a3 = query == null ? void 0 : query.filters) == null ? void 0 : _a3.$and; if (!filters) { return false; } const result = filters.find((filter) => { return Object.keys(filter).includes("mime"); }); return !!result; }; var containsAssetFilter = (query) => { return containsMimeTypeFilter(query); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/EditAssetContent.mjs var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1); var React16 = __toESM(require_react(), 1); var import_isEqual = __toESM(require_isEqual(), 1); // node_modules/@strapi/upload/dist/admin/hooks/useEditAsset.mjs var React4 = __toESM(require_react(), 1); var import_qs2 = __toESM(require_lib(), 1); var editAssetRequest = (asset, file, signal, onProgress, post) => { const endpoint2 = `/${pluginId}?id=${asset.id}`; const formData = new FormData(); if (file) { formData.append("files", file); } formData.append("fileInfo", JSON.stringify({ alternativeText: asset.alternativeText, caption: asset.caption, folder: asset.folder, name: asset.name })); return post(endpoint2, formData, { signal }).then((res) => res.data); }; var useEditAsset = () => { const [progress, setProgress] = React4.useState(0); const { formatMessage } = useIntl(); const { toggleNotification } = useNotification(); const queryClient = useQueryClient(); const abortController = new AbortController(); const signal = abortController.signal; const { post } = useFetchClient(); const mutation = useMutation(({ asset, file }) => editAssetRequest(asset, file, signal, setProgress, post), { onSuccess() { queryClient.refetchQueries([ pluginId, "assets" ], { active: true }); queryClient.refetchQueries([ pluginId, "asset-count" ], { active: true }); queryClient.refetchQueries([ pluginId, "folders" ], { active: true }); }, onError(reason) { var _a3; if (((_a3 = reason == null ? void 0 : reason.response) == null ? void 0 : _a3.status) === 403) { toggleNotification({ type: "info", message: formatMessage({ id: getTrad("permissions.not-allowed.update") }) }); } else { toggleNotification({ type: "danger", message: reason == null ? void 0 : reason.message }); } } }); const editAsset = (asset, file) => mutation.mutateAsync({ asset, file }); const cancel = () => abortController.abort(); return { ...mutation, cancel, editAsset, progress, status: mutation.status }; }; // node_modules/@strapi/upload/dist/admin/hooks/useFolderStructure.mjs var import_qs3 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/hooks/utils/renameKeys.mjs var recursiveRenameKeys = (obj, fn) => Object.fromEntries(Object.entries(obj).map(([key, value]) => { const getValue = (v2) => typeof v2 === "object" && v2 !== null ? recursiveRenameKeys(v2, fn) : v2; return [ fn(key), Array.isArray(value) ? value.map((val) => getValue(val)) : getValue(value) ]; })); // node_modules/@strapi/upload/dist/admin/hooks/useFolderStructure.mjs var FIELD_MAPPING = { name: "label", id: "value" }; var useFolderStructure = ({ enabled = true } = {}) => { const { formatMessage } = useIntl(); const { get } = useFetchClient(); const fetchFolderStructure = async () => { const { data: { data: data2 } } = await get("/upload/folder-structure"); const children = data2.map((f) => recursiveRenameKeys(f, (key) => (FIELD_MAPPING == null ? void 0 : FIELD_MAPPING[key]) ?? key)); return [ { value: null, label: formatMessage({ id: getTrad("form.input.label.folder-location-default-label"), defaultMessage: "Media Library" }), children } ]; }; const { data, error, isLoading } = useQuery([ pluginId, "folder", "structure" ], fetchFolderStructure, { enabled, staleTime: 0, cacheTime: 0 }); return { data, error, isLoading }; }; // node_modules/@strapi/upload/dist/admin/utils/findRecursiveFolderByValue.mjs function findRecursiveFolderByValue(data, value) { let result; function iter(a2) { if (a2.value === value) { result = a2; return true; } return Array.isArray(a2.children) && a2.children.some(iter); } data.some(iter); return result; } // node_modules/@strapi/upload/dist/admin/utils/formatBytes.mjs function formatBytes(receivedBytes, decimals = 0) { const realBytes = typeof receivedBytes === "string" ? Number(receivedBytes) : receivedBytes; const { value, unit } = byte_size_default(realBytes * 1e3, { precision: decimals }); if (!unit) { return "0B"; } return `${value}${unit.toUpperCase()}`; } // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/EditAssetContent.mjs var import_qs8 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/utils/getFileExtension.mjs var getFileExtension = (ext) => ext && ext[0] === "." ? ext.substring(1) : ext; // node_modules/@strapi/upload/dist/admin/components/ContextInfo/ContextInfo.mjs var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); var ContextInfo = ({ blocks }) => { return (0, import_jsx_runtime.jsx)(Box, { hasRadius: true, paddingLeft: 6, paddingRight: 6, paddingTop: 4, paddingBottom: 4, background: "neutral100", children: (0, import_jsx_runtime.jsx)(Grid.Root, { gap: 4, children: blocks.map(({ label, value }) => (0, import_jsx_runtime.jsx)(Grid.Item, { col: 6, xs: 12, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime.jsxs)(Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [ (0, import_jsx_runtime.jsx)(Typography, { variant: "sigma", textColor: "neutral600", children: label }), (0, import_jsx_runtime.jsx)(Typography, { variant: "pi", textColor: "neutral700", children: value }) ] }) }, label)) }) }); }; // node_modules/@strapi/upload/dist/admin/components/SelectTree/SelectTree.mjs var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); var React10 = __toESM(require_react(), 1); // node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js function _arrayWithHoles(r9) { if (Array.isArray(r9)) return r9; } // node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js function _iterableToArrayLimit(r9, l2) { var t2 = null == r9 ? null : "undefined" != typeof Symbol && r9[Symbol.iterator] || r9["@@iterator"]; if (null != t2) { var e, n2, i3, u3, a2 = [], f = true, o2 = false; try { if (i3 = (t2 = t2.call(r9)).next, 0 === l2) { if (Object(t2) !== t2) return; f = false; } else for (; !(f = (e = i3.call(t2)).done) && (a2.push(e.value), a2.length !== l2); f = true) ; } catch (r10) { o2 = true, n2 = r10; } finally { try { if (!f && null != t2["return"] && (u3 = t2["return"](), Object(u3) !== u3)) return; } finally { if (o2) throw n2; } } return a2; } } // node_modules/@babel/runtime/helpers/esm/nonIterableRest.js function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } // node_modules/@babel/runtime/helpers/esm/slicedToArray.js function _slicedToArray(r9, e) { return _arrayWithHoles(r9) || _iterableToArrayLimit(r9, e) || _unsupportedIterableToArray(r9, e) || _nonIterableRest(); } // node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js function _objectWithoutProperties(e, t2) { if (null == e) return {}; var o2, r9, i3 = _objectWithoutPropertiesLoose(e, t2); if (Object.getOwnPropertySymbols) { var n2 = Object.getOwnPropertySymbols(e); for (r9 = 0; r9 < n2.length; r9++) o2 = n2[r9], -1 === t2.indexOf(o2) && {}.propertyIsEnumerable.call(e, o2) && (i3[o2] = e[o2]); } return i3; } // node_modules/react-select/dist/useStateManager-7e1e8489.esm.js var import_react = __toESM(require_react()); var _excluded = ["defaultInputValue", "defaultMenuIsOpen", "defaultValue", "inputValue", "menuIsOpen", "onChange", "onInputChange", "onMenuClose", "onMenuOpen", "value"]; function useStateManager(_ref3) { var _ref$defaultInputValu = _ref3.defaultInputValue, defaultInputValue = _ref$defaultInputValu === void 0 ? "" : _ref$defaultInputValu, _ref$defaultMenuIsOpe = _ref3.defaultMenuIsOpen, defaultMenuIsOpen = _ref$defaultMenuIsOpe === void 0 ? false : _ref$defaultMenuIsOpe, _ref$defaultValue = _ref3.defaultValue, defaultValue = _ref$defaultValue === void 0 ? null : _ref$defaultValue, propsInputValue = _ref3.inputValue, propsMenuIsOpen = _ref3.menuIsOpen, propsOnChange = _ref3.onChange, propsOnInputChange = _ref3.onInputChange, propsOnMenuClose = _ref3.onMenuClose, propsOnMenuOpen = _ref3.onMenuOpen, propsValue = _ref3.value, restSelectProps = _objectWithoutProperties(_ref3, _excluded); var _useState = (0, import_react.useState)(propsInputValue !== void 0 ? propsInputValue : defaultInputValue), _useState2 = _slicedToArray(_useState, 2), stateInputValue = _useState2[0], setStateInputValue = _useState2[1]; var _useState3 = (0, import_react.useState)(propsMenuIsOpen !== void 0 ? propsMenuIsOpen : defaultMenuIsOpen), _useState4 = _slicedToArray(_useState3, 2), stateMenuIsOpen = _useState4[0], setStateMenuIsOpen = _useState4[1]; var _useState5 = (0, import_react.useState)(propsValue !== void 0 ? propsValue : defaultValue), _useState6 = _slicedToArray(_useState5, 2), stateValue = _useState6[0], setStateValue = _useState6[1]; var onChange2 = (0, import_react.useCallback)(function(value2, actionMeta) { if (typeof propsOnChange === "function") { propsOnChange(value2, actionMeta); } setStateValue(value2); }, [propsOnChange]); var onInputChange = (0, import_react.useCallback)(function(value2, actionMeta) { var newValue; if (typeof propsOnInputChange === "function") { newValue = propsOnInputChange(value2, actionMeta); } setStateInputValue(newValue !== void 0 ? newValue : value2); }, [propsOnInputChange]); var onMenuOpen = (0, import_react.useCallback)(function() { if (typeof propsOnMenuOpen === "function") { propsOnMenuOpen(); } setStateMenuIsOpen(true); }, [propsOnMenuOpen]); var onMenuClose = (0, import_react.useCallback)(function() { if (typeof propsOnMenuClose === "function") { propsOnMenuClose(); } setStateMenuIsOpen(false); }, [propsOnMenuClose]); var inputValue = propsInputValue !== void 0 ? propsInputValue : stateInputValue; var menuIsOpen = propsMenuIsOpen !== void 0 ? propsMenuIsOpen : stateMenuIsOpen; var value = propsValue !== void 0 ? propsValue : stateValue; return _objectSpread2(_objectSpread2({}, restSelectProps), {}, { inputValue, menuIsOpen, onChange: onChange2, onInputChange, onMenuClose, onMenuOpen, value }); } // node_modules/react-select/dist/react-select.esm.js var React9 = __toESM(require_react()); var import_react8 = __toESM(require_react()); // node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js function _arrayWithoutHoles(r9) { if (Array.isArray(r9)) return _arrayLikeToArray(r9); } // node_modules/@babel/runtime/helpers/esm/iterableToArray.js function _iterableToArray(r9) { if ("undefined" != typeof Symbol && null != r9[Symbol.iterator] || null != r9["@@iterator"]) return Array.from(r9); } // node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } // node_modules/@babel/runtime/helpers/esm/toConsumableArray.js function _toConsumableArray(r9) { return _arrayWithoutHoles(r9) || _iterableToArray(r9) || _unsupportedIterableToArray(r9) || _nonIterableSpread(); } // node_modules/react-select/dist/Select-49a62830.esm.js var React8 = __toESM(require_react()); var import_react6 = __toESM(require_react()); // node_modules/@emotion/react/dist/emotion-element-489459f2.browser.development.esm.js var React6 = __toESM(require_react()); var import_react2 = __toESM(require_react()); // node_modules/@emotion/sheet/dist/emotion-sheet.development.esm.js var isDevelopment = true; function sheetForTag(tag) { if (tag.sheet) { return tag.sheet; } for (var i3 = 0; i3 < document.styleSheets.length; i3++) { if (document.styleSheets[i3].ownerNode === tag) { return document.styleSheets[i3]; } } return void 0; } function createStyleElement(options2) { var tag = document.createElement("style"); tag.setAttribute("data-emotion", options2.key); if (options2.nonce !== void 0) { tag.setAttribute("nonce", options2.nonce); } tag.appendChild(document.createTextNode("")); tag.setAttribute("data-s", ""); return tag; } var StyleSheet = function() { function StyleSheet2(options2) { var _this = this; this._insertTag = function(tag) { var before; if (_this.tags.length === 0) { if (_this.insertionPoint) { before = _this.insertionPoint.nextSibling; } else if (_this.prepend) { before = _this.container.firstChild; } else { before = _this.before; } } else { before = _this.tags[_this.tags.length - 1].nextSibling; } _this.container.insertBefore(tag, before); _this.tags.push(tag); }; this.isSpeedy = options2.speedy === void 0 ? !isDevelopment : options2.speedy; this.tags = []; this.ctr = 0; this.nonce = options2.nonce; this.key = options2.key; this.container = options2.container; this.prepend = options2.prepend; this.insertionPoint = options2.insertionPoint; this.before = null; } var _proto = StyleSheet2.prototype; _proto.hydrate = function hydrate(nodes) { nodes.forEach(this._insertTag); }; _proto.insert = function insert(rule) { if (this.ctr % (this.isSpeedy ? 65e3 : 1) === 0) { this._insertTag(createStyleElement(this)); } var tag = this.tags[this.tags.length - 1]; { var isImportRule3 = rule.charCodeAt(0) === 64 && rule.charCodeAt(1) === 105; if (isImportRule3 && this._alreadyInsertedOrderInsensitiveRule) { console.error("You're attempting to insert the following rule:\n" + rule + "\n\n`@import` rules must be before all other types of rules in a stylesheet but other rules have already been inserted. Please ensure that `@import` rules are before all other rules."); } this._alreadyInsertedOrderInsensitiveRule = this._alreadyInsertedOrderInsensitiveRule || !isImportRule3; } if (this.isSpeedy) { var sheet = sheetForTag(tag); try { sheet.insertRule(rule, sheet.cssRules.length); } catch (e) { if (!/:(-moz-placeholder|-moz-focus-inner|-moz-focusring|-ms-input-placeholder|-moz-read-write|-moz-read-only|-ms-clear|-ms-expand|-ms-reveal){/.test(rule)) { console.error('There was a problem inserting the following rule: "' + rule + '"', e); } } } else { tag.appendChild(document.createTextNode(rule)); } this.ctr++; }; _proto.flush = function flush() { this.tags.forEach(function(tag) { var _tag$parentNode; return (_tag$parentNode = tag.parentNode) == null ? void 0 : _tag$parentNode.removeChild(tag); }); this.tags = []; this.ctr = 0; { this._alreadyInsertedOrderInsensitiveRule = false; } }; return StyleSheet2; }(); // node_modules/stylis/src/Enum.js var MS = "-ms-"; var MOZ = "-moz-"; var WEBKIT = "-webkit-"; var COMMENT = "comm"; var RULESET = "rule"; var DECLARATION = "decl"; var IMPORT = "@import"; var KEYFRAMES = "@keyframes"; var LAYER = "@layer"; // node_modules/stylis/src/Utility.js var abs = Math.abs; var from = String.fromCharCode; var assign = Object.assign; function hash(value, length2) { return charat(value, 0) ^ 45 ? (((length2 << 2 ^ charat(value, 0)) << 2 ^ charat(value, 1)) << 2 ^ charat(value, 2)) << 2 ^ charat(value, 3) : 0; } function trim(value) { return value.trim(); } function match(value, pattern) { return (value = pattern.exec(value)) ? value[0] : value; } function replace(value, pattern, replacement) { return value.replace(pattern, replacement); } function indexof(value, search) { return value.indexOf(search); } function charat(value, index2) { return value.charCodeAt(index2) | 0; } function substr(value, begin, end) { return value.slice(begin, end); } function strlen(value) { return value.length; } function sizeof(value) { return value.length; } function append(value, array) { return array.push(value), value; } function combine(array, callback) { return array.map(callback).join(""); } // node_modules/stylis/src/Tokenizer.js var line = 1; var column = 1; var length = 0; var position = 0; var character = 0; var characters = ""; function node(value, root, parent, type, props, children, length2) { return { value, root, parent, type, props, children, line, column, length: length2, return: "" }; } function copy(root, props) { return assign(node("", null, null, "", null, null, 0), root, { length: -root.length }, props); } function char() { return character; } function prev() { character = position > 0 ? charat(characters, --position) : 0; if (column--, character === 10) column = 1, line--; return character; } function next() { character = position < length ? charat(characters, position++) : 0; if (column++, character === 10) column = 1, line++; return character; } function peek() { return charat(characters, position); } function caret() { return position; } function slice(begin, end) { return substr(characters, begin, end); } function token(type) { switch (type) { case 0: case 9: case 10: case 13: case 32: return 5; case 33: case 43: case 44: case 47: case 62: case 64: case 126: case 59: case 123: case 125: return 4; case 58: return 3; case 34: case 39: case 40: case 91: return 2; case 41: case 93: return 1; } return 0; } function alloc(value) { return line = column = 1, length = strlen(characters = value), position = 0, []; } function dealloc(value) { return characters = "", value; } function delimit(type) { return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type))); } function whitespace(type) { while (character = peek()) if (character < 33) next(); else break; return token(type) > 2 || token(character) > 3 ? "" : " "; } function escaping(index2, count) { while (--count && next()) if (character < 48 || character > 102 || character > 57 && character < 65 || character > 70 && character < 97) break; return slice(index2, caret() + (count < 6 && peek() == 32 && next() == 32)); } function delimiter(type) { while (next()) switch (character) { case type: return position; case 34: case 39: if (type !== 34 && type !== 39) delimiter(character); break; case 40: if (type === 41) delimiter(type); break; case 92: next(); break; } return position; } function commenter(type, index2) { while (next()) if (type + character === 47 + 10) break; else if (type + character === 42 + 42 && peek() === 47) break; return "/*" + slice(index2, position - 1) + "*" + from(type === 47 ? type : next()); } function identifier(index2) { while (!token(peek())) next(); return slice(index2, position); } // node_modules/stylis/src/Parser.js function compile(value) { return dealloc(parse("", null, null, null, [""], value = alloc(value), 0, [0], value)); } function parse(value, root, parent, rule, rules, rulesets, pseudo, points, declarations) { var index2 = 0; var offset = 0; var length2 = pseudo; var atrule = 0; var property = 0; var previous = 0; var variable = 1; var scanning = 1; var ampersand = 1; var character2 = 0; var type = ""; var props = rules; var children = rulesets; var reference = rule; var characters2 = type; while (scanning) switch (previous = character2, character2 = next()) { case 40: if (previous != 108 && charat(characters2, length2 - 1) == 58) { if (indexof(characters2 += replace(delimit(character2), "&", "&\f"), "&\f") != -1) ampersand = -1; break; } case 34: case 39: case 91: characters2 += delimit(character2); break; case 9: case 10: case 13: case 32: characters2 += whitespace(previous); break; case 92: characters2 += escaping(caret() - 1, 7); continue; case 47: switch (peek()) { case 42: case 47: append(comment(commenter(next(), caret()), root, parent), declarations); break; default: characters2 += "/"; } break; case 123 * variable: points[index2++] = strlen(characters2) * ampersand; case 125 * variable: case 59: case 0: switch (character2) { case 0: case 125: scanning = 0; case 59 + offset: if (ampersand == -1) characters2 = replace(characters2, /\f/g, ""); if (property > 0 && strlen(characters2) - length2) append(property > 32 ? declaration(characters2 + ";", rule, parent, length2 - 1) : declaration(replace(characters2, " ", "") + ";", rule, parent, length2 - 2), declarations); break; case 59: characters2 += ";"; default: append(reference = ruleset(characters2, root, parent, index2, offset, rules, points, type, props = [], children = [], length2), rulesets); if (character2 === 123) if (offset === 0) parse(characters2, root, reference, reference, props, rulesets, length2, points, children); else switch (atrule === 99 && charat(characters2, 3) === 110 ? 100 : atrule) { case 100: case 108: case 109: case 115: parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length2), children), rules, children, length2, points, rule ? props : children); break; default: parse(characters2, reference, reference, reference, [""], children, 0, points, children); } } index2 = offset = property = 0, variable = ampersand = 1, type = characters2 = "", length2 = pseudo; break; case 58: length2 = 1 + strlen(characters2), property = previous; default: if (variable < 1) { if (character2 == 123) --variable; else if (character2 == 125 && variable++ == 0 && prev() == 125) continue; } switch (characters2 += from(character2), character2 * variable) { case 38: ampersand = offset > 0 ? 1 : (characters2 += "\f", -1); break; case 44: points[index2++] = (strlen(characters2) - 1) * ampersand, ampersand = 1; break; case 64: if (peek() === 45) characters2 += delimit(next()); atrule = peek(), offset = length2 = strlen(type = characters2 += identifier(caret())), character2++; break; case 45: if (previous === 45 && strlen(characters2) == 2) variable = 0; } } return rulesets; } function ruleset(value, root, parent, index2, offset, rules, points, type, props, children, length2) { var post = offset - 1; var rule = offset === 0 ? rules : [""]; var size = sizeof(rule); for (var i3 = 0, j3 = 0, k3 = 0; i3 < index2; ++i3) for (var x2 = 0, y4 = substr(value, post + 1, post = abs(j3 = points[i3])), z3 = value; x2 < size; ++x2) if (z3 = trim(j3 > 0 ? rule[x2] + " " + y4 : replace(y4, /&\f/g, rule[x2]))) props[k3++] = z3; return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length2); } function comment(value, root, parent) { return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0); } function declaration(value, root, parent, length2) { return node(value, root, parent, DECLARATION, substr(value, 0, length2), substr(value, length2 + 1, -1), length2); } // node_modules/stylis/src/Serializer.js function serialize(children, callback) { var output2 = ""; var length2 = sizeof(children); for (var i3 = 0; i3 < length2; i3++) output2 += callback(children[i3], i3, children, callback) || ""; return output2; } function stringify2(element, index2, children, callback) { switch (element.type) { case LAYER: if (element.children.length) break; case IMPORT: case DECLARATION: return element.return = element.return || element.value; case COMMENT: return ""; case KEYFRAMES: return element.return = element.value + "{" + serialize(element.children, callback) + "}"; case RULESET: element.value = element.props.join(","); } return strlen(children = serialize(element.children, callback)) ? element.return = element.value + "{" + children + "}" : ""; } // node_modules/stylis/src/Middleware.js function middleware(collection) { var length2 = sizeof(collection); return function(element, index2, children, callback) { var output2 = ""; for (var i3 = 0; i3 < length2; i3++) output2 += collection[i3](element, index2, children, callback) || ""; return output2; }; } // node_modules/@emotion/weak-memoize/dist/emotion-weak-memoize.esm.js var weakMemoize = function weakMemoize2(func) { var cache = /* @__PURE__ */ new WeakMap(); return function(arg) { if (cache.has(arg)) { return cache.get(arg); } var ret = func(arg); cache.set(arg, ret); return ret; }; }; // node_modules/@emotion/memoize/dist/emotion-memoize.esm.js function memoize(fn) { var cache = /* @__PURE__ */ Object.create(null); return function(arg) { if (cache[arg] === void 0) cache[arg] = fn(arg); return cache[arg]; }; } // node_modules/@emotion/cache/dist/emotion-cache.browser.development.esm.js var identifierWithPointTracking = function identifierWithPointTracking2(begin, points, index2) { var previous = 0; var character2 = 0; while (true) { previous = character2; character2 = peek(); if (previous === 38 && character2 === 12) { points[index2] = 1; } if (token(character2)) { break; } next(); } return slice(begin, position); }; var toRules = function toRules2(parsed, points) { var index2 = -1; var character2 = 44; do { switch (token(character2)) { case 0: if (character2 === 38 && peek() === 12) { points[index2] = 1; } parsed[index2] += identifierWithPointTracking(position - 1, points, index2); break; case 2: parsed[index2] += delimit(character2); break; case 4: if (character2 === 44) { parsed[++index2] = peek() === 58 ? "&\f" : ""; points[index2] = parsed[index2].length; break; } default: parsed[index2] += from(character2); } } while (character2 = next()); return parsed; }; var getRules = function getRules2(value, points) { return dealloc(toRules(alloc(value), points)); }; var fixedElements = /* @__PURE__ */ new WeakMap(); var compat = function compat2(element) { if (element.type !== "rule" || !element.parent || // positive .length indicates that this rule contains pseudo // negative .length indicates that this rule has been already prefixed element.length < 1) { return; } var value = element.value; var parent = element.parent; var isImplicitRule = element.column === parent.column && element.line === parent.line; while (parent.type !== "rule") { parent = parent.parent; if (!parent) return; } if (element.props.length === 1 && value.charCodeAt(0) !== 58 && !fixedElements.get(parent)) { return; } if (isImplicitRule) { return; } fixedElements.set(element, true); var points = []; var rules = getRules(value, points); var parentRules = parent.props; for (var i3 = 0, k3 = 0; i3 < rules.length; i3++) { for (var j3 = 0; j3 < parentRules.length; j3++, k3++) { element.props[k3] = points[i3] ? rules[i3].replace(/&\f/g, parentRules[j3]) : parentRules[j3] + " " + rules[i3]; } } }; var removeLabel = function removeLabel2(element) { if (element.type === "decl") { var value = element.value; if ( // charcode for l value.charCodeAt(0) === 108 && // charcode for b value.charCodeAt(2) === 98 ) { element["return"] = ""; element.value = ""; } } }; var ignoreFlag = "emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason"; var isIgnoringComment = function isIgnoringComment2(element) { return element.type === "comm" && element.children.indexOf(ignoreFlag) > -1; }; var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm2(cache) { return function(element, index2, children) { if (element.type !== "rule" || cache.compat) return; var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g); if (unsafePseudoClasses) { var isNested = !!element.parent; var commentContainer = isNested ? element.parent.children : ( // global rule at the root level children ); for (var i3 = commentContainer.length - 1; i3 >= 0; i3--) { var node2 = commentContainer[i3]; if (node2.line < element.line) { break; } if (node2.column < element.column) { if (isIgnoringComment(node2)) { return; } break; } } unsafePseudoClasses.forEach(function(unsafePseudoClass) { console.error('The pseudo class "' + unsafePseudoClass + '" is potentially unsafe when doing server-side rendering. Try changing it to "' + unsafePseudoClass.split("-child")[0] + '-of-type".'); }); } }; }; var isImportRule = function isImportRule2(element) { return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64; }; var isPrependedWithRegularRules = function isPrependedWithRegularRules2(index2, children) { for (var i3 = index2 - 1; i3 >= 0; i3--) { if (!isImportRule(children[i3])) { return true; } } return false; }; var nullifyElement = function nullifyElement2(element) { element.type = ""; element.value = ""; element["return"] = ""; element.children = ""; element.props = ""; }; var incorrectImportAlarm = function incorrectImportAlarm2(element, index2, children) { if (!isImportRule(element)) { return; } if (element.parent) { console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles."); nullifyElement(element); } else if (isPrependedWithRegularRules(index2, children)) { console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules."); nullifyElement(element); } }; function prefix2(value, length2) { switch (hash(value, length2)) { case 5103: return WEBKIT + "print-" + value + value; case 5737: case 4201: case 3177: case 3433: case 1641: case 4457: case 2921: case 5572: case 6356: case 5844: case 3191: case 6645: case 3005: case 6391: case 5879: case 5623: case 6135: case 4599: case 4855: case 4215: case 6389: case 5109: case 5365: case 5621: case 3829: return WEBKIT + value + value; case 5349: case 4246: case 4810: case 6968: case 2756: return WEBKIT + value + MOZ + value + MS + value + value; case 6828: case 4268: return WEBKIT + value + MS + value + value; case 6165: return WEBKIT + value + MS + "flex-" + value + value; case 5187: return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + "box-$1$2" + MS + "flex-$1$2") + value; case 5443: return WEBKIT + value + MS + "flex-item-" + replace(value, /flex-|-self/, "") + value; case 4675: return WEBKIT + value + MS + "flex-line-pack" + replace(value, /align-content|flex-|-self/, "") + value; case 5548: return WEBKIT + value + MS + replace(value, "shrink", "negative") + value; case 5292: return WEBKIT + value + MS + replace(value, "basis", "preferred-size") + value; case 6060: return WEBKIT + "box-" + replace(value, "-grow", "") + WEBKIT + value + MS + replace(value, "grow", "positive") + value; case 4554: return WEBKIT + replace(value, /([^-])(transform)/g, "$1" + WEBKIT + "$2") + value; case 6187: return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + "$1"), /(image-set)/, WEBKIT + "$1"), value, "") + value; case 5495: case 3959: return replace(value, /(image-set\([^]*)/, WEBKIT + "$1$`$1"); case 4968: return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + "box-pack:$3" + MS + "flex-pack:$3"), /s.+-b[^;]+/, "justify") + WEBKIT + value + value; case 4095: case 3583: case 4068: case 2532: return replace(value, /(.+)-inline(.+)/, WEBKIT + "$1$2") + value; case 8116: case 7059: case 5753: case 5535: case 5445: case 5701: case 4933: case 4677: case 5533: case 5789: case 5021: case 4765: if (strlen(value) - 1 - length2 > 6) switch (charat(value, length2 + 1)) { case 109: if (charat(value, length2 + 4) !== 45) break; case 102: return replace(value, /(.+:)(.+)-([^]+)/, "$1" + WEBKIT + "$2-$3$1" + MOZ + (charat(value, length2 + 3) == 108 ? "$3" : "$2-$3")) + value; case 115: return ~indexof(value, "stretch") ? prefix2(replace(value, "stretch", "fill-available"), length2) + value : value; } break; case 4949: if (charat(value, length2 + 1) !== 115) break; case 6444: switch (charat(value, strlen(value) - 3 - (~indexof(value, "!important") && 10))) { case 107: return replace(value, ":", ":" + WEBKIT) + value; case 101: return replace(value, /(.+:)([^;!]+)(;|!.+)?/, "$1" + WEBKIT + (charat(value, 14) === 45 ? "inline-" : "") + "box$3$1" + WEBKIT + "$2$3$1" + MS + "$2box$3") + value; } break; case 5936: switch (charat(value, length2 + 11)) { case 114: return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, "tb") + value; case 108: return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, "tb-rl") + value; case 45: return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, "lr") + value; } return WEBKIT + value + MS + value + value; } return value; } var prefixer = function prefixer2(element, index2, children, callback) { if (element.length > -1) { if (!element["return"]) switch (element.type) { case DECLARATION: element["return"] = prefix2(element.value, element.length); break; case KEYFRAMES: return serialize([copy(element, { value: replace(element.value, "@", "@" + WEBKIT) })], callback); case RULESET: if (element.length) return combine(element.props, function(value) { switch (match(value, /(::plac\w+|:read-\w+)/)) { case ":read-only": case ":read-write": return serialize([copy(element, { props: [replace(value, /:(read-\w+)/, ":" + MOZ + "$1")] })], callback); case "::placeholder": return serialize([copy(element, { props: [replace(value, /:(plac\w+)/, ":" + WEBKIT + "input-$1")] }), copy(element, { props: [replace(value, /:(plac\w+)/, ":" + MOZ + "$1")] }), copy(element, { props: [replace(value, /:(plac\w+)/, MS + "input-$1")] })], callback); } return ""; }); } } }; var defaultStylisPlugins = [prefixer]; var getSourceMap; { sourceMapPattern = /\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g; getSourceMap = function getSourceMap2(styles) { var matches = styles.match(sourceMapPattern); if (!matches) return; return matches[matches.length - 1]; }; } var sourceMapPattern; var createCache = function createCache2(options2) { var key = options2.key; if (!key) { throw new Error("You have to configure `key` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.\nIf multiple caches share the same key they might \"fight\" for each other's style elements."); } if (key === "css") { var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); Array.prototype.forEach.call(ssrStyles, function(node2) { var dataEmotionAttribute = node2.getAttribute("data-emotion"); if (dataEmotionAttribute.indexOf(" ") === -1) { return; } document.head.appendChild(node2); node2.setAttribute("data-s", ""); }); } var stylisPlugins = options2.stylisPlugins || defaultStylisPlugins; { if (/[^a-z-]/.test(key)) { throw new Error('Emotion key must only contain lower case alphabetical characters and - but "' + key + '" was passed'); } } var inserted = {}; var container; var nodesToHydrate = []; { container = options2.container || document.head; Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which // means that the style elements we're looking at are only Emotion 11 server-rendered style elements document.querySelectorAll('style[data-emotion^="' + key + ' "]'), function(node2) { var attrib = node2.getAttribute("data-emotion").split(" "); for (var i3 = 1; i3 < attrib.length; i3++) { inserted[attrib[i3]] = true; } nodesToHydrate.push(node2); } ); } var _insert; var omnipresentPlugins = [compat, removeLabel]; { omnipresentPlugins.push(createUnsafeSelectorsAlarm({ get compat() { return cache.compat; } }), incorrectImportAlarm); } { var currentSheet; var finalizingPlugins = [stringify2, function(element) { if (!element.root) { if (element["return"]) { currentSheet.insert(element["return"]); } else if (element.value && element.type !== COMMENT) { currentSheet.insert(element.value + "{}"); } } }]; var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins)); var stylis = function stylis2(styles) { return serialize(compile(styles), serializer); }; _insert = function insert(selector, serialized, sheet, shouldCache) { currentSheet = sheet; if (getSourceMap) { var sourceMap = getSourceMap(serialized.styles); if (sourceMap) { currentSheet = { insert: function insert2(rule) { sheet.insert(rule + sourceMap); } }; } } stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles); if (shouldCache) { cache.inserted[serialized.name] = true; } }; } var cache = { key, sheet: new StyleSheet({ key, container, nonce: options2.nonce, speedy: options2.speedy, prepend: options2.prepend, insertionPoint: options2.insertionPoint }), nonce: options2.nonce, inserted, registered: {}, insert: _insert }; cache.sheet.hydrate(nodesToHydrate); return cache; }; // node_modules/@emotion/react/_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.development.esm.js var import_hoist_non_react_statics = __toESM(require_hoist_non_react_statics_cjs()); // node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js var isBrowser = true; function getRegisteredStyles(registered, registeredStyles, classNames2) { var rawClassName = ""; classNames2.split(" ").forEach(function(className) { if (registered[className] !== void 0) { registeredStyles.push(registered[className] + ";"); } else if (className) { rawClassName += className + " "; } }); return rawClassName; } var registerStyles = function registerStyles2(cache, serialized, isStringTag) { var className = cache.key + "-" + serialized.name; if ( // we only need to add the styles to the registered cache if the // class name could be used further down // the tree but if it's a string tag, we know it won't // so we don't have to add it to registered cache. // this improves memory usage since we can avoid storing the whole style string (isStringTag === false || // we need to always store it if we're in compat mode and // in node since emotion-server relies on whether a style is in // the registered cache to know whether a style is global or not // also, note that this check will be dead code eliminated in the browser isBrowser === false) && cache.registered[className] === void 0 ) { cache.registered[className] = serialized.styles; } }; var insertStyles = function insertStyles2(cache, serialized, isStringTag) { registerStyles(cache, serialized, isStringTag); var className = cache.key + "-" + serialized.name; if (cache.inserted[serialized.name] === void 0) { var current = serialized; do { cache.insert(serialized === current ? "." + className : "", current, cache.sheet, true); current = current.next; } while (current !== void 0); } }; // node_modules/@emotion/hash/dist/emotion-hash.esm.js function murmur2(str) { var h3 = 0; var k3, i3 = 0, len = str.length; for (; len >= 4; ++i3, len -= 4) { k3 = str.charCodeAt(i3) & 255 | (str.charCodeAt(++i3) & 255) << 8 | (str.charCodeAt(++i3) & 255) << 16 | (str.charCodeAt(++i3) & 255) << 24; k3 = /* Math.imul(k, m): */ (k3 & 65535) * 1540483477 + ((k3 >>> 16) * 59797 << 16); k3 ^= /* k >>> r: */ k3 >>> 24; h3 = /* Math.imul(k, m): */ (k3 & 65535) * 1540483477 + ((k3 >>> 16) * 59797 << 16) ^ /* Math.imul(h, m): */ (h3 & 65535) * 1540483477 + ((h3 >>> 16) * 59797 << 16); } switch (len) { case 3: h3 ^= (str.charCodeAt(i3 + 2) & 255) << 16; case 2: h3 ^= (str.charCodeAt(i3 + 1) & 255) << 8; case 1: h3 ^= str.charCodeAt(i3) & 255; h3 = /* Math.imul(h, m): */ (h3 & 65535) * 1540483477 + ((h3 >>> 16) * 59797 << 16); } h3 ^= h3 >>> 13; h3 = /* Math.imul(h, m): */ (h3 & 65535) * 1540483477 + ((h3 >>> 16) * 59797 << 16); return ((h3 ^ h3 >>> 15) >>> 0).toString(36); } // node_modules/@emotion/unitless/dist/emotion-unitless.esm.js var unitlessKeys = { animationIterationCount: 1, aspectRatio: 1, borderImageOutset: 1, borderImageSlice: 1, borderImageWidth: 1, boxFlex: 1, boxFlexGroup: 1, boxOrdinalGroup: 1, columnCount: 1, columns: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, flexOrder: 1, gridRow: 1, gridRowEnd: 1, gridRowSpan: 1, gridRowStart: 1, gridColumn: 1, gridColumnEnd: 1, gridColumnSpan: 1, gridColumnStart: 1, msGridRow: 1, msGridRowSpan: 1, msGridColumn: 1, msGridColumnSpan: 1, fontWeight: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, scale: 1, tabSize: 1, widows: 1, zIndex: 1, zoom: 1, WebkitLineClamp: 1, // SVG-related properties fillOpacity: 1, floodOpacity: 1, stopOpacity: 1, strokeDasharray: 1, strokeDashoffset: 1, strokeMiterlimit: 1, strokeOpacity: 1, strokeWidth: 1 }; // node_modules/@emotion/serialize/dist/emotion-serialize.development.esm.js var isDevelopment2 = true; var ILLEGAL_ESCAPE_SEQUENCE_ERROR = `You have illegal escape sequence in your template literal, most likely inside content's property value. Because you write your CSS inside a JavaScript string you actually have to do double escaping, so for example "content: '\\00d7';" should become "content: '\\\\00d7';". You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences`; var UNDEFINED_AS_OBJECT_KEY_ERROR = "You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key)."; var hyphenateRegex = /[A-Z]|^ms/g; var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g; var isCustomProperty = function isCustomProperty2(property) { return property.charCodeAt(1) === 45; }; var isProcessableValue = function isProcessableValue2(value) { return value != null && typeof value !== "boolean"; }; var processStyleName = memoize(function(styleName) { return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, "-$&").toLowerCase(); }); var processStyleValue = function processStyleValue2(key, value) { switch (key) { case "animation": case "animationName": { if (typeof value === "string") { return value.replace(animationRegex, function(match2, p1, p22) { cursor = { name: p1, styles: p22, next: cursor }; return p1; }); } } } if (unitlessKeys[key] !== 1 && !isCustomProperty(key) && typeof value === "number" && value !== 0) { return value + "px"; } return value; }; { contentValuePattern = /(var|attr|counters?|url|element|(((repeating-)?(linear|radial))|conic)-gradient)\(|(no-)?(open|close)-quote/; contentValues = ["normal", "none", "initial", "inherit", "unset"]; oldProcessStyleValue = processStyleValue; msPattern = /^-ms-/; hyphenPattern = /-(.)/g; hyphenatedCache = {}; processStyleValue = function processStyleValue3(key, value) { if (key === "content") { if (typeof value !== "string" || contentValues.indexOf(value) === -1 && !contentValuePattern.test(value) && (value.charAt(0) !== value.charAt(value.length - 1) || value.charAt(0) !== '"' && value.charAt(0) !== "'")) { throw new Error("You seem to be using a value for 'content' without quotes, try replacing it with `content: '\"" + value + "\"'`"); } } var processed = oldProcessStyleValue(key, value); if (processed !== "" && !isCustomProperty(key) && key.indexOf("-") !== -1 && hyphenatedCache[key] === void 0) { hyphenatedCache[key] = true; console.error("Using kebab-case for css properties in objects is not supported. Did you mean " + key.replace(msPattern, "ms-").replace(hyphenPattern, function(str, _char) { return _char.toUpperCase(); }) + "?"); } return processed; }; } var contentValuePattern; var contentValues; var oldProcessStyleValue; var msPattern; var hyphenPattern; var hyphenatedCache; var noComponentSelectorMessage = "Component selectors can only be used in conjunction with @emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware compiler transform."; function handleInterpolation(mergedProps, registered, interpolation) { if (interpolation == null) { return ""; } var componentSelector = interpolation; if (componentSelector.__emotion_styles !== void 0) { if (String(componentSelector) === "NO_COMPONENT_SELECTOR") { throw new Error(noComponentSelectorMessage); } return componentSelector; } switch (typeof interpolation) { case "boolean": { return ""; } case "object": { var keyframes2 = interpolation; if (keyframes2.anim === 1) { cursor = { name: keyframes2.name, styles: keyframes2.styles, next: cursor }; return keyframes2.name; } var serializedStyles = interpolation; if (serializedStyles.styles !== void 0) { var next2 = serializedStyles.next; if (next2 !== void 0) { while (next2 !== void 0) { cursor = { name: next2.name, styles: next2.styles, next: cursor }; next2 = next2.next; } } var styles = serializedStyles.styles + ";"; return styles; } return createStringFromObject(mergedProps, registered, interpolation); } case "function": { if (mergedProps !== void 0) { var previousCursor = cursor; var result = interpolation(mergedProps); cursor = previousCursor; return handleInterpolation(mergedProps, registered, result); } else { console.error("Functions that are interpolated in css calls will be stringified.\nIf you want to have a css call based on props, create a function that returns a css call like this\nlet dynamicStyle = (props) => css`color: ${props.color}`\nIt can be called directly with props or interpolated in a styled call like this\nlet SomeComponent = styled('div')`${dynamicStyle}`"); } break; } case "string": { var matched = []; var replaced = interpolation.replace(animationRegex, function(_match, _p1, p22) { var fakeVarName = "animation" + matched.length; matched.push("const " + fakeVarName + " = keyframes`" + p22.replace(/^@keyframes animation-\w+/, "") + "`"); return "${" + fakeVarName + "}"; }); if (matched.length) { console.error("`keyframes` output got interpolated into plain string, please wrap it with `css`.\n\nInstead of doing this:\n\n" + [].concat(matched, ["`" + replaced + "`"]).join("\n") + "\n\nYou should wrap it with `css` like this:\n\ncss`" + replaced + "`"); } } break; } var asString = interpolation; if (registered == null) { return asString; } var cached = registered[asString]; return cached !== void 0 ? cached : asString; } function createStringFromObject(mergedProps, registered, obj) { var string = ""; if (Array.isArray(obj)) { for (var i3 = 0; i3 < obj.length; i3++) { string += handleInterpolation(mergedProps, registered, obj[i3]) + ";"; } } else { for (var key in obj) { var value = obj[key]; if (typeof value !== "object") { var asString = value; if (registered != null && registered[asString] !== void 0) { string += key + "{" + registered[asString] + "}"; } else if (isProcessableValue(asString)) { string += processStyleName(key) + ":" + processStyleValue(key, asString) + ";"; } } else { if (key === "NO_COMPONENT_SELECTOR" && isDevelopment2) { throw new Error(noComponentSelectorMessage); } if (Array.isArray(value) && typeof value[0] === "string" && (registered == null || registered[value[0]] === void 0)) { for (var _i2 = 0; _i2 < value.length; _i2++) { if (isProcessableValue(value[_i2])) { string += processStyleName(key) + ":" + processStyleValue(key, value[_i2]) + ";"; } } } else { var interpolated = handleInterpolation(mergedProps, registered, value); switch (key) { case "animation": case "animationName": { string += processStyleName(key) + ":" + interpolated + ";"; break; } default: { if (key === "undefined") { console.error(UNDEFINED_AS_OBJECT_KEY_ERROR); } string += key + "{" + interpolated + "}"; } } } } } } return string; } var labelPattern = /label:\s*([^\s;{]+)\s*(;|$)/g; var cursor; function serializeStyles(args, registered, mergedProps) { if (args.length === 1 && typeof args[0] === "object" && args[0] !== null && args[0].styles !== void 0) { return args[0]; } var stringMode = true; var styles = ""; cursor = void 0; var strings = args[0]; if (strings == null || strings.raw === void 0) { stringMode = false; styles += handleInterpolation(mergedProps, registered, strings); } else { var asTemplateStringsArr = strings; if (asTemplateStringsArr[0] === void 0) { console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR); } styles += asTemplateStringsArr[0]; } for (var i3 = 1; i3 < args.length; i3++) { styles += handleInterpolation(mergedProps, registered, args[i3]); if (stringMode) { var templateStringsArr = strings; if (templateStringsArr[i3] === void 0) { console.error(ILLEGAL_ESCAPE_SEQUENCE_ERROR); } styles += templateStringsArr[i3]; } } labelPattern.lastIndex = 0; var identifierName = ""; var match2; while ((match2 = labelPattern.exec(styles)) !== null) { identifierName += "-" + match2[1]; } var name = murmur2(styles) + identifierName; { var devStyles = { name, styles, next: cursor, toString: function toString() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } }; return devStyles; } } // node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js var React5 = __toESM(require_react()); var syncFallback = function syncFallback2(create4) { return create4(); }; var useInsertionEffect2 = React5["useInsertionEffect"] ? React5["useInsertionEffect"] : false; var useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect2 || syncFallback; var useInsertionEffectWithLayoutFallback = useInsertionEffect2 || React5.useLayoutEffect; // node_modules/@emotion/react/dist/emotion-element-489459f2.browser.development.esm.js var EmotionCacheContext = React6.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case // because this module is primarily intended for the browser and node // but it's also required in react native and similar environments sometimes // and we could have a special build just for that // but this is much easier and the native packages // might use a different theme context in the future anyway typeof HTMLElement !== "undefined" ? createCache({ key: "css" }) : null ); { EmotionCacheContext.displayName = "EmotionCacheContext"; } var CacheProvider = EmotionCacheContext.Provider; var withEmotionCache = function withEmotionCache2(func) { return (0, import_react2.forwardRef)(function(props, ref) { var cache = (0, import_react2.useContext)(EmotionCacheContext); return func(props, cache, ref); }); }; var ThemeContext = React6.createContext({}); { ThemeContext.displayName = "EmotionThemeContext"; } var getTheme = function getTheme2(outerTheme, theme) { if (typeof theme === "function") { var mergedTheme = theme(outerTheme); if (mergedTheme == null || typeof mergedTheme !== "object" || Array.isArray(mergedTheme)) { throw new Error("[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!"); } return mergedTheme; } if (theme == null || typeof theme !== "object" || Array.isArray(theme)) { throw new Error("[ThemeProvider] Please make your theme prop a plain object"); } return _extends({}, outerTheme, theme); }; var createCacheWithTheme = weakMemoize(function(outerTheme) { return weakMemoize(function(theme) { return getTheme(outerTheme, theme); }); }); var hasOwn = {}.hasOwnProperty; var getLastPart = function getLastPart2(functionName) { var parts = functionName.split("."); return parts[parts.length - 1]; }; var getFunctionNameFromStackTraceLine = function getFunctionNameFromStackTraceLine2(line2) { var match2 = /^\s+at\s+([A-Za-z0-9$.]+)\s/.exec(line2); if (match2) return getLastPart(match2[1]); match2 = /^([A-Za-z0-9$.]+)@/.exec(line2); if (match2) return getLastPart(match2[1]); return void 0; }; var internalReactFunctionNames = /* @__PURE__ */ new Set(["renderWithHooks", "processChild", "finishClassComponent", "renderToString"]); var sanitizeIdentifier = function sanitizeIdentifier2(identifier2) { return identifier2.replace(/\$/g, "-"); }; var getLabelFromStackTrace = function getLabelFromStackTrace2(stackTrace) { if (!stackTrace) return void 0; var lines = stackTrace.split("\n"); for (var i3 = 0; i3 < lines.length; i3++) { var functionName = getFunctionNameFromStackTraceLine(lines[i3]); if (!functionName) continue; if (internalReactFunctionNames.has(functionName)) break; if (/^[A-Z]/.test(functionName)) return sanitizeIdentifier(functionName); } return void 0; }; var typePropName = "__EMOTION_TYPE_PLEASE_DO_NOT_USE__"; var labelPropName = "__EMOTION_LABEL_PLEASE_DO_NOT_USE__"; var createEmotionProps = function createEmotionProps2(type, props) { if (typeof props.css === "string" && // check if there is a css declaration props.css.indexOf(":") !== -1) { throw new Error("Strings are not allowed as css prop values, please wrap it in a css template literal from '@emotion/react' like this: css`" + props.css + "`"); } var newProps = {}; for (var _key in props) { if (hasOwn.call(props, _key)) { newProps[_key] = props[_key]; } } newProps[typePropName] = type; if (typeof globalThis !== "undefined" && !!globalThis.EMOTION_RUNTIME_AUTO_LABEL && !!props.css && (typeof props.css !== "object" || !("name" in props.css) || typeof props.css.name !== "string" || props.css.name.indexOf("-") === -1)) { var label = getLabelFromStackTrace(new Error().stack); if (label) newProps[labelPropName] = label; } return newProps; }; var Insertion = function Insertion2(_ref3) { var cache = _ref3.cache, serialized = _ref3.serialized, isStringTag = _ref3.isStringTag; registerStyles(cache, serialized, isStringTag); useInsertionEffectAlwaysWithSyncFallback(function() { return insertStyles(cache, serialized, isStringTag); }); return null; }; var Emotion = withEmotionCache(function(props, cache, ref) { var cssProp = props.css; if (typeof cssProp === "string" && cache.registered[cssProp] !== void 0) { cssProp = cache.registered[cssProp]; } var WrappedComponent = props[typePropName]; var registeredStyles = [cssProp]; var className = ""; if (typeof props.className === "string") { className = getRegisteredStyles(cache.registered, registeredStyles, props.className); } else if (props.className != null) { className = props.className + " "; } var serialized = serializeStyles(registeredStyles, void 0, React6.useContext(ThemeContext)); if (serialized.name.indexOf("-") === -1) { var labelFromStack = props[labelPropName]; if (labelFromStack) { serialized = serializeStyles([serialized, "label:" + labelFromStack + ";"]); } } className += cache.key + "-" + serialized.name; var newProps = {}; for (var _key2 in props) { if (hasOwn.call(props, _key2) && _key2 !== "css" && _key2 !== typePropName && _key2 !== labelPropName) { newProps[_key2] = props[_key2]; } } newProps.className = className; if (ref) { newProps.ref = ref; } return React6.createElement(React6.Fragment, null, React6.createElement(Insertion, { cache, serialized, isStringTag: typeof WrappedComponent === "string" }), React6.createElement(WrappedComponent, newProps)); }); { Emotion.displayName = "EmotionCssPropInternal"; } var Emotion$1 = Emotion; // node_modules/@emotion/react/dist/emotion-react.browser.development.esm.js var React7 = __toESM(require_react()); var import_hoist_non_react_statics2 = __toESM(require_hoist_non_react_statics_cjs()); var isDevelopment3 = true; var pkg = { name: "@emotion/react", version: "11.14.0", main: "dist/emotion-react.cjs.js", module: "dist/emotion-react.esm.js", types: "dist/emotion-react.cjs.d.ts", exports: { ".": { types: { "import": "./dist/emotion-react.cjs.mjs", "default": "./dist/emotion-react.cjs.js" }, development: { "edge-light": { module: "./dist/emotion-react.development.edge-light.esm.js", "import": "./dist/emotion-react.development.edge-light.cjs.mjs", "default": "./dist/emotion-react.development.edge-light.cjs.js" }, worker: { module: "./dist/emotion-react.development.edge-light.esm.js", "import": "./dist/emotion-react.development.edge-light.cjs.mjs", "default": "./dist/emotion-react.development.edge-light.cjs.js" }, workerd: { module: "./dist/emotion-react.development.edge-light.esm.js", "import": "./dist/emotion-react.development.edge-light.cjs.mjs", "default": "./dist/emotion-react.development.edge-light.cjs.js" }, browser: { module: "./dist/emotion-react.browser.development.esm.js", "import": "./dist/emotion-react.browser.development.cjs.mjs", "default": "./dist/emotion-react.browser.development.cjs.js" }, module: "./dist/emotion-react.development.esm.js", "import": "./dist/emotion-react.development.cjs.mjs", "default": "./dist/emotion-react.development.cjs.js" }, "edge-light": { module: "./dist/emotion-react.edge-light.esm.js", "import": "./dist/emotion-react.edge-light.cjs.mjs", "default": "./dist/emotion-react.edge-light.cjs.js" }, worker: { module: "./dist/emotion-react.edge-light.esm.js", "import": "./dist/emotion-react.edge-light.cjs.mjs", "default": "./dist/emotion-react.edge-light.cjs.js" }, workerd: { module: "./dist/emotion-react.edge-light.esm.js", "import": "./dist/emotion-react.edge-light.cjs.mjs", "default": "./dist/emotion-react.edge-light.cjs.js" }, browser: { module: "./dist/emotion-react.browser.esm.js", "import": "./dist/emotion-react.browser.cjs.mjs", "default": "./dist/emotion-react.browser.cjs.js" }, module: "./dist/emotion-react.esm.js", "import": "./dist/emotion-react.cjs.mjs", "default": "./dist/emotion-react.cjs.js" }, "./jsx-runtime": { types: { "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.js" }, development: { "edge-light": { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.cjs.js" }, worker: { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.cjs.js" }, workerd: { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.edge-light.cjs.js" }, browser: { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.development.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.development.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.development.cjs.js" }, module: "./jsx-runtime/dist/emotion-react-jsx-runtime.development.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.development.cjs.js" }, "edge-light": { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.cjs.js" }, worker: { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.cjs.js" }, workerd: { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.edge-light.cjs.js" }, browser: { module: "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.cjs.js" }, module: "./jsx-runtime/dist/emotion-react-jsx-runtime.esm.js", "import": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.mjs", "default": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.js" }, "./_isolated-hnrs": { types: { "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.js" }, development: { "edge-light": { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.cjs.js" }, worker: { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.cjs.js" }, workerd: { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.edge-light.cjs.js" }, browser: { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.development.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.development.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.development.cjs.js" }, module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.development.cjs.js" }, "edge-light": { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.cjs.js" }, worker: { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.cjs.js" }, workerd: { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.edge-light.cjs.js" }, browser: { module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.cjs.js" }, module: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.esm.js", "import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.mjs", "default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.js" }, "./jsx-dev-runtime": { types: { "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.js" }, development: { "edge-light": { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.cjs.js" }, worker: { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.cjs.js" }, workerd: { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.edge-light.cjs.js" }, browser: { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.development.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.development.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.development.cjs.js" }, module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.development.cjs.js" }, "edge-light": { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.cjs.js" }, worker: { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.cjs.js" }, workerd: { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.edge-light.cjs.js" }, browser: { module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.cjs.js" }, module: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.esm.js", "import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.mjs", "default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.js" }, "./package.json": "./package.json", "./types/css-prop": "./types/css-prop.d.ts", "./macro": { types: { "import": "./macro.d.mts", "default": "./macro.d.ts" }, "default": "./macro.js" } }, imports: { "#is-development": { development: "./src/conditions/true.ts", "default": "./src/conditions/false.ts" }, "#is-browser": { "edge-light": "./src/conditions/false.ts", workerd: "./src/conditions/false.ts", worker: "./src/conditions/false.ts", browser: "./src/conditions/true.ts", "default": "./src/conditions/is-browser.ts" } }, files: [ "src", "dist", "jsx-runtime", "jsx-dev-runtime", "_isolated-hnrs", "types/css-prop.d.ts", "macro.*" ], sideEffects: false, author: "Emotion Contributors", license: "MIT", scripts: { "test:typescript": "dtslint types" }, dependencies: { "@babel/runtime": "^7.18.3", "@emotion/babel-plugin": "^11.13.5", "@emotion/cache": "^11.14.0", "@emotion/serialize": "^1.3.3", "@emotion/use-insertion-effect-with-fallbacks": "^1.2.0", "@emotion/utils": "^1.4.2", "@emotion/weak-memoize": "^0.4.0", "hoist-non-react-statics": "^3.3.1" }, peerDependencies: { react: ">=16.8.0" }, peerDependenciesMeta: { "@types/react": { optional: true } }, devDependencies: { "@definitelytyped/dtslint": "0.0.112", "@emotion/css": "11.13.5", "@emotion/css-prettifier": "1.2.0", "@emotion/server": "11.11.0", "@emotion/styled": "11.14.0", "@types/hoist-non-react-statics": "^3.3.5", "html-tag-names": "^1.1.2", react: "16.14.0", "svg-tag-names": "^1.1.1", typescript: "^5.4.5" }, repository: "https://github.com/emotion-js/emotion/tree/main/packages/react", publishConfig: { access: "public" }, "umd:main": "dist/emotion-react.umd.min.js", preconstruct: { entrypoints: [ "./index.ts", "./jsx-runtime.ts", "./jsx-dev-runtime.ts", "./_isolated-hnrs.ts" ], umdName: "emotionReact", exports: { extra: { "./types/css-prop": "./types/css-prop.d.ts", "./macro": { types: { "import": "./macro.d.mts", "default": "./macro.d.ts" }, "default": "./macro.js" } } } } }; var jsx2 = function jsx3(type, props) { var args = arguments; if (props == null || !hasOwn.call(props, "css")) { return React7.createElement.apply(void 0, args); } var argsLength = args.length; var createElementArgArray = new Array(argsLength); createElementArgArray[0] = Emotion$1; createElementArgArray[1] = createEmotionProps(type, props); for (var i3 = 2; i3 < argsLength; i3++) { createElementArgArray[i3] = args[i3]; } return React7.createElement.apply(null, createElementArgArray); }; (function(_jsx) { var JSX; /* @__PURE__ */ (function(_JSX) { })(JSX || (JSX = _jsx.JSX || (_jsx.JSX = {}))); })(jsx2 || (jsx2 = {})); var warnedAboutCssPropForGlobal = false; var Global = withEmotionCache(function(props, cache) { if (!warnedAboutCssPropForGlobal && // check for className as well since the user is // probably using the custom createElement which // means it will be turned into a className prop // I don't really want to add it to the type since it shouldn't be used ("className" in props && props.className || "css" in props && props.css)) { console.error("It looks like you're using the css prop on Global, did you mean to use the styles prop instead?"); warnedAboutCssPropForGlobal = true; } var styles = props.styles; var serialized = serializeStyles([styles], void 0, React7.useContext(ThemeContext)); var sheetRef = React7.useRef(); useInsertionEffectWithLayoutFallback(function() { var key = cache.key + "-global"; var sheet = new cache.sheet.constructor({ key, nonce: cache.sheet.nonce, container: cache.sheet.container, speedy: cache.sheet.isSpeedy }); var rehydrating = false; var node2 = document.querySelector('style[data-emotion="' + key + " " + serialized.name + '"]'); if (cache.sheet.tags.length) { sheet.before = cache.sheet.tags[0]; } if (node2 !== null) { rehydrating = true; node2.setAttribute("data-emotion", key); sheet.hydrate([node2]); } sheetRef.current = [sheet, rehydrating]; return function() { sheet.flush(); }; }, [cache]); useInsertionEffectWithLayoutFallback(function() { var sheetRefCurrent = sheetRef.current; var sheet = sheetRefCurrent[0], rehydrating = sheetRefCurrent[1]; if (rehydrating) { sheetRefCurrent[1] = false; return; } if (serialized.next !== void 0) { insertStyles(cache, serialized.next, true); } if (sheet.tags.length) { var element = sheet.tags[sheet.tags.length - 1].nextElementSibling; sheet.before = element; sheet.flush(); } cache.insert("", serialized, sheet, false); }, [cache, serialized.name]); return null; }); { Global.displayName = "EmotionGlobal"; } function css() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return serializeStyles(args); } function keyframes() { var insertable = css.apply(void 0, arguments); var name = "animation-" + insertable.name; return { name, styles: "@keyframes " + name + "{" + insertable.styles + "}", anim: 1, toString: function toString() { return "_EMO_" + this.name + "_" + this.styles + "_EMO_"; } }; } var classnames = function classnames2(args) { var len = args.length; var i3 = 0; var cls = ""; for (; i3 < len; i3++) { var arg = args[i3]; if (arg == null) continue; var toAdd = void 0; switch (typeof arg) { case "boolean": break; case "object": { if (Array.isArray(arg)) { toAdd = classnames2(arg); } else { if (arg.styles !== void 0 && arg.name !== void 0) { console.error("You have passed styles created with `css` from `@emotion/react` package to the `cx`.\n`cx` is meant to compose class names (strings) so you should convert those styles to a class name by passing them to the `css` received from component."); } toAdd = ""; for (var k3 in arg) { if (arg[k3] && k3) { toAdd && (toAdd += " "); toAdd += k3; } } } break; } default: { toAdd = arg; } } if (toAdd) { cls && (cls += " "); cls += toAdd; } } return cls; }; function merge(registered, css5, className) { var registeredStyles = []; var rawClassName = getRegisteredStyles(registered, registeredStyles, className); if (registeredStyles.length < 2) { return className; } return rawClassName + css5(registeredStyles); } var Insertion3 = function Insertion4(_ref3) { var cache = _ref3.cache, serializedArr = _ref3.serializedArr; useInsertionEffectAlwaysWithSyncFallback(function() { for (var i3 = 0; i3 < serializedArr.length; i3++) { insertStyles(cache, serializedArr[i3], false); } }); return null; }; var ClassNames = withEmotionCache(function(props, cache) { var hasRendered = false; var serializedArr = []; var css5 = function css6() { if (hasRendered && isDevelopment3) { throw new Error("css can only be used during render"); } for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var serialized = serializeStyles(args, cache.registered); serializedArr.push(serialized); registerStyles(cache, serialized, false); return cache.key + "-" + serialized.name; }; var cx = function cx2() { if (hasRendered && isDevelopment3) { throw new Error("cx can only be used during render"); } for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return merge(cache.registered, css5, classnames(args)); }; var content = { css: css5, cx, theme: React7.useContext(ThemeContext) }; var ele = props.children(content); hasRendered = true; return React7.createElement(React7.Fragment, null, React7.createElement(Insertion3, { cache, serializedArr }), ele); }); { ClassNames.displayName = "EmotionClassNames"; } { isBrowser2 = typeof document !== "undefined"; isTestEnv = typeof jest !== "undefined" || typeof vi !== "undefined"; if (isBrowser2 && !isTestEnv) { globalContext = typeof globalThis !== "undefined" ? globalThis : isBrowser2 ? window : global; globalKey = "__EMOTION_REACT_" + pkg.version.split(".")[0] + "__"; if (globalContext[globalKey]) { console.warn("You are loading @emotion/react when it is already loaded. Running multiple instances may cause problems. This can happen if multiple versions are used, or if multiple builds of the same version are used."); } globalContext[globalKey] = true; } } var isBrowser2; var isTestEnv; var globalContext; var globalKey; // node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js function _taggedTemplateLiteral(e, t2) { return t2 || (t2 = e.slice(0)), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t2) } })); } // node_modules/react-select/dist/index-a301f526.esm.js var import_react5 = __toESM(require_react()); var import_react_dom = __toESM(require_react_dom()); // node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js var import_react3 = __toESM(require_react()); var index = import_react3.useLayoutEffect; // node_modules/react-select/dist/index-a301f526.esm.js var _excluded$4 = ["className", "clearValue", "cx", "getStyles", "getClassNames", "getValue", "hasValue", "isMulti", "isRtl", "options", "selectOption", "selectProps", "setValue", "theme"]; var noop = function noop2() { }; function applyPrefixToName(prefix3, name) { if (!name) { return prefix3; } else if (name[0] === "-") { return prefix3 + name; } else { return prefix3 + "__" + name; } } function classNames(prefix3, state) { for (var _len = arguments.length, classNameList = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { classNameList[_key - 2] = arguments[_key]; } var arr = [].concat(classNameList); if (state && prefix3) { for (var key in state) { if (state.hasOwnProperty(key) && state[key]) { arr.push("".concat(applyPrefixToName(prefix3, key))); } } } return arr.filter(function(i3) { return i3; }).map(function(i3) { return String(i3).trim(); }).join(" "); } var cleanValue = function cleanValue2(value) { if (isArray(value)) return value.filter(Boolean); if (_typeof(value) === "object" && value !== null) return [value]; return []; }; var cleanCommonProps = function cleanCommonProps2(props) { props.className; props.clearValue; props.cx; props.getStyles; props.getClassNames; props.getValue; props.hasValue; props.isMulti; props.isRtl; props.options; props.selectOption; props.selectProps; props.setValue; props.theme; var innerProps = _objectWithoutProperties(props, _excluded$4); return _objectSpread2({}, innerProps); }; var getStyleProps = function getStyleProps2(props, name, classNamesState) { var cx = props.cx, getStyles = props.getStyles, getClassNames = props.getClassNames, className = props.className; return { css: getStyles(name, props), className: cx(classNamesState !== null && classNamesState !== void 0 ? classNamesState : {}, getClassNames(name, props), className) }; }; function isDocumentElement(el) { return [document.documentElement, document.body, window].indexOf(el) > -1; } function normalizedHeight(el) { if (isDocumentElement(el)) { return window.innerHeight; } return el.clientHeight; } function getScrollTop(el) { if (isDocumentElement(el)) { return window.pageYOffset; } return el.scrollTop; } function scrollTo(el, top) { if (isDocumentElement(el)) { window.scrollTo(0, top); return; } el.scrollTop = top; } function getScrollParent(element) { var style = getComputedStyle(element); var excludeStaticParent = style.position === "absolute"; var overflowRx = /(auto|scroll)/; if (style.position === "fixed") return document.documentElement; for (var parent = element; parent = parent.parentElement; ) { style = getComputedStyle(parent); if (excludeStaticParent && style.position === "static") { continue; } if (overflowRx.test(style.overflow + style.overflowY + style.overflowX)) { return parent; } } return document.documentElement; } function easeOutCubic(t2, b2, c3, d2) { return c3 * ((t2 = t2 / d2 - 1) * t2 * t2 + 1) + b2; } function animatedScrollTo(element, to) { var duration = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 200; var callback = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : noop; var start = getScrollTop(element); var change3 = to - start; var increment = 10; var currentTime = 0; function animateScroll() { currentTime += increment; var val = easeOutCubic(currentTime, start, change3, duration); scrollTo(element, val); if (currentTime < duration) { window.requestAnimationFrame(animateScroll); } else { callback(element); } } animateScroll(); } function scrollIntoView(menuEl, focusedEl) { var menuRect = menuEl.getBoundingClientRect(); var focusedRect = focusedEl.getBoundingClientRect(); var overScroll = focusedEl.offsetHeight / 3; if (focusedRect.bottom + overScroll > menuRect.bottom) { scrollTo(menuEl, Math.min(focusedEl.offsetTop + focusedEl.clientHeight - menuEl.offsetHeight + overScroll, menuEl.scrollHeight)); } else if (focusedRect.top - overScroll < menuRect.top) { scrollTo(menuEl, Math.max(focusedEl.offsetTop - overScroll, 0)); } } function getBoundingClientObj(element) { var rect = element.getBoundingClientRect(); return { bottom: rect.bottom, height: rect.height, left: rect.left, right: rect.right, top: rect.top, width: rect.width }; } function isTouchCapable() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } } function isMobileDevice() { try { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); } catch (e) { return false; } } var passiveOptionAccessed = false; var options = { get passive() { return passiveOptionAccessed = true; } }; var w = typeof window !== "undefined" ? window : {}; if (w.addEventListener && w.removeEventListener) { w.addEventListener("p", noop, options); w.removeEventListener("p", noop, false); } var supportsPassiveEvents = passiveOptionAccessed; function notNullish(item) { return item != null; } function isArray(arg) { return Array.isArray(arg); } function valueTernary(isMulti, multiValue, singleValue) { return isMulti ? multiValue : singleValue; } function singleValueAsValue(singleValue) { return singleValue; } function multiValueAsValue(multiValue) { return multiValue; } var removeProps = function removeProps2(propsObj) { for (var _len2 = arguments.length, properties = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { properties[_key2 - 1] = arguments[_key2]; } var propsMap = Object.entries(propsObj).filter(function(_ref3) { var _ref23 = _slicedToArray(_ref3, 1), key = _ref23[0]; return !properties.includes(key); }); return propsMap.reduce(function(newProps, _ref3) { var _ref4 = _slicedToArray(_ref3, 2), key = _ref4[0], val = _ref4[1]; newProps[key] = val; return newProps; }, {}); }; var _excluded$3 = ["children", "innerProps"]; var _excluded2$1 = ["children", "innerProps"]; function getMenuPlacement(_ref3) { var preferredMaxHeight = _ref3.maxHeight, menuEl = _ref3.menuEl, minHeight = _ref3.minHeight, preferredPlacement = _ref3.placement, shouldScroll = _ref3.shouldScroll, isFixedPosition = _ref3.isFixedPosition, controlHeight2 = _ref3.controlHeight; var scrollParent = getScrollParent(menuEl); var defaultState = { placement: "bottom", maxHeight: preferredMaxHeight }; if (!menuEl || !menuEl.offsetParent) return defaultState; var _scrollParent$getBoun = scrollParent.getBoundingClientRect(), scrollHeight = _scrollParent$getBoun.height; var _menuEl$getBoundingCl = menuEl.getBoundingClientRect(), menuBottom = _menuEl$getBoundingCl.bottom, menuHeight = _menuEl$getBoundingCl.height, menuTop = _menuEl$getBoundingCl.top; var _menuEl$offsetParent$ = menuEl.offsetParent.getBoundingClientRect(), containerTop = _menuEl$offsetParent$.top; var viewHeight = isFixedPosition ? window.innerHeight : normalizedHeight(scrollParent); var scrollTop = getScrollTop(scrollParent); var marginBottom = parseInt(getComputedStyle(menuEl).marginBottom, 10); var marginTop = parseInt(getComputedStyle(menuEl).marginTop, 10); var viewSpaceAbove = containerTop - marginTop; var viewSpaceBelow = viewHeight - menuTop; var scrollSpaceAbove = viewSpaceAbove + scrollTop; var scrollSpaceBelow = scrollHeight - scrollTop - menuTop; var scrollDown = menuBottom - viewHeight + scrollTop + marginBottom; var scrollUp = scrollTop + menuTop - marginTop; var scrollDuration = 160; switch (preferredPlacement) { case "auto": case "bottom": if (viewSpaceBelow >= menuHeight) { return { placement: "bottom", maxHeight: preferredMaxHeight }; } if (scrollSpaceBelow >= menuHeight && !isFixedPosition) { if (shouldScroll) { animatedScrollTo(scrollParent, scrollDown, scrollDuration); } return { placement: "bottom", maxHeight: preferredMaxHeight }; } if (!isFixedPosition && scrollSpaceBelow >= minHeight || isFixedPosition && viewSpaceBelow >= minHeight) { if (shouldScroll) { animatedScrollTo(scrollParent, scrollDown, scrollDuration); } var constrainedHeight = isFixedPosition ? viewSpaceBelow - marginBottom : scrollSpaceBelow - marginBottom; return { placement: "bottom", maxHeight: constrainedHeight }; } if (preferredPlacement === "auto" || isFixedPosition) { var _constrainedHeight = preferredMaxHeight; var spaceAbove = isFixedPosition ? viewSpaceAbove : scrollSpaceAbove; if (spaceAbove >= minHeight) { _constrainedHeight = Math.min(spaceAbove - marginBottom - controlHeight2, preferredMaxHeight); } return { placement: "top", maxHeight: _constrainedHeight }; } if (preferredPlacement === "bottom") { if (shouldScroll) { scrollTo(scrollParent, scrollDown); } return { placement: "bottom", maxHeight: preferredMaxHeight }; } break; case "top": if (viewSpaceAbove >= menuHeight) { return { placement: "top", maxHeight: preferredMaxHeight }; } if (scrollSpaceAbove >= menuHeight && !isFixedPosition) { if (shouldScroll) { animatedScrollTo(scrollParent, scrollUp, scrollDuration); } return { placement: "top", maxHeight: preferredMaxHeight }; } if (!isFixedPosition && scrollSpaceAbove >= minHeight || isFixedPosition && viewSpaceAbove >= minHeight) { var _constrainedHeight2 = preferredMaxHeight; if (!isFixedPosition && scrollSpaceAbove >= minHeight || isFixedPosition && viewSpaceAbove >= minHeight) { _constrainedHeight2 = isFixedPosition ? viewSpaceAbove - marginTop : scrollSpaceAbove - marginTop; } if (shouldScroll) { animatedScrollTo(scrollParent, scrollUp, scrollDuration); } return { placement: "top", maxHeight: _constrainedHeight2 }; } return { placement: "bottom", maxHeight: preferredMaxHeight }; default: throw new Error('Invalid placement provided "'.concat(preferredPlacement, '".')); } return defaultState; } function alignToControl(placement) { var placementToCSSProp = { bottom: "top", top: "bottom" }; return placement ? placementToCSSProp[placement] : "bottom"; } var coercePlacement = function coercePlacement2(p3) { return p3 === "auto" ? "bottom" : p3; }; var menuCSS = function menuCSS2(_ref23, unstyled) { var _objectSpread24; var placement = _ref23.placement, _ref2$theme = _ref23.theme, borderRadius2 = _ref2$theme.borderRadius, spacing2 = _ref2$theme.spacing, colors2 = _ref2$theme.colors; return _objectSpread2((_objectSpread24 = { label: "menu" }, _defineProperty(_objectSpread24, alignToControl(placement), "100%"), _defineProperty(_objectSpread24, "position", "absolute"), _defineProperty(_objectSpread24, "width", "100%"), _defineProperty(_objectSpread24, "zIndex", 1), _objectSpread24), unstyled ? {} : { backgroundColor: colors2.neutral0, borderRadius: borderRadius2, boxShadow: "0 0 0 1px hsla(0, 0%, 0%, 0.1), 0 4px 11px hsla(0, 0%, 0%, 0.1)", marginBottom: spacing2.menuGutter, marginTop: spacing2.menuGutter }); }; var PortalPlacementContext = (0, import_react5.createContext)(null); var MenuPlacer = function MenuPlacer2(props) { var children = props.children, minMenuHeight = props.minMenuHeight, maxMenuHeight = props.maxMenuHeight, menuPlacement = props.menuPlacement, menuPosition = props.menuPosition, menuShouldScrollIntoView = props.menuShouldScrollIntoView, theme = props.theme; var _ref3 = (0, import_react5.useContext)(PortalPlacementContext) || {}, setPortalPlacement = _ref3.setPortalPlacement; var ref = (0, import_react5.useRef)(null); var _useState = (0, import_react5.useState)(maxMenuHeight), _useState2 = _slicedToArray(_useState, 2), maxHeight = _useState2[0], setMaxHeight = _useState2[1]; var _useState3 = (0, import_react5.useState)(null), _useState4 = _slicedToArray(_useState3, 2), placement = _useState4[0], setPlacement = _useState4[1]; var controlHeight2 = theme.spacing.controlHeight; index(function() { var menuEl = ref.current; if (!menuEl) return; var isFixedPosition = menuPosition === "fixed"; var shouldScroll = menuShouldScrollIntoView && !isFixedPosition; var state = getMenuPlacement({ maxHeight: maxMenuHeight, menuEl, minHeight: minMenuHeight, placement: menuPlacement, shouldScroll, isFixedPosition, controlHeight: controlHeight2 }); setMaxHeight(state.maxHeight); setPlacement(state.placement); setPortalPlacement === null || setPortalPlacement === void 0 ? void 0 : setPortalPlacement(state.placement); }, [maxMenuHeight, menuPlacement, menuPosition, menuShouldScrollIntoView, minMenuHeight, setPortalPlacement, controlHeight2]); return children({ ref, placerProps: _objectSpread2(_objectSpread2({}, props), {}, { placement: placement || coercePlacement(menuPlacement), maxHeight }) }); }; var Menu2 = function Menu3(props) { var children = props.children, innerRef = props.innerRef, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "menu", { menu: true }), { ref: innerRef }, innerProps), children); }; var Menu$1 = Menu2; var menuListCSS = function menuListCSS2(_ref4, unstyled) { var maxHeight = _ref4.maxHeight, baseUnit2 = _ref4.theme.spacing.baseUnit; return _objectSpread2({ maxHeight, overflowY: "auto", position: "relative", // required for offset[Height, Top] > keyboard scroll WebkitOverflowScrolling: "touch" }, unstyled ? {} : { paddingBottom: baseUnit2, paddingTop: baseUnit2 }); }; var MenuList = function MenuList2(props) { var children = props.children, innerProps = props.innerProps, innerRef = props.innerRef, isMulti = props.isMulti; return jsx2("div", _extends({}, getStyleProps(props, "menuList", { "menu-list": true, "menu-list--is-multi": isMulti }), { ref: innerRef }, innerProps), children); }; var noticeCSS = function noticeCSS2(_ref5, unstyled) { var _ref5$theme = _ref5.theme, baseUnit2 = _ref5$theme.spacing.baseUnit, colors2 = _ref5$theme.colors; return _objectSpread2({ textAlign: "center" }, unstyled ? {} : { color: colors2.neutral40, padding: "".concat(baseUnit2 * 2, "px ").concat(baseUnit2 * 3, "px") }); }; var noOptionsMessageCSS = noticeCSS; var loadingMessageCSS = noticeCSS; var NoOptionsMessage = function NoOptionsMessage2(_ref6) { var _ref6$children = _ref6.children, children = _ref6$children === void 0 ? "No options" : _ref6$children, innerProps = _ref6.innerProps, restProps = _objectWithoutProperties(_ref6, _excluded$3); return jsx2("div", _extends({}, getStyleProps(_objectSpread2(_objectSpread2({}, restProps), {}, { children, innerProps }), "noOptionsMessage", { "menu-notice": true, "menu-notice--no-options": true }), innerProps), children); }; var LoadingMessage = function LoadingMessage2(_ref7) { var _ref7$children = _ref7.children, children = _ref7$children === void 0 ? "Loading..." : _ref7$children, innerProps = _ref7.innerProps, restProps = _objectWithoutProperties(_ref7, _excluded2$1); return jsx2("div", _extends({}, getStyleProps(_objectSpread2(_objectSpread2({}, restProps), {}, { children, innerProps }), "loadingMessage", { "menu-notice": true, "menu-notice--loading": true }), innerProps), children); }; var menuPortalCSS = function menuPortalCSS2(_ref8) { var rect = _ref8.rect, offset = _ref8.offset, position2 = _ref8.position; return { left: rect.left, position: position2, top: offset, width: rect.width, zIndex: 1 }; }; var MenuPortal = function MenuPortal2(props) { var appendTo = props.appendTo, children = props.children, controlElement = props.controlElement, innerProps = props.innerProps, menuPlacement = props.menuPlacement, menuPosition = props.menuPosition; var menuPortalRef = (0, import_react5.useRef)(null); var cleanupRef = (0, import_react5.useRef)(null); var _useState5 = (0, import_react5.useState)(coercePlacement(menuPlacement)), _useState6 = _slicedToArray(_useState5, 2), placement = _useState6[0], setPortalPlacement = _useState6[1]; var portalPlacementContext = (0, import_react5.useMemo)(function() { return { setPortalPlacement }; }, []); var _useState7 = (0, import_react5.useState)(null), _useState8 = _slicedToArray(_useState7, 2), computedPosition = _useState8[0], setComputedPosition = _useState8[1]; var updateComputedPosition = (0, import_react5.useCallback)(function() { if (!controlElement) return; var rect = getBoundingClientObj(controlElement); var scrollDistance = menuPosition === "fixed" ? 0 : window.pageYOffset; var offset = rect[placement] + scrollDistance; if (offset !== (computedPosition === null || computedPosition === void 0 ? void 0 : computedPosition.offset) || rect.left !== (computedPosition === null || computedPosition === void 0 ? void 0 : computedPosition.rect.left) || rect.width !== (computedPosition === null || computedPosition === void 0 ? void 0 : computedPosition.rect.width)) { setComputedPosition({ offset, rect }); } }, [controlElement, menuPosition, placement, computedPosition === null || computedPosition === void 0 ? void 0 : computedPosition.offset, computedPosition === null || computedPosition === void 0 ? void 0 : computedPosition.rect.left, computedPosition === null || computedPosition === void 0 ? void 0 : computedPosition.rect.width]); index(function() { updateComputedPosition(); }, [updateComputedPosition]); var runAutoUpdate = (0, import_react5.useCallback)(function() { if (typeof cleanupRef.current === "function") { cleanupRef.current(); cleanupRef.current = null; } if (controlElement && menuPortalRef.current) { cleanupRef.current = autoUpdate(controlElement, menuPortalRef.current, updateComputedPosition, { elementResize: "ResizeObserver" in window }); } }, [controlElement, updateComputedPosition]); index(function() { runAutoUpdate(); }, [runAutoUpdate]); var setMenuPortalElement = (0, import_react5.useCallback)(function(menuPortalElement) { menuPortalRef.current = menuPortalElement; runAutoUpdate(); }, [runAutoUpdate]); if (!appendTo && menuPosition !== "fixed" || !computedPosition) return null; var menuWrapper = jsx2("div", _extends({ ref: setMenuPortalElement }, getStyleProps(_objectSpread2(_objectSpread2({}, props), {}, { offset: computedPosition.offset, position: menuPosition, rect: computedPosition.rect }), "menuPortal", { "menu-portal": true }), innerProps), children); return jsx2(PortalPlacementContext.Provider, { value: portalPlacementContext }, appendTo ? (0, import_react_dom.createPortal)(menuWrapper, appendTo) : menuWrapper); }; var containerCSS = function containerCSS2(_ref3) { var isDisabled = _ref3.isDisabled, isRtl = _ref3.isRtl; return { label: "container", direction: isRtl ? "rtl" : void 0, pointerEvents: isDisabled ? "none" : void 0, // cancel mouse events when disabled position: "relative" }; }; var SelectContainer = function SelectContainer2(props) { var children = props.children, innerProps = props.innerProps, isDisabled = props.isDisabled, isRtl = props.isRtl; return jsx2("div", _extends({}, getStyleProps(props, "container", { "--is-disabled": isDisabled, "--is-rtl": isRtl }), innerProps), children); }; var valueContainerCSS = function valueContainerCSS2(_ref23, unstyled) { var spacing2 = _ref23.theme.spacing, isMulti = _ref23.isMulti, hasValue = _ref23.hasValue, controlShouldRenderValue = _ref23.selectProps.controlShouldRenderValue; return _objectSpread2({ alignItems: "center", display: isMulti && hasValue && controlShouldRenderValue ? "flex" : "grid", flex: 1, flexWrap: "wrap", WebkitOverflowScrolling: "touch", position: "relative", overflow: "hidden" }, unstyled ? {} : { padding: "".concat(spacing2.baseUnit / 2, "px ").concat(spacing2.baseUnit * 2, "px") }); }; var ValueContainer = function ValueContainer2(props) { var children = props.children, innerProps = props.innerProps, isMulti = props.isMulti, hasValue = props.hasValue; return jsx2("div", _extends({}, getStyleProps(props, "valueContainer", { "value-container": true, "value-container--is-multi": isMulti, "value-container--has-value": hasValue }), innerProps), children); }; var indicatorsContainerCSS = function indicatorsContainerCSS2() { return { alignItems: "center", alignSelf: "stretch", display: "flex", flexShrink: 0 }; }; var IndicatorsContainer = function IndicatorsContainer2(props) { var children = props.children, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "indicatorsContainer", { indicators: true }), innerProps), children); }; var _templateObject; var _excluded$2 = ["size"]; var _excluded2 = ["innerProps", "isRtl", "size"]; function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } var _ref2 = false ? { name: "8mmkcg", styles: "display:inline-block;fill:currentColor;line-height:1;stroke:currentColor;stroke-width:0" } : { name: "tj5bde-Svg", styles: "display:inline-block;fill:currentColor;line-height:1;stroke:currentColor;stroke-width:0;label:Svg;", map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGljYXRvcnMudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQXlCSSIsImZpbGUiOiJpbmRpY2F0b3JzLnRzeCIsInNvdXJjZXNDb250ZW50IjpbIi8qKiBAanN4IGpzeCAqL1xuaW1wb3J0IHsgUmVhY3ROb2RlIH0gZnJvbSAncmVhY3QnO1xuaW1wb3J0IHsganN4LCBrZXlmcmFtZXMgfSBmcm9tICdAZW1vdGlvbi9yZWFjdCc7XG5cbmltcG9ydCB7XG4gIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lLFxuICBDU1NPYmplY3RXaXRoTGFiZWwsXG4gIEdyb3VwQmFzZSxcbn0gZnJvbSAnLi4vdHlwZXMnO1xuaW1wb3J0IHsgZ2V0U3R5bGVQcm9wcyB9IGZyb20gJy4uL3V0aWxzJztcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBEcm9wZG93biAmIENsZWFyIEljb25zXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuY29uc3QgU3ZnID0gKHtcbiAgc2l6ZSxcbiAgLi4ucHJvcHNcbn06IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snc3ZnJ10gJiB7IHNpemU6IG51bWJlciB9KSA9PiAoXG4gIDxzdmdcbiAgICBoZWlnaHQ9e3NpemV9XG4gICAgd2lkdGg9e3NpemV9XG4gICAgdmlld0JveD1cIjAgMCAyMCAyMFwiXG4gICAgYXJpYS1oaWRkZW49XCJ0cnVlXCJcbiAgICBmb2N1c2FibGU9XCJmYWxzZVwiXG4gICAgY3NzPXt7XG4gICAgICBkaXNwbGF5OiAnaW5saW5lLWJsb2NrJyxcbiAgICAgIGZpbGw6ICdjdXJyZW50Q29sb3InLFxuICAgICAgbGluZUhlaWdodDogMSxcbiAgICAgIHN0cm9rZTogJ2N1cnJlbnRDb2xvcicsXG4gICAgICBzdHJva2VXaWR0aDogMCxcbiAgICB9fVxuICAgIHsuLi5wcm9wc31cbiAgLz5cbik7XG5cbmV4cG9ydCB0eXBlIENyb3NzSWNvblByb3BzID0gSlNYLkludHJpbnNpY0VsZW1lbnRzWydzdmcnXSAmIHsgc2l6ZT86IG51bWJlciB9O1xuZXhwb3J0IGNvbnN0IENyb3NzSWNvbiA9IChwcm9wczogQ3Jvc3NJY29uUHJvcHMpID0+IChcbiAgPFN2ZyBzaXplPXsyMH0gey4uLnByb3BzfT5cbiAgICA8cGF0aCBkPVwiTTE0LjM0OCAxNC44NDljLTAuNDY5IDAuNDY5LTEuMjI5IDAuNDY5LTEuNjk3IDBsLTIuNjUxLTMuMDMwLTIuNjUxIDMuMDI5Yy0wLjQ2OSAwLjQ2OS0xLjIyOSAwLjQ2OS0xLjY5NyAwLTAuNDY5LTAuNDY5LTAuNDY5LTEuMjI5IDAtMS42OTdsMi43NTgtMy4xNS0yLjc1OS0zLjE1MmMtMC40NjktMC40NjktMC40NjktMS4yMjggMC0xLjY5N3MxLjIyOC0wLjQ2OSAxLjY5NyAwbDIuNjUyIDMuMDMxIDIuNjUxLTMuMDMxYzAuNDY5LTAuNDY5IDEuMjI4LTAuNDY5IDEuNjk3IDBzMC40NjkgMS4yMjkgMCAxLjY5N2wtMi43NTggMy4xNTIgMi43NTggMy4xNWMwLjQ2OSAwLjQ2OSAwLjQ2OSAxLjIyOSAwIDEuNjk4elwiIC8+XG4gIDwvU3ZnPlxuKTtcbmV4cG9ydCB0eXBlIERvd25DaGV2cm9uUHJvcHMgPSBKU1guSW50cmluc2ljRWxlbWVudHNbJ3N2ZyddICYgeyBzaXplPzogbnVtYmVyIH07XG5leHBvcnQgY29uc3QgRG93bkNoZXZyb24gPSAocHJvcHM6IERvd25DaGV2cm9uUHJvcHMpID0+IChcbiAgPFN2ZyBzaXplPXsyMH0gey4uLnByb3BzfT5cbiAgICA8cGF0aCBkPVwiTTQuNTE2IDcuNTQ4YzAuNDM2LTAuNDQ2IDEuMDQzLTAuNDgxIDEuNTc2IDBsMy45MDggMy43NDcgMy45MDgtMy43NDdjMC41MzMtMC40ODEgMS4xNDEtMC40NDYgMS41NzQgMCAwLjQzNiAwLjQ0NSAwLjQwOCAxLjE5NyAwIDEuNjE1LTAuNDA2IDAuNDE4LTQuNjk1IDQuNTAyLTQuNjk1IDQuNTAyLTAuMjE3IDAuMjIzLTAuNTAyIDAuMzM1LTAuNzg3IDAuMzM1cy0wLjU3LTAuMTEyLTAuNzg5LTAuMzM1YzAgMC00LjI4Ny00LjA4NC00LjY5NS00LjUwMnMtMC40MzYtMS4xNyAwLTEuNjE1elwiIC8+XG4gIDwvU3ZnPlxuKTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBEcm9wZG93biAmIENsZWFyIEJ1dHRvbnNcbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuXG5leHBvcnQgaW50ZXJmYWNlIERyb3Bkb3duSW5kaWNhdG9yUHJvcHM8XG4gIE9wdGlvbiA9IHVua25vd24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuID0gYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPiA9IEdyb3VwQmFzZTxPcHRpb24+XG4+IGV4dGVuZHMgQ29tbW9uUHJvcHNBbmRDbGFzc05hbWU8T3B0aW9uLCBJc011bHRpLCBHcm91cD4ge1xuICAvKiogVGhlIGNoaWxkcmVuIHRvIGJlIHJlbmRlcmVkIGluc2lkZSB0aGUgaW5kaWNhdG9yLiAqL1xuICBjaGlsZHJlbj86IFJlYWN0Tm9kZTtcbiAgLyoqIFByb3BzIHRoYXQgd2lsbCBiZSBwYXNzZWQgb24gdG8gdGhlIGNoaWxkcmVuLiAqL1xuICBpbm5lclByb3BzOiBKU1guSW50cmluc2ljRWxlbWVudHNbJ2RpdiddO1xuICAvKiogVGhlIGZvY3VzZWQgc3RhdGUgb2YgdGhlIHNlbGVjdC4gKi9cbiAgaXNGb2N1c2VkOiBib29sZWFuO1xuICBpc0Rpc2FibGVkOiBib29sZWFuO1xufVxuXG5jb25zdCBiYXNlQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICB7XG4gICAgaXNGb2N1c2VkLFxuICAgIHRoZW1lOiB7XG4gICAgICBzcGFjaW5nOiB7IGJhc2VVbml0IH0sXG4gICAgICBjb2xvcnMsXG4gICAgfSxcbiAgfTpcbiAgICB8IERyb3Bkb3duSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbiAgICB8IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4sXG4gIHVuc3R5bGVkOiBib29sZWFuXG4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdpbmRpY2F0b3JDb250YWluZXInLFxuICBkaXNwbGF5OiAnZmxleCcsXG4gIHRyYW5zaXRpb246ICdjb2xvciAxNTBtcycsXG4gIC4uLih1bnN0eWxlZFxuICAgID8ge31cbiAgICA6IHtcbiAgICAgICAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsNjAgOiBjb2xvcnMubmV1dHJhbDIwLFxuICAgICAgICBwYWRkaW5nOiBiYXNlVW5pdCAqIDIsXG4gICAgICAgICc6aG92ZXInOiB7XG4gICAgICAgICAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsODAgOiBjb2xvcnMubmV1dHJhbDQwLFxuICAgICAgICB9LFxuICAgICAgfSksXG59KTtcblxuZXhwb3J0IGNvbnN0IGRyb3Bkb3duSW5kaWNhdG9yQ1NTID0gYmFzZUNTUztcbmV4cG9ydCBjb25zdCBEcm9wZG93bkluZGljYXRvciA9IDxcbiAgT3B0aW9uLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPlxuPihcbiAgcHJvcHM6IERyb3Bkb3duSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNoaWxkcmVuLCBpbm5lclByb3BzIH0gPSBwcm9wcztcbiAgcmV0dXJuIChcbiAgICA8ZGl2XG4gICAgICB7Li4uZ2V0U3R5bGVQcm9wcyhwcm9wcywgJ2Ryb3Bkb3duSW5kaWNhdG9yJywge1xuICAgICAgICBpbmRpY2F0b3I6IHRydWUsXG4gICAgICAgICdkcm9wZG93bi1pbmRpY2F0b3InOiB0cnVlLFxuICAgICAgfSl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICB7Y2hpbGRyZW4gfHwgPERvd25DaGV2cm9uIC8+fVxuICAgIDwvZGl2PlxuICApO1xufTtcblxuZXhwb3J0IGludGVyZmFjZSBDbGVhckluZGljYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgLyoqIFRoZSBjaGlsZHJlbiB0byBiZSByZW5kZXJlZCBpbnNpZGUgdGhlIGluZGljYXRvci4gKi9cbiAgY2hpbGRyZW4/OiBSZWFjdE5vZGU7XG4gIC8qKiBQcm9wcyB0aGF0IHdpbGwgYmUgcGFzc2VkIG9uIHRvIHRoZSBjaGlsZHJlbi4gKi9cbiAgaW5uZXJQcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydkaXYnXTtcbiAgLyoqIFRoZSBmb2N1c2VkIHN0YXRlIG9mIHRoZSBzZWxlY3QuICovXG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbn1cblxuZXhwb3J0IGNvbnN0IGNsZWFySW5kaWNhdG9yQ1NTID0gYmFzZUNTUztcbmV4cG9ydCBjb25zdCBDbGVhckluZGljYXRvciA9IDxcbiAgT3B0aW9uLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPlxuPihcbiAgcHJvcHM6IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNoaWxkcmVuLCBpbm5lclByb3BzIH0gPSBwcm9wcztcbiAgcmV0dXJuIChcbiAgICA8ZGl2XG4gICAgICB7Li4uZ2V0U3R5bGVQcm9wcyhwcm9wcywgJ2NsZWFySW5kaWNhdG9yJywge1xuICAgICAgICBpbmRpY2F0b3I6IHRydWUsXG4gICAgICAgICdjbGVhci1pbmRpY2F0b3InOiB0cnVlLFxuICAgICAgfSl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICB7Y2hpbGRyZW4gfHwgPENyb3NzSWNvbiAvPn1cbiAgICA8L2Rpdj5cbiAgKTtcbn07XG5cbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuLy8gU2VwYXJhdG9yXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuZXhwb3J0IGludGVyZmFjZSBJbmRpY2F0b3JTZXBhcmF0b3JQcm9wczxcbiAgT3B0aW9uID0gdW5rbm93bixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4gPSBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+ID0gR3JvdXBCYXNlPE9wdGlvbj5cbj4gZXh0ZW5kcyBDb21tb25Qcm9wc0FuZENsYXNzTmFtZTxPcHRpb24sIElzTXVsdGksIEdyb3VwPiB7XG4gIGlzRGlzYWJsZWQ6IGJvb2xlYW47XG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbiAgaW5uZXJQcm9wcz86IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snc3BhbiddO1xufVxuXG5leHBvcnQgY29uc3QgaW5kaWNhdG9yU2VwYXJhdG9yQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICB7XG4gICAgaXNEaXNhYmxlZCxcbiAgICB0aGVtZToge1xuICAgICAgc3BhY2luZzogeyBiYXNlVW5pdCB9LFxuICAgICAgY29sb3JzLFxuICAgIH0sXG4gIH06IEluZGljYXRvclNlcGFyYXRvclByb3BzPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+LFxuICB1bnN0eWxlZDogYm9vbGVhblxuKTogQ1NTT2JqZWN0V2l0aExhYmVsID0+ICh7XG4gIGxhYmVsOiAnaW5kaWNhdG9yU2VwYXJhdG9yJyxcbiAgYWxpZ25TZWxmOiAnc3RyZXRjaCcsXG4gIHdpZHRoOiAxLFxuICAuLi4odW5zdHlsZWRcbiAgICA/IHt9XG4gICAgOiB7XG4gICAgICAgIGJhY2tncm91bmRDb2xvcjogaXNEaXNhYmxlZCA/IGNvbG9ycy5uZXV0cmFsMTAgOiBjb2xvcnMubmV1dHJhbDIwLFxuICAgICAgICBtYXJnaW5Cb3R0b206IGJhc2VVbml0ICogMixcbiAgICAgICAgbWFyZ2luVG9wOiBiYXNlVW5pdCAqIDIsXG4gICAgICB9KSxcbn0pO1xuXG5leHBvcnQgY29uc3QgSW5kaWNhdG9yU2VwYXJhdG9yID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICBwcm9wczogSW5kaWNhdG9yU2VwYXJhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGlubmVyUHJvcHMgfSA9IHByb3BzO1xuICByZXR1cm4gKFxuICAgIDxzcGFuXG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICAgIHsuLi5nZXRTdHlsZVByb3BzKHByb3BzLCAnaW5kaWNhdG9yU2VwYXJhdG9yJywge1xuICAgICAgICAnaW5kaWNhdG9yLXNlcGFyYXRvcic6IHRydWUsXG4gICAgICB9KX1cbiAgICAvPlxuICApO1xufTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBMb2FkaW5nXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuY29uc3QgbG9hZGluZ0RvdEFuaW1hdGlvbnMgPSBrZXlmcmFtZXNgXG4gIDAlLCA4MCUsIDEwMCUgeyBvcGFjaXR5OiAwOyB9XG4gIDQwJSB7IG9wYWNpdHk6IDE7IH1cbmA7XG5cbmV4cG9ydCBjb25zdCBsb2FkaW5nSW5kaWNhdG9yQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICB7XG4gICAgaXNGb2N1c2VkLFxuICAgIHNpemUsXG4gICAgdGhlbWU6IHtcbiAgICAgIGNvbG9ycyxcbiAgICAgIHNwYWNpbmc6IHsgYmFzZVVuaXQgfSxcbiAgICB9LFxuICB9OiBMb2FkaW5nSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4sXG4gIHVuc3R5bGVkOiBib29sZWFuXG4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdsb2FkaW5nSW5kaWNhdG9yJyxcbiAgZGlzcGxheTogJ2ZsZXgnLFxuICB0cmFuc2l0aW9uOiAnY29sb3IgMTUwbXMnLFxuICBhbGlnblNlbGY6ICdjZW50ZXInLFxuICBmb250U2l6ZTogc2l6ZSxcbiAgbGluZUhlaWdodDogMSxcbiAgbWFyZ2luUmlnaHQ6IHNpemUsXG4gIHRleHRBbGlnbjogJ2NlbnRlcicsXG4gIHZlcnRpY2FsQWxpZ246ICdtaWRkbGUnLFxuICAuLi4odW5zdHlsZWRcbiAgICA/IHt9XG4gICAgOiB7XG4gICAgICAgIGNvbG9yOiBpc0ZvY3VzZWQgPyBjb2xvcnMubmV1dHJhbDYwIDogY29sb3JzLm5ldXRyYWwyMCxcbiAgICAgICAgcGFkZGluZzogYmFzZVVuaXQgKiAyLFxuICAgICAgfSksXG59KTtcblxuaW50ZXJmYWNlIExvYWRpbmdEb3RQcm9wcyB7XG4gIGRlbGF5OiBudW1iZXI7XG4gIG9mZnNldDogYm9vbGVhbjtcbn1cbmNvbnN0IExvYWRpbmdEb3QgPSAoeyBkZWxheSwgb2Zmc2V0IH06IExvYWRpbmdEb3RQcm9wcykgPT4gKFxuICA8c3BhblxuICAgIGNzcz17e1xuICAgICAgYW5pbWF0aW9uOiBgJHtsb2FkaW5nRG90QW5pbWF0aW9uc30gMXMgZWFzZS1pbi1vdXQgJHtkZWxheX1tcyBpbmZpbml0ZTtgLFxuICAgICAgYmFja2dyb3VuZENvbG9yOiAnY3VycmVudENvbG9yJyxcbiAgICAgIGJvcmRlclJhZGl1czogJzFlbScsXG4gICAgICBkaXNwbGF5OiAnaW5saW5lLWJsb2NrJyxcbiAgICAgIG1hcmdpbkxlZnQ6IG9mZnNldCA/ICcxZW0nIDogdW5kZWZpbmVkLFxuICAgICAgaGVpZ2h0OiAnMWVtJyxcbiAgICAgIHZlcnRpY2FsQWxpZ246ICd0b3AnLFxuICAgICAgd2lkdGg6ICcxZW0nLFxuICAgIH19XG4gIC8+XG4pO1xuXG5leHBvcnQgaW50ZXJmYWNlIExvYWRpbmdJbmRpY2F0b3JQcm9wczxcbiAgT3B0aW9uID0gdW5rbm93bixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4gPSBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+ID0gR3JvdXBCYXNlPE9wdGlvbj5cbj4gZXh0ZW5kcyBDb21tb25Qcm9wc0FuZENsYXNzTmFtZTxPcHRpb24sIElzTXVsdGksIEdyb3VwPiB7XG4gIC8qKiBQcm9wcyB0aGF0IHdpbGwgYmUgcGFzc2VkIG9uIHRvIHRoZSBjaGlsZHJlbi4gKi9cbiAgaW5uZXJQcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydkaXYnXTtcbiAgLyoqIFRoZSBmb2N1c2VkIHN0YXRlIG9mIHRoZSBzZWxlY3QuICovXG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbiAgaXNEaXNhYmxlZDogYm9vbGVhbjtcbiAgLyoqIFNldCBzaXplIG9mIHRoZSBjb250YWluZXIuICovXG4gIHNpemU6IG51bWJlcjtcbn1cbmV4cG9ydCBjb25zdCBMb2FkaW5nSW5kaWNhdG9yID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KHtcbiAgaW5uZXJQcm9wcyxcbiAgaXNSdGwsXG4gIHNpemUgPSA0LFxuICAuLi5yZXN0UHJvcHNcbn06IExvYWRpbmdJbmRpY2F0b3JQcm9wczxPcHRpb24sIElzTXVsdGksIEdyb3VwPikgPT4ge1xuICByZXR1cm4gKFxuICAgIDxkaXZcbiAgICAgIHsuLi5nZXRTdHlsZVByb3BzKFxuICAgICAgICB7IC4uLnJlc3RQcm9wcywgaW5uZXJQcm9wcywgaXNSdGwsIHNpemUgfSxcbiAgICAgICAgJ2xvYWRpbmdJbmRpY2F0b3InLFxuICAgICAgICB7XG4gICAgICAgICAgaW5kaWNhdG9yOiB0cnVlLFxuICAgICAgICAgICdsb2FkaW5nLWluZGljYXRvcic6IHRydWUsXG4gICAgICAgIH1cbiAgICAgICl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICA8TG9hZGluZ0RvdCBkZWxheT17MH0gb2Zmc2V0PXtpc1J0bH0gLz5cbiAgICAgIDxMb2FkaW5nRG90IGRlbGF5PXsxNjB9IG9mZnNldCAvPlxuICAgICAgPExvYWRpbmdEb3QgZGVsYXk9ezMyMH0gb2Zmc2V0PXshaXNSdGx9IC8+XG4gICAgPC9kaXY+XG4gICk7XG59O1xuIl19 */", toString: _EMOTION_STRINGIFIED_CSS_ERROR__ }; var Svg = function Svg2(_ref3) { var size = _ref3.size, props = _objectWithoutProperties(_ref3, _excluded$2); return jsx2("svg", _extends({ height: size, width: size, viewBox: "0 0 20 20", "aria-hidden": "true", focusable: "false", css: _ref2 }, props)); }; var CrossIcon = function CrossIcon2(props) { return jsx2(Svg, _extends({ size: 20 }, props), jsx2("path", { d: "M14.348 14.849c-0.469 0.469-1.229 0.469-1.697 0l-2.651-3.030-2.651 3.029c-0.469 0.469-1.229 0.469-1.697 0-0.469-0.469-0.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-0.469-0.469-0.469-1.228 0-1.697s1.228-0.469 1.697 0l2.652 3.031 2.651-3.031c0.469-0.469 1.228-0.469 1.697 0s0.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c0.469 0.469 0.469 1.229 0 1.698z" })); }; var DownChevron = function DownChevron2(props) { return jsx2(Svg, _extends({ size: 20 }, props), jsx2("path", { d: "M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z" })); }; var baseCSS = function baseCSS2(_ref3, unstyled) { var isFocused = _ref3.isFocused, _ref3$theme = _ref3.theme, baseUnit2 = _ref3$theme.spacing.baseUnit, colors2 = _ref3$theme.colors; return _objectSpread2({ label: "indicatorContainer", display: "flex", transition: "color 150ms" }, unstyled ? {} : { color: isFocused ? colors2.neutral60 : colors2.neutral20, padding: baseUnit2 * 2, ":hover": { color: isFocused ? colors2.neutral80 : colors2.neutral40 } }); }; var dropdownIndicatorCSS = baseCSS; var DropdownIndicator = function DropdownIndicator2(props) { var children = props.children, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "dropdownIndicator", { indicator: true, "dropdown-indicator": true }), innerProps), children || jsx2(DownChevron, null)); }; var clearIndicatorCSS = baseCSS; var ClearIndicator = function ClearIndicator2(props) { var children = props.children, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "clearIndicator", { indicator: true, "clear-indicator": true }), innerProps), children || jsx2(CrossIcon, null)); }; var indicatorSeparatorCSS = function indicatorSeparatorCSS2(_ref4, unstyled) { var isDisabled = _ref4.isDisabled, _ref4$theme = _ref4.theme, baseUnit2 = _ref4$theme.spacing.baseUnit, colors2 = _ref4$theme.colors; return _objectSpread2({ label: "indicatorSeparator", alignSelf: "stretch", width: 1 }, unstyled ? {} : { backgroundColor: isDisabled ? colors2.neutral10 : colors2.neutral20, marginBottom: baseUnit2 * 2, marginTop: baseUnit2 * 2 }); }; var IndicatorSeparator = function IndicatorSeparator2(props) { var innerProps = props.innerProps; return jsx2("span", _extends({}, innerProps, getStyleProps(props, "indicatorSeparator", { "indicator-separator": true }))); }; var loadingDotAnimations = keyframes(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n 0%, 80%, 100% { opacity: 0; }\n 40% { opacity: 1; }\n"]))); var loadingIndicatorCSS = function loadingIndicatorCSS2(_ref5, unstyled) { var isFocused = _ref5.isFocused, size = _ref5.size, _ref5$theme = _ref5.theme, colors2 = _ref5$theme.colors, baseUnit2 = _ref5$theme.spacing.baseUnit; return _objectSpread2({ label: "loadingIndicator", display: "flex", transition: "color 150ms", alignSelf: "center", fontSize: size, lineHeight: 1, marginRight: size, textAlign: "center", verticalAlign: "middle" }, unstyled ? {} : { color: isFocused ? colors2.neutral60 : colors2.neutral20, padding: baseUnit2 * 2 }); }; var LoadingDot = function LoadingDot2(_ref6) { var delay2 = _ref6.delay, offset = _ref6.offset; return jsx2("span", { css: css({ animation: "".concat(loadingDotAnimations, " 1s ease-in-out ").concat(delay2, "ms infinite;"), backgroundColor: "currentColor", borderRadius: "1em", display: "inline-block", marginLeft: offset ? "1em" : void 0, height: "1em", verticalAlign: "top", width: "1em" }, false ? "" : ";label:LoadingDot;", false ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGljYXRvcnMudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQW1RSSIsImZpbGUiOiJpbmRpY2F0b3JzLnRzeCIsInNvdXJjZXNDb250ZW50IjpbIi8qKiBAanN4IGpzeCAqL1xuaW1wb3J0IHsgUmVhY3ROb2RlIH0gZnJvbSAncmVhY3QnO1xuaW1wb3J0IHsganN4LCBrZXlmcmFtZXMgfSBmcm9tICdAZW1vdGlvbi9yZWFjdCc7XG5cbmltcG9ydCB7XG4gIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lLFxuICBDU1NPYmplY3RXaXRoTGFiZWwsXG4gIEdyb3VwQmFzZSxcbn0gZnJvbSAnLi4vdHlwZXMnO1xuaW1wb3J0IHsgZ2V0U3R5bGVQcm9wcyB9IGZyb20gJy4uL3V0aWxzJztcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBEcm9wZG93biAmIENsZWFyIEljb25zXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuY29uc3QgU3ZnID0gKHtcbiAgc2l6ZSxcbiAgLi4ucHJvcHNcbn06IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snc3ZnJ10gJiB7IHNpemU6IG51bWJlciB9KSA9PiAoXG4gIDxzdmdcbiAgICBoZWlnaHQ9e3NpemV9XG4gICAgd2lkdGg9e3NpemV9XG4gICAgdmlld0JveD1cIjAgMCAyMCAyMFwiXG4gICAgYXJpYS1oaWRkZW49XCJ0cnVlXCJcbiAgICBmb2N1c2FibGU9XCJmYWxzZVwiXG4gICAgY3NzPXt7XG4gICAgICBkaXNwbGF5OiAnaW5saW5lLWJsb2NrJyxcbiAgICAgIGZpbGw6ICdjdXJyZW50Q29sb3InLFxuICAgICAgbGluZUhlaWdodDogMSxcbiAgICAgIHN0cm9rZTogJ2N1cnJlbnRDb2xvcicsXG4gICAgICBzdHJva2VXaWR0aDogMCxcbiAgICB9fVxuICAgIHsuLi5wcm9wc31cbiAgLz5cbik7XG5cbmV4cG9ydCB0eXBlIENyb3NzSWNvblByb3BzID0gSlNYLkludHJpbnNpY0VsZW1lbnRzWydzdmcnXSAmIHsgc2l6ZT86IG51bWJlciB9O1xuZXhwb3J0IGNvbnN0IENyb3NzSWNvbiA9IChwcm9wczogQ3Jvc3NJY29uUHJvcHMpID0+IChcbiAgPFN2ZyBzaXplPXsyMH0gey4uLnByb3BzfT5cbiAgICA8cGF0aCBkPVwiTTE0LjM0OCAxNC44NDljLTAuNDY5IDAuNDY5LTEuMjI5IDAuNDY5LTEuNjk3IDBsLTIuNjUxLTMuMDMwLTIuNjUxIDMuMDI5Yy0wLjQ2OSAwLjQ2OS0xLjIyOSAwLjQ2OS0xLjY5NyAwLTAuNDY5LTAuNDY5LTAuNDY5LTEuMjI5IDAtMS42OTdsMi43NTgtMy4xNS0yLjc1OS0zLjE1MmMtMC40NjktMC40NjktMC40NjktMS4yMjggMC0xLjY5N3MxLjIyOC0wLjQ2OSAxLjY5NyAwbDIuNjUyIDMuMDMxIDIuNjUxLTMuMDMxYzAuNDY5LTAuNDY5IDEuMjI4LTAuNDY5IDEuNjk3IDBzMC40NjkgMS4yMjkgMCAxLjY5N2wtMi43NTggMy4xNTIgMi43NTggMy4xNWMwLjQ2OSAwLjQ2OSAwLjQ2OSAxLjIyOSAwIDEuNjk4elwiIC8+XG4gIDwvU3ZnPlxuKTtcbmV4cG9ydCB0eXBlIERvd25DaGV2cm9uUHJvcHMgPSBKU1guSW50cmluc2ljRWxlbWVudHNbJ3N2ZyddICYgeyBzaXplPzogbnVtYmVyIH07XG5leHBvcnQgY29uc3QgRG93bkNoZXZyb24gPSAocHJvcHM6IERvd25DaGV2cm9uUHJvcHMpID0+IChcbiAgPFN2ZyBzaXplPXsyMH0gey4uLnByb3BzfT5cbiAgICA8cGF0aCBkPVwiTTQuNTE2IDcuNTQ4YzAuNDM2LTAuNDQ2IDEuMDQzLTAuNDgxIDEuNTc2IDBsMy45MDggMy43NDcgMy45MDgtMy43NDdjMC41MzMtMC40ODEgMS4xNDEtMC40NDYgMS41NzQgMCAwLjQzNiAwLjQ0NSAwLjQwOCAxLjE5NyAwIDEuNjE1LTAuNDA2IDAuNDE4LTQuNjk1IDQuNTAyLTQuNjk1IDQuNTAyLTAuMjE3IDAuMjIzLTAuNTAyIDAuMzM1LTAuNzg3IDAuMzM1cy0wLjU3LTAuMTEyLTAuNzg5LTAuMzM1YzAgMC00LjI4Ny00LjA4NC00LjY5NS00LjUwMnMtMC40MzYtMS4xNyAwLTEuNjE1elwiIC8+XG4gIDwvU3ZnPlxuKTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBEcm9wZG93biAmIENsZWFyIEJ1dHRvbnNcbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuXG5leHBvcnQgaW50ZXJmYWNlIERyb3Bkb3duSW5kaWNhdG9yUHJvcHM8XG4gIE9wdGlvbiA9IHVua25vd24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuID0gYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPiA9IEdyb3VwQmFzZTxPcHRpb24+XG4+IGV4dGVuZHMgQ29tbW9uUHJvcHNBbmRDbGFzc05hbWU8T3B0aW9uLCBJc011bHRpLCBHcm91cD4ge1xuICAvKiogVGhlIGNoaWxkcmVuIHRvIGJlIHJlbmRlcmVkIGluc2lkZSB0aGUgaW5kaWNhdG9yLiAqL1xuICBjaGlsZHJlbj86IFJlYWN0Tm9kZTtcbiAgLyoqIFByb3BzIHRoYXQgd2lsbCBiZSBwYXNzZWQgb24gdG8gdGhlIGNoaWxkcmVuLiAqL1xuICBpbm5lclByb3BzOiBKU1guSW50cmluc2ljRWxlbWVudHNbJ2RpdiddO1xuICAvKiogVGhlIGZvY3VzZWQgc3RhdGUgb2YgdGhlIHNlbGVjdC4gKi9cbiAgaXNGb2N1c2VkOiBib29sZWFuO1xuICBpc0Rpc2FibGVkOiBib29sZWFuO1xufVxuXG5jb25zdCBiYXNlQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICB7XG4gICAgaXNGb2N1c2VkLFxuICAgIHRoZW1lOiB7XG4gICAgICBzcGFjaW5nOiB7IGJhc2VVbml0IH0sXG4gICAgICBjb2xvcnMsXG4gICAgfSxcbiAgfTpcbiAgICB8IERyb3Bkb3duSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbiAgICB8IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4sXG4gIHVuc3R5bGVkOiBib29sZWFuXG4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdpbmRpY2F0b3JDb250YWluZXInLFxuICBkaXNwbGF5OiAnZmxleCcsXG4gIHRyYW5zaXRpb246ICdjb2xvciAxNTBtcycsXG4gIC4uLih1bnN0eWxlZFxuICAgID8ge31cbiAgICA6IHtcbiAgICAgICAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsNjAgOiBjb2xvcnMubmV1dHJhbDIwLFxuICAgICAgICBwYWRkaW5nOiBiYXNlVW5pdCAqIDIsXG4gICAgICAgICc6aG92ZXInOiB7XG4gICAgICAgICAgY29sb3I6IGlzRm9jdXNlZCA/IGNvbG9ycy5uZXV0cmFsODAgOiBjb2xvcnMubmV1dHJhbDQwLFxuICAgICAgICB9LFxuICAgICAgfSksXG59KTtcblxuZXhwb3J0IGNvbnN0IGRyb3Bkb3duSW5kaWNhdG9yQ1NTID0gYmFzZUNTUztcbmV4cG9ydCBjb25zdCBEcm9wZG93bkluZGljYXRvciA9IDxcbiAgT3B0aW9uLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPlxuPihcbiAgcHJvcHM6IERyb3Bkb3duSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNoaWxkcmVuLCBpbm5lclByb3BzIH0gPSBwcm9wcztcbiAgcmV0dXJuIChcbiAgICA8ZGl2XG4gICAgICB7Li4uZ2V0U3R5bGVQcm9wcyhwcm9wcywgJ2Ryb3Bkb3duSW5kaWNhdG9yJywge1xuICAgICAgICBpbmRpY2F0b3I6IHRydWUsXG4gICAgICAgICdkcm9wZG93bi1pbmRpY2F0b3InOiB0cnVlLFxuICAgICAgfSl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICB7Y2hpbGRyZW4gfHwgPERvd25DaGV2cm9uIC8+fVxuICAgIDwvZGl2PlxuICApO1xufTtcblxuZXhwb3J0IGludGVyZmFjZSBDbGVhckluZGljYXRvclByb3BzPFxuICBPcHRpb24gPSB1bmtub3duLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbiA9IGJvb2xlYW4sXG4gIEdyb3VwIGV4dGVuZHMgR3JvdXBCYXNlPE9wdGlvbj4gPSBHcm91cEJhc2U8T3B0aW9uPlxuPiBleHRlbmRzIENvbW1vblByb3BzQW5kQ2xhc3NOYW1lPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+IHtcbiAgLyoqIFRoZSBjaGlsZHJlbiB0byBiZSByZW5kZXJlZCBpbnNpZGUgdGhlIGluZGljYXRvci4gKi9cbiAgY2hpbGRyZW4/OiBSZWFjdE5vZGU7XG4gIC8qKiBQcm9wcyB0aGF0IHdpbGwgYmUgcGFzc2VkIG9uIHRvIHRoZSBjaGlsZHJlbi4gKi9cbiAgaW5uZXJQcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydkaXYnXTtcbiAgLyoqIFRoZSBmb2N1c2VkIHN0YXRlIG9mIHRoZSBzZWxlY3QuICovXG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbn1cblxuZXhwb3J0IGNvbnN0IGNsZWFySW5kaWNhdG9yQ1NTID0gYmFzZUNTUztcbmV4cG9ydCBjb25zdCBDbGVhckluZGljYXRvciA9IDxcbiAgT3B0aW9uLFxuICBJc011bHRpIGV4dGVuZHMgYm9vbGVhbixcbiAgR3JvdXAgZXh0ZW5kcyBHcm91cEJhc2U8T3B0aW9uPlxuPihcbiAgcHJvcHM6IENsZWFySW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGNoaWxkcmVuLCBpbm5lclByb3BzIH0gPSBwcm9wcztcbiAgcmV0dXJuIChcbiAgICA8ZGl2XG4gICAgICB7Li4uZ2V0U3R5bGVQcm9wcyhwcm9wcywgJ2NsZWFySW5kaWNhdG9yJywge1xuICAgICAgICBpbmRpY2F0b3I6IHRydWUsXG4gICAgICAgICdjbGVhci1pbmRpY2F0b3InOiB0cnVlLFxuICAgICAgfSl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICB7Y2hpbGRyZW4gfHwgPENyb3NzSWNvbiAvPn1cbiAgICA8L2Rpdj5cbiAgKTtcbn07XG5cbi8vID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVxuLy8gU2VwYXJhdG9yXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuZXhwb3J0IGludGVyZmFjZSBJbmRpY2F0b3JTZXBhcmF0b3JQcm9wczxcbiAgT3B0aW9uID0gdW5rbm93bixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4gPSBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+ID0gR3JvdXBCYXNlPE9wdGlvbj5cbj4gZXh0ZW5kcyBDb21tb25Qcm9wc0FuZENsYXNzTmFtZTxPcHRpb24sIElzTXVsdGksIEdyb3VwPiB7XG4gIGlzRGlzYWJsZWQ6IGJvb2xlYW47XG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbiAgaW5uZXJQcm9wcz86IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snc3BhbiddO1xufVxuXG5leHBvcnQgY29uc3QgaW5kaWNhdG9yU2VwYXJhdG9yQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICB7XG4gICAgaXNEaXNhYmxlZCxcbiAgICB0aGVtZToge1xuICAgICAgc3BhY2luZzogeyBiYXNlVW5pdCB9LFxuICAgICAgY29sb3JzLFxuICAgIH0sXG4gIH06IEluZGljYXRvclNlcGFyYXRvclByb3BzPE9wdGlvbiwgSXNNdWx0aSwgR3JvdXA+LFxuICB1bnN0eWxlZDogYm9vbGVhblxuKTogQ1NTT2JqZWN0V2l0aExhYmVsID0+ICh7XG4gIGxhYmVsOiAnaW5kaWNhdG9yU2VwYXJhdG9yJyxcbiAgYWxpZ25TZWxmOiAnc3RyZXRjaCcsXG4gIHdpZHRoOiAxLFxuICAuLi4odW5zdHlsZWRcbiAgICA/IHt9XG4gICAgOiB7XG4gICAgICAgIGJhY2tncm91bmRDb2xvcjogaXNEaXNhYmxlZCA/IGNvbG9ycy5uZXV0cmFsMTAgOiBjb2xvcnMubmV1dHJhbDIwLFxuICAgICAgICBtYXJnaW5Cb3R0b206IGJhc2VVbml0ICogMixcbiAgICAgICAgbWFyZ2luVG9wOiBiYXNlVW5pdCAqIDIsXG4gICAgICB9KSxcbn0pO1xuXG5leHBvcnQgY29uc3QgSW5kaWNhdG9yU2VwYXJhdG9yID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICBwcm9wczogSW5kaWNhdG9yU2VwYXJhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD5cbikgPT4ge1xuICBjb25zdCB7IGlubmVyUHJvcHMgfSA9IHByb3BzO1xuICByZXR1cm4gKFxuICAgIDxzcGFuXG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICAgIHsuLi5nZXRTdHlsZVByb3BzKHByb3BzLCAnaW5kaWNhdG9yU2VwYXJhdG9yJywge1xuICAgICAgICAnaW5kaWNhdG9yLXNlcGFyYXRvcic6IHRydWUsXG4gICAgICB9KX1cbiAgICAvPlxuICApO1xufTtcblxuLy8gPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09XG4vLyBMb2FkaW5nXG4vLyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT1cblxuY29uc3QgbG9hZGluZ0RvdEFuaW1hdGlvbnMgPSBrZXlmcmFtZXNgXG4gIDAlLCA4MCUsIDEwMCUgeyBvcGFjaXR5OiAwOyB9XG4gIDQwJSB7IG9wYWNpdHk6IDE7IH1cbmA7XG5cbmV4cG9ydCBjb25zdCBsb2FkaW5nSW5kaWNhdG9yQ1NTID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KFxuICB7XG4gICAgaXNGb2N1c2VkLFxuICAgIHNpemUsXG4gICAgdGhlbWU6IHtcbiAgICAgIGNvbG9ycyxcbiAgICAgIHNwYWNpbmc6IHsgYmFzZVVuaXQgfSxcbiAgICB9LFxuICB9OiBMb2FkaW5nSW5kaWNhdG9yUHJvcHM8T3B0aW9uLCBJc011bHRpLCBHcm91cD4sXG4gIHVuc3R5bGVkOiBib29sZWFuXG4pOiBDU1NPYmplY3RXaXRoTGFiZWwgPT4gKHtcbiAgbGFiZWw6ICdsb2FkaW5nSW5kaWNhdG9yJyxcbiAgZGlzcGxheTogJ2ZsZXgnLFxuICB0cmFuc2l0aW9uOiAnY29sb3IgMTUwbXMnLFxuICBhbGlnblNlbGY6ICdjZW50ZXInLFxuICBmb250U2l6ZTogc2l6ZSxcbiAgbGluZUhlaWdodDogMSxcbiAgbWFyZ2luUmlnaHQ6IHNpemUsXG4gIHRleHRBbGlnbjogJ2NlbnRlcicsXG4gIHZlcnRpY2FsQWxpZ246ICdtaWRkbGUnLFxuICAuLi4odW5zdHlsZWRcbiAgICA/IHt9XG4gICAgOiB7XG4gICAgICAgIGNvbG9yOiBpc0ZvY3VzZWQgPyBjb2xvcnMubmV1dHJhbDYwIDogY29sb3JzLm5ldXRyYWwyMCxcbiAgICAgICAgcGFkZGluZzogYmFzZVVuaXQgKiAyLFxuICAgICAgfSksXG59KTtcblxuaW50ZXJmYWNlIExvYWRpbmdEb3RQcm9wcyB7XG4gIGRlbGF5OiBudW1iZXI7XG4gIG9mZnNldDogYm9vbGVhbjtcbn1cbmNvbnN0IExvYWRpbmdEb3QgPSAoeyBkZWxheSwgb2Zmc2V0IH06IExvYWRpbmdEb3RQcm9wcykgPT4gKFxuICA8c3BhblxuICAgIGNzcz17e1xuICAgICAgYW5pbWF0aW9uOiBgJHtsb2FkaW5nRG90QW5pbWF0aW9uc30gMXMgZWFzZS1pbi1vdXQgJHtkZWxheX1tcyBpbmZpbml0ZTtgLFxuICAgICAgYmFja2dyb3VuZENvbG9yOiAnY3VycmVudENvbG9yJyxcbiAgICAgIGJvcmRlclJhZGl1czogJzFlbScsXG4gICAgICBkaXNwbGF5OiAnaW5saW5lLWJsb2NrJyxcbiAgICAgIG1hcmdpbkxlZnQ6IG9mZnNldCA/ICcxZW0nIDogdW5kZWZpbmVkLFxuICAgICAgaGVpZ2h0OiAnMWVtJyxcbiAgICAgIHZlcnRpY2FsQWxpZ246ICd0b3AnLFxuICAgICAgd2lkdGg6ICcxZW0nLFxuICAgIH19XG4gIC8+XG4pO1xuXG5leHBvcnQgaW50ZXJmYWNlIExvYWRpbmdJbmRpY2F0b3JQcm9wczxcbiAgT3B0aW9uID0gdW5rbm93bixcbiAgSXNNdWx0aSBleHRlbmRzIGJvb2xlYW4gPSBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+ID0gR3JvdXBCYXNlPE9wdGlvbj5cbj4gZXh0ZW5kcyBDb21tb25Qcm9wc0FuZENsYXNzTmFtZTxPcHRpb24sIElzTXVsdGksIEdyb3VwPiB7XG4gIC8qKiBQcm9wcyB0aGF0IHdpbGwgYmUgcGFzc2VkIG9uIHRvIHRoZSBjaGlsZHJlbi4gKi9cbiAgaW5uZXJQcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydkaXYnXTtcbiAgLyoqIFRoZSBmb2N1c2VkIHN0YXRlIG9mIHRoZSBzZWxlY3QuICovXG4gIGlzRm9jdXNlZDogYm9vbGVhbjtcbiAgaXNEaXNhYmxlZDogYm9vbGVhbjtcbiAgLyoqIFNldCBzaXplIG9mIHRoZSBjb250YWluZXIuICovXG4gIHNpemU6IG51bWJlcjtcbn1cbmV4cG9ydCBjb25zdCBMb2FkaW5nSW5kaWNhdG9yID0gPFxuICBPcHRpb24sXG4gIElzTXVsdGkgZXh0ZW5kcyBib29sZWFuLFxuICBHcm91cCBleHRlbmRzIEdyb3VwQmFzZTxPcHRpb24+XG4+KHtcbiAgaW5uZXJQcm9wcyxcbiAgaXNSdGwsXG4gIHNpemUgPSA0LFxuICAuLi5yZXN0UHJvcHNcbn06IExvYWRpbmdJbmRpY2F0b3JQcm9wczxPcHRpb24sIElzTXVsdGksIEdyb3VwPikgPT4ge1xuICByZXR1cm4gKFxuICAgIDxkaXZcbiAgICAgIHsuLi5nZXRTdHlsZVByb3BzKFxuICAgICAgICB7IC4uLnJlc3RQcm9wcywgaW5uZXJQcm9wcywgaXNSdGwsIHNpemUgfSxcbiAgICAgICAgJ2xvYWRpbmdJbmRpY2F0b3InLFxuICAgICAgICB7XG4gICAgICAgICAgaW5kaWNhdG9yOiB0cnVlLFxuICAgICAgICAgICdsb2FkaW5nLWluZGljYXRvcic6IHRydWUsXG4gICAgICAgIH1cbiAgICAgICl9XG4gICAgICB7Li4uaW5uZXJQcm9wc31cbiAgICA+XG4gICAgICA8TG9hZGluZ0RvdCBkZWxheT17MH0gb2Zmc2V0PXtpc1J0bH0gLz5cbiAgICAgIDxMb2FkaW5nRG90IGRlbGF5PXsxNjB9IG9mZnNldCAvPlxuICAgICAgPExvYWRpbmdEb3QgZGVsYXk9ezMyMH0gb2Zmc2V0PXshaXNSdGx9IC8+XG4gICAgPC9kaXY+XG4gICk7XG59O1xuIl19 */") }); }; var LoadingIndicator = function LoadingIndicator2(_ref7) { var innerProps = _ref7.innerProps, isRtl = _ref7.isRtl, _ref7$size = _ref7.size, size = _ref7$size === void 0 ? 4 : _ref7$size, restProps = _objectWithoutProperties(_ref7, _excluded2); return jsx2("div", _extends({}, getStyleProps(_objectSpread2(_objectSpread2({}, restProps), {}, { innerProps, isRtl, size }), "loadingIndicator", { indicator: true, "loading-indicator": true }), innerProps), jsx2(LoadingDot, { delay: 0, offset: isRtl }), jsx2(LoadingDot, { delay: 160, offset: true }), jsx2(LoadingDot, { delay: 320, offset: !isRtl })); }; var css$1 = function css2(_ref3, unstyled) { var isDisabled = _ref3.isDisabled, isFocused = _ref3.isFocused, _ref$theme = _ref3.theme, colors2 = _ref$theme.colors, borderRadius2 = _ref$theme.borderRadius, spacing2 = _ref$theme.spacing; return _objectSpread2({ label: "control", alignItems: "center", cursor: "default", display: "flex", flexWrap: "wrap", justifyContent: "space-between", minHeight: spacing2.controlHeight, outline: "0 !important", position: "relative", transition: "all 100ms" }, unstyled ? {} : { backgroundColor: isDisabled ? colors2.neutral5 : colors2.neutral0, borderColor: isDisabled ? colors2.neutral10 : isFocused ? colors2.primary : colors2.neutral20, borderRadius: borderRadius2, borderStyle: "solid", borderWidth: 1, boxShadow: isFocused ? "0 0 0 1px ".concat(colors2.primary) : void 0, "&:hover": { borderColor: isFocused ? colors2.primary : colors2.neutral30 } }); }; var Control = function Control2(props) { var children = props.children, isDisabled = props.isDisabled, isFocused = props.isFocused, innerRef = props.innerRef, innerProps = props.innerProps, menuIsOpen = props.menuIsOpen; return jsx2("div", _extends({ ref: innerRef }, getStyleProps(props, "control", { control: true, "control--is-disabled": isDisabled, "control--is-focused": isFocused, "control--menu-is-open": menuIsOpen }), innerProps, { "aria-disabled": isDisabled || void 0 }), children); }; var Control$1 = Control; var _excluded$1 = ["data"]; var groupCSS = function groupCSS2(_ref3, unstyled) { var spacing2 = _ref3.theme.spacing; return unstyled ? {} : { paddingBottom: spacing2.baseUnit * 2, paddingTop: spacing2.baseUnit * 2 }; }; var Group = function Group2(props) { var children = props.children, cx = props.cx, getStyles = props.getStyles, getClassNames = props.getClassNames, Heading = props.Heading, headingProps = props.headingProps, innerProps = props.innerProps, label = props.label, theme = props.theme, selectProps = props.selectProps; return jsx2("div", _extends({}, getStyleProps(props, "group", { group: true }), innerProps), jsx2(Heading, _extends({}, headingProps, { selectProps, theme, getStyles, getClassNames, cx }), label), jsx2("div", null, children)); }; var groupHeadingCSS = function groupHeadingCSS2(_ref23, unstyled) { var _ref2$theme = _ref23.theme, colors2 = _ref2$theme.colors, spacing2 = _ref2$theme.spacing; return _objectSpread2({ label: "group", cursor: "default", display: "block" }, unstyled ? {} : { color: colors2.neutral40, fontSize: "75%", fontWeight: 500, marginBottom: "0.25em", paddingLeft: spacing2.baseUnit * 3, paddingRight: spacing2.baseUnit * 3, textTransform: "uppercase" }); }; var GroupHeading = function GroupHeading2(props) { var _cleanCommonProps = cleanCommonProps(props); _cleanCommonProps.data; var innerProps = _objectWithoutProperties(_cleanCommonProps, _excluded$1); return jsx2("div", _extends({}, getStyleProps(props, "groupHeading", { "group-heading": true }), innerProps)); }; var Group$1 = Group; var _excluded3 = ["innerRef", "isDisabled", "isHidden", "inputClassName"]; var inputCSS = function inputCSS2(_ref3, unstyled) { var isDisabled = _ref3.isDisabled, value = _ref3.value, _ref$theme = _ref3.theme, spacing2 = _ref$theme.spacing, colors2 = _ref$theme.colors; return _objectSpread2(_objectSpread2({ visibility: isDisabled ? "hidden" : "visible", // force css to recompute when value change due to @emotion bug. // We can remove it whenever the bug is fixed. transform: value ? "translateZ(0)" : "" }, containerStyle), unstyled ? {} : { margin: spacing2.baseUnit / 2, paddingBottom: spacing2.baseUnit / 2, paddingTop: spacing2.baseUnit / 2, color: colors2.neutral80 }); }; var spacingStyle = { gridArea: "1 / 2", font: "inherit", minWidth: "2px", border: 0, margin: 0, outline: 0, padding: 0 }; var containerStyle = { flex: "1 1 auto", display: "inline-grid", gridArea: "1 / 1 / 2 / 3", gridTemplateColumns: "0 min-content", "&:after": _objectSpread2({ content: 'attr(data-value) " "', visibility: "hidden", whiteSpace: "pre" }, spacingStyle) }; var inputStyle = function inputStyle2(isHidden) { return _objectSpread2({ label: "input", color: "inherit", background: 0, opacity: isHidden ? 0 : 1, width: "100%" }, spacingStyle); }; var Input = function Input2(props) { var cx = props.cx, value = props.value; var _cleanCommonProps = cleanCommonProps(props), innerRef = _cleanCommonProps.innerRef, isDisabled = _cleanCommonProps.isDisabled, isHidden = _cleanCommonProps.isHidden, inputClassName = _cleanCommonProps.inputClassName, innerProps = _objectWithoutProperties(_cleanCommonProps, _excluded3); return jsx2("div", _extends({}, getStyleProps(props, "input", { "input-container": true }), { "data-value": value || "" }), jsx2("input", _extends({ className: cx({ input: true }, inputClassName), ref: innerRef, style: inputStyle(isHidden), disabled: isDisabled }, innerProps))); }; var Input$1 = Input; var multiValueCSS = function multiValueCSS2(_ref3, unstyled) { var _ref$theme = _ref3.theme, spacing2 = _ref$theme.spacing, borderRadius2 = _ref$theme.borderRadius, colors2 = _ref$theme.colors; return _objectSpread2({ label: "multiValue", display: "flex", minWidth: 0 }, unstyled ? {} : { backgroundColor: colors2.neutral10, borderRadius: borderRadius2 / 2, margin: spacing2.baseUnit / 2 }); }; var multiValueLabelCSS = function multiValueLabelCSS2(_ref23, unstyled) { var _ref2$theme = _ref23.theme, borderRadius2 = _ref2$theme.borderRadius, colors2 = _ref2$theme.colors, cropWithEllipsis = _ref23.cropWithEllipsis; return _objectSpread2({ overflow: "hidden", textOverflow: cropWithEllipsis || cropWithEllipsis === void 0 ? "ellipsis" : void 0, whiteSpace: "nowrap" }, unstyled ? {} : { borderRadius: borderRadius2 / 2, color: colors2.neutral80, fontSize: "85%", padding: 3, paddingLeft: 6 }); }; var multiValueRemoveCSS = function multiValueRemoveCSS2(_ref3, unstyled) { var _ref3$theme = _ref3.theme, spacing2 = _ref3$theme.spacing, borderRadius2 = _ref3$theme.borderRadius, colors2 = _ref3$theme.colors, isFocused = _ref3.isFocused; return _objectSpread2({ alignItems: "center", display: "flex" }, unstyled ? {} : { borderRadius: borderRadius2 / 2, backgroundColor: isFocused ? colors2.dangerLight : void 0, paddingLeft: spacing2.baseUnit, paddingRight: spacing2.baseUnit, ":hover": { backgroundColor: colors2.dangerLight, color: colors2.danger } }); }; var MultiValueGeneric = function MultiValueGeneric2(_ref4) { var children = _ref4.children, innerProps = _ref4.innerProps; return jsx2("div", innerProps, children); }; var MultiValueContainer = MultiValueGeneric; var MultiValueLabel = MultiValueGeneric; function MultiValueRemove(_ref5) { var children = _ref5.children, innerProps = _ref5.innerProps; return jsx2("div", _extends({ role: "button" }, innerProps), children || jsx2(CrossIcon, { size: 14 })); } var MultiValue = function MultiValue2(props) { var children = props.children, components2 = props.components, data = props.data, innerProps = props.innerProps, isDisabled = props.isDisabled, removeProps3 = props.removeProps, selectProps = props.selectProps; var Container = components2.Container, Label = components2.Label, Remove = components2.Remove; return jsx2(Container, { data, innerProps: _objectSpread2(_objectSpread2({}, getStyleProps(props, "multiValue", { "multi-value": true, "multi-value--is-disabled": isDisabled })), innerProps), selectProps }, jsx2(Label, { data, innerProps: _objectSpread2({}, getStyleProps(props, "multiValueLabel", { "multi-value__label": true })), selectProps }, children), jsx2(Remove, { data, innerProps: _objectSpread2(_objectSpread2({}, getStyleProps(props, "multiValueRemove", { "multi-value__remove": true })), {}, { "aria-label": "Remove ".concat(children || "option") }, removeProps3), selectProps })); }; var MultiValue$1 = MultiValue; var optionCSS = function optionCSS2(_ref3, unstyled) { var isDisabled = _ref3.isDisabled, isFocused = _ref3.isFocused, isSelected = _ref3.isSelected, _ref$theme = _ref3.theme, spacing2 = _ref$theme.spacing, colors2 = _ref$theme.colors; return _objectSpread2({ label: "option", cursor: "default", display: "block", fontSize: "inherit", width: "100%", userSelect: "none", WebkitTapHighlightColor: "rgba(0, 0, 0, 0)" }, unstyled ? {} : { backgroundColor: isSelected ? colors2.primary : isFocused ? colors2.primary25 : "transparent", color: isDisabled ? colors2.neutral20 : isSelected ? colors2.neutral0 : "inherit", padding: "".concat(spacing2.baseUnit * 2, "px ").concat(spacing2.baseUnit * 3, "px"), // provide some affordance on touch devices ":active": { backgroundColor: !isDisabled ? isSelected ? colors2.primary : colors2.primary50 : void 0 } }); }; var Option = function Option2(props) { var children = props.children, isDisabled = props.isDisabled, isFocused = props.isFocused, isSelected = props.isSelected, innerRef = props.innerRef, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "option", { option: true, "option--is-disabled": isDisabled, "option--is-focused": isFocused, "option--is-selected": isSelected }), { ref: innerRef, "aria-disabled": isDisabled }, innerProps), children); }; var Option$1 = Option; var placeholderCSS = function placeholderCSS2(_ref3, unstyled) { var _ref$theme = _ref3.theme, spacing2 = _ref$theme.spacing, colors2 = _ref$theme.colors; return _objectSpread2({ label: "placeholder", gridArea: "1 / 1 / 2 / 3" }, unstyled ? {} : { color: colors2.neutral50, marginLeft: spacing2.baseUnit / 2, marginRight: spacing2.baseUnit / 2 }); }; var Placeholder = function Placeholder2(props) { var children = props.children, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "placeholder", { placeholder: true }), innerProps), children); }; var Placeholder$1 = Placeholder; var css3 = function css4(_ref3, unstyled) { var isDisabled = _ref3.isDisabled, _ref$theme = _ref3.theme, spacing2 = _ref$theme.spacing, colors2 = _ref$theme.colors; return _objectSpread2({ label: "singleValue", gridArea: "1 / 1 / 2 / 3", maxWidth: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, unstyled ? {} : { color: isDisabled ? colors2.neutral40 : colors2.neutral80, marginLeft: spacing2.baseUnit / 2, marginRight: spacing2.baseUnit / 2 }); }; var SingleValue = function SingleValue2(props) { var children = props.children, isDisabled = props.isDisabled, innerProps = props.innerProps; return jsx2("div", _extends({}, getStyleProps(props, "singleValue", { "single-value": true, "single-value--is-disabled": isDisabled }), innerProps), children); }; var SingleValue$1 = SingleValue; var components = { ClearIndicator, Control: Control$1, DropdownIndicator, DownChevron, CrossIcon, Group: Group$1, GroupHeading, IndicatorsContainer, IndicatorSeparator, Input: Input$1, LoadingIndicator, Menu: Menu$1, MenuList, MenuPortal, LoadingMessage, NoOptionsMessage, MultiValue: MultiValue$1, MultiValueContainer, MultiValueLabel, MultiValueRemove, Option: Option$1, Placeholder: Placeholder$1, SelectContainer, SingleValue: SingleValue$1, ValueContainer }; var defaultComponents = function defaultComponents2(props) { return _objectSpread2(_objectSpread2({}, components), props.components); }; // node_modules/memoize-one/dist/memoize-one.esm.js var safeIsNaN = Number.isNaN || function ponyfill(value) { return typeof value === "number" && value !== value; }; function isEqual(first, second) { if (first === second) { return true; } if (safeIsNaN(first) && safeIsNaN(second)) { return true; } return false; } function areInputsEqual(newInputs, lastInputs) { if (newInputs.length !== lastInputs.length) { return false; } for (var i3 = 0; i3 < newInputs.length; i3++) { if (!isEqual(newInputs[i3], lastInputs[i3])) { return false; } } return true; } function memoizeOne(resultFn, isEqual3) { if (isEqual3 === void 0) { isEqual3 = areInputsEqual; } var cache = null; function memoized() { var newArgs = []; for (var _i2 = 0; _i2 < arguments.length; _i2++) { newArgs[_i2] = arguments[_i2]; } if (cache && cache.lastThis === this && isEqual3(newArgs, cache.lastArgs)) { return cache.lastResult; } var lastResult = resultFn.apply(this, newArgs); cache = { lastResult, lastArgs: newArgs, lastThis: this }; return lastResult; } memoized.clear = function clear2() { cache = null; }; return memoized; } // node_modules/react-select/dist/Select-49a62830.esm.js function _EMOTION_STRINGIFIED_CSS_ERROR__$2() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } var _ref = false ? { name: "7pg0cj-a11yText", styles: "label:a11yText;z-index:9999;border:0;clip:rect(1px, 1px, 1px, 1px);height:1px;width:1px;position:absolute;overflow:hidden;padding:0;white-space:nowrap" } : { name: "1f43avz-a11yText-A11yText", styles: "label:a11yText;z-index:9999;border:0;clip:rect(1px, 1px, 1px, 1px);height:1px;width:1px;position:absolute;overflow:hidden;padding:0;white-space:nowrap;label:A11yText;", map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkExMXlUZXh0LnRzeCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFNSSIsImZpbGUiOiJBMTF5VGV4dC50c3giLCJzb3VyY2VzQ29udGVudCI6WyIvKiogQGpzeCBqc3ggKi9cbmltcG9ydCB7IGpzeCB9IGZyb20gJ0BlbW90aW9uL3JlYWN0JztcblxuLy8gQXNzaXN0aXZlIHRleHQgdG8gZGVzY3JpYmUgdmlzdWFsIGVsZW1lbnRzLiBIaWRkZW4gZm9yIHNpZ2h0ZWQgdXNlcnMuXG5jb25zdCBBMTF5VGV4dCA9IChwcm9wczogSlNYLkludHJpbnNpY0VsZW1lbnRzWydzcGFuJ10pID0+IChcbiAgPHNwYW5cbiAgICBjc3M9e3tcbiAgICAgIGxhYmVsOiAnYTExeVRleHQnLFxuICAgICAgekluZGV4OiA5OTk5LFxuICAgICAgYm9yZGVyOiAwLFxuICAgICAgY2xpcDogJ3JlY3QoMXB4LCAxcHgsIDFweCwgMXB4KScsXG4gICAgICBoZWlnaHQ6IDEsXG4gICAgICB3aWR0aDogMSxcbiAgICAgIHBvc2l0aW9uOiAnYWJzb2x1dGUnLFxuICAgICAgb3ZlcmZsb3c6ICdoaWRkZW4nLFxuICAgICAgcGFkZGluZzogMCxcbiAgICAgIHdoaXRlU3BhY2U6ICdub3dyYXAnLFxuICAgIH19XG4gICAgey4uLnByb3BzfVxuICAvPlxuKTtcblxuZXhwb3J0IGRlZmF1bHQgQTExeVRleHQ7XG4iXX0= */", toString: _EMOTION_STRINGIFIED_CSS_ERROR__$2 }; var A11yText = function A11yText2(props) { return jsx2("span", _extends({ css: _ref }, props)); }; var A11yText$1 = A11yText; var defaultAriaLiveMessages = { guidance: function guidance(props) { var isSearchable = props.isSearchable, isMulti = props.isMulti, tabSelectsValue = props.tabSelectsValue, context = props.context, isInitialFocus = props.isInitialFocus; switch (context) { case "menu": return "Use Up and Down to choose options, press Enter to select the currently focused option, press Escape to exit the menu".concat(tabSelectsValue ? ", press Tab to select the option and exit the menu" : "", "."); case "input": return isInitialFocus ? "".concat(props["aria-label"] || "Select", " is focused ").concat(isSearchable ? ",type to refine list" : "", ", press Down to open the menu, ").concat(isMulti ? " press left to focus selected values" : "") : ""; case "value": return "Use left and right to toggle between focused values, press Backspace to remove the currently focused value"; default: return ""; } }, onChange: function onChange(props) { var action = props.action, _props$label = props.label, label = _props$label === void 0 ? "" : _props$label, labels = props.labels, isDisabled = props.isDisabled; switch (action) { case "deselect-option": case "pop-value": case "remove-value": return "option ".concat(label, ", deselected."); case "clear": return "All selected options have been cleared."; case "initial-input-focus": return "option".concat(labels.length > 1 ? "s" : "", " ").concat(labels.join(","), ", selected."); case "select-option": return isDisabled ? "option ".concat(label, " is disabled. Select another option.") : "option ".concat(label, ", selected."); default: return ""; } }, onFocus: function onFocus(props) { var context = props.context, focused = props.focused, options2 = props.options, _props$label2 = props.label, label = _props$label2 === void 0 ? "" : _props$label2, selectValue = props.selectValue, isDisabled = props.isDisabled, isSelected = props.isSelected, isAppleDevice2 = props.isAppleDevice; var getArrayIndex = function getArrayIndex2(arr, item) { return arr && arr.length ? "".concat(arr.indexOf(item) + 1, " of ").concat(arr.length) : ""; }; if (context === "value" && selectValue) { return "value ".concat(label, " focused, ").concat(getArrayIndex(selectValue, focused), "."); } if (context === "menu" && isAppleDevice2) { var disabled = isDisabled ? " disabled" : ""; var status2 = "".concat(isSelected ? " selected" : "").concat(disabled); return "".concat(label).concat(status2, ", ").concat(getArrayIndex(options2, focused), "."); } return ""; }, onFilter: function onFilter(props) { var inputValue = props.inputValue, resultsMessage = props.resultsMessage; return "".concat(resultsMessage).concat(inputValue ? " for search term " + inputValue : "", "."); } }; var LiveRegion = function LiveRegion2(props) { var ariaSelection = props.ariaSelection, focusedOption = props.focusedOption, focusedValue = props.focusedValue, focusableOptions = props.focusableOptions, isFocused = props.isFocused, selectValue = props.selectValue, selectProps = props.selectProps, id = props.id, isAppleDevice2 = props.isAppleDevice; var ariaLiveMessages = selectProps.ariaLiveMessages, getOptionLabel4 = selectProps.getOptionLabel, inputValue = selectProps.inputValue, isMulti = selectProps.isMulti, isOptionDisabled3 = selectProps.isOptionDisabled, isSearchable = selectProps.isSearchable, menuIsOpen = selectProps.menuIsOpen, options2 = selectProps.options, screenReaderStatus2 = selectProps.screenReaderStatus, tabSelectsValue = selectProps.tabSelectsValue, isLoading = selectProps.isLoading; var ariaLabel = selectProps["aria-label"]; var ariaLive = selectProps["aria-live"]; var messages = (0, import_react6.useMemo)(function() { return _objectSpread2(_objectSpread2({}, defaultAriaLiveMessages), ariaLiveMessages || {}); }, [ariaLiveMessages]); var ariaSelected = (0, import_react6.useMemo)(function() { var message = ""; if (ariaSelection && messages.onChange) { var option = ariaSelection.option, selectedOptions = ariaSelection.options, removedValue = ariaSelection.removedValue, removedValues = ariaSelection.removedValues, value = ariaSelection.value; var asOption = function asOption2(val) { return !Array.isArray(val) ? val : null; }; var selected = removedValue || option || asOption(value); var label = selected ? getOptionLabel4(selected) : ""; var multiSelected = selectedOptions || removedValues || void 0; var labels = multiSelected ? multiSelected.map(getOptionLabel4) : []; var onChangeProps = _objectSpread2({ // multiSelected items are usually items that have already been selected // or set by the user as a default value so we assume they are not disabled isDisabled: selected && isOptionDisabled3(selected, selectValue), label, labels }, ariaSelection); message = messages.onChange(onChangeProps); } return message; }, [ariaSelection, messages, isOptionDisabled3, selectValue, getOptionLabel4]); var ariaFocused = (0, import_react6.useMemo)(function() { var focusMsg = ""; var focused = focusedOption || focusedValue; var isSelected = !!(focusedOption && selectValue && selectValue.includes(focusedOption)); if (focused && messages.onFocus) { var onFocusProps = { focused, label: getOptionLabel4(focused), isDisabled: isOptionDisabled3(focused, selectValue), isSelected, options: focusableOptions, context: focused === focusedOption ? "menu" : "value", selectValue, isAppleDevice: isAppleDevice2 }; focusMsg = messages.onFocus(onFocusProps); } return focusMsg; }, [focusedOption, focusedValue, getOptionLabel4, isOptionDisabled3, messages, focusableOptions, selectValue, isAppleDevice2]); var ariaResults = (0, import_react6.useMemo)(function() { var resultsMsg = ""; if (menuIsOpen && options2.length && !isLoading && messages.onFilter) { var resultsMessage = screenReaderStatus2({ count: focusableOptions.length }); resultsMsg = messages.onFilter({ inputValue, resultsMessage }); } return resultsMsg; }, [focusableOptions, inputValue, menuIsOpen, messages, options2, screenReaderStatus2, isLoading]); var isInitialFocus = (ariaSelection === null || ariaSelection === void 0 ? void 0 : ariaSelection.action) === "initial-input-focus"; var ariaGuidance = (0, import_react6.useMemo)(function() { var guidanceMsg = ""; if (messages.guidance) { var context = focusedValue ? "value" : menuIsOpen ? "menu" : "input"; guidanceMsg = messages.guidance({ "aria-label": ariaLabel, context, isDisabled: focusedOption && isOptionDisabled3(focusedOption, selectValue), isMulti, isSearchable, tabSelectsValue, isInitialFocus }); } return guidanceMsg; }, [ariaLabel, focusedOption, focusedValue, isMulti, isOptionDisabled3, isSearchable, menuIsOpen, messages, selectValue, tabSelectsValue, isInitialFocus]); var ScreenReaderText = jsx2(import_react6.Fragment, null, jsx2("span", { id: "aria-selection" }, ariaSelected), jsx2("span", { id: "aria-focused" }, ariaFocused), jsx2("span", { id: "aria-results" }, ariaResults), jsx2("span", { id: "aria-guidance" }, ariaGuidance)); return jsx2(import_react6.Fragment, null, jsx2(A11yText$1, { id }, isInitialFocus && ScreenReaderText), jsx2(A11yText$1, { "aria-live": ariaLive, "aria-atomic": "false", "aria-relevant": "additions text", role: "log" }, isFocused && !isInitialFocus && ScreenReaderText)); }; var LiveRegion$1 = LiveRegion; var diacritics = [{ base: "A", letters: "AⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ" }, { base: "AA", letters: "Ꜳ" }, { base: "AE", letters: "ÆǼǢ" }, { base: "AO", letters: "Ꜵ" }, { base: "AU", letters: "Ꜷ" }, { base: "AV", letters: "ꜸꜺ" }, { base: "AY", letters: "Ꜽ" }, { base: "B", letters: "BⒷBḂḄḆɃƂƁ" }, { base: "C", letters: "CⒸCĆĈĊČÇḈƇȻꜾ" }, { base: "D", letters: "DⒹDḊĎḌḐḒḎĐƋƊƉꝹ" }, { base: "DZ", letters: "DZDŽ" }, { base: "Dz", letters: "DzDž" }, { base: "E", letters: "EⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ" }, { base: "F", letters: "FⒻFḞƑꝻ" }, { base: "G", letters: "GⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾ" }, { base: "H", letters: "HⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ" }, { base: "I", letters: "IⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ" }, { base: "J", letters: "JⒿJĴɈ" }, { base: "K", letters: "KⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ" }, { base: "L", letters: "LⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ" }, { base: "LJ", letters: "LJ" }, { base: "Lj", letters: "Lj" }, { base: "M", letters: "MⓂMḾṀṂⱮƜ" }, { base: "N", letters: "NⓃNǸŃÑṄŇṆŅṊṈȠƝꞐꞤ" }, { base: "NJ", letters: "NJ" }, { base: "Nj", letters: "Nj" }, { base: "O", letters: "OⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ" }, { base: "OI", letters: "Ƣ" }, { base: "OO", letters: "Ꝏ" }, { base: "OU", letters: "Ȣ" }, { base: "P", letters: "PⓅPṔṖƤⱣꝐꝒꝔ" }, { base: "Q", letters: "QⓆQꝖꝘɊ" }, { base: "R", letters: "RⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ" }, { base: "S", letters: "SⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ" }, { base: "T", letters: "TⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ" }, { base: "TZ", letters: "Ꜩ" }, { base: "U", letters: "UⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ" }, { base: "V", letters: "VⓋVṼṾƲꝞɅ" }, { base: "VY", letters: "Ꝡ" }, { base: "W", letters: "WⓌWẀẂŴẆẄẈⱲ" }, { base: "X", letters: "XⓍXẊẌ" }, { base: "Y", letters: "YⓎYỲÝŶỸȲẎŸỶỴƳɎỾ" }, { base: "Z", letters: "ZⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ" }, { base: "a", letters: "aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ" }, { base: "aa", letters: "ꜳ" }, { base: "ae", letters: "æǽǣ" }, { base: "ao", letters: "ꜵ" }, { base: "au", letters: "ꜷ" }, { base: "av", letters: "ꜹꜻ" }, { base: "ay", letters: "ꜽ" }, { base: "b", letters: "bⓑbḃḅḇƀƃɓ" }, { base: "c", letters: "cⓒcćĉċčçḉƈȼꜿↄ" }, { base: "d", letters: "dⓓdḋďḍḑḓḏđƌɖɗꝺ" }, { base: "dz", letters: "dzdž" }, { base: "e", letters: "eⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ" }, { base: "f", letters: "fⓕfḟƒꝼ" }, { base: "g", letters: "gⓖgǵĝḡğġǧģǥɠꞡᵹꝿ" }, { base: "h", letters: "hⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ" }, { base: "hv", letters: "ƕ" }, { base: "i", letters: "iⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı" }, { base: "j", letters: "jⓙjĵǰɉ" }, { base: "k", letters: "kⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ" }, { base: "l", letters: "lⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ" }, { base: "lj", letters: "lj" }, { base: "m", letters: "mⓜmḿṁṃɱɯ" }, { base: "n", letters: "nⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥ" }, { base: "nj", letters: "nj" }, { base: "o", letters: "oⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ" }, { base: "oi", letters: "ƣ" }, { base: "ou", letters: "ȣ" }, { base: "oo", letters: "ꝏ" }, { base: "p", letters: "pⓟpṕṗƥᵽꝑꝓꝕ" }, { base: "q", letters: "qⓠqɋꝗꝙ" }, { base: "r", letters: "rⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ" }, { base: "s", letters: "sⓢsßśṥŝṡšṧṣṩșşȿꞩꞅẛ" }, { base: "t", letters: "tⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ" }, { base: "tz", letters: "ꜩ" }, { base: "u", letters: "uⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ" }, { base: "v", letters: "vⓥvṽṿʋꝟʌ" }, { base: "vy", letters: "ꝡ" }, { base: "w", letters: "wⓦwẁẃŵẇẅẘẉⱳ" }, { base: "x", letters: "xⓧxẋẍ" }, { base: "y", letters: "yⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ" }, { base: "z", letters: "zⓩzźẑżžẓẕƶȥɀⱬꝣ" }]; var anyDiacritic = new RegExp("[" + diacritics.map(function(d2) { return d2.letters; }).join("") + "]", "g"); var diacriticToBase = {}; for (i3 = 0; i3 < diacritics.length; i3++) { diacritic = diacritics[i3]; for (j3 = 0; j3 < diacritic.letters.length; j3++) { diacriticToBase[diacritic.letters[j3]] = diacritic.base; } } var diacritic; var j3; var i3; var stripDiacritics = function stripDiacritics2(str) { return str.replace(anyDiacritic, function(match2) { return diacriticToBase[match2]; }); }; var memoizedStripDiacriticsForInput = memoizeOne(stripDiacritics); var trimString = function trimString2(str) { return str.replace(/^\s+|\s+$/g, ""); }; var defaultStringify = function defaultStringify2(option) { return "".concat(option.label, " ").concat(option.value); }; var createFilter = function createFilter2(config) { return function(option, rawInput) { if (option.data.__isNew__) return true; var _ignoreCase$ignoreAcc = _objectSpread2({ ignoreCase: true, ignoreAccents: true, stringify: defaultStringify, trim: true, matchFrom: "any" }, config), ignoreCase = _ignoreCase$ignoreAcc.ignoreCase, ignoreAccents = _ignoreCase$ignoreAcc.ignoreAccents, stringify4 = _ignoreCase$ignoreAcc.stringify, trim2 = _ignoreCase$ignoreAcc.trim, matchFrom = _ignoreCase$ignoreAcc.matchFrom; var input = trim2 ? trimString(rawInput) : rawInput; var candidate = trim2 ? trimString(stringify4(option)) : stringify4(option); if (ignoreCase) { input = input.toLowerCase(); candidate = candidate.toLowerCase(); } if (ignoreAccents) { input = memoizedStripDiacriticsForInput(input); candidate = stripDiacritics(candidate); } return matchFrom === "start" ? candidate.substr(0, input.length) === input : candidate.indexOf(input) > -1; }; }; var _excluded4 = ["innerRef"]; function DummyInput(_ref3) { var innerRef = _ref3.innerRef, props = _objectWithoutProperties(_ref3, _excluded4); var filteredProps = removeProps(props, "onExited", "in", "enter", "exit", "appear"); return jsx2("input", _extends({ ref: innerRef }, filteredProps, { css: css({ label: "dummyInput", // get rid of any default styles background: 0, border: 0, // important! this hides the flashing cursor caretColor: "transparent", fontSize: "inherit", gridArea: "1 / 1 / 2 / 3", outline: 0, padding: 0, // important! without `width` browsers won't allow focus width: 1, // remove cursor on desktop color: "transparent", // remove cursor on mobile whilst maintaining "scroll into view" behaviour left: -100, opacity: 0, position: "relative", transform: "scale(.01)" }, false ? "" : ";label:DummyInput;", false ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkR1bW15SW5wdXQudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQXlCTSIsImZpbGUiOiJEdW1teUlucHV0LnRzeCIsInNvdXJjZXNDb250ZW50IjpbIi8qKiBAanN4IGpzeCAqL1xuaW1wb3J0IHsgUmVmIH0gZnJvbSAncmVhY3QnO1xuaW1wb3J0IHsganN4IH0gZnJvbSAnQGVtb3Rpb24vcmVhY3QnO1xuaW1wb3J0IHsgcmVtb3ZlUHJvcHMgfSBmcm9tICcuLi91dGlscyc7XG5cbmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uIER1bW15SW5wdXQoe1xuICBpbm5lclJlZixcbiAgLi4ucHJvcHNcbn06IEpTWC5JbnRyaW5zaWNFbGVtZW50c1snaW5wdXQnXSAmIHtcbiAgcmVhZG9ubHkgaW5uZXJSZWY6IFJlZjxIVE1MSW5wdXRFbGVtZW50Pjtcbn0pIHtcbiAgLy8gUmVtb3ZlIGFuaW1hdGlvbiBwcm9wcyBub3QgbWVhbnQgZm9yIEhUTUwgZWxlbWVudHNcbiAgY29uc3QgZmlsdGVyZWRQcm9wcyA9IHJlbW92ZVByb3BzKFxuICAgIHByb3BzLFxuICAgICdvbkV4aXRlZCcsXG4gICAgJ2luJyxcbiAgICAnZW50ZXInLFxuICAgICdleGl0JyxcbiAgICAnYXBwZWFyJ1xuICApO1xuXG4gIHJldHVybiAoXG4gICAgPGlucHV0XG4gICAgICByZWY9e2lubmVyUmVmfVxuICAgICAgey4uLmZpbHRlcmVkUHJvcHN9XG4gICAgICBjc3M9e3tcbiAgICAgICAgbGFiZWw6ICdkdW1teUlucHV0JyxcbiAgICAgICAgLy8gZ2V0IHJpZCBvZiBhbnkgZGVmYXVsdCBzdHlsZXNcbiAgICAgICAgYmFja2dyb3VuZDogMCxcbiAgICAgICAgYm9yZGVyOiAwLFxuICAgICAgICAvLyBpbXBvcnRhbnQhIHRoaXMgaGlkZXMgdGhlIGZsYXNoaW5nIGN1cnNvclxuICAgICAgICBjYXJldENvbG9yOiAndHJhbnNwYXJlbnQnLFxuICAgICAgICBmb250U2l6ZTogJ2luaGVyaXQnLFxuICAgICAgICBncmlkQXJlYTogJzEgLyAxIC8gMiAvIDMnLFxuICAgICAgICBvdXRsaW5lOiAwLFxuICAgICAgICBwYWRkaW5nOiAwLFxuICAgICAgICAvLyBpbXBvcnRhbnQhIHdpdGhvdXQgYHdpZHRoYCBicm93c2VycyB3b24ndCBhbGxvdyBmb2N1c1xuICAgICAgICB3aWR0aDogMSxcblxuICAgICAgICAvLyByZW1vdmUgY3Vyc29yIG9uIGRlc2t0b3BcbiAgICAgICAgY29sb3I6ICd0cmFuc3BhcmVudCcsXG5cbiAgICAgICAgLy8gcmVtb3ZlIGN1cnNvciBvbiBtb2JpbGUgd2hpbHN0IG1haW50YWluaW5nIFwic2Nyb2xsIGludG8gdmlld1wiIGJlaGF2aW91clxuICAgICAgICBsZWZ0OiAtMTAwLFxuICAgICAgICBvcGFjaXR5OiAwLFxuICAgICAgICBwb3NpdGlvbjogJ3JlbGF0aXZlJyxcbiAgICAgICAgdHJhbnNmb3JtOiAnc2NhbGUoLjAxKScsXG4gICAgICB9fVxuICAgIC8+XG4gICk7XG59XG4iXX0= */") })); } var cancelScroll = function cancelScroll2(event) { if (event.cancelable) event.preventDefault(); event.stopPropagation(); }; function useScrollCapture(_ref3) { var isEnabled = _ref3.isEnabled, onBottomArrive = _ref3.onBottomArrive, onBottomLeave = _ref3.onBottomLeave, onTopArrive = _ref3.onTopArrive, onTopLeave = _ref3.onTopLeave; var isBottom = (0, import_react6.useRef)(false); var isTop = (0, import_react6.useRef)(false); var touchStart = (0, import_react6.useRef)(0); var scrollTarget = (0, import_react6.useRef)(null); var handleEventDelta = (0, import_react6.useCallback)(function(event, delta) { if (scrollTarget.current === null) return; var _scrollTarget$current = scrollTarget.current, scrollTop = _scrollTarget$current.scrollTop, scrollHeight = _scrollTarget$current.scrollHeight, clientHeight = _scrollTarget$current.clientHeight; var target = scrollTarget.current; var isDeltaPositive = delta > 0; var availableScroll = scrollHeight - clientHeight - scrollTop; var shouldCancelScroll = false; if (availableScroll > delta && isBottom.current) { if (onBottomLeave) onBottomLeave(event); isBottom.current = false; } if (isDeltaPositive && isTop.current) { if (onTopLeave) onTopLeave(event); isTop.current = false; } if (isDeltaPositive && delta > availableScroll) { if (onBottomArrive && !isBottom.current) { onBottomArrive(event); } target.scrollTop = scrollHeight; shouldCancelScroll = true; isBottom.current = true; } else if (!isDeltaPositive && -delta > scrollTop) { if (onTopArrive && !isTop.current) { onTopArrive(event); } target.scrollTop = 0; shouldCancelScroll = true; isTop.current = true; } if (shouldCancelScroll) { cancelScroll(event); } }, [onBottomArrive, onBottomLeave, onTopArrive, onTopLeave]); var onWheel = (0, import_react6.useCallback)(function(event) { handleEventDelta(event, event.deltaY); }, [handleEventDelta]); var onTouchStart = (0, import_react6.useCallback)(function(event) { touchStart.current = event.changedTouches[0].clientY; }, []); var onTouchMove = (0, import_react6.useCallback)(function(event) { var deltaY = touchStart.current - event.changedTouches[0].clientY; handleEventDelta(event, deltaY); }, [handleEventDelta]); var startListening = (0, import_react6.useCallback)(function(el) { if (!el) return; var notPassive = supportsPassiveEvents ? { passive: false } : false; el.addEventListener("wheel", onWheel, notPassive); el.addEventListener("touchstart", onTouchStart, notPassive); el.addEventListener("touchmove", onTouchMove, notPassive); }, [onTouchMove, onTouchStart, onWheel]); var stopListening = (0, import_react6.useCallback)(function(el) { if (!el) return; el.removeEventListener("wheel", onWheel, false); el.removeEventListener("touchstart", onTouchStart, false); el.removeEventListener("touchmove", onTouchMove, false); }, [onTouchMove, onTouchStart, onWheel]); (0, import_react6.useEffect)(function() { if (!isEnabled) return; var element = scrollTarget.current; startListening(element); return function() { stopListening(element); }; }, [isEnabled, startListening, stopListening]); return function(element) { scrollTarget.current = element; }; } var STYLE_KEYS = ["boxSizing", "height", "overflow", "paddingRight", "position"]; var LOCK_STYLES = { boxSizing: "border-box", // account for possible declaration `width: 100%;` on body overflow: "hidden", position: "relative", height: "100%" }; function preventTouchMove(e) { e.preventDefault(); } function allowTouchMove(e) { e.stopPropagation(); } function preventInertiaScroll() { var top = this.scrollTop; var totalScroll = this.scrollHeight; var currentScroll = top + this.offsetHeight; if (top === 0) { this.scrollTop = 1; } else if (currentScroll === totalScroll) { this.scrollTop = top - 1; } } function isTouchDevice() { return "ontouchstart" in window || navigator.maxTouchPoints; } var canUseDOM = !!(typeof window !== "undefined" && window.document && window.document.createElement); var activeScrollLocks = 0; var listenerOptions = { capture: false, passive: false }; function useScrollLock(_ref3) { var isEnabled = _ref3.isEnabled, _ref$accountForScroll = _ref3.accountForScrollbars, accountForScrollbars = _ref$accountForScroll === void 0 ? true : _ref$accountForScroll; var originalStyles = (0, import_react6.useRef)({}); var scrollTarget = (0, import_react6.useRef)(null); var addScrollLock = (0, import_react6.useCallback)(function(touchScrollTarget) { if (!canUseDOM) return; var target = document.body; var targetStyle = target && target.style; if (accountForScrollbars) { STYLE_KEYS.forEach(function(key) { var val = targetStyle && targetStyle[key]; originalStyles.current[key] = val; }); } if (accountForScrollbars && activeScrollLocks < 1) { var currentPadding = parseInt(originalStyles.current.paddingRight, 10) || 0; var clientWidth = document.body ? document.body.clientWidth : 0; var adjustedPadding = window.innerWidth - clientWidth + currentPadding || 0; Object.keys(LOCK_STYLES).forEach(function(key) { var val = LOCK_STYLES[key]; if (targetStyle) { targetStyle[key] = val; } }); if (targetStyle) { targetStyle.paddingRight = "".concat(adjustedPadding, "px"); } } if (target && isTouchDevice()) { target.addEventListener("touchmove", preventTouchMove, listenerOptions); if (touchScrollTarget) { touchScrollTarget.addEventListener("touchstart", preventInertiaScroll, listenerOptions); touchScrollTarget.addEventListener("touchmove", allowTouchMove, listenerOptions); } } activeScrollLocks += 1; }, [accountForScrollbars]); var removeScrollLock = (0, import_react6.useCallback)(function(touchScrollTarget) { if (!canUseDOM) return; var target = document.body; var targetStyle = target && target.style; activeScrollLocks = Math.max(activeScrollLocks - 1, 0); if (accountForScrollbars && activeScrollLocks < 1) { STYLE_KEYS.forEach(function(key) { var val = originalStyles.current[key]; if (targetStyle) { targetStyle[key] = val; } }); } if (target && isTouchDevice()) { target.removeEventListener("touchmove", preventTouchMove, listenerOptions); if (touchScrollTarget) { touchScrollTarget.removeEventListener("touchstart", preventInertiaScroll, listenerOptions); touchScrollTarget.removeEventListener("touchmove", allowTouchMove, listenerOptions); } } }, [accountForScrollbars]); (0, import_react6.useEffect)(function() { if (!isEnabled) return; var element = scrollTarget.current; addScrollLock(element); return function() { removeScrollLock(element); }; }, [isEnabled, addScrollLock, removeScrollLock]); return function(element) { scrollTarget.current = element; }; } function _EMOTION_STRINGIFIED_CSS_ERROR__$1() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } var blurSelectInput = function blurSelectInput2(event) { var element = event.target; return element.ownerDocument.activeElement && element.ownerDocument.activeElement.blur(); }; var _ref2$1 = false ? { name: "1kfdb0e", styles: "position:fixed;left:0;bottom:0;right:0;top:0" } : { name: "bp8cua-ScrollManager", styles: "position:fixed;left:0;bottom:0;right:0;top:0;label:ScrollManager;", map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlNjcm9sbE1hbmFnZXIudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQW9EVSIsImZpbGUiOiJTY3JvbGxNYW5hZ2VyLnRzeCIsInNvdXJjZXNDb250ZW50IjpbIi8qKiBAanN4IGpzeCAqL1xuaW1wb3J0IHsganN4IH0gZnJvbSAnQGVtb3Rpb24vcmVhY3QnO1xuaW1wb3J0IHsgRnJhZ21lbnQsIFJlYWN0RWxlbWVudCwgUmVmQ2FsbGJhY2ssIE1vdXNlRXZlbnQgfSBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlU2Nyb2xsQ2FwdHVyZSBmcm9tICcuL3VzZVNjcm9sbENhcHR1cmUnO1xuaW1wb3J0IHVzZVNjcm9sbExvY2sgZnJvbSAnLi91c2VTY3JvbGxMb2NrJztcblxuaW50ZXJmYWNlIFByb3BzIHtcbiAgcmVhZG9ubHkgY2hpbGRyZW46IChyZWY6IFJlZkNhbGxiYWNrPEhUTUxFbGVtZW50PikgPT4gUmVhY3RFbGVtZW50O1xuICByZWFkb25seSBsb2NrRW5hYmxlZDogYm9vbGVhbjtcbiAgcmVhZG9ubHkgY2FwdHVyZUVuYWJsZWQ6IGJvb2xlYW47XG4gIHJlYWRvbmx5IG9uQm90dG9tQXJyaXZlPzogKGV2ZW50OiBXaGVlbEV2ZW50IHwgVG91Y2hFdmVudCkgPT4gdm9pZDtcbiAgcmVhZG9ubHkgb25Cb3R0b21MZWF2ZT86IChldmVudDogV2hlZWxFdmVudCB8IFRvdWNoRXZlbnQpID0+IHZvaWQ7XG4gIHJlYWRvbmx5IG9uVG9wQXJyaXZlPzogKGV2ZW50OiBXaGVlbEV2ZW50IHwgVG91Y2hFdmVudCkgPT4gdm9pZDtcbiAgcmVhZG9ubHkgb25Ub3BMZWF2ZT86IChldmVudDogV2hlZWxFdmVudCB8IFRvdWNoRXZlbnQpID0+IHZvaWQ7XG59XG5cbmNvbnN0IGJsdXJTZWxlY3RJbnB1dCA9IChldmVudDogTW91c2VFdmVudDxIVE1MRGl2RWxlbWVudD4pID0+IHtcbiAgY29uc3QgZWxlbWVudCA9IGV2ZW50LnRhcmdldCBhcyBIVE1MRGl2RWxlbWVudDtcbiAgcmV0dXJuIChcbiAgICBlbGVtZW50Lm93bmVyRG9jdW1lbnQuYWN0aXZlRWxlbWVudCAmJlxuICAgIChlbGVtZW50Lm93bmVyRG9jdW1lbnQuYWN0aXZlRWxlbWVudCBhcyBIVE1MRWxlbWVudCkuYmx1cigpXG4gICk7XG59O1xuXG5leHBvcnQgZGVmYXVsdCBmdW5jdGlvbiBTY3JvbGxNYW5hZ2VyKHtcbiAgY2hpbGRyZW4sXG4gIGxvY2tFbmFibGVkLFxuICBjYXB0dXJlRW5hYmxlZCA9IHRydWUsXG4gIG9uQm90dG9tQXJyaXZlLFxuICBvbkJvdHRvbUxlYXZlLFxuICBvblRvcEFycml2ZSxcbiAgb25Ub3BMZWF2ZSxcbn06IFByb3BzKSB7XG4gIGNvbnN0IHNldFNjcm9sbENhcHR1cmVUYXJnZXQgPSB1c2VTY3JvbGxDYXB0dXJlKHtcbiAgICBpc0VuYWJsZWQ6IGNhcHR1cmVFbmFibGVkLFxuICAgIG9uQm90dG9tQXJyaXZlLFxuICAgIG9uQm90dG9tTGVhdmUsXG4gICAgb25Ub3BBcnJpdmUsXG4gICAgb25Ub3BMZWF2ZSxcbiAgfSk7XG4gIGNvbnN0IHNldFNjcm9sbExvY2tUYXJnZXQgPSB1c2VTY3JvbGxMb2NrKHsgaXNFbmFibGVkOiBsb2NrRW5hYmxlZCB9KTtcblxuICBjb25zdCB0YXJnZXRSZWY6IFJlZkNhbGxiYWNrPEhUTUxFbGVtZW50PiA9IChlbGVtZW50KSA9PiB7XG4gICAgc2V0U2Nyb2xsQ2FwdHVyZVRhcmdldChlbGVtZW50KTtcbiAgICBzZXRTY3JvbGxMb2NrVGFyZ2V0KGVsZW1lbnQpO1xuICB9O1xuXG4gIHJldHVybiAoXG4gICAgPEZyYWdtZW50PlxuICAgICAge2xvY2tFbmFibGVkICYmIChcbiAgICAgICAgPGRpdlxuICAgICAgICAgIG9uQ2xpY2s9e2JsdXJTZWxlY3RJbnB1dH1cbiAgICAgICAgICBjc3M9e3sgcG9zaXRpb246ICdmaXhlZCcsIGxlZnQ6IDAsIGJvdHRvbTogMCwgcmlnaHQ6IDAsIHRvcDogMCB9fVxuICAgICAgICAvPlxuICAgICAgKX1cbiAgICAgIHtjaGlsZHJlbih0YXJnZXRSZWYpfVxuICAgIDwvRnJhZ21lbnQ+XG4gICk7XG59XG4iXX0= */", toString: _EMOTION_STRINGIFIED_CSS_ERROR__$1 }; function ScrollManager(_ref3) { var children = _ref3.children, lockEnabled = _ref3.lockEnabled, _ref$captureEnabled = _ref3.captureEnabled, captureEnabled = _ref$captureEnabled === void 0 ? true : _ref$captureEnabled, onBottomArrive = _ref3.onBottomArrive, onBottomLeave = _ref3.onBottomLeave, onTopArrive = _ref3.onTopArrive, onTopLeave = _ref3.onTopLeave; var setScrollCaptureTarget = useScrollCapture({ isEnabled: captureEnabled, onBottomArrive, onBottomLeave, onTopArrive, onTopLeave }); var setScrollLockTarget = useScrollLock({ isEnabled: lockEnabled }); var targetRef = function targetRef2(element) { setScrollCaptureTarget(element); setScrollLockTarget(element); }; return jsx2(import_react6.Fragment, null, lockEnabled && jsx2("div", { onClick: blurSelectInput, css: _ref2$1 }), children(targetRef)); } function _EMOTION_STRINGIFIED_CSS_ERROR__2() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } var _ref22 = false ? { name: "1a0ro4n-requiredInput", styles: "label:requiredInput;opacity:0;pointer-events:none;position:absolute;bottom:0;left:0;right:0;width:100%" } : { name: "5kkxb2-requiredInput-RequiredInput", styles: "label:requiredInput;opacity:0;pointer-events:none;position:absolute;bottom:0;left:0;right:0;width:100%;label:RequiredInput;", map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlJlcXVpcmVkSW5wdXQudHN4Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQWNJIiwiZmlsZSI6IlJlcXVpcmVkSW5wdXQudHN4Iiwic291cmNlc0NvbnRlbnQiOlsiLyoqIEBqc3gganN4ICovXG5pbXBvcnQgeyBGb2N1c0V2ZW50SGFuZGxlciwgRnVuY3Rpb25Db21wb25lbnQgfSBmcm9tICdyZWFjdCc7XG5pbXBvcnQgeyBqc3ggfSBmcm9tICdAZW1vdGlvbi9yZWFjdCc7XG5cbmNvbnN0IFJlcXVpcmVkSW5wdXQ6IEZ1bmN0aW9uQ29tcG9uZW50PHtcbiAgcmVhZG9ubHkgbmFtZT86IHN0cmluZztcbiAgcmVhZG9ubHkgb25Gb2N1czogRm9jdXNFdmVudEhhbmRsZXI8SFRNTElucHV0RWxlbWVudD47XG59PiA9ICh7IG5hbWUsIG9uRm9jdXMgfSkgPT4gKFxuICA8aW5wdXRcbiAgICByZXF1aXJlZFxuICAgIG5hbWU9e25hbWV9XG4gICAgdGFiSW5kZXg9ey0xfVxuICAgIGFyaWEtaGlkZGVuPVwidHJ1ZVwiXG4gICAgb25Gb2N1cz17b25Gb2N1c31cbiAgICBjc3M9e3tcbiAgICAgIGxhYmVsOiAncmVxdWlyZWRJbnB1dCcsXG4gICAgICBvcGFjaXR5OiAwLFxuICAgICAgcG9pbnRlckV2ZW50czogJ25vbmUnLFxuICAgICAgcG9zaXRpb246ICdhYnNvbHV0ZScsXG4gICAgICBib3R0b206IDAsXG4gICAgICBsZWZ0OiAwLFxuICAgICAgcmlnaHQ6IDAsXG4gICAgICB3aWR0aDogJzEwMCUnLFxuICAgIH19XG4gICAgLy8gUHJldmVudCBgU3dpdGNoaW5nIGZyb20gdW5jb250cm9sbGVkIHRvIGNvbnRyb2xsZWRgIGVycm9yXG4gICAgdmFsdWU9XCJcIlxuICAgIG9uQ2hhbmdlPXsoKSA9PiB7fX1cbiAgLz5cbik7XG5cbmV4cG9ydCBkZWZhdWx0IFJlcXVpcmVkSW5wdXQ7XG4iXX0= */", toString: _EMOTION_STRINGIFIED_CSS_ERROR__2 }; var RequiredInput = function RequiredInput2(_ref3) { var name = _ref3.name, onFocus2 = _ref3.onFocus; return jsx2("input", { required: true, name, tabIndex: -1, "aria-hidden": "true", onFocus: onFocus2, css: _ref22, value: "", onChange: function onChange2() { } }); }; var RequiredInput$1 = RequiredInput; function testPlatform(re6) { var _window$navigator$use; return typeof window !== "undefined" && window.navigator != null ? re6.test(((_window$navigator$use = window.navigator["userAgentData"]) === null || _window$navigator$use === void 0 ? void 0 : _window$navigator$use.platform) || window.navigator.platform) : false; } function isIPhone() { return testPlatform(/^iPhone/i); } function isMac() { return testPlatform(/^Mac/i); } function isIPad() { return testPlatform(/^iPad/i) || // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support. isMac() && navigator.maxTouchPoints > 1; } function isIOS() { return isIPhone() || isIPad(); } function isAppleDevice() { return isMac() || isIOS(); } var formatGroupLabel = function formatGroupLabel2(group) { return group.label; }; var getOptionLabel$1 = function getOptionLabel(option) { return option.label; }; var getOptionValue$1 = function getOptionValue(option) { return option.value; }; var isOptionDisabled = function isOptionDisabled2(option) { return !!option.isDisabled; }; var defaultStyles = { clearIndicator: clearIndicatorCSS, container: containerCSS, control: css$1, dropdownIndicator: dropdownIndicatorCSS, group: groupCSS, groupHeading: groupHeadingCSS, indicatorsContainer: indicatorsContainerCSS, indicatorSeparator: indicatorSeparatorCSS, input: inputCSS, loadingIndicator: loadingIndicatorCSS, loadingMessage: loadingMessageCSS, menu: menuCSS, menuList: menuListCSS, menuPortal: menuPortalCSS, multiValue: multiValueCSS, multiValueLabel: multiValueLabelCSS, multiValueRemove: multiValueRemoveCSS, noOptionsMessage: noOptionsMessageCSS, option: optionCSS, placeholder: placeholderCSS, singleValue: css3, valueContainer: valueContainerCSS }; var colors = { primary: "#2684FF", primary75: "#4C9AFF", primary50: "#B2D4FF", primary25: "#DEEBFF", danger: "#DE350B", dangerLight: "#FFBDAD", neutral0: "hsl(0, 0%, 100%)", neutral5: "hsl(0, 0%, 95%)", neutral10: "hsl(0, 0%, 90%)", neutral20: "hsl(0, 0%, 80%)", neutral30: "hsl(0, 0%, 70%)", neutral40: "hsl(0, 0%, 60%)", neutral50: "hsl(0, 0%, 50%)", neutral60: "hsl(0, 0%, 40%)", neutral70: "hsl(0, 0%, 30%)", neutral80: "hsl(0, 0%, 20%)", neutral90: "hsl(0, 0%, 10%)" }; var borderRadius = 4; var baseUnit = 4; var controlHeight = 38; var menuGutter = baseUnit * 2; var spacing = { baseUnit, controlHeight, menuGutter }; var defaultTheme = { borderRadius, colors, spacing }; var defaultProps = { "aria-live": "polite", backspaceRemovesValue: true, blurInputOnSelect: isTouchCapable(), captureMenuScroll: !isTouchCapable(), classNames: {}, closeMenuOnSelect: true, closeMenuOnScroll: false, components: {}, controlShouldRenderValue: true, escapeClearsValue: false, filterOption: createFilter(), formatGroupLabel, getOptionLabel: getOptionLabel$1, getOptionValue: getOptionValue$1, isDisabled: false, isLoading: false, isMulti: false, isRtl: false, isSearchable: true, isOptionDisabled, loadingMessage: function loadingMessage() { return "Loading..."; }, maxMenuHeight: 300, minMenuHeight: 140, menuIsOpen: false, menuPlacement: "bottom", menuPosition: "absolute", menuShouldBlockScroll: false, menuShouldScrollIntoView: !isMobileDevice(), noOptionsMessage: function noOptionsMessage() { return "No options"; }, openMenuOnFocus: false, openMenuOnClick: true, options: [], pageSize: 5, placeholder: "Select...", screenReaderStatus: function screenReaderStatus(_ref3) { var count = _ref3.count; return "".concat(count, " result").concat(count !== 1 ? "s" : "", " available"); }, styles: {}, tabIndex: 0, tabSelectsValue: true, unstyled: false }; function toCategorizedOption(props, option, selectValue, index2) { var isDisabled = _isOptionDisabled(props, option, selectValue); var isSelected = _isOptionSelected(props, option, selectValue); var label = getOptionLabel2(props, option); var value = getOptionValue2(props, option); return { type: "option", data: option, isDisabled, isSelected, label, value, index: index2 }; } function buildCategorizedOptions(props, selectValue) { return props.options.map(function(groupOrOption, groupOrOptionIndex) { if ("options" in groupOrOption) { var categorizedOptions = groupOrOption.options.map(function(option, optionIndex) { return toCategorizedOption(props, option, selectValue, optionIndex); }).filter(function(categorizedOption2) { return isFocusable(props, categorizedOption2); }); return categorizedOptions.length > 0 ? { type: "group", data: groupOrOption, options: categorizedOptions, index: groupOrOptionIndex } : void 0; } var categorizedOption = toCategorizedOption(props, groupOrOption, selectValue, groupOrOptionIndex); return isFocusable(props, categorizedOption) ? categorizedOption : void 0; }).filter(notNullish); } function buildFocusableOptionsFromCategorizedOptions(categorizedOptions) { return categorizedOptions.reduce(function(optionsAccumulator, categorizedOption) { if (categorizedOption.type === "group") { optionsAccumulator.push.apply(optionsAccumulator, _toConsumableArray(categorizedOption.options.map(function(option) { return option.data; }))); } else { optionsAccumulator.push(categorizedOption.data); } return optionsAccumulator; }, []); } function buildFocusableOptionsWithIds(categorizedOptions, optionId) { return categorizedOptions.reduce(function(optionsAccumulator, categorizedOption) { if (categorizedOption.type === "group") { optionsAccumulator.push.apply(optionsAccumulator, _toConsumableArray(categorizedOption.options.map(function(option) { return { data: option.data, id: "".concat(optionId, "-").concat(categorizedOption.index, "-").concat(option.index) }; }))); } else { optionsAccumulator.push({ data: categorizedOption.data, id: "".concat(optionId, "-").concat(categorizedOption.index) }); } return optionsAccumulator; }, []); } function buildFocusableOptions(props, selectValue) { return buildFocusableOptionsFromCategorizedOptions(buildCategorizedOptions(props, selectValue)); } function isFocusable(props, categorizedOption) { var _props$inputValue = props.inputValue, inputValue = _props$inputValue === void 0 ? "" : _props$inputValue; var data = categorizedOption.data, isSelected = categorizedOption.isSelected, label = categorizedOption.label, value = categorizedOption.value; return (!shouldHideSelectedOptions(props) || !isSelected) && _filterOption(props, { label, value, data }, inputValue); } function getNextFocusedValue(state, nextSelectValue) { var focusedValue = state.focusedValue, lastSelectValue = state.selectValue; var lastFocusedIndex = lastSelectValue.indexOf(focusedValue); if (lastFocusedIndex > -1) { var nextFocusedIndex = nextSelectValue.indexOf(focusedValue); if (nextFocusedIndex > -1) { return focusedValue; } else if (lastFocusedIndex < nextSelectValue.length) { return nextSelectValue[lastFocusedIndex]; } } return null; } function getNextFocusedOption(state, options2) { var lastFocusedOption = state.focusedOption; return lastFocusedOption && options2.indexOf(lastFocusedOption) > -1 ? lastFocusedOption : options2[0]; } var getFocusedOptionId = function getFocusedOptionId2(focusableOptionsWithIds, focusedOption) { var _focusableOptionsWith; var focusedOptionId = (_focusableOptionsWith = focusableOptionsWithIds.find(function(option) { return option.data === focusedOption; })) === null || _focusableOptionsWith === void 0 ? void 0 : _focusableOptionsWith.id; return focusedOptionId || null; }; var getOptionLabel2 = function getOptionLabel3(props, data) { return props.getOptionLabel(data); }; var getOptionValue2 = function getOptionValue3(props, data) { return props.getOptionValue(data); }; function _isOptionDisabled(props, option, selectValue) { return typeof props.isOptionDisabled === "function" ? props.isOptionDisabled(option, selectValue) : false; } function _isOptionSelected(props, option, selectValue) { if (selectValue.indexOf(option) > -1) return true; if (typeof props.isOptionSelected === "function") { return props.isOptionSelected(option, selectValue); } var candidate = getOptionValue2(props, option); return selectValue.some(function(i3) { return getOptionValue2(props, i3) === candidate; }); } function _filterOption(props, option, inputValue) { return props.filterOption ? props.filterOption(option, inputValue) : true; } var shouldHideSelectedOptions = function shouldHideSelectedOptions2(props) { var hideSelectedOptions = props.hideSelectedOptions, isMulti = props.isMulti; if (hideSelectedOptions === void 0) return isMulti; return hideSelectedOptions; }; var instanceId = 1; var Select = function(_Component) { _inherits(Select3, _Component); var _super = _createSuper(Select3); function Select3(_props) { var _this; _classCallCheck(this, Select3); _this = _super.call(this, _props); _this.state = { ariaSelection: null, focusedOption: null, focusedOptionId: null, focusableOptionsWithIds: [], focusedValue: null, inputIsHidden: false, isFocused: false, selectValue: [], clearFocusValueOnUpdate: false, prevWasFocused: false, inputIsHiddenAfterUpdate: void 0, prevProps: void 0, instancePrefix: "" }; _this.blockOptionHover = false; _this.isComposing = false; _this.commonProps = void 0; _this.initialTouchX = 0; _this.initialTouchY = 0; _this.openAfterFocus = false; _this.scrollToFocusedOptionOnUpdate = false; _this.userIsDragging = void 0; _this.isAppleDevice = isAppleDevice(); _this.controlRef = null; _this.getControlRef = function(ref) { _this.controlRef = ref; }; _this.focusedOptionRef = null; _this.getFocusedOptionRef = function(ref) { _this.focusedOptionRef = ref; }; _this.menuListRef = null; _this.getMenuListRef = function(ref) { _this.menuListRef = ref; }; _this.inputRef = null; _this.getInputRef = function(ref) { _this.inputRef = ref; }; _this.focus = _this.focusInput; _this.blur = _this.blurInput; _this.onChange = function(newValue, actionMeta) { var _this$props = _this.props, onChange2 = _this$props.onChange, name = _this$props.name; actionMeta.name = name; _this.ariaOnChange(newValue, actionMeta); onChange2(newValue, actionMeta); }; _this.setValue = function(newValue, action, option) { var _this$props2 = _this.props, closeMenuOnSelect = _this$props2.closeMenuOnSelect, isMulti = _this$props2.isMulti, inputValue = _this$props2.inputValue; _this.onInputChange("", { action: "set-value", prevInputValue: inputValue }); if (closeMenuOnSelect) { _this.setState({ inputIsHiddenAfterUpdate: !isMulti }); _this.onMenuClose(); } _this.setState({ clearFocusValueOnUpdate: true }); _this.onChange(newValue, { action, option }); }; _this.selectOption = function(newValue) { var _this$props3 = _this.props, blurInputOnSelect = _this$props3.blurInputOnSelect, isMulti = _this$props3.isMulti, name = _this$props3.name; var selectValue = _this.state.selectValue; var deselected = isMulti && _this.isOptionSelected(newValue, selectValue); var isDisabled = _this.isOptionDisabled(newValue, selectValue); if (deselected) { var candidate = _this.getOptionValue(newValue); _this.setValue(multiValueAsValue(selectValue.filter(function(i3) { return _this.getOptionValue(i3) !== candidate; })), "deselect-option", newValue); } else if (!isDisabled) { if (isMulti) { _this.setValue(multiValueAsValue([].concat(_toConsumableArray(selectValue), [newValue])), "select-option", newValue); } else { _this.setValue(singleValueAsValue(newValue), "select-option"); } } else { _this.ariaOnChange(singleValueAsValue(newValue), { action: "select-option", option: newValue, name }); return; } if (blurInputOnSelect) { _this.blurInput(); } }; _this.removeValue = function(removedValue) { var isMulti = _this.props.isMulti; var selectValue = _this.state.selectValue; var candidate = _this.getOptionValue(removedValue); var newValueArray = selectValue.filter(function(i3) { return _this.getOptionValue(i3) !== candidate; }); var newValue = valueTernary(isMulti, newValueArray, newValueArray[0] || null); _this.onChange(newValue, { action: "remove-value", removedValue }); _this.focusInput(); }; _this.clearValue = function() { var selectValue = _this.state.selectValue; _this.onChange(valueTernary(_this.props.isMulti, [], null), { action: "clear", removedValues: selectValue }); }; _this.popValue = function() { var isMulti = _this.props.isMulti; var selectValue = _this.state.selectValue; var lastSelectedValue = selectValue[selectValue.length - 1]; var newValueArray = selectValue.slice(0, selectValue.length - 1); var newValue = valueTernary(isMulti, newValueArray, newValueArray[0] || null); _this.onChange(newValue, { action: "pop-value", removedValue: lastSelectedValue }); }; _this.getFocusedOptionId = function(focusedOption) { return getFocusedOptionId(_this.state.focusableOptionsWithIds, focusedOption); }; _this.getFocusableOptionsWithIds = function() { return buildFocusableOptionsWithIds(buildCategorizedOptions(_this.props, _this.state.selectValue), _this.getElementId("option")); }; _this.getValue = function() { return _this.state.selectValue; }; _this.cx = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return classNames.apply(void 0, [_this.props.classNamePrefix].concat(args)); }; _this.getOptionLabel = function(data) { return getOptionLabel2(_this.props, data); }; _this.getOptionValue = function(data) { return getOptionValue2(_this.props, data); }; _this.getStyles = function(key, props) { var unstyled = _this.props.unstyled; var base = defaultStyles[key](props, unstyled); base.boxSizing = "border-box"; var custom = _this.props.styles[key]; return custom ? custom(base, props) : base; }; _this.getClassNames = function(key, props) { var _this$props$className, _this$props$className2; return (_this$props$className = (_this$props$className2 = _this.props.classNames)[key]) === null || _this$props$className === void 0 ? void 0 : _this$props$className.call(_this$props$className2, props); }; _this.getElementId = function(element) { return "".concat(_this.state.instancePrefix, "-").concat(element); }; _this.getComponents = function() { return defaultComponents(_this.props); }; _this.buildCategorizedOptions = function() { return buildCategorizedOptions(_this.props, _this.state.selectValue); }; _this.getCategorizedOptions = function() { return _this.props.menuIsOpen ? _this.buildCategorizedOptions() : []; }; _this.buildFocusableOptions = function() { return buildFocusableOptionsFromCategorizedOptions(_this.buildCategorizedOptions()); }; _this.getFocusableOptions = function() { return _this.props.menuIsOpen ? _this.buildFocusableOptions() : []; }; _this.ariaOnChange = function(value, actionMeta) { _this.setState({ ariaSelection: _objectSpread2({ value }, actionMeta) }); }; _this.onMenuMouseDown = function(event) { if (event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); _this.focusInput(); }; _this.onMenuMouseMove = function(event) { _this.blockOptionHover = false; }; _this.onControlMouseDown = function(event) { if (event.defaultPrevented) { return; } var openMenuOnClick = _this.props.openMenuOnClick; if (!_this.state.isFocused) { if (openMenuOnClick) { _this.openAfterFocus = true; } _this.focusInput(); } else if (!_this.props.menuIsOpen) { if (openMenuOnClick) { _this.openMenu("first"); } } else { if (event.target.tagName !== "INPUT" && event.target.tagName !== "TEXTAREA") { _this.onMenuClose(); } } if (event.target.tagName !== "INPUT" && event.target.tagName !== "TEXTAREA") { event.preventDefault(); } }; _this.onDropdownIndicatorMouseDown = function(event) { if (event && event.type === "mousedown" && event.button !== 0) { return; } if (_this.props.isDisabled) return; var _this$props4 = _this.props, isMulti = _this$props4.isMulti, menuIsOpen = _this$props4.menuIsOpen; _this.focusInput(); if (menuIsOpen) { _this.setState({ inputIsHiddenAfterUpdate: !isMulti }); _this.onMenuClose(); } else { _this.openMenu("first"); } event.preventDefault(); }; _this.onClearIndicatorMouseDown = function(event) { if (event && event.type === "mousedown" && event.button !== 0) { return; } _this.clearValue(); event.preventDefault(); _this.openAfterFocus = false; if (event.type === "touchend") { _this.focusInput(); } else { setTimeout(function() { return _this.focusInput(); }); } }; _this.onScroll = function(event) { if (typeof _this.props.closeMenuOnScroll === "boolean") { if (event.target instanceof HTMLElement && isDocumentElement(event.target)) { _this.props.onMenuClose(); } } else if (typeof _this.props.closeMenuOnScroll === "function") { if (_this.props.closeMenuOnScroll(event)) { _this.props.onMenuClose(); } } }; _this.onCompositionStart = function() { _this.isComposing = true; }; _this.onCompositionEnd = function() { _this.isComposing = false; }; _this.onTouchStart = function(_ref23) { var touches = _ref23.touches; var touch = touches && touches.item(0); if (!touch) { return; } _this.initialTouchX = touch.clientX; _this.initialTouchY = touch.clientY; _this.userIsDragging = false; }; _this.onTouchMove = function(_ref3) { var touches = _ref3.touches; var touch = touches && touches.item(0); if (!touch) { return; } var deltaX = Math.abs(touch.clientX - _this.initialTouchX); var deltaY = Math.abs(touch.clientY - _this.initialTouchY); var moveThreshold = 5; _this.userIsDragging = deltaX > moveThreshold || deltaY > moveThreshold; }; _this.onTouchEnd = function(event) { if (_this.userIsDragging) return; if (_this.controlRef && !_this.controlRef.contains(event.target) && _this.menuListRef && !_this.menuListRef.contains(event.target)) { _this.blurInput(); } _this.initialTouchX = 0; _this.initialTouchY = 0; }; _this.onControlTouchEnd = function(event) { if (_this.userIsDragging) return; _this.onControlMouseDown(event); }; _this.onClearIndicatorTouchEnd = function(event) { if (_this.userIsDragging) return; _this.onClearIndicatorMouseDown(event); }; _this.onDropdownIndicatorTouchEnd = function(event) { if (_this.userIsDragging) return; _this.onDropdownIndicatorMouseDown(event); }; _this.handleInputChange = function(event) { var prevInputValue = _this.props.inputValue; var inputValue = event.currentTarget.value; _this.setState({ inputIsHiddenAfterUpdate: false }); _this.onInputChange(inputValue, { action: "input-change", prevInputValue }); if (!_this.props.menuIsOpen) { _this.onMenuOpen(); } }; _this.onInputFocus = function(event) { if (_this.props.onFocus) { _this.props.onFocus(event); } _this.setState({ inputIsHiddenAfterUpdate: false, isFocused: true }); if (_this.openAfterFocus || _this.props.openMenuOnFocus) { _this.openMenu("first"); } _this.openAfterFocus = false; }; _this.onInputBlur = function(event) { var prevInputValue = _this.props.inputValue; if (_this.menuListRef && _this.menuListRef.contains(document.activeElement)) { _this.inputRef.focus(); return; } if (_this.props.onBlur) { _this.props.onBlur(event); } _this.onInputChange("", { action: "input-blur", prevInputValue }); _this.onMenuClose(); _this.setState({ focusedValue: null, isFocused: false }); }; _this.onOptionHover = function(focusedOption) { if (_this.blockOptionHover || _this.state.focusedOption === focusedOption) { return; } var options2 = _this.getFocusableOptions(); var focusedOptionIndex = options2.indexOf(focusedOption); _this.setState({ focusedOption, focusedOptionId: focusedOptionIndex > -1 ? _this.getFocusedOptionId(focusedOption) : null }); }; _this.shouldHideSelectedOptions = function() { return shouldHideSelectedOptions(_this.props); }; _this.onValueInputFocus = function(e) { e.preventDefault(); e.stopPropagation(); _this.focus(); }; _this.onKeyDown = function(event) { var _this$props5 = _this.props, isMulti = _this$props5.isMulti, backspaceRemovesValue = _this$props5.backspaceRemovesValue, escapeClearsValue = _this$props5.escapeClearsValue, inputValue = _this$props5.inputValue, isClearable = _this$props5.isClearable, isDisabled = _this$props5.isDisabled, menuIsOpen = _this$props5.menuIsOpen, onKeyDown = _this$props5.onKeyDown, tabSelectsValue = _this$props5.tabSelectsValue, openMenuOnFocus = _this$props5.openMenuOnFocus; var _this$state = _this.state, focusedOption = _this$state.focusedOption, focusedValue = _this$state.focusedValue, selectValue = _this$state.selectValue; if (isDisabled) return; if (typeof onKeyDown === "function") { onKeyDown(event); if (event.defaultPrevented) { return; } } _this.blockOptionHover = true; switch (event.key) { case "ArrowLeft": if (!isMulti || inputValue) return; _this.focusValue("previous"); break; case "ArrowRight": if (!isMulti || inputValue) return; _this.focusValue("next"); break; case "Delete": case "Backspace": if (inputValue) return; if (focusedValue) { _this.removeValue(focusedValue); } else { if (!backspaceRemovesValue) return; if (isMulti) { _this.popValue(); } else if (isClearable) { _this.clearValue(); } } break; case "Tab": if (_this.isComposing) return; if (event.shiftKey || !menuIsOpen || !tabSelectsValue || !focusedOption || // don't capture the event if the menu opens on focus and the focused // option is already selected; it breaks the flow of navigation openMenuOnFocus && _this.isOptionSelected(focusedOption, selectValue)) { return; } _this.selectOption(focusedOption); break; case "Enter": if (event.keyCode === 229) { break; } if (menuIsOpen) { if (!focusedOption) return; if (_this.isComposing) return; _this.selectOption(focusedOption); break; } return; case "Escape": if (menuIsOpen) { _this.setState({ inputIsHiddenAfterUpdate: false }); _this.onInputChange("", { action: "menu-close", prevInputValue: inputValue }); _this.onMenuClose(); } else if (isClearable && escapeClearsValue) { _this.clearValue(); } break; case " ": if (inputValue) { return; } if (!menuIsOpen) { _this.openMenu("first"); break; } if (!focusedOption) return; _this.selectOption(focusedOption); break; case "ArrowUp": if (menuIsOpen) { _this.focusOption("up"); } else { _this.openMenu("last"); } break; case "ArrowDown": if (menuIsOpen) { _this.focusOption("down"); } else { _this.openMenu("first"); } break; case "PageUp": if (!menuIsOpen) return; _this.focusOption("pageup"); break; case "PageDown": if (!menuIsOpen) return; _this.focusOption("pagedown"); break; case "Home": if (!menuIsOpen) return; _this.focusOption("first"); break; case "End": if (!menuIsOpen) return; _this.focusOption("last"); break; default: return; } event.preventDefault(); }; _this.state.instancePrefix = "react-select-" + (_this.props.instanceId || ++instanceId); _this.state.selectValue = cleanValue(_props.value); if (_props.menuIsOpen && _this.state.selectValue.length) { var focusableOptionsWithIds = _this.getFocusableOptionsWithIds(); var focusableOptions = _this.buildFocusableOptions(); var optionIndex = focusableOptions.indexOf(_this.state.selectValue[0]); _this.state.focusableOptionsWithIds = focusableOptionsWithIds; _this.state.focusedOption = focusableOptions[optionIndex]; _this.state.focusedOptionId = getFocusedOptionId(focusableOptionsWithIds, focusableOptions[optionIndex]); } return _this; } _createClass(Select3, [{ key: "componentDidMount", value: function componentDidMount() { this.startListeningComposition(); this.startListeningToTouch(); if (this.props.closeMenuOnScroll && document && document.addEventListener) { document.addEventListener("scroll", this.onScroll, true); } if (this.props.autoFocus) { this.focusInput(); } if (this.props.menuIsOpen && this.state.focusedOption && this.menuListRef && this.focusedOptionRef) { scrollIntoView(this.menuListRef, this.focusedOptionRef); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var _this$props6 = this.props, isDisabled = _this$props6.isDisabled, menuIsOpen = _this$props6.menuIsOpen; var isFocused = this.state.isFocused; if ( // ensure focus is restored correctly when the control becomes enabled isFocused && !isDisabled && prevProps.isDisabled || // ensure focus is on the Input when the menu opens isFocused && menuIsOpen && !prevProps.menuIsOpen ) { this.focusInput(); } if (isFocused && isDisabled && !prevProps.isDisabled) { this.setState({ isFocused: false }, this.onMenuClose); } else if (!isFocused && !isDisabled && prevProps.isDisabled && this.inputRef === document.activeElement) { this.setState({ isFocused: true }); } if (this.menuListRef && this.focusedOptionRef && this.scrollToFocusedOptionOnUpdate) { scrollIntoView(this.menuListRef, this.focusedOptionRef); this.scrollToFocusedOptionOnUpdate = false; } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.stopListeningComposition(); this.stopListeningToTouch(); document.removeEventListener("scroll", this.onScroll, true); } // ============================== // Consumer Handlers // ============================== }, { key: "onMenuOpen", value: function onMenuOpen() { this.props.onMenuOpen(); } }, { key: "onMenuClose", value: function onMenuClose() { this.onInputChange("", { action: "menu-close", prevInputValue: this.props.inputValue }); this.props.onMenuClose(); } }, { key: "onInputChange", value: function onInputChange(newValue, actionMeta) { this.props.onInputChange(newValue, actionMeta); } // ============================== // Methods // ============================== }, { key: "focusInput", value: function focusInput() { if (!this.inputRef) return; this.inputRef.focus(); } }, { key: "blurInput", value: function blurInput() { if (!this.inputRef) return; this.inputRef.blur(); } // aliased for consumers }, { key: "openMenu", value: function openMenu(focusOption) { var _this2 = this; var _this$state2 = this.state, selectValue = _this$state2.selectValue, isFocused = _this$state2.isFocused; var focusableOptions = this.buildFocusableOptions(); var openAtIndex = focusOption === "first" ? 0 : focusableOptions.length - 1; if (!this.props.isMulti) { var selectedIndex = focusableOptions.indexOf(selectValue[0]); if (selectedIndex > -1) { openAtIndex = selectedIndex; } } this.scrollToFocusedOptionOnUpdate = !(isFocused && this.menuListRef); this.setState({ inputIsHiddenAfterUpdate: false, focusedValue: null, focusedOption: focusableOptions[openAtIndex], focusedOptionId: this.getFocusedOptionId(focusableOptions[openAtIndex]) }, function() { return _this2.onMenuOpen(); }); } }, { key: "focusValue", value: function focusValue(direction) { var _this$state3 = this.state, selectValue = _this$state3.selectValue, focusedValue = _this$state3.focusedValue; if (!this.props.isMulti) return; this.setState({ focusedOption: null }); var focusedIndex = selectValue.indexOf(focusedValue); if (!focusedValue) { focusedIndex = -1; } var lastIndex = selectValue.length - 1; var nextFocus = -1; if (!selectValue.length) return; switch (direction) { case "previous": if (focusedIndex === 0) { nextFocus = 0; } else if (focusedIndex === -1) { nextFocus = lastIndex; } else { nextFocus = focusedIndex - 1; } break; case "next": if (focusedIndex > -1 && focusedIndex < lastIndex) { nextFocus = focusedIndex + 1; } break; } this.setState({ inputIsHidden: nextFocus !== -1, focusedValue: selectValue[nextFocus] }); } }, { key: "focusOption", value: function focusOption() { var direction = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "first"; var pageSize = this.props.pageSize; var focusedOption = this.state.focusedOption; var options2 = this.getFocusableOptions(); if (!options2.length) return; var nextFocus = 0; var focusedIndex = options2.indexOf(focusedOption); if (!focusedOption) { focusedIndex = -1; } if (direction === "up") { nextFocus = focusedIndex > 0 ? focusedIndex - 1 : options2.length - 1; } else if (direction === "down") { nextFocus = (focusedIndex + 1) % options2.length; } else if (direction === "pageup") { nextFocus = focusedIndex - pageSize; if (nextFocus < 0) nextFocus = 0; } else if (direction === "pagedown") { nextFocus = focusedIndex + pageSize; if (nextFocus > options2.length - 1) nextFocus = options2.length - 1; } else if (direction === "last") { nextFocus = options2.length - 1; } this.scrollToFocusedOptionOnUpdate = true; this.setState({ focusedOption: options2[nextFocus], focusedValue: null, focusedOptionId: this.getFocusedOptionId(options2[nextFocus]) }); } }, { key: "getTheme", value: ( // ============================== // Getters // ============================== function getTheme3() { if (!this.props.theme) { return defaultTheme; } if (typeof this.props.theme === "function") { return this.props.theme(defaultTheme); } return _objectSpread2(_objectSpread2({}, defaultTheme), this.props.theme); } ) }, { key: "getCommonProps", value: function getCommonProps() { var clearValue = this.clearValue, cx = this.cx, getStyles = this.getStyles, getClassNames = this.getClassNames, getValue = this.getValue, selectOption = this.selectOption, setValue = this.setValue, props = this.props; var isMulti = props.isMulti, isRtl = props.isRtl, options2 = props.options; var hasValue = this.hasValue(); return { clearValue, cx, getStyles, getClassNames, getValue, hasValue, isMulti, isRtl, options: options2, selectOption, selectProps: props, setValue, theme: this.getTheme() }; } }, { key: "hasValue", value: function hasValue() { var selectValue = this.state.selectValue; return selectValue.length > 0; } }, { key: "hasOptions", value: function hasOptions() { return !!this.getFocusableOptions().length; } }, { key: "isClearable", value: function isClearable() { var _this$props7 = this.props, isClearable2 = _this$props7.isClearable, isMulti = _this$props7.isMulti; if (isClearable2 === void 0) return isMulti; return isClearable2; } }, { key: "isOptionDisabled", value: function isOptionDisabled3(option, selectValue) { return _isOptionDisabled(this.props, option, selectValue); } }, { key: "isOptionSelected", value: function isOptionSelected(option, selectValue) { return _isOptionSelected(this.props, option, selectValue); } }, { key: "filterOption", value: function filterOption(option, inputValue) { return _filterOption(this.props, option, inputValue); } }, { key: "formatOptionLabel", value: function formatOptionLabel(data, context) { if (typeof this.props.formatOptionLabel === "function") { var _inputValue = this.props.inputValue; var _selectValue = this.state.selectValue; return this.props.formatOptionLabel(data, { context, inputValue: _inputValue, selectValue: _selectValue }); } else { return this.getOptionLabel(data); } } }, { key: "formatGroupLabel", value: function formatGroupLabel3(data) { return this.props.formatGroupLabel(data); } // ============================== // Mouse Handlers // ============================== }, { key: "startListeningComposition", value: ( // ============================== // Composition Handlers // ============================== function startListeningComposition() { if (document && document.addEventListener) { document.addEventListener("compositionstart", this.onCompositionStart, false); document.addEventListener("compositionend", this.onCompositionEnd, false); } } ) }, { key: "stopListeningComposition", value: function stopListeningComposition() { if (document && document.removeEventListener) { document.removeEventListener("compositionstart", this.onCompositionStart); document.removeEventListener("compositionend", this.onCompositionEnd); } } }, { key: "startListeningToTouch", value: ( // ============================== // Touch Handlers // ============================== function startListeningToTouch() { if (document && document.addEventListener) { document.addEventListener("touchstart", this.onTouchStart, false); document.addEventListener("touchmove", this.onTouchMove, false); document.addEventListener("touchend", this.onTouchEnd, false); } } ) }, { key: "stopListeningToTouch", value: function stopListeningToTouch() { if (document && document.removeEventListener) { document.removeEventListener("touchstart", this.onTouchStart); document.removeEventListener("touchmove", this.onTouchMove); document.removeEventListener("touchend", this.onTouchEnd); } } }, { key: "renderInput", value: ( // ============================== // Renderers // ============================== function renderInput() { var _this$props8 = this.props, isDisabled = _this$props8.isDisabled, isSearchable = _this$props8.isSearchable, inputId = _this$props8.inputId, inputValue = _this$props8.inputValue, tabIndex = _this$props8.tabIndex, form = _this$props8.form, menuIsOpen = _this$props8.menuIsOpen, required = _this$props8.required; var _this$getComponents = this.getComponents(), Input3 = _this$getComponents.Input; var _this$state4 = this.state, inputIsHidden = _this$state4.inputIsHidden, ariaSelection = _this$state4.ariaSelection; var commonProps = this.commonProps; var id = inputId || this.getElementId("input"); var ariaAttributes = _objectSpread2(_objectSpread2(_objectSpread2({ "aria-autocomplete": "list", "aria-expanded": menuIsOpen, "aria-haspopup": true, "aria-errormessage": this.props["aria-errormessage"], "aria-invalid": this.props["aria-invalid"], "aria-label": this.props["aria-label"], "aria-labelledby": this.props["aria-labelledby"], "aria-required": required, role: "combobox", "aria-activedescendant": this.isAppleDevice ? void 0 : this.state.focusedOptionId || "" }, menuIsOpen && { "aria-controls": this.getElementId("listbox") }), !isSearchable && { "aria-readonly": true }), this.hasValue() ? (ariaSelection === null || ariaSelection === void 0 ? void 0 : ariaSelection.action) === "initial-input-focus" && { "aria-describedby": this.getElementId("live-region") } : { "aria-describedby": this.getElementId("placeholder") }); if (!isSearchable) { return React8.createElement(DummyInput, _extends({ id, innerRef: this.getInputRef, onBlur: this.onInputBlur, onChange: noop, onFocus: this.onInputFocus, disabled: isDisabled, tabIndex, inputMode: "none", form, value: "" }, ariaAttributes)); } return React8.createElement(Input3, _extends({}, commonProps, { autoCapitalize: "none", autoComplete: "off", autoCorrect: "off", id, innerRef: this.getInputRef, isDisabled, isHidden: inputIsHidden, onBlur: this.onInputBlur, onChange: this.handleInputChange, onFocus: this.onInputFocus, spellCheck: "false", tabIndex, form, type: "text", value: inputValue }, ariaAttributes)); } ) }, { key: "renderPlaceholderOrValue", value: function renderPlaceholderOrValue() { var _this3 = this; var _this$getComponents2 = this.getComponents(), MultiValue3 = _this$getComponents2.MultiValue, MultiValueContainer2 = _this$getComponents2.MultiValueContainer, MultiValueLabel2 = _this$getComponents2.MultiValueLabel, MultiValueRemove2 = _this$getComponents2.MultiValueRemove, SingleValue3 = _this$getComponents2.SingleValue, Placeholder3 = _this$getComponents2.Placeholder; var commonProps = this.commonProps; var _this$props9 = this.props, controlShouldRenderValue = _this$props9.controlShouldRenderValue, isDisabled = _this$props9.isDisabled, isMulti = _this$props9.isMulti, inputValue = _this$props9.inputValue, placeholder = _this$props9.placeholder; var _this$state5 = this.state, selectValue = _this$state5.selectValue, focusedValue = _this$state5.focusedValue, isFocused = _this$state5.isFocused; if (!this.hasValue() || !controlShouldRenderValue) { return inputValue ? null : React8.createElement(Placeholder3, _extends({}, commonProps, { key: "placeholder", isDisabled, isFocused, innerProps: { id: this.getElementId("placeholder") } }), placeholder); } if (isMulti) { return selectValue.map(function(opt, index2) { var isOptionFocused = opt === focusedValue; var key = "".concat(_this3.getOptionLabel(opt), "-").concat(_this3.getOptionValue(opt)); return React8.createElement(MultiValue3, _extends({}, commonProps, { components: { Container: MultiValueContainer2, Label: MultiValueLabel2, Remove: MultiValueRemove2 }, isFocused: isOptionFocused, isDisabled, key, index: index2, removeProps: { onClick: function onClick() { return _this3.removeValue(opt); }, onTouchEnd: function onTouchEnd() { return _this3.removeValue(opt); }, onMouseDown: function onMouseDown(e) { e.preventDefault(); } }, data: opt }), _this3.formatOptionLabel(opt, "value")); }); } if (inputValue) { return null; } var singleValue = selectValue[0]; return React8.createElement(SingleValue3, _extends({}, commonProps, { data: singleValue, isDisabled }), this.formatOptionLabel(singleValue, "value")); } }, { key: "renderClearIndicator", value: function renderClearIndicator() { var _this$getComponents3 = this.getComponents(), ClearIndicator4 = _this$getComponents3.ClearIndicator; var commonProps = this.commonProps; var _this$props10 = this.props, isDisabled = _this$props10.isDisabled, isLoading = _this$props10.isLoading; var isFocused = this.state.isFocused; if (!this.isClearable() || !ClearIndicator4 || isDisabled || !this.hasValue() || isLoading) { return null; } var innerProps = { onMouseDown: this.onClearIndicatorMouseDown, onTouchEnd: this.onClearIndicatorTouchEnd, "aria-hidden": "true" }; return React8.createElement(ClearIndicator4, _extends({}, commonProps, { innerProps, isFocused })); } }, { key: "renderLoadingIndicator", value: function renderLoadingIndicator() { var _this$getComponents4 = this.getComponents(), LoadingIndicator3 = _this$getComponents4.LoadingIndicator; var commonProps = this.commonProps; var _this$props11 = this.props, isDisabled = _this$props11.isDisabled, isLoading = _this$props11.isLoading; var isFocused = this.state.isFocused; if (!LoadingIndicator3 || !isLoading) return null; var innerProps = { "aria-hidden": "true" }; return React8.createElement(LoadingIndicator3, _extends({}, commonProps, { innerProps, isDisabled, isFocused })); } }, { key: "renderIndicatorSeparator", value: function renderIndicatorSeparator() { var _this$getComponents5 = this.getComponents(), DropdownIndicator4 = _this$getComponents5.DropdownIndicator, IndicatorSeparator3 = _this$getComponents5.IndicatorSeparator; if (!DropdownIndicator4 || !IndicatorSeparator3) return null; var commonProps = this.commonProps; var isDisabled = this.props.isDisabled; var isFocused = this.state.isFocused; return React8.createElement(IndicatorSeparator3, _extends({}, commonProps, { isDisabled, isFocused })); } }, { key: "renderDropdownIndicator", value: function renderDropdownIndicator() { var _this$getComponents6 = this.getComponents(), DropdownIndicator4 = _this$getComponents6.DropdownIndicator; if (!DropdownIndicator4) return null; var commonProps = this.commonProps; var isDisabled = this.props.isDisabled; var isFocused = this.state.isFocused; var innerProps = { onMouseDown: this.onDropdownIndicatorMouseDown, onTouchEnd: this.onDropdownIndicatorTouchEnd, "aria-hidden": "true" }; return React8.createElement(DropdownIndicator4, _extends({}, commonProps, { innerProps, isDisabled, isFocused })); } }, { key: "renderMenu", value: function renderMenu() { var _this4 = this; var _this$getComponents7 = this.getComponents(), Group3 = _this$getComponents7.Group, GroupHeading3 = _this$getComponents7.GroupHeading, Menu4 = _this$getComponents7.Menu, MenuList3 = _this$getComponents7.MenuList, MenuPortal3 = _this$getComponents7.MenuPortal, LoadingMessage3 = _this$getComponents7.LoadingMessage, NoOptionsMessage3 = _this$getComponents7.NoOptionsMessage, Option4 = _this$getComponents7.Option; var commonProps = this.commonProps; var focusedOption = this.state.focusedOption; var _this$props12 = this.props, captureMenuScroll = _this$props12.captureMenuScroll, inputValue = _this$props12.inputValue, isLoading = _this$props12.isLoading, loadingMessage2 = _this$props12.loadingMessage, minMenuHeight = _this$props12.minMenuHeight, maxMenuHeight = _this$props12.maxMenuHeight, menuIsOpen = _this$props12.menuIsOpen, menuPlacement = _this$props12.menuPlacement, menuPosition = _this$props12.menuPosition, menuPortalTarget = _this$props12.menuPortalTarget, menuShouldBlockScroll = _this$props12.menuShouldBlockScroll, menuShouldScrollIntoView = _this$props12.menuShouldScrollIntoView, noOptionsMessage2 = _this$props12.noOptionsMessage, onMenuScrollToTop = _this$props12.onMenuScrollToTop, onMenuScrollToBottom = _this$props12.onMenuScrollToBottom; if (!menuIsOpen) return null; var render3 = function render4(props, id) { var type = props.type, data = props.data, isDisabled = props.isDisabled, isSelected = props.isSelected, label = props.label, value = props.value; var isFocused = focusedOption === data; var onHover = isDisabled ? void 0 : function() { return _this4.onOptionHover(data); }; var onSelect = isDisabled ? void 0 : function() { return _this4.selectOption(data); }; var optionId = "".concat(_this4.getElementId("option"), "-").concat(id); var innerProps = { id: optionId, onClick: onSelect, onMouseMove: onHover, onMouseOver: onHover, tabIndex: -1, role: "option", "aria-selected": _this4.isAppleDevice ? void 0 : isSelected // is not supported on Apple devices }; return React8.createElement(Option4, _extends({}, commonProps, { innerProps, data, isDisabled, isSelected, key: optionId, label, type, value, isFocused, innerRef: isFocused ? _this4.getFocusedOptionRef : void 0 }), _this4.formatOptionLabel(props.data, "menu")); }; var menuUI; if (this.hasOptions()) { menuUI = this.getCategorizedOptions().map(function(item) { if (item.type === "group") { var _data = item.data, options2 = item.options, groupIndex = item.index; var groupId = "".concat(_this4.getElementId("group"), "-").concat(groupIndex); var headingId = "".concat(groupId, "-heading"); return React8.createElement(Group3, _extends({}, commonProps, { key: groupId, data: _data, options: options2, Heading: GroupHeading3, headingProps: { id: headingId, data: item.data }, label: _this4.formatGroupLabel(item.data) }), item.options.map(function(option) { return render3(option, "".concat(groupIndex, "-").concat(option.index)); })); } else if (item.type === "option") { return render3(item, "".concat(item.index)); } }); } else if (isLoading) { var message = loadingMessage2({ inputValue }); if (message === null) return null; menuUI = React8.createElement(LoadingMessage3, commonProps, message); } else { var _message = noOptionsMessage2({ inputValue }); if (_message === null) return null; menuUI = React8.createElement(NoOptionsMessage3, commonProps, _message); } var menuPlacementProps = { minMenuHeight, maxMenuHeight, menuPlacement, menuPosition, menuShouldScrollIntoView }; var menuElement = React8.createElement(MenuPlacer, _extends({}, commonProps, menuPlacementProps), function(_ref4) { var ref = _ref4.ref, _ref4$placerProps = _ref4.placerProps, placement = _ref4$placerProps.placement, maxHeight = _ref4$placerProps.maxHeight; return React8.createElement(Menu4, _extends({}, commonProps, menuPlacementProps, { innerRef: ref, innerProps: { onMouseDown: _this4.onMenuMouseDown, onMouseMove: _this4.onMenuMouseMove }, isLoading, placement }), React8.createElement(ScrollManager, { captureEnabled: captureMenuScroll, onTopArrive: onMenuScrollToTop, onBottomArrive: onMenuScrollToBottom, lockEnabled: menuShouldBlockScroll }, function(scrollTargetRef) { return React8.createElement(MenuList3, _extends({}, commonProps, { innerRef: function innerRef(instance) { _this4.getMenuListRef(instance); scrollTargetRef(instance); }, innerProps: { role: "listbox", "aria-multiselectable": commonProps.isMulti, id: _this4.getElementId("listbox") }, isLoading, maxHeight, focusedOption }), menuUI); })); }); return menuPortalTarget || menuPosition === "fixed" ? React8.createElement(MenuPortal3, _extends({}, commonProps, { appendTo: menuPortalTarget, controlElement: this.controlRef, menuPlacement, menuPosition }), menuElement) : menuElement; } }, { key: "renderFormField", value: function renderFormField() { var _this5 = this; var _this$props13 = this.props, delimiter2 = _this$props13.delimiter, isDisabled = _this$props13.isDisabled, isMulti = _this$props13.isMulti, name = _this$props13.name, required = _this$props13.required; var selectValue = this.state.selectValue; if (required && !this.hasValue() && !isDisabled) { return React8.createElement(RequiredInput$1, { name, onFocus: this.onValueInputFocus }); } if (!name || isDisabled) return; if (isMulti) { if (delimiter2) { var value = selectValue.map(function(opt) { return _this5.getOptionValue(opt); }).join(delimiter2); return React8.createElement("input", { name, type: "hidden", value }); } else { var input = selectValue.length > 0 ? selectValue.map(function(opt, i3) { return React8.createElement("input", { key: "i-".concat(i3), name, type: "hidden", value: _this5.getOptionValue(opt) }); }) : React8.createElement("input", { name, type: "hidden", value: "" }); return React8.createElement("div", null, input); } } else { var _value2 = selectValue[0] ? this.getOptionValue(selectValue[0]) : ""; return React8.createElement("input", { name, type: "hidden", value: _value2 }); } } }, { key: "renderLiveRegion", value: function renderLiveRegion() { var commonProps = this.commonProps; var _this$state6 = this.state, ariaSelection = _this$state6.ariaSelection, focusedOption = _this$state6.focusedOption, focusedValue = _this$state6.focusedValue, isFocused = _this$state6.isFocused, selectValue = _this$state6.selectValue; var focusableOptions = this.getFocusableOptions(); return React8.createElement(LiveRegion$1, _extends({}, commonProps, { id: this.getElementId("live-region"), ariaSelection, focusedOption, focusedValue, isFocused, selectValue, focusableOptions, isAppleDevice: this.isAppleDevice })); } }, { key: "render", value: function render3() { var _this$getComponents8 = this.getComponents(), Control3 = _this$getComponents8.Control, IndicatorsContainer3 = _this$getComponents8.IndicatorsContainer, SelectContainer3 = _this$getComponents8.SelectContainer, ValueContainer3 = _this$getComponents8.ValueContainer; var _this$props14 = this.props, className = _this$props14.className, id = _this$props14.id, isDisabled = _this$props14.isDisabled, menuIsOpen = _this$props14.menuIsOpen; var isFocused = this.state.isFocused; var commonProps = this.commonProps = this.getCommonProps(); return React8.createElement(SelectContainer3, _extends({}, commonProps, { className, innerProps: { id, onKeyDown: this.onKeyDown }, isDisabled, isFocused }), this.renderLiveRegion(), React8.createElement(Control3, _extends({}, commonProps, { innerRef: this.getControlRef, innerProps: { onMouseDown: this.onControlMouseDown, onTouchEnd: this.onControlTouchEnd }, isDisabled, isFocused, menuIsOpen }), React8.createElement(ValueContainer3, _extends({}, commonProps, { isDisabled }), this.renderPlaceholderOrValue(), this.renderInput()), React8.createElement(IndicatorsContainer3, _extends({}, commonProps, { isDisabled }), this.renderClearIndicator(), this.renderLoadingIndicator(), this.renderIndicatorSeparator(), this.renderDropdownIndicator())), this.renderMenu(), this.renderFormField()); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props, state) { var prevProps = state.prevProps, clearFocusValueOnUpdate = state.clearFocusValueOnUpdate, inputIsHiddenAfterUpdate = state.inputIsHiddenAfterUpdate, ariaSelection = state.ariaSelection, isFocused = state.isFocused, prevWasFocused = state.prevWasFocused, instancePrefix = state.instancePrefix; var options2 = props.options, value = props.value, menuIsOpen = props.menuIsOpen, inputValue = props.inputValue, isMulti = props.isMulti; var selectValue = cleanValue(value); var newMenuOptionsState = {}; if (prevProps && (value !== prevProps.value || options2 !== prevProps.options || menuIsOpen !== prevProps.menuIsOpen || inputValue !== prevProps.inputValue)) { var focusableOptions = menuIsOpen ? buildFocusableOptions(props, selectValue) : []; var focusableOptionsWithIds = menuIsOpen ? buildFocusableOptionsWithIds(buildCategorizedOptions(props, selectValue), "".concat(instancePrefix, "-option")) : []; var focusedValue = clearFocusValueOnUpdate ? getNextFocusedValue(state, selectValue) : null; var focusedOption = getNextFocusedOption(state, focusableOptions); var focusedOptionId = getFocusedOptionId(focusableOptionsWithIds, focusedOption); newMenuOptionsState = { selectValue, focusedOption, focusedOptionId, focusableOptionsWithIds, focusedValue, clearFocusValueOnUpdate: false }; } var newInputIsHiddenState = inputIsHiddenAfterUpdate != null && props !== prevProps ? { inputIsHidden: inputIsHiddenAfterUpdate, inputIsHiddenAfterUpdate: void 0 } : {}; var newAriaSelection = ariaSelection; var hasKeptFocus = isFocused && prevWasFocused; if (isFocused && !hasKeptFocus) { newAriaSelection = { value: valueTernary(isMulti, selectValue, selectValue[0] || null), options: selectValue, action: "initial-input-focus" }; hasKeptFocus = !prevWasFocused; } if ((ariaSelection === null || ariaSelection === void 0 ? void 0 : ariaSelection.action) === "initial-input-focus") { newAriaSelection = null; } return _objectSpread2(_objectSpread2(_objectSpread2({}, newMenuOptionsState), newInputIsHiddenState), {}, { prevProps: props, ariaSelection: newAriaSelection, prevWasFocused: hasKeptFocus }); } }]); return Select3; }(import_react6.Component); Select.defaultProps = defaultProps; // node_modules/react-select/dist/react-select.esm.js var import_react_dom2 = __toESM(require_react_dom()); var StateManagedSelect = (0, import_react8.forwardRef)(function(props, ref) { var baseSelectProps = useStateManager(props); return React9.createElement(Select, _extends({ ref }, baseSelectProps)); }); var StateManagedSelect$1 = StateManagedSelect; // node_modules/@strapi/upload/dist/admin/components/SelectTree/Option.mjs var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); var import_react10 = __toESM(require_react(), 1); var ToggleButton = dt(Flex)` align-self: flex-end; height: 2.2rem; width: 2.8rem; &:hover, &:focus { background-color: ${({ theme }) => theme.colors.primary200}; } `; var Option3 = ({ children, data, selectProps, ...props }) => { const { formatMessage } = useIntl(); const { depth, value, children: options2 } = data; const { maxDisplayDepth, openValues, onOptionToggle } = selectProps; const isOpen = openValues.includes(value); const Icon = isOpen ? ForwardRef$4t : ForwardRef$4z; return (0, import_jsx_runtime2.jsx)(components.Option, { data, selectProps, ...props, children: (0, import_jsx_runtime2.jsxs)(Flex, { alignItems: "start", children: [ (0, import_jsx_runtime2.jsx)(Typography, { textColor: "neutral800", ellipsis: true, children: (0, import_jsx_runtime2.jsx)("span", { style: { paddingLeft: `${Math.min(depth, maxDisplayDepth) * 14}px` }, children }) }), options2 && (options2 == null ? void 0 : options2.length) > 0 && (0, import_jsx_runtime2.jsx)(ToggleButton, { "aria-label": formatMessage({ id: "app.utils.toggle", defaultMessage: "Toggle" }), tag: "button", alignItems: "center", hasRadius: true, justifyContent: "center", marginLeft: "auto", onClick: (event) => { event.preventDefault(); event.stopPropagation(); onOptionToggle(value); }, children: (0, import_jsx_runtime2.jsx)(Icon, { width: "1.4rem", fill: "neutral500" }) }) ] }) }); }; // node_modules/@strapi/upload/dist/admin/components/SelectTree/utils/flattenTree.mjs function flattenTree(tree, parent = null, depth = 0) { return tree.flatMap((item) => item.children ? [ { ...item, parent: parent == null ? void 0 : parent.value, depth }, ...flattenTree(item.children, item, depth + 1) ] : { ...item, depth, parent: parent == null ? void 0 : parent.value }); } // node_modules/@strapi/upload/dist/admin/components/SelectTree/utils/getOpenValues.mjs function getOpenValues(options2, defaultValue = {}) { const values = []; const { value } = defaultValue; const option = options2.find((option2) => option2.value === value); if (!option) { return values; } values.push(option.value); let { parent } = option; while (parent !== void 0) { const option2 = options2.find(({ value: value2 }) => value2 === parent); if (!option2) { break; } values.push(option2.value); parent = option2.parent; } return values.reverse(); } // node_modules/@strapi/upload/dist/admin/components/SelectTree/utils/getValuesToClose.mjs function getValuesToClose(options2, value) { const optionForValue = options2.find((option) => option.value === value); if (!optionForValue) { return []; } return options2.filter((option) => option.depth >= optionForValue.depth).map((option) => option.value); } // node_modules/@strapi/upload/dist/admin/components/SelectTree/SelectTree.mjs var hasParent = (option) => !option.parent; var SelectTree = ({ options: defaultOptions, maxDisplayDepth = 5, defaultValue, ...props }) => { const flatDefaultOptions = React10.useMemo(() => flattenTree(defaultOptions), [ defaultOptions ]); const optionsFiltered = React10.useMemo(() => flatDefaultOptions.filter(hasParent), [ flatDefaultOptions ]); const [options2, setOptions] = React10.useState(optionsFiltered); const [openValues, setOpenValues] = React10.useState(getOpenValues(flatDefaultOptions, defaultValue)); React10.useEffect(() => { if (openValues.length === 0) { setOptions(flatDefaultOptions.filter((option) => option.parent === void 0)); } else { const allOpenValues = openValues.reduce((acc, value) => { const options3 = flatDefaultOptions.filter((option) => option.value === value || option.parent === value); options3.forEach((option) => { const values = getOpenValues(flatDefaultOptions, option); acc = [ ...acc, ...values ]; }); return acc; }, []); const nextOptions = flatDefaultOptions.filter((option) => allOpenValues.includes(option.value)); setOptions(nextOptions); } }, [ openValues, flatDefaultOptions, optionsFiltered ]); const handleToggle = (value) => { if (openValues.includes(value)) { const valuesToClose = getValuesToClose(flatDefaultOptions, value); setOpenValues((prev2) => prev2.filter((prevData) => !valuesToClose.includes(prevData))); } else { setOpenValues((prev2) => [ ...prev2, value ]); } }; return (0, import_jsx_runtime3.jsx)(Select2, { components: { Option: Option3 }, options: options2, defaultValue, isSearchable: false, /* -- custom props, used by the Option component */ maxDisplayDepth, openValues, onOptionToggle: handleToggle, ...props }); }; var Select2 = ({ components: components2 = {}, styles = {}, error, ariaErrorMessage, ...props }) => { const theme = nt(); const customStyles = getSelectStyles(theme, error); return (0, import_jsx_runtime3.jsx)(StateManagedSelect$1, { menuPosition: "fixed", components: { ...components2, ClearIndicator: ClearIndicator3, DropdownIndicator: DropdownIndicator3, IndicatorSeparator: () => null, LoadingIndicator: () => null }, "aria-errormessage": error && ariaErrorMessage, "aria-invalid": !!error, styles: { ...customStyles, ...styles }, ...props }); }; var IconBox = dt(Box)` background: transparent; border: none; position: relative; z-index: 1; svg { height: 1.1rem; width: 1.1rem; } svg path { fill: ${({ theme }) => theme.colors.neutral600}; } `; var ClearIndicator3 = (props) => { const Component2 = components.ClearIndicator; return (0, import_jsx_runtime3.jsx)(Component2, { ...props, children: (0, import_jsx_runtime3.jsx)(IconBox, { tag: "button", type: "button", children: (0, import_jsx_runtime3.jsx)(ForwardRef$45, {}) }) }); }; var CarretBox = dt(IconBox)` display: flex; background: none; border: none; svg { width: 0.9rem; } `; var DropdownIndicator3 = ({ innerProps }) => { return (0, import_jsx_runtime3.jsx)(CarretBox, { paddingRight: 3, ...innerProps, children: (0, import_jsx_runtime3.jsx)(ForwardRef$4T, {}) }); }; var getSelectStyles = (theme, error) => { return { clearIndicator: (base) => ({ ...base, padding: 0, paddingRight: theme.spaces[3] }), container: (base) => ({ ...base, background: theme.colors.neutral0, lineHeight: "normal" }), control(base, state) { let borderColor = theme.colors.neutral200; let boxShadowColor = void 0; let backgroundColor = void 0; if (state.isFocused) { borderColor = theme.colors.primary600; boxShadowColor = theme.colors.primary600; } else if (error) { borderColor = theme.colors.danger600; } if (state.isDisabled) { backgroundColor = `${theme.colors.neutral150} !important`; } return { ...base, fontSize: theme.fontSizes[2], height: 40, border: `1px solid ${borderColor} !important`, outline: 0, backgroundColor, borderRadius: theme.borderRadius, boxShadow: boxShadowColor ? `${boxShadowColor} 0px 0px 0px 2px` : "" }; }, indicatorsContainer: (base) => ({ ...base, padding: 0, paddingRight: theme.spaces[3] }), input: (base) => ({ ...base, margin: 0, padding: 0, color: theme.colors.neutral800, gridTemplateColumns: "0 100%" }), menuPortal: (base) => ({ ...base, zIndex: theme.zIndices.dialog, pointerEvents: "auto" }), menu(base) { return { ...base, width: "100%", marginTop: theme.spaces[1], backgroundColor: theme.colors.neutral0, color: theme.colors.neutral800, borderRadius: theme.borderRadius, border: `1px solid ${theme.colors.neutral200}`, boxShadow: theme.shadows.tableShadow, fontSize: theme.fontSizes[2], zIndex: 2 }; }, menuList: (base) => ({ ...base, paddingLeft: theme.spaces[1], paddingTop: theme.spaces[1], paddingRight: theme.spaces[1], paddingBottom: theme.spaces[1] }), // eslint-disable-next-line @typescript-eslint/no-explicit-any option(base, state) { let backgroundColor = base == null ? void 0 : base.backgroundColor; if (state.isFocused || state.isSelected) { backgroundColor = theme.colors.primary100; } return { ...base, color: theme.colors.neutral800, lineHeight: theme.spaces[5], backgroundColor, borderRadius: theme.borderRadius, "&:active": { backgroundColor: theme.colors.primary100 } }; }, placeholder: (base) => ({ ...base, color: theme.colors.neutral600, marginLeft: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "80%" }), singleValue(base, state) { let color = theme.colors.neutral800; if (state.isDisabled) { color = theme.colors.neutral600; } return { ...base, marginLeft: 0, color }; }, valueContainer: (base) => ({ ...base, cursor: "pointer", padding: 0, paddingLeft: theme.spaces[4], marginLeft: 0, marginRight: 0 }) }; }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/DialogHeader.mjs var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1); var DialogHeader = () => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime4.jsx)(Modal.Header, { children: (0, import_jsx_runtime4.jsx)(Modal.Title, { children: formatMessage({ id: "global.details", defaultMessage: "Details" }) }) }); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/PreviewBox.mjs var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1); var React14 = __toESM(require_react(), 1); // node_modules/@strapi/upload/dist/admin/hooks/useCropImg.mjs var React11 = __toESM(require_react(), 1); // node_modules/cropperjs/dist/cropper.esm.js function ownKeys(e, r9) { var t2 = Object.keys(e); if (Object.getOwnPropertySymbols) { var o2 = Object.getOwnPropertySymbols(e); r9 && (o2 = o2.filter(function(r10) { return Object.getOwnPropertyDescriptor(e, r10).enumerable; })), t2.push.apply(t2, o2); } return t2; } function _objectSpread22(e) { for (var r9 = 1; r9 < arguments.length; r9++) { var t2 = null != arguments[r9] ? arguments[r9] : {}; r9 % 2 ? ownKeys(Object(t2), true).forEach(function(r10) { _defineProperty2(e, r10, t2[r10]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t2)) : ownKeys(Object(t2)).forEach(function(r10) { Object.defineProperty(e, r10, Object.getOwnPropertyDescriptor(t2, r10)); }); } return e; } function _typeof2(o2) { "@babel/helpers - typeof"; return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o3) { return typeof o3; } : function(o3) { return o3 && "function" == typeof Symbol && o3.constructor === Symbol && o3 !== Symbol.prototype ? "symbol" : typeof o3; }, _typeof2(o2); } function _classCallCheck2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i3 = 0; i3 < props.length; i3++) { var descriptor = props[i3]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty2(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray2(arr) { return _arrayWithoutHoles2(arr) || _iterableToArray2(arr) || _unsupportedIterableToArray2(arr) || _nonIterableSpread2(); } function _arrayWithoutHoles2(arr) { if (Array.isArray(arr)) return _arrayLikeToArray2(arr); } function _iterableToArray2(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray2(o2, minLen) { if (!o2) return; if (typeof o2 === "string") return _arrayLikeToArray2(o2, minLen); var n2 = Object.prototype.toString.call(o2).slice(8, -1); if (n2 === "Object" && o2.constructor) n2 = o2.constructor.name; if (n2 === "Map" || n2 === "Set") return Array.from(o2); if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) return _arrayLikeToArray2(o2, minLen); } function _arrayLikeToArray2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) arr2[i3] = arr[i3]; return arr2; } function _nonIterableSpread2() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== void 0) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } var IS_BROWSER = typeof window !== "undefined" && typeof window.document !== "undefined"; var WINDOW = IS_BROWSER ? window : {}; var IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? "ontouchstart" in WINDOW.document.documentElement : false; var HAS_POINTER_EVENT = IS_BROWSER ? "PointerEvent" in WINDOW : false; var NAMESPACE = "cropper"; var ACTION_ALL = "all"; var ACTION_CROP = "crop"; var ACTION_MOVE = "move"; var ACTION_ZOOM = "zoom"; var ACTION_EAST = "e"; var ACTION_WEST = "w"; var ACTION_SOUTH = "s"; var ACTION_NORTH = "n"; var ACTION_NORTH_EAST = "ne"; var ACTION_NORTH_WEST = "nw"; var ACTION_SOUTH_EAST = "se"; var ACTION_SOUTH_WEST = "sw"; var CLASS_CROP = "".concat(NAMESPACE, "-crop"); var CLASS_DISABLED = "".concat(NAMESPACE, "-disabled"); var CLASS_HIDDEN = "".concat(NAMESPACE, "-hidden"); var CLASS_HIDE = "".concat(NAMESPACE, "-hide"); var CLASS_INVISIBLE = "".concat(NAMESPACE, "-invisible"); var CLASS_MODAL = "".concat(NAMESPACE, "-modal"); var CLASS_MOVE = "".concat(NAMESPACE, "-move"); var DATA_ACTION = "".concat(NAMESPACE, "Action"); var DATA_PREVIEW = "".concat(NAMESPACE, "Preview"); var DRAG_MODE_CROP = "crop"; var DRAG_MODE_MOVE = "move"; var DRAG_MODE_NONE = "none"; var EVENT_CROP = "crop"; var EVENT_CROP_END = "cropend"; var EVENT_CROP_MOVE = "cropmove"; var EVENT_CROP_START = "cropstart"; var EVENT_DBLCLICK = "dblclick"; var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? "touchstart" : "mousedown"; var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? "touchmove" : "mousemove"; var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? "touchend touchcancel" : "mouseup"; var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? "pointerdown" : EVENT_TOUCH_START; var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? "pointermove" : EVENT_TOUCH_MOVE; var EVENT_POINTER_UP = HAS_POINTER_EVENT ? "pointerup pointercancel" : EVENT_TOUCH_END; var EVENT_READY = "ready"; var EVENT_RESIZE = "resize"; var EVENT_WHEEL = "wheel"; var EVENT_ZOOM = "zoom"; var MIME_TYPE_JPEG = "image/jpeg"; var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/; var REGEXP_DATA_URL = /^data:/; var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/; var REGEXP_TAG_NAME = /^img|canvas$/i; var MIN_CONTAINER_WIDTH = 200; var MIN_CONTAINER_HEIGHT = 100; var DEFAULTS = { // Define the view mode of the cropper viewMode: 0, // 0, 1, 2, 3 // Define the dragging mode of the cropper dragMode: DRAG_MODE_CROP, // 'crop', 'move' or 'none' // Define the initial aspect ratio of the crop box initialAspectRatio: NaN, // Define the aspect ratio of the crop box aspectRatio: NaN, // An object with the previous cropping result data data: null, // A selector for adding extra containers to preview preview: "", // Re-render the cropper when resize the window responsive: true, // Restore the cropped area after resize the window restore: true, // Check if the current image is a cross-origin image checkCrossOrigin: true, // Check the current image's Exif Orientation information checkOrientation: true, // Show the black modal modal: true, // Show the dashed lines for guiding guides: true, // Show the center indicator for guiding center: true, // Show the white modal to highlight the crop box highlight: true, // Show the grid background background: true, // Enable to crop the image automatically when initialize autoCrop: true, // Define the percentage of automatic cropping area when initializes autoCropArea: 0.8, // Enable to move the image movable: true, // Enable to rotate the image rotatable: true, // Enable to scale the image scalable: true, // Enable to zoom the image zoomable: true, // Enable to zoom the image by dragging touch zoomOnTouch: true, // Enable to zoom the image by wheeling mouse zoomOnWheel: true, // Define zoom ratio when zoom the image by wheeling mouse wheelZoomRatio: 0.1, // Enable to move the crop box cropBoxMovable: true, // Enable to resize the crop box cropBoxResizable: true, // Toggle drag mode between "crop" and "move" when click twice on the cropper toggleDragModeOnDblclick: true, // Size limitation minCanvasWidth: 0, minCanvasHeight: 0, minCropBoxWidth: 0, minCropBoxHeight: 0, minContainerWidth: MIN_CONTAINER_WIDTH, minContainerHeight: MIN_CONTAINER_HEIGHT, // Shortcuts of events ready: null, cropstart: null, cropmove: null, cropend: null, crop: null, zoom: null }; var TEMPLATE = '
'; var isNaN2 = Number.isNaN || WINDOW.isNaN; function isNumber(value) { return typeof value === "number" && !isNaN2(value); } var isPositiveNumber = function isPositiveNumber2(value) { return value > 0 && value < Infinity; }; function isUndefined(value) { return typeof value === "undefined"; } function isObject(value) { return _typeof2(value) === "object" && value !== null; } var hasOwnProperty = Object.prototype.hasOwnProperty; function isPlainObject(value) { if (!isObject(value)) { return false; } try { var _constructor = value.constructor; var prototype = _constructor.prototype; return _constructor && prototype && hasOwnProperty.call(prototype, "isPrototypeOf"); } catch (error) { return false; } } function isFunction(value) { return typeof value === "function"; } var slice2 = Array.prototype.slice; function toArray(value) { return Array.from ? Array.from(value) : slice2.call(value); } function forEach(data, callback) { if (data && isFunction(callback)) { if (Array.isArray(data) || isNumber(data.length)) { toArray(data).forEach(function(value, key) { callback.call(data, value, key, data); }); } else if (isObject(data)) { Object.keys(data).forEach(function(key) { callback.call(data, data[key], key, data); }); } } return data; } var assign2 = Object.assign || function assign3(target) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (isObject(target) && args.length > 0) { args.forEach(function(arg) { if (isObject(arg)) { Object.keys(arg).forEach(function(key) { target[key] = arg[key]; }); } }); } return target; }; var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/; function normalizeDecimalNumber(value) { var times = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1e11; return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value; } var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/; function setStyle(element, styles) { var style = element.style; forEach(styles, function(value, property) { if (REGEXP_SUFFIX.test(property) && isNumber(value)) { value = "".concat(value, "px"); } style[property] = value; }); } function hasClass(element, value) { return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1; } function addClass(element, value) { if (!value) { return; } if (isNumber(element.length)) { forEach(element, function(elem) { addClass(elem, value); }); return; } if (element.classList) { element.classList.add(value); return; } var className = element.className.trim(); if (!className) { element.className = value; } else if (className.indexOf(value) < 0) { element.className = "".concat(className, " ").concat(value); } } function removeClass(element, value) { if (!value) { return; } if (isNumber(element.length)) { forEach(element, function(elem) { removeClass(elem, value); }); return; } if (element.classList) { element.classList.remove(value); return; } if (element.className.indexOf(value) >= 0) { element.className = element.className.replace(value, ""); } } function toggleClass(element, value, added) { if (!value) { return; } if (isNumber(element.length)) { forEach(element, function(elem) { toggleClass(elem, value, added); }); return; } if (added) { addClass(element, value); } else { removeClass(element, value); } } var REGEXP_CAMEL_CASE = /([a-z\d])([A-Z])/g; function toParamCase(value) { return value.replace(REGEXP_CAMEL_CASE, "$1-$2").toLowerCase(); } function getData(element, name) { if (isObject(element[name])) { return element[name]; } if (element.dataset) { return element.dataset[name]; } return element.getAttribute("data-".concat(toParamCase(name))); } function setData(element, name, data) { if (isObject(data)) { element[name] = data; } else if (element.dataset) { element.dataset[name] = data; } else { element.setAttribute("data-".concat(toParamCase(name)), data); } } function removeData(element, name) { if (isObject(element[name])) { try { delete element[name]; } catch (error) { element[name] = void 0; } } else if (element.dataset) { try { delete element.dataset[name]; } catch (error) { element.dataset[name] = void 0; } } else { element.removeAttribute("data-".concat(toParamCase(name))); } } var REGEXP_SPACES = /\s\s*/; var onceSupported = function() { var supported = false; if (IS_BROWSER) { var once = false; var listener = function listener2() { }; var options2 = Object.defineProperty({}, "once", { get: function get() { supported = true; return once; }, /** * This setter can fix a `TypeError` in strict mode * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only} * @param {boolean} value - The value to set */ set: function set(value) { once = value; } }); WINDOW.addEventListener("test", listener, options2); WINDOW.removeEventListener("test", listener, options2); } return supported; }(); function removeListener(element, type, listener) { var options2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; var handler = listener; type.trim().split(REGEXP_SPACES).forEach(function(event) { if (!onceSupported) { var listeners = element.listeners; if (listeners && listeners[event] && listeners[event][listener]) { handler = listeners[event][listener]; delete listeners[event][listener]; if (Object.keys(listeners[event]).length === 0) { delete listeners[event]; } if (Object.keys(listeners).length === 0) { delete element.listeners; } } } element.removeEventListener(event, handler, options2); }); } function addListener(element, type, listener) { var options2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; var _handler = listener; type.trim().split(REGEXP_SPACES).forEach(function(event) { if (options2.once && !onceSupported) { var _element$listeners = element.listeners, listeners = _element$listeners === void 0 ? {} : _element$listeners; _handler = function handler() { delete listeners[event][listener]; element.removeEventListener(event, _handler, options2); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } listener.apply(element, args); }; if (!listeners[event]) { listeners[event] = {}; } if (listeners[event][listener]) { element.removeEventListener(event, listeners[event][listener], options2); } listeners[event][listener] = _handler; element.listeners = listeners; } element.addEventListener(event, _handler, options2); }); } function dispatchEvent(element, type, data) { var event; if (isFunction(Event) && isFunction(CustomEvent)) { event = new CustomEvent(type, { detail: data, bubbles: true, cancelable: true }); } else { event = document.createEvent("CustomEvent"); event.initCustomEvent(type, true, true, data); } return element.dispatchEvent(event); } function getOffset(element) { var box = element.getBoundingClientRect(); return { left: box.left + (window.pageXOffset - document.documentElement.clientLeft), top: box.top + (window.pageYOffset - document.documentElement.clientTop) }; } var location2 = WINDOW.location; var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i; function isCrossOriginURL(url) { var parts = url.match(REGEXP_ORIGINS); return parts !== null && (parts[1] !== location2.protocol || parts[2] !== location2.hostname || parts[3] !== location2.port); } function addTimestamp(url) { var timestamp = "timestamp=".concat((/* @__PURE__ */ new Date()).getTime()); return url + (url.indexOf("?") === -1 ? "?" : "&") + timestamp; } function getTransforms(_ref3) { var rotate2 = _ref3.rotate, scaleX2 = _ref3.scaleX, scaleY2 = _ref3.scaleY, translateX = _ref3.translateX, translateY = _ref3.translateY; var values = []; if (isNumber(translateX) && translateX !== 0) { values.push("translateX(".concat(translateX, "px)")); } if (isNumber(translateY) && translateY !== 0) { values.push("translateY(".concat(translateY, "px)")); } if (isNumber(rotate2) && rotate2 !== 0) { values.push("rotate(".concat(rotate2, "deg)")); } if (isNumber(scaleX2) && scaleX2 !== 1) { values.push("scaleX(".concat(scaleX2, ")")); } if (isNumber(scaleY2) && scaleY2 !== 1) { values.push("scaleY(".concat(scaleY2, ")")); } var transform = values.length ? values.join(" ") : "none"; return { WebkitTransform: transform, msTransform: transform, transform }; } function getMaxZoomRatio(pointers) { var pointers2 = _objectSpread22({}, pointers); var maxRatio = 0; forEach(pointers, function(pointer, pointerId) { delete pointers2[pointerId]; forEach(pointers2, function(pointer2) { var x1 = Math.abs(pointer.startX - pointer2.startX); var y1 = Math.abs(pointer.startY - pointer2.startY); var x2 = Math.abs(pointer.endX - pointer2.endX); var y22 = Math.abs(pointer.endY - pointer2.endY); var z1 = Math.sqrt(x1 * x1 + y1 * y1); var z22 = Math.sqrt(x2 * x2 + y22 * y22); var ratio = (z22 - z1) / z1; if (Math.abs(ratio) > Math.abs(maxRatio)) { maxRatio = ratio; } }); }); return maxRatio; } function getPointer(_ref23, endOnly) { var pageX = _ref23.pageX, pageY = _ref23.pageY; var end = { endX: pageX, endY: pageY }; return endOnly ? end : _objectSpread22({ startX: pageX, startY: pageY }, end); } function getPointersCenter(pointers) { var pageX = 0; var pageY = 0; var count = 0; forEach(pointers, function(_ref3) { var startX = _ref3.startX, startY = _ref3.startY; pageX += startX; pageY += startY; count += 1; }); pageX /= count; pageY /= count; return { pageX, pageY }; } function getAdjustedSizes(_ref4) { var aspectRatio = _ref4.aspectRatio, height = _ref4.height, width = _ref4.width; var type = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "contain"; var isValidWidth = isPositiveNumber(width); var isValidHeight = isPositiveNumber(height); if (isValidWidth && isValidHeight) { var adjustedWidth = height * aspectRatio; if (type === "contain" && adjustedWidth > width || type === "cover" && adjustedWidth < width) { height = width / aspectRatio; } else { width = height * aspectRatio; } } else if (isValidWidth) { height = width / aspectRatio; } else if (isValidHeight) { width = height * aspectRatio; } return { width, height }; } function getRotatedSizes(_ref5) { var width = _ref5.width, height = _ref5.height, degree = _ref5.degree; degree = Math.abs(degree) % 180; if (degree === 90) { return { width: height, height: width }; } var arc = degree % 90 * Math.PI / 180; var sinArc = Math.sin(arc); var cosArc = Math.cos(arc); var newWidth = width * cosArc + height * sinArc; var newHeight = width * sinArc + height * cosArc; return degree > 90 ? { width: newHeight, height: newWidth } : { width: newWidth, height: newHeight }; } function getSourceCanvas(image, _ref6, _ref7, _ref8) { var imageAspectRatio = _ref6.aspectRatio, imageNaturalWidth = _ref6.naturalWidth, imageNaturalHeight = _ref6.naturalHeight, _ref6$rotate = _ref6.rotate, rotate2 = _ref6$rotate === void 0 ? 0 : _ref6$rotate, _ref6$scaleX = _ref6.scaleX, scaleX2 = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX, _ref6$scaleY = _ref6.scaleY, scaleY2 = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY; var aspectRatio = _ref7.aspectRatio, naturalWidth = _ref7.naturalWidth, naturalHeight = _ref7.naturalHeight; var _ref8$fillColor = _ref8.fillColor, fillColor = _ref8$fillColor === void 0 ? "transparent" : _ref8$fillColor, _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled, imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE, _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality, imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? "low" : _ref8$imageSmoothingQ, _ref8$maxWidth = _ref8.maxWidth, maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth, _ref8$maxHeight = _ref8.maxHeight, maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight, _ref8$minWidth = _ref8.minWidth, minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth, _ref8$minHeight = _ref8.minHeight, minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight; var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); var maxSizes = getAdjustedSizes({ aspectRatio, width: maxWidth, height: maxHeight }); var minSizes = getAdjustedSizes({ aspectRatio, width: minWidth, height: minHeight }, "cover"); var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth)); var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight)); var destMaxSizes = getAdjustedSizes({ aspectRatio: imageAspectRatio, width: maxWidth, height: maxHeight }); var destMinSizes = getAdjustedSizes({ aspectRatio: imageAspectRatio, width: minWidth, height: minHeight }, "cover"); var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth)); var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight)); var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight]; canvas.width = normalizeDecimalNumber(width); canvas.height = normalizeDecimalNumber(height); context.fillStyle = fillColor; context.fillRect(0, 0, width, height); context.save(); context.translate(width / 2, height / 2); context.rotate(rotate2 * Math.PI / 180); context.scale(scaleX2, scaleY2); context.imageSmoothingEnabled = imageSmoothingEnabled; context.imageSmoothingQuality = imageSmoothingQuality; context.drawImage.apply(context, [image].concat(_toConsumableArray2(params.map(function(param) { return Math.floor(normalizeDecimalNumber(param)); })))); context.restore(); return canvas; } var fromCharCode = String.fromCharCode; function getStringFromCharCode(dataView, start, length2) { var str = ""; length2 += start; for (var i3 = start; i3 < length2; i3 += 1) { str += fromCharCode(dataView.getUint8(i3)); } return str; } var REGEXP_DATA_URL_HEAD = /^data:.*,/; function dataURLToArrayBuffer(dataURL) { var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, ""); var binary = atob(base64); var arrayBuffer = new ArrayBuffer(binary.length); var uint8 = new Uint8Array(arrayBuffer); forEach(uint8, function(value, i3) { uint8[i3] = binary.charCodeAt(i3); }); return arrayBuffer; } function arrayBufferToDataURL(arrayBuffer, mimeType) { var chunks = []; var chunkSize = 8192; var uint8 = new Uint8Array(arrayBuffer); while (uint8.length > 0) { chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize)))); uint8 = uint8.subarray(chunkSize); } return "data:".concat(mimeType, ";base64,").concat(btoa(chunks.join(""))); } function resetAndGetOrientation(arrayBuffer) { var dataView = new DataView(arrayBuffer); var orientation; try { var littleEndian; var app1Start; var ifdStart; if (dataView.getUint8(0) === 255 && dataView.getUint8(1) === 216) { var length2 = dataView.byteLength; var offset = 2; while (offset + 1 < length2) { if (dataView.getUint8(offset) === 255 && dataView.getUint8(offset + 1) === 225) { app1Start = offset; break; } offset += 1; } } if (app1Start) { var exifIDCode = app1Start + 4; var tiffOffset = app1Start + 10; if (getStringFromCharCode(dataView, exifIDCode, 4) === "Exif") { var endianness = dataView.getUint16(tiffOffset); littleEndian = endianness === 18761; if (littleEndian || endianness === 19789) { if (dataView.getUint16(tiffOffset + 2, littleEndian) === 42) { var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian); if (firstIFDOffset >= 8) { ifdStart = tiffOffset + firstIFDOffset; } } } } } if (ifdStart) { var _length = dataView.getUint16(ifdStart, littleEndian); var _offset; var i3; for (i3 = 0; i3 < _length; i3 += 1) { _offset = ifdStart + i3 * 12 + 2; if (dataView.getUint16(_offset, littleEndian) === 274) { _offset += 8; orientation = dataView.getUint16(_offset, littleEndian); dataView.setUint16(_offset, 1, littleEndian); break; } } } } catch (error) { orientation = 1; } return orientation; } function parseOrientation(orientation) { var rotate2 = 0; var scaleX2 = 1; var scaleY2 = 1; switch (orientation) { case 2: scaleX2 = -1; break; case 3: rotate2 = -180; break; case 4: scaleY2 = -1; break; case 5: rotate2 = 90; scaleY2 = -1; break; case 6: rotate2 = 90; break; case 7: rotate2 = 90; scaleX2 = -1; break; case 8: rotate2 = -90; break; } return { rotate: rotate2, scaleX: scaleX2, scaleY: scaleY2 }; } var render = { render: function render2() { this.initContainer(); this.initCanvas(); this.initCropBox(); this.renderCanvas(); if (this.cropped) { this.renderCropBox(); } }, initContainer: function initContainer() { var element = this.element, options2 = this.options, container = this.container, cropper = this.cropper; var minWidth = Number(options2.minContainerWidth); var minHeight = Number(options2.minContainerHeight); addClass(cropper, CLASS_HIDDEN); removeClass(element, CLASS_HIDDEN); var containerData = { width: Math.max(container.offsetWidth, minWidth >= 0 ? minWidth : MIN_CONTAINER_WIDTH), height: Math.max(container.offsetHeight, minHeight >= 0 ? minHeight : MIN_CONTAINER_HEIGHT) }; this.containerData = containerData; setStyle(cropper, { width: containerData.width, height: containerData.height }); addClass(element, CLASS_HIDDEN); removeClass(cropper, CLASS_HIDDEN); }, // Canvas (image wrapper) initCanvas: function initCanvas() { var containerData = this.containerData, imageData = this.imageData; var viewMode = this.options.viewMode; var rotated = Math.abs(imageData.rotate) % 180 === 90; var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth; var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight; var aspectRatio = naturalWidth / naturalHeight; var canvasWidth = containerData.width; var canvasHeight = containerData.height; if (containerData.height * aspectRatio > containerData.width) { if (viewMode === 3) { canvasWidth = containerData.height * aspectRatio; } else { canvasHeight = containerData.width / aspectRatio; } } else if (viewMode === 3) { canvasHeight = containerData.width / aspectRatio; } else { canvasWidth = containerData.height * aspectRatio; } var canvasData = { aspectRatio, naturalWidth, naturalHeight, width: canvasWidth, height: canvasHeight }; this.canvasData = canvasData; this.limited = viewMode === 1 || viewMode === 2; this.limitCanvas(true, true); canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth); canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight); canvasData.left = (containerData.width - canvasData.width) / 2; canvasData.top = (containerData.height - canvasData.height) / 2; canvasData.oldLeft = canvasData.left; canvasData.oldTop = canvasData.top; this.initialCanvasData = assign2({}, canvasData); }, limitCanvas: function limitCanvas(sizeLimited, positionLimited) { var options2 = this.options, containerData = this.containerData, canvasData = this.canvasData, cropBoxData = this.cropBoxData; var viewMode = options2.viewMode; var aspectRatio = canvasData.aspectRatio; var cropped = this.cropped && cropBoxData; if (sizeLimited) { var minCanvasWidth = Number(options2.minCanvasWidth) || 0; var minCanvasHeight = Number(options2.minCanvasHeight) || 0; if (viewMode > 1) { minCanvasWidth = Math.max(minCanvasWidth, containerData.width); minCanvasHeight = Math.max(minCanvasHeight, containerData.height); if (viewMode === 3) { if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } else if (viewMode > 0) { if (minCanvasWidth) { minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0); } else if (minCanvasHeight) { minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0); } else if (cropped) { minCanvasWidth = cropBoxData.width; minCanvasHeight = cropBoxData.height; if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } var _getAdjustedSizes = getAdjustedSizes({ aspectRatio, width: minCanvasWidth, height: minCanvasHeight }); minCanvasWidth = _getAdjustedSizes.width; minCanvasHeight = _getAdjustedSizes.height; canvasData.minWidth = minCanvasWidth; canvasData.minHeight = minCanvasHeight; canvasData.maxWidth = Infinity; canvasData.maxHeight = Infinity; } if (positionLimited) { if (viewMode > (cropped ? 0 : 1)) { var newCanvasLeft = containerData.width - canvasData.width; var newCanvasTop = containerData.height - canvasData.height; canvasData.minLeft = Math.min(0, newCanvasLeft); canvasData.minTop = Math.min(0, newCanvasTop); canvasData.maxLeft = Math.max(0, newCanvasLeft); canvasData.maxTop = Math.max(0, newCanvasTop); if (cropped && this.limited) { canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width)); canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height)); canvasData.maxLeft = cropBoxData.left; canvasData.maxTop = cropBoxData.top; if (viewMode === 2) { if (canvasData.width >= containerData.width) { canvasData.minLeft = Math.min(0, newCanvasLeft); canvasData.maxLeft = Math.max(0, newCanvasLeft); } if (canvasData.height >= containerData.height) { canvasData.minTop = Math.min(0, newCanvasTop); canvasData.maxTop = Math.max(0, newCanvasTop); } } } } else { canvasData.minLeft = -canvasData.width; canvasData.minTop = -canvasData.height; canvasData.maxLeft = containerData.width; canvasData.maxTop = containerData.height; } } }, renderCanvas: function renderCanvas(changed, transformed) { var canvasData = this.canvasData, imageData = this.imageData; if (transformed) { var _getRotatedSizes = getRotatedSizes({ width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1), height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1), degree: imageData.rotate || 0 }), naturalWidth = _getRotatedSizes.width, naturalHeight = _getRotatedSizes.height; var width = canvasData.width * (naturalWidth / canvasData.naturalWidth); var height = canvasData.height * (naturalHeight / canvasData.naturalHeight); canvasData.left -= (width - canvasData.width) / 2; canvasData.top -= (height - canvasData.height) / 2; canvasData.width = width; canvasData.height = height; canvasData.aspectRatio = naturalWidth / naturalHeight; canvasData.naturalWidth = naturalWidth; canvasData.naturalHeight = naturalHeight; this.limitCanvas(true, false); } if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) { canvasData.left = canvasData.oldLeft; } if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) { canvasData.top = canvasData.oldTop; } canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth); canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight); this.limitCanvas(false, true); canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft); canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop); canvasData.oldLeft = canvasData.left; canvasData.oldTop = canvasData.top; setStyle(this.canvas, assign2({ width: canvasData.width, height: canvasData.height }, getTransforms({ translateX: canvasData.left, translateY: canvasData.top }))); this.renderImage(changed); if (this.cropped && this.limited) { this.limitCropBox(true, true); } }, renderImage: function renderImage(changed) { var canvasData = this.canvasData, imageData = this.imageData; var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth); var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight); assign2(imageData, { width, height, left: (canvasData.width - width) / 2, top: (canvasData.height - height) / 2 }); setStyle(this.image, assign2({ width: imageData.width, height: imageData.height }, getTransforms(assign2({ translateX: imageData.left, translateY: imageData.top }, imageData)))); if (changed) { this.output(); } }, initCropBox: function initCropBox() { var options2 = this.options, canvasData = this.canvasData; var aspectRatio = options2.aspectRatio || options2.initialAspectRatio; var autoCropArea = Number(options2.autoCropArea) || 0.8; var cropBoxData = { width: canvasData.width, height: canvasData.height }; if (aspectRatio) { if (canvasData.height * aspectRatio > canvasData.width) { cropBoxData.height = cropBoxData.width / aspectRatio; } else { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.cropBoxData = cropBoxData; this.limitCropBox(true, true); cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth); cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea); cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea); cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2; cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2; cropBoxData.oldLeft = cropBoxData.left; cropBoxData.oldTop = cropBoxData.top; this.initialCropBoxData = assign2({}, cropBoxData); }, limitCropBox: function limitCropBox(sizeLimited, positionLimited) { var options2 = this.options, containerData = this.containerData, canvasData = this.canvasData, cropBoxData = this.cropBoxData, limited = this.limited; var aspectRatio = options2.aspectRatio; if (sizeLimited) { var minCropBoxWidth = Number(options2.minCropBoxWidth) || 0; var minCropBoxHeight = Number(options2.minCropBoxHeight) || 0; var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width; var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height; minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width); minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height); if (aspectRatio) { if (minCropBoxWidth && minCropBoxHeight) { if (minCropBoxHeight * aspectRatio > minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else { minCropBoxWidth = minCropBoxHeight * aspectRatio; } } else if (minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else if (minCropBoxHeight) { minCropBoxWidth = minCropBoxHeight * aspectRatio; } if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) { maxCropBoxHeight = maxCropBoxWidth / aspectRatio; } else { maxCropBoxWidth = maxCropBoxHeight * aspectRatio; } } cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth); cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight); cropBoxData.maxWidth = maxCropBoxWidth; cropBoxData.maxHeight = maxCropBoxHeight; } if (positionLimited) { if (limited) { cropBoxData.minLeft = Math.max(0, canvasData.left); cropBoxData.minTop = Math.max(0, canvasData.top); cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width; cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height; } else { cropBoxData.minLeft = 0; cropBoxData.minTop = 0; cropBoxData.maxLeft = containerData.width - cropBoxData.width; cropBoxData.maxTop = containerData.height - cropBoxData.height; } } }, renderCropBox: function renderCropBox() { var options2 = this.options, containerData = this.containerData, cropBoxData = this.cropBoxData; if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) { cropBoxData.left = cropBoxData.oldLeft; } if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) { cropBoxData.top = cropBoxData.oldTop; } cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth); cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); this.limitCropBox(false, true); cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft); cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop); cropBoxData.oldLeft = cropBoxData.left; cropBoxData.oldTop = cropBoxData.top; if (options2.movable && options2.cropBoxMovable) { setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL); } setStyle(this.cropBox, assign2({ width: cropBoxData.width, height: cropBoxData.height }, getTransforms({ translateX: cropBoxData.left, translateY: cropBoxData.top }))); if (this.cropped && this.limited) { this.limitCanvas(true, true); } if (!this.disabled) { this.output(); } }, output: function output() { this.preview(); dispatchEvent(this.element, EVENT_CROP, this.getData()); } }; var preview = { initPreview: function initPreview() { var element = this.element, crossOrigin = this.crossOrigin; var preview3 = this.options.preview; var url = crossOrigin ? this.crossOriginUrl : this.url; var alt = element.alt || "The image to preview"; var image = document.createElement("img"); if (crossOrigin) { image.crossOrigin = crossOrigin; } image.src = url; image.alt = alt; this.viewBox.appendChild(image); this.viewBoxImage = image; if (!preview3) { return; } var previews = preview3; if (typeof preview3 === "string") { previews = element.ownerDocument.querySelectorAll(preview3); } else if (preview3.querySelector) { previews = [preview3]; } this.previews = previews; forEach(previews, function(el) { var img = document.createElement("img"); setData(el, DATA_PREVIEW, { width: el.offsetWidth, height: el.offsetHeight, html: el.innerHTML }); if (crossOrigin) { img.crossOrigin = crossOrigin; } img.src = url; img.alt = alt; img.style.cssText = 'display:block;width:100%;height:auto;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation:0deg!important;"'; el.innerHTML = ""; el.appendChild(img); }); }, resetPreview: function resetPreview() { forEach(this.previews, function(element) { var data = getData(element, DATA_PREVIEW); setStyle(element, { width: data.width, height: data.height }); element.innerHTML = data.html; removeData(element, DATA_PREVIEW); }); }, preview: function preview2() { var imageData = this.imageData, canvasData = this.canvasData, cropBoxData = this.cropBoxData; var cropBoxWidth = cropBoxData.width, cropBoxHeight = cropBoxData.height; var width = imageData.width, height = imageData.height; var left = cropBoxData.left - canvasData.left - imageData.left; var top = cropBoxData.top - canvasData.top - imageData.top; if (!this.cropped || this.disabled) { return; } setStyle(this.viewBoxImage, assign2({ width, height }, getTransforms(assign2({ translateX: -left, translateY: -top }, imageData)))); forEach(this.previews, function(element) { var data = getData(element, DATA_PREVIEW); var originalWidth = data.width; var originalHeight = data.height; var newWidth = originalWidth; var newHeight = originalHeight; var ratio = 1; if (cropBoxWidth) { ratio = originalWidth / cropBoxWidth; newHeight = cropBoxHeight * ratio; } if (cropBoxHeight && newHeight > originalHeight) { ratio = originalHeight / cropBoxHeight; newWidth = cropBoxWidth * ratio; newHeight = originalHeight; } setStyle(element, { width: newWidth, height: newHeight }); setStyle(element.getElementsByTagName("img")[0], assign2({ width: width * ratio, height: height * ratio }, getTransforms(assign2({ translateX: -left * ratio, translateY: -top * ratio }, imageData)))); }); } }; var events = { bind: function bind() { var element = this.element, options2 = this.options, cropper = this.cropper; if (isFunction(options2.cropstart)) { addListener(element, EVENT_CROP_START, options2.cropstart); } if (isFunction(options2.cropmove)) { addListener(element, EVENT_CROP_MOVE, options2.cropmove); } if (isFunction(options2.cropend)) { addListener(element, EVENT_CROP_END, options2.cropend); } if (isFunction(options2.crop)) { addListener(element, EVENT_CROP, options2.crop); } if (isFunction(options2.zoom)) { addListener(element, EVENT_ZOOM, options2.zoom); } addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this)); if (options2.zoomable && options2.zoomOnWheel) { addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), { passive: false, capture: true }); } if (options2.toggleDragModeOnDblclick) { addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this)); } addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this)); addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this)); if (options2.responsive) { addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this)); } }, unbind: function unbind() { var element = this.element, options2 = this.options, cropper = this.cropper; if (isFunction(options2.cropstart)) { removeListener(element, EVENT_CROP_START, options2.cropstart); } if (isFunction(options2.cropmove)) { removeListener(element, EVENT_CROP_MOVE, options2.cropmove); } if (isFunction(options2.cropend)) { removeListener(element, EVENT_CROP_END, options2.cropend); } if (isFunction(options2.crop)) { removeListener(element, EVENT_CROP, options2.crop); } if (isFunction(options2.zoom)) { removeListener(element, EVENT_ZOOM, options2.zoom); } removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart); if (options2.zoomable && options2.zoomOnWheel) { removeListener(cropper, EVENT_WHEEL, this.onWheel, { passive: false, capture: true }); } if (options2.toggleDragModeOnDblclick) { removeListener(cropper, EVENT_DBLCLICK, this.onDblclick); } removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove); removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd); if (options2.responsive) { removeListener(window, EVENT_RESIZE, this.onResize); } } }; var handlers = { resize: function resize() { if (this.disabled) { return; } var options2 = this.options, container = this.container, containerData = this.containerData; var ratioX = container.offsetWidth / containerData.width; var ratioY = container.offsetHeight / containerData.height; var ratio = Math.abs(ratioX - 1) > Math.abs(ratioY - 1) ? ratioX : ratioY; if (ratio !== 1) { var canvasData; var cropBoxData; if (options2.restore) { canvasData = this.getCanvasData(); cropBoxData = this.getCropBoxData(); } this.render(); if (options2.restore) { this.setCanvasData(forEach(canvasData, function(n2, i3) { canvasData[i3] = n2 * ratio; })); this.setCropBoxData(forEach(cropBoxData, function(n2, i3) { cropBoxData[i3] = n2 * ratio; })); } } }, dblclick: function dblclick() { if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) { return; } this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP); }, wheel: function wheel(event) { var _this = this; var ratio = Number(this.options.wheelZoomRatio) || 0.1; var delta = 1; if (this.disabled) { return; } event.preventDefault(); if (this.wheeling) { return; } this.wheeling = true; setTimeout(function() { _this.wheeling = false; }, 50); if (event.deltaY) { delta = event.deltaY > 0 ? 1 : -1; } else if (event.wheelDelta) { delta = -event.wheelDelta / 120; } else if (event.detail) { delta = event.detail > 0 ? 1 : -1; } this.zoom(-delta * ratio, event); }, cropStart: function cropStart(event) { var buttons = event.buttons, button = event.button; if (this.disabled || (event.type === "mousedown" || event.type === "pointerdown" && event.pointerType === "mouse") && // No primary button (Usually the left button) (isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 || event.ctrlKey)) { return; } var options2 = this.options, pointers = this.pointers; var action; if (event.changedTouches) { forEach(event.changedTouches, function(touch) { pointers[touch.identifier] = getPointer(touch); }); } else { pointers[event.pointerId || 0] = getPointer(event); } if (Object.keys(pointers).length > 1 && options2.zoomable && options2.zoomOnTouch) { action = ACTION_ZOOM; } else { action = getData(event.target, DATA_ACTION); } if (!REGEXP_ACTIONS.test(action)) { return; } if (dispatchEvent(this.element, EVENT_CROP_START, { originalEvent: event, action }) === false) { return; } event.preventDefault(); this.action = action; this.cropping = false; if (action === ACTION_CROP) { this.cropping = true; addClass(this.dragBox, CLASS_MODAL); } }, cropMove: function cropMove(event) { var action = this.action; if (this.disabled || !action) { return; } var pointers = this.pointers; event.preventDefault(); if (dispatchEvent(this.element, EVENT_CROP_MOVE, { originalEvent: event, action }) === false) { return; } if (event.changedTouches) { forEach(event.changedTouches, function(touch) { assign2(pointers[touch.identifier] || {}, getPointer(touch, true)); }); } else { assign2(pointers[event.pointerId || 0] || {}, getPointer(event, true)); } this.change(event); }, cropEnd: function cropEnd(event) { if (this.disabled) { return; } var action = this.action, pointers = this.pointers; if (event.changedTouches) { forEach(event.changedTouches, function(touch) { delete pointers[touch.identifier]; }); } else { delete pointers[event.pointerId || 0]; } if (!action) { return; } event.preventDefault(); if (!Object.keys(pointers).length) { this.action = ""; } if (this.cropping) { this.cropping = false; toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal); } dispatchEvent(this.element, EVENT_CROP_END, { originalEvent: event, action }); } }; var change = { change: function change2(event) { var options2 = this.options, canvasData = this.canvasData, containerData = this.containerData, cropBoxData = this.cropBoxData, pointers = this.pointers; var action = this.action; var aspectRatio = options2.aspectRatio; var left = cropBoxData.left, top = cropBoxData.top, width = cropBoxData.width, height = cropBoxData.height; var right = left + width; var bottom = top + height; var minLeft = 0; var minTop = 0; var maxWidth = containerData.width; var maxHeight = containerData.height; var renderable = true; var offset; if (!aspectRatio && event.shiftKey) { aspectRatio = width && height ? width / height : 1; } if (this.limited) { minLeft = cropBoxData.minLeft; minTop = cropBoxData.minTop; maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width); maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height); } var pointer = pointers[Object.keys(pointers)[0]]; var range = { x: pointer.endX - pointer.startX, y: pointer.endY - pointer.startY }; var check = function check2(side) { switch (side) { case ACTION_EAST: if (right + range.x > maxWidth) { range.x = maxWidth - right; } break; case ACTION_WEST: if (left + range.x < minLeft) { range.x = minLeft - left; } break; case ACTION_NORTH: if (top + range.y < minTop) { range.y = minTop - top; } break; case ACTION_SOUTH: if (bottom + range.y > maxHeight) { range.y = maxHeight - bottom; } break; } }; switch (action) { case ACTION_ALL: left += range.x; top += range.y; break; case ACTION_EAST: if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) { renderable = false; break; } check(ACTION_EAST); width += range.x; if (width < 0) { action = ACTION_WEST; width = -width; left -= width; } if (aspectRatio) { height = width / aspectRatio; top += (cropBoxData.height - height) / 2; } break; case ACTION_NORTH: if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) { renderable = false; break; } check(ACTION_NORTH); height -= range.y; top += range.y; if (height < 0) { action = ACTION_SOUTH; height = -height; top -= height; } if (aspectRatio) { width = height * aspectRatio; left += (cropBoxData.width - width) / 2; } break; case ACTION_WEST: if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) { renderable = false; break; } check(ACTION_WEST); width -= range.x; left += range.x; if (width < 0) { action = ACTION_EAST; width = -width; left -= width; } if (aspectRatio) { height = width / aspectRatio; top += (cropBoxData.height - height) / 2; } break; case ACTION_SOUTH: if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) { renderable = false; break; } check(ACTION_SOUTH); height += range.y; if (height < 0) { action = ACTION_NORTH; height = -height; top -= height; } if (aspectRatio) { width = height * aspectRatio; left += (cropBoxData.width - width) / 2; } break; case ACTION_NORTH_EAST: if (aspectRatio) { if (range.y <= 0 && (top <= minTop || right >= maxWidth)) { renderable = false; break; } check(ACTION_NORTH); height -= range.y; top += range.y; width = height * aspectRatio; } else { check(ACTION_NORTH); check(ACTION_EAST); if (range.x >= 0) { if (right < maxWidth) { width += range.x; } else if (range.y <= 0 && top <= minTop) { renderable = false; } } else { width += range.x; } if (range.y <= 0) { if (top > minTop) { height -= range.y; top += range.y; } } else { height -= range.y; top += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_WEST; height = -height; width = -width; top -= height; left -= width; } else if (width < 0) { action = ACTION_NORTH_WEST; width = -width; left -= width; } else if (height < 0) { action = ACTION_SOUTH_EAST; height = -height; top -= height; } break; case ACTION_NORTH_WEST: if (aspectRatio) { if (range.y <= 0 && (top <= minTop || left <= minLeft)) { renderable = false; break; } check(ACTION_NORTH); height -= range.y; top += range.y; width = height * aspectRatio; left += cropBoxData.width - width; } else { check(ACTION_NORTH); check(ACTION_WEST); if (range.x <= 0) { if (left > minLeft) { width -= range.x; left += range.x; } else if (range.y <= 0 && top <= minTop) { renderable = false; } } else { width -= range.x; left += range.x; } if (range.y <= 0) { if (top > minTop) { height -= range.y; top += range.y; } } else { height -= range.y; top += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_EAST; height = -height; width = -width; top -= height; left -= width; } else if (width < 0) { action = ACTION_NORTH_EAST; width = -width; left -= width; } else if (height < 0) { action = ACTION_SOUTH_WEST; height = -height; top -= height; } break; case ACTION_SOUTH_WEST: if (aspectRatio) { if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) { renderable = false; break; } check(ACTION_WEST); width -= range.x; left += range.x; height = width / aspectRatio; } else { check(ACTION_SOUTH); check(ACTION_WEST); if (range.x <= 0) { if (left > minLeft) { width -= range.x; left += range.x; } else if (range.y >= 0 && bottom >= maxHeight) { renderable = false; } } else { width -= range.x; left += range.x; } if (range.y >= 0) { if (bottom < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_EAST; height = -height; width = -width; top -= height; left -= width; } else if (width < 0) { action = ACTION_SOUTH_EAST; width = -width; left -= width; } else if (height < 0) { action = ACTION_NORTH_WEST; height = -height; top -= height; } break; case ACTION_SOUTH_EAST: if (aspectRatio) { if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) { renderable = false; break; } check(ACTION_EAST); width += range.x; height = width / aspectRatio; } else { check(ACTION_SOUTH); check(ACTION_EAST); if (range.x >= 0) { if (right < maxWidth) { width += range.x; } else if (range.y >= 0 && bottom >= maxHeight) { renderable = false; } } else { width += range.x; } if (range.y >= 0) { if (bottom < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_WEST; height = -height; width = -width; top -= height; left -= width; } else if (width < 0) { action = ACTION_SOUTH_WEST; width = -width; left -= width; } else if (height < 0) { action = ACTION_NORTH_EAST; height = -height; top -= height; } break; case ACTION_MOVE: this.move(range.x, range.y); renderable = false; break; case ACTION_ZOOM: this.zoom(getMaxZoomRatio(pointers), event); renderable = false; break; case ACTION_CROP: if (!range.x || !range.y) { renderable = false; break; } offset = getOffset(this.cropper); left = pointer.startX - offset.left; top = pointer.startY - offset.top; width = cropBoxData.minWidth; height = cropBoxData.minHeight; if (range.x > 0) { action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST; } else if (range.x < 0) { left -= width; action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST; } if (range.y < 0) { top -= height; } if (!this.cropped) { removeClass(this.cropBox, CLASS_HIDDEN); this.cropped = true; if (this.limited) { this.limitCropBox(true, true); } } break; } if (renderable) { cropBoxData.width = width; cropBoxData.height = height; cropBoxData.left = left; cropBoxData.top = top; this.action = action; this.renderCropBox(); } forEach(pointers, function(p3) { p3.startX = p3.endX; p3.startY = p3.endY; }); } }; var methods = { // Show the crop box manually crop: function crop() { if (this.ready && !this.cropped && !this.disabled) { this.cropped = true; this.limitCropBox(true, true); if (this.options.modal) { addClass(this.dragBox, CLASS_MODAL); } removeClass(this.cropBox, CLASS_HIDDEN); this.setCropBoxData(this.initialCropBoxData); } return this; }, // Reset the image and crop box to their initial states reset: function reset() { if (this.ready && !this.disabled) { this.imageData = assign2({}, this.initialImageData); this.canvasData = assign2({}, this.initialCanvasData); this.cropBoxData = assign2({}, this.initialCropBoxData); this.renderCanvas(); if (this.cropped) { this.renderCropBox(); } } return this; }, // Clear the crop box clear: function clear() { if (this.cropped && !this.disabled) { assign2(this.cropBoxData, { left: 0, top: 0, width: 0, height: 0 }); this.cropped = false; this.renderCropBox(); this.limitCanvas(true, true); this.renderCanvas(); removeClass(this.dragBox, CLASS_MODAL); addClass(this.cropBox, CLASS_HIDDEN); } return this; }, /** * Replace the image's src and rebuild the cropper * @param {string} url - The new URL. * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one. * @returns {Cropper} this */ replace: function replace2(url) { var hasSameSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; if (!this.disabled && url) { if (this.isImg) { this.element.src = url; } if (hasSameSize) { this.url = url; this.image.src = url; if (this.ready) { this.viewBoxImage.src = url; forEach(this.previews, function(element) { element.getElementsByTagName("img")[0].src = url; }); } } else { if (this.isImg) { this.replaced = true; } this.options.data = null; this.uncreate(); this.load(url); } } return this; }, // Enable (unfreeze) the cropper enable: function enable() { if (this.ready && this.disabled) { this.disabled = false; removeClass(this.cropper, CLASS_DISABLED); } return this; }, // Disable (freeze) the cropper disable: function disable() { if (this.ready && !this.disabled) { this.disabled = true; addClass(this.cropper, CLASS_DISABLED); } return this; }, /** * Destroy the cropper and remove the instance from the image * @returns {Cropper} this */ destroy: function destroy() { var element = this.element; if (!element[NAMESPACE]) { return this; } element[NAMESPACE] = void 0; if (this.isImg && this.replaced) { element.src = this.originalUrl; } this.uncreate(); return this; }, /** * Move the canvas with relative offsets * @param {number} offsetX - The relative offset distance on the x-axis. * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis. * @returns {Cropper} this */ move: function move(offsetX) { var offsetY = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : offsetX; var _this$canvasData = this.canvasData, left = _this$canvasData.left, top = _this$canvasData.top; return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY)); }, /** * Move the canvas to an absolute point * @param {number} x - The x-axis coordinate. * @param {number} [y=x] - The y-axis coordinate. * @returns {Cropper} this */ moveTo: function moveTo(x2) { var y4 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : x2; var canvasData = this.canvasData; var changed = false; x2 = Number(x2); y4 = Number(y4); if (this.ready && !this.disabled && this.options.movable) { if (isNumber(x2)) { canvasData.left = x2; changed = true; } if (isNumber(y4)) { canvasData.top = y4; changed = true; } if (changed) { this.renderCanvas(true); } } return this; }, /** * Zoom the canvas with a relative ratio * @param {number} ratio - The target ratio. * @param {Event} _originalEvent - The original event if any. * @returns {Cropper} this */ zoom: function zoom(ratio, _originalEvent) { var canvasData = this.canvasData; ratio = Number(ratio); if (ratio < 0) { ratio = 1 / (1 - ratio); } else { ratio = 1 + ratio; } return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent); }, /** * Zoom the canvas to an absolute ratio * @param {number} ratio - The target ratio. * @param {Object} pivot - The zoom pivot point coordinate. * @param {Event} _originalEvent - The original event if any. * @returns {Cropper} this */ zoomTo: function zoomTo(ratio, pivot, _originalEvent) { var options2 = this.options, canvasData = this.canvasData; var width = canvasData.width, height = canvasData.height, naturalWidth = canvasData.naturalWidth, naturalHeight = canvasData.naturalHeight; ratio = Number(ratio); if (ratio >= 0 && this.ready && !this.disabled && options2.zoomable) { var newWidth = naturalWidth * ratio; var newHeight = naturalHeight * ratio; if (dispatchEvent(this.element, EVENT_ZOOM, { ratio, oldRatio: width / naturalWidth, originalEvent: _originalEvent }) === false) { return this; } if (_originalEvent) { var pointers = this.pointers; var offset = getOffset(this.cropper); var center2 = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : { pageX: _originalEvent.pageX, pageY: _originalEvent.pageY }; canvasData.left -= (newWidth - width) * ((center2.pageX - offset.left - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((center2.pageY - offset.top - canvasData.top) / height); } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) { canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height); } else { canvasData.left -= (newWidth - width) / 2; canvasData.top -= (newHeight - height) / 2; } canvasData.width = newWidth; canvasData.height = newHeight; this.renderCanvas(true); } return this; }, /** * Rotate the canvas with a relative degree * @param {number} degree - The rotate degree. * @returns {Cropper} this */ rotate: function rotate(degree) { return this.rotateTo((this.imageData.rotate || 0) + Number(degree)); }, /** * Rotate the canvas to an absolute degree * @param {number} degree - The rotate degree. * @returns {Cropper} this */ rotateTo: function rotateTo(degree) { degree = Number(degree); if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) { this.imageData.rotate = degree % 360; this.renderCanvas(true, true); } return this; }, /** * Scale the image on the x-axis. * @param {number} scaleX - The scale ratio on the x-axis. * @returns {Cropper} this */ scaleX: function scaleX(_scaleX) { var scaleY2 = this.imageData.scaleY; return this.scale(_scaleX, isNumber(scaleY2) ? scaleY2 : 1); }, /** * Scale the image on the y-axis. * @param {number} scaleY - The scale ratio on the y-axis. * @returns {Cropper} this */ scaleY: function scaleY(_scaleY) { var scaleX2 = this.imageData.scaleX; return this.scale(isNumber(scaleX2) ? scaleX2 : 1, _scaleY); }, /** * Scale the image * @param {number} scaleX - The scale ratio on the x-axis. * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis. * @returns {Cropper} this */ scale: function scale(scaleX2) { var scaleY2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : scaleX2; var imageData = this.imageData; var transformed = false; scaleX2 = Number(scaleX2); scaleY2 = Number(scaleY2); if (this.ready && !this.disabled && this.options.scalable) { if (isNumber(scaleX2)) { imageData.scaleX = scaleX2; transformed = true; } if (isNumber(scaleY2)) { imageData.scaleY = scaleY2; transformed = true; } if (transformed) { this.renderCanvas(true, true); } } return this; }, /** * Get the cropped area position and size data (base on the original image) * @param {boolean} [rounded=false] - Indicate if round the data values or not. * @returns {Object} The result cropped data. */ getData: function getData2() { var rounded = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false; var options2 = this.options, imageData = this.imageData, canvasData = this.canvasData, cropBoxData = this.cropBoxData; var data; if (this.ready && this.cropped) { data = { x: cropBoxData.left - canvasData.left, y: cropBoxData.top - canvasData.top, width: cropBoxData.width, height: cropBoxData.height }; var ratio = imageData.width / imageData.naturalWidth; forEach(data, function(n2, i3) { data[i3] = n2 / ratio; }); if (rounded) { var bottom = Math.round(data.y + data.height); var right = Math.round(data.x + data.width); data.x = Math.round(data.x); data.y = Math.round(data.y); data.width = right - data.x; data.height = bottom - data.y; } } else { data = { x: 0, y: 0, width: 0, height: 0 }; } if (options2.rotatable) { data.rotate = imageData.rotate || 0; } if (options2.scalable) { data.scaleX = imageData.scaleX || 1; data.scaleY = imageData.scaleY || 1; } return data; }, /** * Set the cropped area position and size with new data * @param {Object} data - The new data. * @returns {Cropper} this */ setData: function setData2(data) { var options2 = this.options, imageData = this.imageData, canvasData = this.canvasData; var cropBoxData = {}; if (this.ready && !this.disabled && isPlainObject(data)) { var transformed = false; if (options2.rotatable) { if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { imageData.rotate = data.rotate; transformed = true; } } if (options2.scalable) { if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { imageData.scaleX = data.scaleX; transformed = true; } if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { imageData.scaleY = data.scaleY; transformed = true; } } if (transformed) { this.renderCanvas(true, true); } var ratio = imageData.width / imageData.naturalWidth; if (isNumber(data.x)) { cropBoxData.left = data.x * ratio + canvasData.left; } if (isNumber(data.y)) { cropBoxData.top = data.y * ratio + canvasData.top; } if (isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (isNumber(data.height)) { cropBoxData.height = data.height * ratio; } this.setCropBoxData(cropBoxData); } return this; }, /** * Get the container size data. * @returns {Object} The result container data. */ getContainerData: function getContainerData() { return this.ready ? assign2({}, this.containerData) : {}; }, /** * Get the image position and size data. * @returns {Object} The result image data. */ getImageData: function getImageData() { return this.sized ? assign2({}, this.imageData) : {}; }, /** * Get the canvas position and size data. * @returns {Object} The result canvas data. */ getCanvasData: function getCanvasData() { var canvasData = this.canvasData; var data = {}; if (this.ready) { forEach(["left", "top", "width", "height", "naturalWidth", "naturalHeight"], function(n2) { data[n2] = canvasData[n2]; }); } return data; }, /** * Set the canvas position and size with new data. * @param {Object} data - The new canvas data. * @returns {Cropper} this */ setCanvasData: function setCanvasData(data) { var canvasData = this.canvasData; var aspectRatio = canvasData.aspectRatio; if (this.ready && !this.disabled && isPlainObject(data)) { if (isNumber(data.left)) { canvasData.left = data.left; } if (isNumber(data.top)) { canvasData.top = data.top; } if (isNumber(data.width)) { canvasData.width = data.width; canvasData.height = data.width / aspectRatio; } else if (isNumber(data.height)) { canvasData.height = data.height; canvasData.width = data.height * aspectRatio; } this.renderCanvas(true); } return this; }, /** * Get the crop box position and size data. * @returns {Object} The result crop box data. */ getCropBoxData: function getCropBoxData() { var cropBoxData = this.cropBoxData; var data; if (this.ready && this.cropped) { data = { left: cropBoxData.left, top: cropBoxData.top, width: cropBoxData.width, height: cropBoxData.height }; } return data || {}; }, /** * Set the crop box position and size with new data. * @param {Object} data - The new crop box data. * @returns {Cropper} this */ setCropBoxData: function setCropBoxData(data) { var cropBoxData = this.cropBoxData; var aspectRatio = this.options.aspectRatio; var widthChanged; var heightChanged; if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) { if (isNumber(data.left)) { cropBoxData.left = data.left; } if (isNumber(data.top)) { cropBoxData.top = data.top; } if (isNumber(data.width) && data.width !== cropBoxData.width) { widthChanged = true; cropBoxData.width = data.width; } if (isNumber(data.height) && data.height !== cropBoxData.height) { heightChanged = true; cropBoxData.height = data.height; } if (aspectRatio) { if (widthChanged) { cropBoxData.height = cropBoxData.width / aspectRatio; } else if (heightChanged) { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.renderCropBox(); } return this; }, /** * Get a canvas drawn the cropped image. * @param {Object} [options={}] - The config options. * @returns {HTMLCanvasElement} - The result canvas. */ getCroppedCanvas: function getCroppedCanvas() { var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; if (!this.ready || !window.HTMLCanvasElement) { return null; } var canvasData = this.canvasData; var source = getSourceCanvas(this.image, this.imageData, canvasData, options2); if (!this.cropped) { return source; } var _this$getData = this.getData(options2.rounded), initialX = _this$getData.x, initialY = _this$getData.y, initialWidth = _this$getData.width, initialHeight = _this$getData.height; var ratio = source.width / Math.floor(canvasData.naturalWidth); if (ratio !== 1) { initialX *= ratio; initialY *= ratio; initialWidth *= ratio; initialHeight *= ratio; } var aspectRatio = initialWidth / initialHeight; var maxSizes = getAdjustedSizes({ aspectRatio, width: options2.maxWidth || Infinity, height: options2.maxHeight || Infinity }); var minSizes = getAdjustedSizes({ aspectRatio, width: options2.minWidth || 0, height: options2.minHeight || 0 }, "cover"); var _getAdjustedSizes = getAdjustedSizes({ aspectRatio, width: options2.width || (ratio !== 1 ? source.width : initialWidth), height: options2.height || (ratio !== 1 ? source.height : initialHeight) }), width = _getAdjustedSizes.width, height = _getAdjustedSizes.height; width = Math.min(maxSizes.width, Math.max(minSizes.width, width)); height = Math.min(maxSizes.height, Math.max(minSizes.height, height)); var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); canvas.width = normalizeDecimalNumber(width); canvas.height = normalizeDecimalNumber(height); context.fillStyle = options2.fillColor || "transparent"; context.fillRect(0, 0, width, height); var _options$imageSmoothi = options2.imageSmoothingEnabled, imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi, imageSmoothingQuality = options2.imageSmoothingQuality; context.imageSmoothingEnabled = imageSmoothingEnabled; if (imageSmoothingQuality) { context.imageSmoothingQuality = imageSmoothingQuality; } var sourceWidth = source.width; var sourceHeight = source.height; var srcX = initialX; var srcY = initialY; var srcWidth; var srcHeight; var dstX; var dstY; var dstWidth; var dstHeight; if (srcX <= -initialWidth || srcX > sourceWidth) { srcX = 0; srcWidth = 0; dstX = 0; dstWidth = 0; } else if (srcX <= 0) { dstX = -srcX; srcX = 0; srcWidth = Math.min(sourceWidth, initialWidth + srcX); dstWidth = srcWidth; } else if (srcX <= sourceWidth) { dstX = 0; srcWidth = Math.min(initialWidth, sourceWidth - srcX); dstWidth = srcWidth; } if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) { srcY = 0; srcHeight = 0; dstY = 0; dstHeight = 0; } else if (srcY <= 0) { dstY = -srcY; srcY = 0; srcHeight = Math.min(sourceHeight, initialHeight + srcY); dstHeight = srcHeight; } else if (srcY <= sourceHeight) { dstY = 0; srcHeight = Math.min(initialHeight, sourceHeight - srcY); dstHeight = srcHeight; } var params = [srcX, srcY, srcWidth, srcHeight]; if (dstWidth > 0 && dstHeight > 0) { var scale2 = width / initialWidth; params.push(dstX * scale2, dstY * scale2, dstWidth * scale2, dstHeight * scale2); } context.drawImage.apply(context, [source].concat(_toConsumableArray2(params.map(function(param) { return Math.floor(normalizeDecimalNumber(param)); })))); return canvas; }, /** * Change the aspect ratio of the crop box. * @param {number} aspectRatio - The new aspect ratio. * @returns {Cropper} this */ setAspectRatio: function setAspectRatio(aspectRatio) { var options2 = this.options; if (!this.disabled && !isUndefined(aspectRatio)) { options2.aspectRatio = Math.max(0, aspectRatio) || NaN; if (this.ready) { this.initCropBox(); if (this.cropped) { this.renderCropBox(); } } } return this; }, /** * Change the drag mode. * @param {string} mode - The new drag mode. * @returns {Cropper} this */ setDragMode: function setDragMode(mode) { var options2 = this.options, dragBox = this.dragBox, face = this.face; if (this.ready && !this.disabled) { var croppable = mode === DRAG_MODE_CROP; var movable = options2.movable && mode === DRAG_MODE_MOVE; mode = croppable || movable ? mode : DRAG_MODE_NONE; options2.dragMode = mode; setData(dragBox, DATA_ACTION, mode); toggleClass(dragBox, CLASS_CROP, croppable); toggleClass(dragBox, CLASS_MOVE, movable); if (!options2.cropBoxMovable) { setData(face, DATA_ACTION, mode); toggleClass(face, CLASS_CROP, croppable); toggleClass(face, CLASS_MOVE, movable); } } return this; } }; var AnotherCropper = WINDOW.Cropper; var Cropper = function() { function Cropper2(element) { var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; _classCallCheck2(this, Cropper2); if (!element || !REGEXP_TAG_NAME.test(element.tagName)) { throw new Error("The first argument is required and must be an or element."); } this.element = element; this.options = assign2({}, DEFAULTS, isPlainObject(options2) && options2); this.cropped = false; this.disabled = false; this.pointers = {}; this.ready = false; this.reloading = false; this.replaced = false; this.sized = false; this.sizing = false; this.init(); } _createClass2(Cropper2, [{ key: "init", value: function init() { var element = this.element; var tagName = element.tagName.toLowerCase(); var url; if (element[NAMESPACE]) { return; } element[NAMESPACE] = this; if (tagName === "img") { this.isImg = true; url = element.getAttribute("src") || ""; this.originalUrl = url; if (!url) { return; } url = element.src; } else if (tagName === "canvas" && window.HTMLCanvasElement) { url = element.toDataURL(); } this.load(url); } }, { key: "load", value: function load(url) { var _this = this; if (!url) { return; } this.url = url; this.imageData = {}; var element = this.element, options2 = this.options; if (!options2.rotatable && !options2.scalable) { options2.checkOrientation = false; } if (!options2.checkOrientation || !window.ArrayBuffer) { this.clone(); return; } if (REGEXP_DATA_URL.test(url)) { if (REGEXP_DATA_URL_JPEG.test(url)) { this.read(dataURLToArrayBuffer(url)); } else { this.clone(); } return; } var xhr = new XMLHttpRequest(); var clone = this.clone.bind(this); this.reloading = true; this.xhr = xhr; xhr.onabort = clone; xhr.onerror = clone; xhr.ontimeout = clone; xhr.onprogress = function() { if (xhr.getResponseHeader("content-type") !== MIME_TYPE_JPEG) { xhr.abort(); } }; xhr.onload = function() { _this.read(xhr.response); }; xhr.onloadend = function() { _this.reloading = false; _this.xhr = null; }; if (options2.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) { url = addTimestamp(url); } xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; xhr.withCredentials = element.crossOrigin === "use-credentials"; xhr.send(); } }, { key: "read", value: function read(arrayBuffer) { var options2 = this.options, imageData = this.imageData; var orientation = resetAndGetOrientation(arrayBuffer); var rotate2 = 0; var scaleX2 = 1; var scaleY2 = 1; if (orientation > 1) { this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG); var _parseOrientation = parseOrientation(orientation); rotate2 = _parseOrientation.rotate; scaleX2 = _parseOrientation.scaleX; scaleY2 = _parseOrientation.scaleY; } if (options2.rotatable) { imageData.rotate = rotate2; } if (options2.scalable) { imageData.scaleX = scaleX2; imageData.scaleY = scaleY2; } this.clone(); } }, { key: "clone", value: function clone() { var element = this.element, url = this.url; var crossOrigin = element.crossOrigin; var crossOriginUrl = url; if (this.options.checkCrossOrigin && isCrossOriginURL(url)) { if (!crossOrigin) { crossOrigin = "anonymous"; } crossOriginUrl = addTimestamp(url); } this.crossOrigin = crossOrigin; this.crossOriginUrl = crossOriginUrl; var image = document.createElement("img"); if (crossOrigin) { image.crossOrigin = crossOrigin; } image.src = crossOriginUrl || url; image.alt = element.alt || "The image to crop"; this.image = image; image.onload = this.start.bind(this); image.onerror = this.stop.bind(this); addClass(image, CLASS_HIDE); element.parentNode.insertBefore(image, element.nextSibling); } }, { key: "start", value: function start() { var _this2 = this; var image = this.image; image.onload = null; image.onerror = null; this.sizing = true; var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent); var done = function done2(naturalWidth, naturalHeight) { assign2(_this2.imageData, { naturalWidth, naturalHeight, aspectRatio: naturalWidth / naturalHeight }); _this2.initialImageData = assign2({}, _this2.imageData); _this2.sizing = false; _this2.sized = true; _this2.build(); }; if (image.naturalWidth && !isIOSWebKit) { done(image.naturalWidth, image.naturalHeight); return; } var sizingImage = document.createElement("img"); var body = document.body || document.documentElement; this.sizingImage = sizingImage; sizingImage.onload = function() { done(sizingImage.width, sizingImage.height); if (!isIOSWebKit) { body.removeChild(sizingImage); } }; sizingImage.src = image.src; if (!isIOSWebKit) { sizingImage.style.cssText = "left:0;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;opacity:0;position:absolute;top:0;z-index:-1;"; body.appendChild(sizingImage); } } }, { key: "stop", value: function stop() { var image = this.image; image.onload = null; image.onerror = null; image.parentNode.removeChild(image); this.image = null; } }, { key: "build", value: function build() { if (!this.sized || this.ready) { return; } var element = this.element, options2 = this.options, image = this.image; var container = element.parentNode; var template18 = document.createElement("div"); template18.innerHTML = TEMPLATE; var cropper = template18.querySelector(".".concat(NAMESPACE, "-container")); var canvas = cropper.querySelector(".".concat(NAMESPACE, "-canvas")); var dragBox = cropper.querySelector(".".concat(NAMESPACE, "-drag-box")); var cropBox = cropper.querySelector(".".concat(NAMESPACE, "-crop-box")); var face = cropBox.querySelector(".".concat(NAMESPACE, "-face")); this.container = container; this.cropper = cropper; this.canvas = canvas; this.dragBox = dragBox; this.cropBox = cropBox; this.viewBox = cropper.querySelector(".".concat(NAMESPACE, "-view-box")); this.face = face; canvas.appendChild(image); addClass(element, CLASS_HIDDEN); container.insertBefore(cropper, element.nextSibling); removeClass(image, CLASS_HIDE); this.initPreview(); this.bind(); options2.initialAspectRatio = Math.max(0, options2.initialAspectRatio) || NaN; options2.aspectRatio = Math.max(0, options2.aspectRatio) || NaN; options2.viewMode = Math.max(0, Math.min(3, Math.round(options2.viewMode))) || 0; addClass(cropBox, CLASS_HIDDEN); if (!options2.guides) { addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-dashed")), CLASS_HIDDEN); } if (!options2.center) { addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-center")), CLASS_HIDDEN); } if (options2.background) { addClass(cropper, "".concat(NAMESPACE, "-bg")); } if (!options2.highlight) { addClass(face, CLASS_INVISIBLE); } if (options2.cropBoxMovable) { addClass(face, CLASS_MOVE); setData(face, DATA_ACTION, ACTION_ALL); } if (!options2.cropBoxResizable) { addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-line")), CLASS_HIDDEN); addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-point")), CLASS_HIDDEN); } this.render(); this.ready = true; this.setDragMode(options2.dragMode); if (options2.autoCrop) { this.crop(); } this.setData(options2.data); if (isFunction(options2.ready)) { addListener(element, EVENT_READY, options2.ready, { once: true }); } dispatchEvent(element, EVENT_READY); } }, { key: "unbuild", value: function unbuild() { if (!this.ready) { return; } this.ready = false; this.unbind(); this.resetPreview(); var parentNode = this.cropper.parentNode; if (parentNode) { parentNode.removeChild(this.cropper); } removeClass(this.element, CLASS_HIDDEN); } }, { key: "uncreate", value: function uncreate() { if (this.ready) { this.unbuild(); this.ready = false; this.cropped = false; } else if (this.sizing) { this.sizingImage.onload = null; this.sizing = false; this.sized = false; } else if (this.reloading) { this.xhr.onabort = null; this.xhr.abort(); } else if (this.image) { this.stop(); } } /** * Get the no conflict cropper class. * @returns {Cropper} The cropper class. */ }], [{ key: "noConflict", value: function noConflict() { window.Cropper = AnotherCropper; return Cropper2; } /** * Change the default options. * @param {Object} options - The new default options. */ }, { key: "setDefaults", value: function setDefaults(options2) { assign2(DEFAULTS, isPlainObject(options2) && options2); } }]); return Cropper2; }(); assign2(Cropper.prototype, render, preview, events, handlers, change, methods); // node_modules/@strapi/upload/dist/admin/hooks/useCropImg.mjs var QUALITY = 1; var useCropImg = () => { const cropperRef = React11.useRef(); const [isCropping, setIsCropping] = React11.useState(false); const [size, setSize] = React11.useState({ width: void 0, height: void 0 }); React11.useEffect(() => { return () => { if (cropperRef.current) { cropperRef.current.destroy(); } }; }, []); const handleResize = ({ detail: { height, width } }) => { const roundedDataWidth = Math.round(width); const roundedDataHeight = Math.round(height); setSize({ width: roundedDataWidth, height: roundedDataHeight }); }; const crop2 = (image) => { if (!cropperRef.current) { cropperRef.current = new Cropper(image, { modal: true, initialAspectRatio: 16 / 9, movable: true, zoomable: false, cropBoxResizable: true, background: false, checkCrossOrigin: false, crop: handleResize }); setIsCropping(true); } }; const stopCropping = () => { if (cropperRef.current) { cropperRef.current.destroy(); cropperRef.current = void 0; setIsCropping(false); } }; const produceFile = (name, mimeType, lastModifiedDate) => new Promise((resolve, reject) => { if (!cropperRef.current) { reject(new Error("The cropper has not been instantiated: make sure to call the crop() function before calling produceFile().")); } else { const canvas = cropperRef.current.getCroppedCanvas(); canvas.toBlob((blob) => { resolve(new File([ blob ], name, { type: mimeType, lastModified: new Date(lastModifiedDate).getTime() })); }, mimeType, QUALITY); } }); return { crop: crop2, produceFile, stopCropping, isCropping, isCropperReady: Boolean(cropperRef.current), ...size }; }; // node_modules/@strapi/upload/dist/admin/hooks/useUpload.mjs var React12 = __toESM(require_react(), 1); var endpoint = `/${pluginId}`; var uploadAsset = (asset, folderId, signal, onProgress, post) => { const { rawFile, caption, name, alternativeText } = asset; const formData = new FormData(); formData.append("files", rawFile); formData.append("fileInfo", JSON.stringify({ name, caption, alternativeText, folder: folderId })); return post(endpoint, formData, { signal }).then((res) => res.data); }; var useUpload = () => { const [progress, setProgress] = React12.useState(0); const queryClient = useQueryClient(); const abortController = new AbortController(); const signal = abortController.signal; const { post } = useFetchClient(); const mutation = useMutation(({ asset, folderId }) => { return uploadAsset(asset, folderId, signal, setProgress, post); }, { onSuccess() { queryClient.refetchQueries([ pluginId, "assets" ], { active: true }); queryClient.refetchQueries([ pluginId, "asset-count" ], { active: true }); } }); const upload = (asset, folderId) => mutation.mutateAsync({ asset, folderId }); const cancel = () => abortController.abort(); return { upload, isLoading: mutation.isLoading, cancel, error: mutation.error, progress, status: mutation.status }; }; // node_modules/@strapi/upload/dist/admin/utils/prefixFileUrlWithBackendUrl.mjs var prefixFileUrlWithBackendUrl = (fileURL) => { return !!fileURL && fileURL.startsWith("/") ? `${window.strapi.backendURL}${fileURL}` : fileURL; }; // node_modules/@strapi/upload/dist/admin/utils/createAssetUrl.mjs var createAssetUrl = (asset, forThumbnail = true) => { var _a3, _b; if (asset.isLocal) { return asset.url; } const assetUrl = forThumbnail ? ((_b = (_a3 = asset == null ? void 0 : asset.formats) == null ? void 0 : _a3.thumbnail) == null ? void 0 : _b.url) || asset.url : asset.url; return prefixFileUrlWithBackendUrl(assetUrl); }; // node_modules/@strapi/upload/dist/admin/utils/downloadFile.mjs var downloadFile = async (url, fileName) => { const fileBlob = await fetch(url).then((res) => res.blob()); const urlDownload = window.URL.createObjectURL(fileBlob); const link = document.createElement("a"); link.href = urlDownload; link.setAttribute("download", fileName); link.click(); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/PreviewBox.mjs var import_qs6 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/CopyLinkButton/CopyLinkButton.mjs var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1); var import_qs4 = __toESM(require_lib(), 1); var CopyLinkButton = ({ url }) => { const { toggleNotification } = useNotification(); const { formatMessage } = useIntl(); const { copy: copy2 } = useClipboard(); const handleClick = async () => { const didCopy = await copy2(url); if (didCopy) { toggleNotification({ type: "success", message: formatMessage({ id: "notification.link-copied", defaultMessage: "Link copied into the clipboard" }) }); } }; return (0, import_jsx_runtime5.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.copy-link"), defaultMessage: "Copy link" }), onClick: handleClick, children: (0, import_jsx_runtime5.jsx)(ForwardRef$2r, {}) }); }; // node_modules/@strapi/upload/dist/admin/components/UploadProgress/UploadProgress.mjs var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1); var BoxWrapper = dt(Flex)` border-radius: ${({ theme }) => `${theme.borderRadius} ${theme.borderRadius} 0 0`}; width: 100%; height: 100%; svg { path { fill: ${({ theme, error }) => error ? theme.colors.danger600 : void 0}; } } `; var CancelButton = dt.button` border: none; background: none; width: min-content; color: ${({ theme }) => theme.colors.neutral600}; &:hover, &:focus { color: ${({ theme }) => theme.colors.neutral700}; } svg { height: 10px; width: 10px; path { fill: currentColor; } } `; var UploadProgress = ({ onCancel, progress = 0, error }) => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime6.jsx)(BoxWrapper, { alignItems: "center", background: error ? "danger100" : "neutral150", error, children: error ? (0, import_jsx_runtime6.jsx)(ForwardRef$45, { "aria-label": error == null ? void 0 : error.message }) : (0, import_jsx_runtime6.jsxs)(Flex, { direction: "column", alignItems: "center", gap: 2, width: "100%", children: [ (0, import_jsx_runtime6.jsx)(ProgressBar, { value: progress }), (0, import_jsx_runtime6.jsx)(Typography, { children: `${progress}/100%` }), (0, import_jsx_runtime6.jsx)(CancelButton, { type: "button", onClick: onCancel, children: (0, import_jsx_runtime6.jsxs)(Flex, { gap: 2, children: [ (0, import_jsx_runtime6.jsx)(Typography, { variant: "pi", tag: "span", textColor: "inherit", children: formatMessage({ id: "app.components.Button.cancel", defaultMessage: "Cancel" }) }), (0, import_jsx_runtime6.jsx)(ForwardRef$45, { "aria-hidden": true }) ] }) }) ] }) }); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/RemoveAssetDialog.mjs var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/hooks/useRemoveAsset.mjs var useRemoveAsset = (onSuccess) => { const { toggleNotification } = useNotification(); const { formatMessage } = useIntl(); const queryClient = useQueryClient(); const { del } = useFetchClient(); const mutation = useMutation((assetId) => del(`/upload/files/${assetId}`), { onSuccess() { queryClient.refetchQueries([ pluginId, "assets" ], { active: true }); queryClient.refetchQueries([ pluginId, "asset-count" ], { active: true }); toggleNotification({ type: "success", message: formatMessage({ id: "modal.remove.success-label", defaultMessage: "Elements have been successfully deleted." }) }); onSuccess(); }, onError(error) { toggleNotification({ type: "danger", message: error.message }); } }); const removeAsset = async (assetId) => { await mutation.mutateAsync(assetId); }; return { ...mutation, removeAsset }; }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/RemoveAssetDialog.mjs var RemoveAssetDialog = ({ open, onClose, asset }) => { const { removeAsset } = useRemoveAsset(() => { onClose(null); }); const handleConfirm = async (event) => { event == null ? void 0 : event.preventDefault(); await removeAsset(asset.id); }; return (0, import_jsx_runtime7.jsx)(Dialog.Root, { open, onOpenChange: onClose, children: (0, import_jsx_runtime7.jsx)(ConfirmDialog, { onConfirm: handleConfirm }) }); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/AssetPreview.mjs var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1); var React13 = __toESM(require_react(), 1); // node_modules/@mux/mux-player-react/dist/index.mjs var import_react11 = __toESM(require_react(), 1); // node_modules/mux-embed/dist/mux.mjs var Yr = Object.create; var ft = Object.defineProperty; var Xr = Object.getOwnPropertyDescriptor; var $r = Object.getOwnPropertyNames; var Zr = Object.getPrototypeOf; var ea = Object.prototype.hasOwnProperty; var pt = function(r9, e) { return function() { return r9 && (e = r9(r9 = 0)), e; }; }; var B = function(r9, e) { return function() { return e || r9((e = { exports: {} }).exports, e), e.exports; }; }; var ta = function(r9, e, t2, i3) { if (e && typeof e == "object" || typeof e == "function") for (var a2 = $r(e), n2 = 0, o2 = a2.length, s; n2 < o2; n2++) s = a2[n2], !ea.call(r9, s) && s !== t2 && ft(r9, s, { get: (function(u3) { return e[u3]; }).bind(null, s), enumerable: !(i3 = Xr(e, s)) || i3.enumerable }); return r9; }; var V = function(r9, e, t2) { return t2 = r9 != null ? Yr(Zr(r9)) : {}, ta(e || !r9 || !r9.__esModule ? ft(t2, "default", { value: r9, enumerable: true }) : t2, r9); }; var J = B(function(ji2, yt3) { var xe3; typeof window != "undefined" ? xe3 = window : typeof global != "undefined" ? xe3 = global : typeof self != "undefined" ? xe3 = self : xe3 = {}; yt3.exports = xe3; }); function U(r9, e) { return e != null && typeof Symbol != "undefined" && e[Symbol.hasInstance] ? !!e[Symbol.hasInstance](r9) : U(r9, e); } var te = pt(function() { te(); }); function Ne(r9) { "@swc/helpers - typeof"; return r9 && typeof Symbol != "undefined" && r9.constructor === Symbol ? "symbol" : typeof r9; } var Je = pt(function() { }); var Ye = B(function(Ts, cr) { var lr = Array.prototype.slice; cr.exports = Pa2; function Pa2(r9, e) { for (("length" in r9) || (r9 = [r9]), r9 = lr.call(r9); r9.length; ) { var t2 = r9.shift(), i3 = e(t2); if (i3) return i3; t2.childNodes && t2.childNodes.length && (r9 = lr.call(t2.childNodes).concat(r9)); } } }); var fr = B(function(Es, _r) { te(); _r.exports = me4; function me4(r9, e) { if (!U(this, me4)) return new me4(r9, e); this.data = r9, this.nodeValue = r9, this.length = r9.length, this.ownerDocument = e || null; } me4.prototype.nodeType = 8; me4.prototype.nodeName = "#comment"; me4.prototype.toString = function() { return "[object Comment]"; }; }); var vr = B(function(xs, pr) { te(); pr.exports = ae5; function ae5(r9, e) { if (!U(this, ae5)) return new ae5(r9); this.data = r9 || "", this.length = this.data.length, this.ownerDocument = e || null; } ae5.prototype.type = "DOMTextNode"; ae5.prototype.nodeType = 3; ae5.prototype.nodeName = "#text"; ae5.prototype.toString = function() { return this.data; }; ae5.prototype.replaceData = function(e, t2, i3) { var a2 = this.data, n2 = a2.substring(0, e), o2 = a2.substring(e + t2, a2.length); this.data = n2 + i3 + o2, this.length = this.data.length; }; }); var Xe = B(function(Ds, mr) { mr.exports = Ia2; function Ia2(r9) { var e = this, t2 = r9.type; r9.target || (r9.target = e), e.listeners || (e.listeners = {}); var i3 = e.listeners[t2]; if (i3) return i3.forEach(function(a2) { r9.currentTarget = e, typeof a2 == "function" ? a2(r9) : a2.handleEvent(r9); }); e.parentNode && e.parentNode.dispatchEvent(r9); } }); var $e = B(function(Ss, hr) { hr.exports = Na; function Na(r9, e) { var t2 = this; t2.listeners || (t2.listeners = {}), t2.listeners[r9] || (t2.listeners[r9] = []), t2.listeners[r9].indexOf(e) === -1 && t2.listeners[r9].push(e); } }); var Ze = B(function(Rs, yr) { yr.exports = La; function La(r9, e) { var t2 = this; if (t2.listeners && t2.listeners[r9]) { var i3 = t2.listeners[r9], a2 = i3.indexOf(e); a2 !== -1 && i3.splice(a2, 1); } } }); var wr = B(function(As, Tr2) { Je(); Tr2.exports = gr; var Ca2 = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]; function gr(r9) { switch (r9.nodeType) { case 3: return et3(r9.data); case 8: return ""; default: return Ma(r9); } } function Ma(r9) { var e = [], t2 = r9.tagName; return r9.namespaceURI === "http://www.w3.org/1999/xhtml" && (t2 = t2.toLowerCase()), e.push("<" + t2 + Fa2(r9) + Ua2(r9)), Ca2.indexOf(t2) > -1 ? e.push(" />") : (e.push(">"), r9.childNodes.length ? e.push.apply(e, r9.childNodes.map(gr)) : r9.textContent || r9.innerText ? e.push(et3(r9.textContent || r9.innerText)) : r9.innerHTML && e.push(r9.innerHTML), e.push("")), e.join(""); } function Ha2(r9, e) { var t2 = Ne(r9[e]); return e === "style" && Object.keys(r9.style).length > 0 ? true : r9.hasOwnProperty(e) && (t2 === "string" || t2 === "boolean" || t2 === "number") && e !== "nodeName" && e !== "className" && e !== "tagName" && e !== "textContent" && e !== "innerText" && e !== "namespaceURI" && e !== "innerHTML"; } function Ba2(r9) { if (typeof r9 == "string") return r9; var e = ""; return Object.keys(r9).forEach(function(t2) { var i3 = r9[t2]; t2 = t2.replace(/[A-Z]/g, function(a2) { return "-" + a2.toLowerCase(); }), e += t2 + ":" + i3 + ";"; }), e; } function Ua2(r9) { var e = r9.dataset, t2 = []; for (var i3 in e) t2.push({ name: "data-" + i3, value: e[i3] }); return t2.length ? br(t2) : ""; } function br(r9) { var e = []; return r9.forEach(function(t2) { var i3 = t2.name, a2 = t2.value; i3 === "style" && (a2 = Ba2(a2)), e.push(i3 + '="' + Va2(a2) + '"'); }), e.length ? " " + e.join(" ") : ""; } function Fa2(r9) { var e = []; for (var t2 in r9) Ha2(r9, t2) && e.push({ name: t2, value: r9[t2] }); for (var i3 in r9._attributes) for (var a2 in r9._attributes[i3]) { var n2 = r9._attributes[i3][a2], o2 = (n2.prefix ? n2.prefix + ":" : "") + a2; e.push({ name: o2, value: n2.value }); } return r9.className && e.push({ name: "class", value: r9.className }), e.length ? br(e) : ""; } function et3(r9) { var e = ""; return typeof r9 == "string" ? e = r9 : r9 && (e = r9.toString()), e.replace(/&/g, "&").replace(//g, ">"); } function Va2(r9) { return et3(r9).replace(/"/g, """); } }); var rt = B(function(Ps, kr) { te(); var tt3 = Ye(), Wa = Xe(), ja = $e(), Ga = Ze(), Ja = wr(), Er = "http://www.w3.org/1999/xhtml"; kr.exports = I4; function I4(r9, e, t2) { if (!U(this, I4)) return new I4(r9); var i3 = t2 === void 0 ? Er : t2 || null; this.tagName = i3 === Er ? String(r9).toUpperCase() : r9, this.nodeName = this.tagName, this.className = "", this.dataset = {}, this.childNodes = [], this.parentNode = null, this.style = {}, this.ownerDocument = e || null, this.namespaceURI = i3, this._attributes = {}, this.tagName === "INPUT" && (this.type = "text"); } I4.prototype.type = "DOMElement"; I4.prototype.nodeType = 1; I4.prototype.appendChild = function(e) { return e.parentNode && e.parentNode.removeChild(e), this.childNodes.push(e), e.parentNode = this, e; }; I4.prototype.replaceChild = function(e, t2) { e.parentNode && e.parentNode.removeChild(e); var i3 = this.childNodes.indexOf(t2); return t2.parentNode = null, this.childNodes[i3] = e, e.parentNode = this, t2; }; I4.prototype.removeChild = function(e) { var t2 = this.childNodes.indexOf(e); return this.childNodes.splice(t2, 1), e.parentNode = null, e; }; I4.prototype.insertBefore = function(e, t2) { e.parentNode && e.parentNode.removeChild(e); var i3 = t2 == null ? -1 : this.childNodes.indexOf(t2); return i3 > -1 ? this.childNodes.splice(i3, 0, e) : this.childNodes.push(e), e.parentNode = this, e; }; I4.prototype.setAttributeNS = function(e, t2, i3) { var a2 = null, n2 = t2, o2 = t2.indexOf(":"); if (o2 > -1 && (a2 = t2.substr(0, o2), n2 = t2.substr(o2 + 1)), this.tagName === "INPUT" && t2 === "type") this.type = i3; else { var s = this._attributes[e] || (this._attributes[e] = {}); s[n2] = { value: i3, prefix: a2 }; } }; I4.prototype.getAttributeNS = function(e, t2) { var i3 = this._attributes[e], a2 = i3 && i3[t2] && i3[t2].value; return this.tagName === "INPUT" && t2 === "type" ? this.type : typeof a2 != "string" ? null : a2; }; I4.prototype.removeAttributeNS = function(e, t2) { var i3 = this._attributes[e]; i3 && delete i3[t2]; }; I4.prototype.hasAttributeNS = function(e, t2) { var i3 = this._attributes[e]; return !!i3 && t2 in i3; }; I4.prototype.setAttribute = function(e, t2) { return this.setAttributeNS(null, e, t2); }; I4.prototype.getAttribute = function(e) { return this.getAttributeNS(null, e); }; I4.prototype.removeAttribute = function(e) { return this.removeAttributeNS(null, e); }; I4.prototype.hasAttribute = function(e) { return this.hasAttributeNS(null, e); }; I4.prototype.removeEventListener = Ga; I4.prototype.addEventListener = ja; I4.prototype.dispatchEvent = Wa; I4.prototype.focus = function() { }; I4.prototype.toString = function() { return Ja(this); }; I4.prototype.getElementsByClassName = function(e) { var t2 = e.split(" "), i3 = []; return tt3(this, function(a2) { if (a2.nodeType === 1) { var n2 = a2.className || "", o2 = n2.split(" "); t2.every(function(s) { return o2.indexOf(s) !== -1; }) && i3.push(a2); } }), i3; }; I4.prototype.getElementsByTagName = function(e) { e = e.toLowerCase(); var t2 = []; return tt3(this.childNodes, function(i3) { i3.nodeType === 1 && (e === "*" || i3.tagName.toLowerCase() === e) && t2.push(i3); }), t2; }; I4.prototype.contains = function(e) { return tt3(this, function(t2) { return e === t2; }) || false; }; }); var Dr = B(function(Ns, xr) { te(); var at3 = rt(); xr.exports = K4; function K4(r9) { if (!U(this, K4)) return new K4(); this.childNodes = [], this.parentNode = null, this.ownerDocument = r9 || null; } K4.prototype.type = "DocumentFragment"; K4.prototype.nodeType = 11; K4.prototype.nodeName = "#document-fragment"; K4.prototype.appendChild = at3.prototype.appendChild; K4.prototype.replaceChild = at3.prototype.replaceChild; K4.prototype.removeChild = at3.prototype.removeChild; K4.prototype.toString = function() { return this.childNodes.map(function(e) { return String(e); }).join(""); }; }); var Rr = B(function(Ls, Sr2) { Sr2.exports = it3; function it3(r9) { } it3.prototype.initEvent = function(e, t2, i3) { this.type = e, this.bubbles = t2, this.cancelable = i3; }; it3.prototype.preventDefault = function() { }; }); var Ar = B(function(Ms, qr) { te(); var Qa = Ye(), za = fr(), Ka2 = vr(), Re4 = rt(), Ya = Dr(), Xa = Rr(), $a2 = Xe(), Za = $e(), ei2 = Ze(); qr.exports = Be4; function Be4() { if (!U(this, Be4)) return new Be4(); this.head = this.createElement("head"), this.body = this.createElement("body"), this.documentElement = this.createElement("html"), this.documentElement.appendChild(this.head), this.documentElement.appendChild(this.body), this.childNodes = [this.documentElement], this.nodeType = 9; } var j3 = Be4.prototype; j3.createTextNode = function(e) { return new Ka2(e, this); }; j3.createElementNS = function(e, t2) { var i3 = e === null ? null : String(e); return new Re4(t2, this, i3); }; j3.createElement = function(e) { return new Re4(e, this); }; j3.createDocumentFragment = function() { return new Ya(this); }; j3.createEvent = function(e) { return new Xa(e); }; j3.createComment = function(e) { return new za(e, this); }; j3.getElementById = function(e) { e = String(e); var t2 = Qa(this.childNodes, function(i3) { if (String(i3.id) === e) return i3; }); return t2 || null; }; j3.getElementsByClassName = Re4.prototype.getElementsByClassName; j3.getElementsByTagName = Re4.prototype.getElementsByTagName; j3.contains = Re4.prototype.contains; j3.removeEventListener = ei2; j3.addEventListener = Za; j3.dispatchEvent = $a2; }); var Pr = B(function(Hs, Or) { var ti2 = Ar(); Or.exports = new ti2(); }); var nt2 = B(function(Bs, Nr2) { var Ir2 = typeof global != "undefined" ? global : typeof window != "undefined" ? window : {}, ri2 = Pr(), qe2; typeof document != "undefined" ? qe2 = document : (qe2 = Ir2["__GLOBAL_DOCUMENT_CACHE@4"], qe2 || (qe2 = Ir2["__GLOBAL_DOCUMENT_CACHE@4"] = ri2)); Nr2.exports = qe2; }); function vt(r9) { if (Array.isArray(r9)) return r9; } function mt(r9, e) { var t2 = r9 == null ? null : typeof Symbol != "undefined" && r9[Symbol.iterator] || r9["@@iterator"]; if (t2 != null) { var i3 = [], a2 = true, n2 = false, o2, s; try { for (t2 = t2.call(r9); !(a2 = (o2 = t2.next()).done) && (i3.push(o2.value), !(e && i3.length === e)); a2 = true) ; } catch (u3) { n2 = true, s = u3; } finally { try { !a2 && t2.return != null && t2.return(); } finally { if (n2) throw s; } } return i3; } } function ht() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function ke(r9, e) { (e == null || e > r9.length) && (e = r9.length); for (var t2 = 0, i3 = new Array(e); t2 < e; t2++) i3[t2] = r9[t2]; return i3; } function Ae(r9, e) { if (r9) { if (typeof r9 == "string") return ke(r9, e); var t2 = Object.prototype.toString.call(r9).slice(8, -1); if (t2 === "Object" && r9.constructor && (t2 = r9.constructor.name), t2 === "Map" || t2 === "Set") return Array.from(t2); if (t2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t2)) return ke(r9, e); } } function H(r9, e) { return vt(r9) || mt(r9, e) || Ae(r9, e) || ht(); } var be = V(J()); var Ge = V(J()); var gt = V(J()); var ra = { now: function() { var r9 = gt.default.performance, e = r9 && r9.timing, t2 = e && e.navigationStart, i3 = typeof t2 == "number" && typeof r9.now == "function" ? t2 + r9.now() : Date.now(); return Math.round(i3); } }; var A = ra; var ee = function() { var e, t2, i3; if (typeof ((e = Ge.default.crypto) === null || e === void 0 ? void 0 : e.getRandomValues) == "function") { i3 = new Uint8Array(32), Ge.default.crypto.getRandomValues(i3); for (var a2 = 0; a2 < 32; a2++) i3[a2] = i3[a2] % 16; } else { i3 = []; for (var n2 = 0; n2 < 32; n2++) i3[n2] = Math.random() * 16 | 0; } var o2 = 0; t2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(p3) { var b2 = p3 === "x" ? i3[o2] : i3[o2] & 3 | 8; return o2++, b2.toString(16); }); var s = A.now(), u3 = s == null ? void 0 : s.toString(16).substring(3); return u3 ? t2.substring(0, 28) + u3 : t2; }; var Oe = function() { return ("000000" + (Math.random() * Math.pow(36, 6) << 0).toString(36)).slice(-6); }; var Q = function(e) { if (e && typeof e.nodeName != "undefined") return e.muxId || (e.muxId = Oe()), e.muxId; var t2; try { t2 = document.querySelector(e); } catch (i3) { } return t2 && !t2.muxId && (t2.muxId = e), (t2 == null ? void 0 : t2.muxId) || e; }; var se = function(e) { var t2; e && typeof e.nodeName != "undefined" ? (t2 = e, e = Q(t2)) : t2 = document.querySelector(e); var i3 = t2 && t2.nodeName ? t2.nodeName.toLowerCase() : ""; return [t2, e, i3]; }; function bt(r9) { if (Array.isArray(r9)) return ke(r9); } function Tt(r9) { if (typeof Symbol != "undefined" && r9[Symbol.iterator] != null || r9["@@iterator"] != null) return Array.from(r9); } function wt() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function W(r9) { return bt(r9) || Tt(r9) || Ae(r9) || wt(); } var Y = { TRACE: 0, DEBUG: 1, INFO: 2, WARN: 3, ERROR: 4, SILENT: 5 }; var Et = function(r9) { var e = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 3, t2, i3, a2, n2, o2, s = r9 ? [console, r9] : [console], u3 = (t2 = console.trace).bind.apply(t2, W(s)), p3 = (i3 = console.info).bind.apply(i3, W(s)), b2 = (a2 = console.debug).bind.apply(a2, W(s)), k3 = (n2 = console.warn).bind.apply(n2, W(s)), y4 = (o2 = console.error).bind.apply(o2, W(s)), c3 = e; return { trace: function() { for (var T3 = arguments.length, x2 = new Array(T3), m2 = 0; m2 < T3; m2++) x2[m2] = arguments[m2]; if (!(c3 > Y.TRACE)) return u3.apply(void 0, W(x2)); }, debug: function() { for (var T3 = arguments.length, x2 = new Array(T3), m2 = 0; m2 < T3; m2++) x2[m2] = arguments[m2]; if (!(c3 > Y.DEBUG)) return b2.apply(void 0, W(x2)); }, info: function() { for (var T3 = arguments.length, x2 = new Array(T3), m2 = 0; m2 < T3; m2++) x2[m2] = arguments[m2]; if (!(c3 > Y.INFO)) return p3.apply(void 0, W(x2)); }, warn: function() { for (var T3 = arguments.length, x2 = new Array(T3), m2 = 0; m2 < T3; m2++) x2[m2] = arguments[m2]; if (!(c3 > Y.WARN)) return k3.apply(void 0, W(x2)); }, error: function() { for (var T3 = arguments.length, x2 = new Array(T3), m2 = 0; m2 < T3; m2++) x2[m2] = arguments[m2]; if (!(c3 > Y.ERROR)) return y4.apply(void 0, W(x2)); }, get level() { return c3; }, set level(v2) { v2 !== this.level && (c3 = v2 != null ? v2 : e); } }; }; var q = Et("[mux]"); var Pe = V(J()); function ce() { var r9 = Pe.default.doNotTrack || Pe.default.navigator && Pe.default.navigator.doNotTrack; return r9 === "1"; } function g(r9) { if (r9 === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return r9; } te(); function D(r9, e) { if (!U(r9, e)) throw new TypeError("Cannot call a class as a function"); } function kt(r9, e) { for (var t2 = 0; t2 < e.length; t2++) { var i3 = e[t2]; i3.enumerable = i3.enumerable || false, i3.configurable = true, "value" in i3 && (i3.writable = true), Object.defineProperty(r9, i3.key, i3); } } function L(r9, e, t2) { return e && kt(r9.prototype, e), t2 && kt(r9, t2), r9; } function l(r9, e, t2) { return e in r9 ? Object.defineProperty(r9, e, { value: t2, enumerable: true, configurable: true, writable: true }) : r9[e] = t2, r9; } function X(r9) { return X = Object.setPrototypeOf ? Object.getPrototypeOf : function(t2) { return t2.__proto__ || Object.getPrototypeOf(t2); }, X(r9); } function xt(r9, e) { for (; !Object.prototype.hasOwnProperty.call(r9, e) && (r9 = X(r9), r9 !== null); ) ; return r9; } function De(r9, e, t2) { return typeof Reflect != "undefined" && Reflect.get ? De = Reflect.get : De = function(a2, n2, o2) { var s = xt(a2, n2); if (s) { var u3 = Object.getOwnPropertyDescriptor(s, n2); return u3.get ? u3.get.call(o2 || a2) : u3.value; } }, De(r9, e, t2 || r9); } function Ie(r9, e) { return Ie = Object.setPrototypeOf || function(i3, a2) { return i3.__proto__ = a2, i3; }, Ie(r9, e); } function Dt(r9, e) { if (typeof e != "function" && e !== null) throw new TypeError("Super expression must either be null or a function"); r9.prototype = Object.create(e && e.prototype, { constructor: { value: r9, writable: true, configurable: true } }), e && Ie(r9, e); } function St() { if (typeof Reflect == "undefined" || !Reflect.construct || Reflect.construct.sham) return false; if (typeof Proxy == "function") return true; try { return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { })), true; } catch (r9) { return false; } } Je(); function Rt(r9, e) { return e && (Ne(e) === "object" || typeof e == "function") ? e : g(r9); } function qt(r9) { var e = St(); return function() { var i3 = X(r9), a2; if (e) { var n2 = X(this).constructor; a2 = Reflect.construct(i3, arguments, n2); } else a2 = i3.apply(this, arguments); return Rt(this, a2); }; } var F = function(r9) { return re(r9)[0]; }; var re = function(r9) { if (typeof r9 != "string" || r9 === "") return ["localhost"]; var e = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/, t2 = r9.match(e) || [], i3 = t2[4], a2; return i3 && (a2 = (i3.match(/[^\.]+\.[^\.]+$/) || [])[0]), [i3, a2]; }; var Le = V(J()); var aa = { exists: function() { var r9 = Le.default.performance, e = r9 && r9.timing; return e !== void 0; }, domContentLoadedEventEnd: function() { var r9 = Le.default.performance, e = r9 && r9.timing; return e && e.domContentLoadedEventEnd; }, navigationStart: function() { var r9 = Le.default.performance, e = r9 && r9.timing; return e && e.navigationStart; } }; var _e = aa; function O(r9, e, t2) { t2 = t2 === void 0 ? 1 : t2, r9[e] = r9[e] || 0, r9[e] += t2; } function ue(r9) { for (var e = 1; e < arguments.length; e++) { var t2 = arguments[e] != null ? arguments[e] : {}, i3 = Object.keys(t2); typeof Object.getOwnPropertySymbols == "function" && (i3 = i3.concat(Object.getOwnPropertySymbols(t2).filter(function(a2) { return Object.getOwnPropertyDescriptor(t2, a2).enumerable; }))), i3.forEach(function(a2) { l(r9, a2, t2[a2]); }); } return r9; } function ia(r9, e) { var t2 = Object.keys(r9); if (Object.getOwnPropertySymbols) { var i3 = Object.getOwnPropertySymbols(r9); e && (i3 = i3.filter(function(a2) { return Object.getOwnPropertyDescriptor(r9, a2).enumerable; })), t2.push.apply(t2, i3); } return t2; } function fe(r9, e) { return e = e != null ? e : {}, Object.getOwnPropertyDescriptors ? Object.defineProperties(r9, Object.getOwnPropertyDescriptors(e)) : ia(Object(e)).forEach(function(t2) { Object.defineProperty(r9, t2, Object.getOwnPropertyDescriptor(e, t2)); }), r9; } var na = ["x-cdn", "content-type"]; var At = ["x-request-id", "cf-ray", "x-amz-cf-id", "x-akamai-request-id"]; var oa = na.concat(At); function pe(r9) { r9 = r9 || ""; var e = {}, t2 = r9.trim().split(/[\r\n]+/); return t2.forEach(function(i3) { if (i3) { var a2 = i3.split(": "), n2 = a2.shift(); n2 && (oa.indexOf(n2.toLowerCase()) >= 0 || n2.toLowerCase().indexOf("x-litix-") === 0) && (e[n2] = a2.join(": ")); } }), e; } function de(r9) { if (r9) { var e = At.find(function(t2) { return r9[t2] !== void 0; }); return e ? r9[e] : void 0; } } var sa = function(r9) { var e = {}; for (var t2 in r9) { var i3 = r9[t2], a2 = i3["DATA-ID"].search("io.litix.data."); if (a2 !== -1) { var n2 = i3["DATA-ID"].replace("io.litix.data.", ""); e[n2] = i3.VALUE; } } return e; }; var Ce = sa; var Me = function(r9) { if (!r9) return {}; var e = _e.navigationStart(), t2 = r9.loading, i3 = t2 ? t2.start : r9.trequest, a2 = t2 ? t2.first : r9.tfirst, n2 = t2 ? t2.end : r9.tload; return { bytesLoaded: r9.total, requestStart: Math.round(e + i3), responseStart: Math.round(e + a2), responseEnd: Math.round(e + n2) }; }; var Se = function(r9) { if (!(!r9 || typeof r9.getAllResponseHeaders != "function")) return pe(r9.getAllResponseHeaders()); }; var Ot = function(r9, e, t2) { var i3 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}, a2 = arguments.length > 4 ? arguments[4] : void 0, n2 = r9.log, o2 = r9.utils.secondsToMs, s = function(m2) { var f = parseInt(a2.version), _3; return f === 1 && m2.programDateTime !== null && (_3 = m2.programDateTime), f === 0 && m2.pdt !== null && (_3 = m2.pdt), _3; }; if (!_e.exists()) { n2.warn("performance timing not supported. Not tracking HLS.js."); return; } var u3 = function(m2, f) { return r9.emit(e, m2, f); }, p3 = function(m2, f) { var _3 = f.levels, d2 = f.audioTracks, h3 = f.url, w4 = f.stats, E5 = f.networkDetails, S3 = f.sessionData, N2 = {}, M4 = {}; _3.forEach(function(G3, oe5) { N2[oe5] = { width: G3.width, height: G3.height, bitrate: G3.bitrate, attrs: G3.attrs }; }), d2.forEach(function(G3, oe5) { M4[oe5] = { name: G3.name, language: G3.lang, bitrate: G3.bitrate }; }); var P2 = Me(w4), R4 = P2.bytesLoaded, Z4 = P2.requestStart, Te4 = P2.responseStart, we4 = P2.responseEnd; u3("requestcompleted", fe(ue({}, Ce(S3)), { request_event_type: m2, request_bytes_loaded: R4, request_start: Z4, request_response_start: Te4, request_response_end: we4, request_type: "manifest", request_hostname: F(h3), request_response_headers: Se(E5), request_rendition_lists: { media: N2, audio: M4, video: {} } })); }; t2.on(a2.Events.MANIFEST_LOADED, p3); var b2 = function(m2, f) { var _3 = f.details, d2 = f.level, h3 = f.networkDetails, w4 = f.stats, E5 = Me(w4), S3 = E5.bytesLoaded, N2 = E5.requestStart, M4 = E5.responseStart, P2 = E5.responseEnd, R4 = _3.fragments[_3.fragments.length - 1], Z4 = s(R4) + o2(R4.duration); u3("requestcompleted", { request_event_type: m2, request_bytes_loaded: S3, request_start: N2, request_response_start: M4, request_response_end: P2, request_current_level: d2, request_type: "manifest", request_hostname: F(_3.url), request_response_headers: Se(h3), video_holdback: _3.holdBack && o2(_3.holdBack), video_part_holdback: _3.partHoldBack && o2(_3.partHoldBack), video_part_target_duration: _3.partTarget && o2(_3.partTarget), video_target_duration: _3.targetduration && o2(_3.targetduration), video_source_is_live: _3.live, player_manifest_newest_program_time: isNaN(Z4) ? void 0 : Z4 }); }; t2.on(a2.Events.LEVEL_LOADED, b2); var k3 = function(m2, f) { var _3 = f.details, d2 = f.networkDetails, h3 = f.stats, w4 = Me(h3), E5 = w4.bytesLoaded, S3 = w4.requestStart, N2 = w4.responseStart, M4 = w4.responseEnd; u3("requestcompleted", { request_event_type: m2, request_bytes_loaded: E5, request_start: S3, request_response_start: N2, request_response_end: M4, request_type: "manifest", request_hostname: F(_3.url), request_response_headers: Se(d2) }); }; t2.on(a2.Events.AUDIO_TRACK_LOADED, k3); var y4 = function(m2, f) { var _3 = f.stats, d2 = f.networkDetails, h3 = f.frag; _3 = _3 || h3.stats; var w4 = Me(_3), E5 = w4.bytesLoaded, S3 = w4.requestStart, N2 = w4.responseStart, M4 = w4.responseEnd, P2 = d2 ? Se(d2) : void 0, R4 = { request_event_type: m2, request_bytes_loaded: E5, request_start: S3, request_response_start: N2, request_response_end: M4, request_hostname: d2 ? F(d2.responseURL) : void 0, request_id: P2 ? de(P2) : void 0, request_response_headers: P2, request_media_duration: h3.duration, request_url: d2 == null ? void 0 : d2.responseURL }; h3.type === "main" ? (R4.request_type = "media", R4.request_current_level = h3.level, R4.request_video_width = (t2.levels[h3.level] || {}).width, R4.request_video_height = (t2.levels[h3.level] || {}).height, R4.request_labeled_bitrate = (t2.levels[h3.level] || {}).bitrate) : R4.request_type = h3.type, u3("requestcompleted", R4); }; t2.on(a2.Events.FRAG_LOADED, y4); var c3 = function(m2, f) { var _3 = f.frag, d2 = _3.start, h3 = s(_3), w4 = { currentFragmentPDT: h3, currentFragmentStart: o2(d2) }; u3("fragmentchange", w4); }; t2.on(a2.Events.FRAG_CHANGED, c3); var v2 = function(m2, f) { var _3 = f.type, d2 = f.details, h3 = f.response, w4 = f.fatal, E5 = f.frag, S3 = f.networkDetails, N2 = (E5 == null ? void 0 : E5.url) || f.url || "", M4 = S3 ? Se(S3) : void 0; if ((d2 === a2.ErrorDetails.MANIFEST_LOAD_ERROR || d2 === a2.ErrorDetails.MANIFEST_LOAD_TIMEOUT || d2 === a2.ErrorDetails.FRAG_LOAD_ERROR || d2 === a2.ErrorDetails.FRAG_LOAD_TIMEOUT || d2 === a2.ErrorDetails.LEVEL_LOAD_ERROR || d2 === a2.ErrorDetails.LEVEL_LOAD_TIMEOUT || d2 === a2.ErrorDetails.AUDIO_TRACK_LOAD_ERROR || d2 === a2.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT || d2 === a2.ErrorDetails.SUBTITLE_LOAD_ERROR || d2 === a2.ErrorDetails.SUBTITLE_LOAD_TIMEOUT || d2 === a2.ErrorDetails.KEY_LOAD_ERROR || d2 === a2.ErrorDetails.KEY_LOAD_TIMEOUT) && u3("requestfailed", { request_error: d2, request_url: N2, request_hostname: F(N2), request_id: M4 ? de(M4) : void 0, request_type: d2 === a2.ErrorDetails.FRAG_LOAD_ERROR || d2 === a2.ErrorDetails.FRAG_LOAD_TIMEOUT ? "media" : d2 === a2.ErrorDetails.AUDIO_TRACK_LOAD_ERROR || d2 === a2.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT ? "audio" : d2 === a2.ErrorDetails.SUBTITLE_LOAD_ERROR || d2 === a2.ErrorDetails.SUBTITLE_LOAD_TIMEOUT ? "subtitle" : d2 === a2.ErrorDetails.KEY_LOAD_ERROR || d2 === a2.ErrorDetails.KEY_LOAD_TIMEOUT ? "encryption" : "manifest", request_error_code: h3 == null ? void 0 : h3.code, request_error_text: h3 == null ? void 0 : h3.text }), w4) { var P2, R4 = "".concat(N2 ? "url: ".concat(N2, "\n") : "") + "".concat(h3 && (h3.code || h3.text) ? "response: ".concat(h3.code, ", ").concat(h3.text, "\n") : "") + "".concat(f.reason ? "failure reason: ".concat(f.reason, "\n") : "") + "".concat(f.level ? "level: ".concat(f.level, "\n") : "") + "".concat(f.parent ? "parent stream controller: ".concat(f.parent, "\n") : "") + "".concat(f.buffer ? "buffer length: ".concat(f.buffer, "\n") : "") + "".concat(f.error ? "error: ".concat(f.error, "\n") : "") + "".concat(f.event ? "event: ".concat(f.event, "\n") : "") + "".concat(f.err ? "error message: ".concat((P2 = f.err) === null || P2 === void 0 ? void 0 : P2.message, "\n") : ""); u3("error", { player_error_code: _3, player_error_message: d2, player_error_context: R4 }); } }; t2.on(a2.Events.ERROR, v2); var T3 = function(m2, f) { var _3 = f.frag, d2 = _3 && _3._url || ""; u3("requestcanceled", { request_event_type: m2, request_url: d2, request_type: "media", request_hostname: F(d2) }); }; t2.on(a2.Events.FRAG_LOAD_EMERGENCY_ABORTED, T3); var x2 = function(m2, f) { var _3 = f.level, d2 = t2.levels[_3]; if (d2 && d2.attrs && d2.attrs.BANDWIDTH) { var h3 = d2.attrs.BANDWIDTH, w4, E5 = parseFloat(d2.attrs["FRAME-RATE"]); isNaN(E5) || (w4 = E5), h3 ? u3("renditionchange", { video_source_fps: w4, video_source_bitrate: h3, video_source_width: d2.width, video_source_height: d2.height, video_source_rendition_name: d2.name, video_source_codec: d2 == null ? void 0 : d2.videoCodec }) : n2.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js"); } }; t2.on(a2.Events.LEVEL_SWITCHED, x2), t2._stopMuxMonitor = function() { t2.off(a2.Events.MANIFEST_LOADED, p3), t2.off(a2.Events.LEVEL_LOADED, b2), t2.off(a2.Events.AUDIO_TRACK_LOADED, k3), t2.off(a2.Events.FRAG_LOADED, y4), t2.off(a2.Events.FRAG_CHANGED, c3), t2.off(a2.Events.ERROR, v2), t2.off(a2.Events.FRAG_LOAD_EMERGENCY_ABORTED, T3), t2.off(a2.Events.LEVEL_SWITCHED, x2), t2.off(a2.Events.DESTROYING, t2._stopMuxMonitor), delete t2._stopMuxMonitor; }, t2.on(a2.Events.DESTROYING, t2._stopMuxMonitor); }; var Pt = function(r9) { r9 && typeof r9._stopMuxMonitor == "function" && r9._stopMuxMonitor(); }; var It = function(r9, e) { if (!r9 || !r9.requestEndDate) return {}; var t2 = F(r9.url), i3 = r9.url, a2 = r9.bytesLoaded, n2 = new Date(r9.requestStartDate).getTime(), o2 = new Date(r9.firstByteDate).getTime(), s = new Date(r9.requestEndDate).getTime(), u3 = isNaN(r9.duration) ? 0 : r9.duration, p3 = typeof e.getMetricsFor == "function" ? e.getMetricsFor(r9.mediaType).HttpList : e.getDashMetrics().getHttpRequests(r9.mediaType), b2; p3.length > 0 && (b2 = pe(p3[p3.length - 1]._responseHeaders || "")); var k3 = b2 ? de(b2) : void 0; return { requestStart: n2, requestResponseStart: o2, requestResponseEnd: s, requestBytesLoaded: a2, requestResponseHeaders: b2, requestMediaDuration: u3, requestHostname: t2, requestUrl: i3, requestId: k3 }; }; var ua = function(r9, e) { var t2 = e.getQualityFor(r9), i3 = e.getCurrentTrackFor(r9).bitrateList; return i3 ? { currentLevel: t2, renditionWidth: i3[t2].width || null, renditionHeight: i3[t2].height || null, renditionBitrate: i3[t2].bandwidth } : {}; }; var da = function(r9) { var e; return (e = r9.match(/.*codecs\*?="(.*)"/)) === null || e === void 0 ? void 0 : e[1]; }; var la = function(e) { try { var t2, i3, a2 = (i3 = e.getVersion) === null || i3 === void 0 || (t2 = i3.call(e)) === null || t2 === void 0 ? void 0 : t2.split(".").map(function(n2) { return parseInt(n2); })[0]; return a2; } catch (n2) { return false; } }; var Nt = function(r9, e, t2) { var i3 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}, a2 = r9.log; if (!t2 || !t2.on) { a2.warn("Invalid dash.js player reference. Monitoring blocked."); return; } var n2 = la(t2), o2 = function(_3, d2) { return r9.emit(e, _3, d2); }, s = function(_3) { var d2 = _3.type, h3 = _3.data, w4 = (h3 || {}).url; o2("requestcompleted", { request_event_type: d2, request_start: 0, request_response_start: 0, request_response_end: 0, request_bytes_loaded: -1, request_type: "manifest", request_hostname: F(w4), request_url: w4 }); }; t2.on("manifestLoaded", s); var u3 = {}, p3 = function(_3) { if (typeof _3.getRequests != "function") return null; var d2 = _3.getRequests({ state: "executed" }); return d2.length === 0 ? null : d2[d2.length - 1]; }, b2 = function(_3) { var d2 = _3.type, h3 = _3.fragmentModel, w4 = _3.chunk, E5 = p3(h3); k3({ type: d2, request: E5, chunk: w4 }); }, k3 = function(_3) { var d2 = _3.type, h3 = _3.chunk, w4 = _3.request, E5 = (h3 || {}).mediaInfo, S3 = E5 || {}, N2 = S3.type, M4 = S3.bitrateList; M4 = M4 || []; var P2 = {}; M4.forEach(function(Ee5, z3) { P2[z3] = {}, P2[z3].width = Ee5.width, P2[z3].height = Ee5.height, P2[z3].bitrate = Ee5.bandwidth, P2[z3].attrs = {}; }), N2 === "video" ? u3.video = P2 : N2 === "audio" ? u3.audio = P2 : u3.media = P2; var R4 = It(w4, t2), Z4 = R4.requestStart, Te4 = R4.requestResponseStart, we4 = R4.requestResponseEnd, G3 = R4.requestResponseHeaders, oe5 = R4.requestMediaDuration, Ve4 = R4.requestHostname, We3 = R4.requestUrl, je3 = R4.requestId; o2("requestcompleted", { request_event_type: d2, request_start: Z4, request_response_start: Te4, request_response_end: we4, request_bytes_loaded: -1, request_type: N2 + "_init", request_response_headers: G3, request_hostname: Ve4, request_id: je3, request_url: We3, request_media_duration: oe5, request_rendition_lists: u3 }); }; n2 >= 4 ? t2.on("initFragmentLoaded", k3) : t2.on("initFragmentLoaded", b2); var y4 = function(_3) { var d2 = _3.type, h3 = _3.fragmentModel, w4 = _3.chunk, E5 = p3(h3); c3({ type: d2, request: E5, chunk: w4 }); }, c3 = function(_3) { var d2 = _3.type, h3 = _3.chunk, w4 = _3.request, E5 = h3 || {}, S3 = E5.mediaInfo, N2 = E5.start, M4 = S3 || {}, P2 = M4.type, R4 = It(w4, t2), Z4 = R4.requestStart, Te4 = R4.requestResponseStart, we4 = R4.requestResponseEnd, G3 = R4.requestBytesLoaded, oe5 = R4.requestResponseHeaders, Ve4 = R4.requestMediaDuration, We3 = R4.requestHostname, je3 = R4.requestUrl, Ee5 = R4.requestId, z3 = ua(P2, t2), Jr = z3.currentLevel, Qr = z3.renditionWidth, zr = z3.renditionHeight, Kr = z3.renditionBitrate; o2("requestcompleted", { request_event_type: d2, request_start: Z4, request_response_start: Te4, request_response_end: we4, request_bytes_loaded: G3, request_type: P2, request_response_headers: oe5, request_hostname: We3, request_id: Ee5, request_url: je3, request_media_start_time: N2, request_media_duration: Ve4, request_current_level: Jr, request_labeled_bitrate: Kr, request_video_width: Qr, request_video_height: zr }); }; n2 >= 4 ? t2.on("mediaFragmentLoaded", c3) : t2.on("mediaFragmentLoaded", y4); var v2 = { video: void 0, audio: void 0, totalBitrate: void 0 }, T3 = function() { if (v2.video && typeof v2.video.bitrate == "number") { if (!(v2.video.width && v2.video.height)) { a2.warn("have bitrate info for video but missing width/height"); return; } var _3 = v2.video.bitrate; if (v2.audio && typeof v2.audio.bitrate == "number" && (_3 += v2.audio.bitrate), _3 !== v2.totalBitrate) return v2.totalBitrate = _3, { video_source_bitrate: _3, video_source_height: v2.video.height, video_source_width: v2.video.width, video_source_codec: da(v2.video.codec) }; } }, x2 = function(_3, d2, h3) { if (typeof _3.newQuality != "number") { a2.warn("missing evt.newQuality in qualityChangeRendered event", _3); return; } var w4 = _3.mediaType; if (w4 === "audio" || w4 === "video") { var E5 = t2.getBitrateInfoListFor(w4).find(function(N2) { var M4 = N2.qualityIndex; return M4 === _3.newQuality; }); if (!(E5 && typeof E5.bitrate == "number")) { a2.warn("missing bitrate info for ".concat(w4)); return; } v2[w4] = fe(ue({}, E5), { codec: t2.getCurrentTrackFor(w4).codec }); var S3 = T3(); S3 && o2("renditionchange", S3); } }; t2.on("qualityChangeRendered", x2); var m2 = function(_3) { var d2 = _3.request, h3 = _3.mediaType; d2 = d2 || {}, o2("requestcanceled", { request_event_type: d2.type + "_" + d2.action, request_url: d2.url, request_type: h3, request_hostname: F(d2.url) }); }; t2.on("fragmentLoadingAbandoned", m2); var f = function(_3) { var d2 = _3.error, h3, w4, E5 = (d2 == null || (h3 = d2.data) === null || h3 === void 0 ? void 0 : h3.request) || {}, S3 = (d2 == null || (w4 = d2.data) === null || w4 === void 0 ? void 0 : w4.response) || {}; (d2 == null ? void 0 : d2.code) === 27 && o2("requestfailed", { request_error: E5.type + "_" + E5.action, request_url: E5.url, request_hostname: F(E5.url), request_type: E5.mediaType, request_error_code: S3.status, request_error_text: S3.statusText }); var N2 = "".concat(E5 != null && E5.url ? "url: ".concat(E5.url, "\n") : "") + "".concat(S3 != null && S3.status || S3 != null && S3.statusText ? "response: ".concat(S3 == null ? void 0 : S3.status, ", ").concat(S3 == null ? void 0 : S3.statusText, "\n") : ""); o2("error", { player_error_code: d2 == null ? void 0 : d2.code, player_error_message: d2 == null ? void 0 : d2.message, player_error_context: N2 }); }; t2.on("error", f), t2._stopMuxMonitor = function() { t2.off("manifestLoaded", s), t2.off("initFragmentLoaded", k3), t2.off("mediaFragmentLoaded", c3), t2.off("qualityChangeRendered", x2), t2.off("error", f), t2.off("fragmentLoadingAbandoned", m2), delete t2._stopMuxMonitor; }; }; var Lt = function(r9) { r9 && typeof r9._stopMuxMonitor == "function" && r9._stopMuxMonitor(); }; var Ct = 0; var ca = function() { "use strict"; function r9() { D(this, r9), l(this, "_listeners", void 0); } return L(r9, [{ key: "on", value: function(t2, i3, a2) { return i3._eventEmitterGuid = i3._eventEmitterGuid || ++Ct, this._listeners = this._listeners || {}, this._listeners[t2] = this._listeners[t2] || [], a2 && (i3 = i3.bind(a2)), this._listeners[t2].push(i3), i3; } }, { key: "off", value: function(t2, i3) { var a2 = this._listeners && this._listeners[t2]; a2 && a2.forEach(function(n2, o2) { n2._eventEmitterGuid === i3._eventEmitterGuid && a2.splice(o2, 1); }); } }, { key: "one", value: function(t2, i3, a2) { var n2 = this; i3._eventEmitterGuid = i3._eventEmitterGuid || ++Ct; var o2 = function() { n2.off(t2, o2), i3.apply(a2 || this, arguments); }; o2._eventEmitterGuid = i3._eventEmitterGuid, this.on(t2, o2); } }, { key: "emit", value: function(t2, i3) { var a2 = this; if (this._listeners) { i3 = i3 || {}; var n2 = this._listeners["before*"] || [], o2 = this._listeners[t2] || [], s = this._listeners["after" + t2] || [], u3 = function(p3, b2) { p3 = p3.slice(), p3.forEach(function(k3) { k3.call(a2, { type: t2 }, b2); }); }; u3(n2, i3), u3(o2, i3), u3(s, i3); } } }]), r9; }(); var Mt = ca; var He = V(J()); var _a = function() { "use strict"; function r9(e) { var t2 = this; D(this, r9), l(this, "_playbackHeartbeatInterval", void 0), l(this, "_playheadShouldBeProgressing", void 0), l(this, "pm", void 0), this.pm = e, this._playbackHeartbeatInterval = null, this._playheadShouldBeProgressing = false, e.on("playing", function() { t2._playheadShouldBeProgressing = true; }), e.on("play", this._startPlaybackHeartbeatInterval.bind(this)), e.on("playing", this._startPlaybackHeartbeatInterval.bind(this)), e.on("adbreakstart", this._startPlaybackHeartbeatInterval.bind(this)), e.on("adplay", this._startPlaybackHeartbeatInterval.bind(this)), e.on("adplaying", this._startPlaybackHeartbeatInterval.bind(this)), e.on("devicewake", this._startPlaybackHeartbeatInterval.bind(this)), e.on("viewstart", this._startPlaybackHeartbeatInterval.bind(this)), e.on("rebufferstart", this._startPlaybackHeartbeatInterval.bind(this)), e.on("pause", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("ended", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("viewend", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("error", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("aderror", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("adpause", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("adended", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("adbreakend", this._stopPlaybackHeartbeatInterval.bind(this)), e.on("seeked", function() { e.data.player_is_paused ? t2._stopPlaybackHeartbeatInterval() : t2._startPlaybackHeartbeatInterval(); }), e.on("timeupdate", function() { t2._playbackHeartbeatInterval !== null && e.emit("playbackheartbeat"); }), e.on("devicesleep", function(i3, a2) { t2._playbackHeartbeatInterval !== null && (He.default.clearInterval(t2._playbackHeartbeatInterval), e.emit("playbackheartbeatend", { viewer_time: a2.viewer_time }), t2._playbackHeartbeatInterval = null); }); } return L(r9, [{ key: "_startPlaybackHeartbeatInterval", value: function() { var t2 = this; this._playbackHeartbeatInterval === null && (this.pm.emit("playbackheartbeat"), this._playbackHeartbeatInterval = He.default.setInterval(function() { t2.pm.emit("playbackheartbeat"); }, this.pm.playbackHeartbeatTime)); } }, { key: "_stopPlaybackHeartbeatInterval", value: function() { this._playheadShouldBeProgressing = false, this._playbackHeartbeatInterval !== null && (He.default.clearInterval(this._playbackHeartbeatInterval), this.pm.emit("playbackheartbeatend"), this._playbackHeartbeatInterval = null); } }]), r9; }(); var Ht = _a; var fa = function r(e) { "use strict"; var t2 = this; D(this, r), l(this, "viewErrored", void 0), e.on("viewinit", function() { t2.viewErrored = false; }), e.on("error", function(i3, a2) { try { var n2 = e.errorTranslator({ player_error_code: a2.player_error_code, player_error_message: a2.player_error_message, player_error_context: a2.player_error_context, player_error_severity: a2.player_error_severity, player_error_business_exception: a2.player_error_business_exception }); n2 && (e.data.player_error_code = n2.player_error_code || a2.player_error_code, e.data.player_error_message = n2.player_error_message || a2.player_error_message, e.data.player_error_context = n2.player_error_context || a2.player_error_context, e.data.player_error_severity = n2.player_error_severity || a2.player_error_severity, e.data.player_error_business_exception = n2.player_error_business_exception || a2.player_error_business_exception, t2.viewErrored = true); } catch (o2) { e.mux.log.warn("Exception in error translator callback.", o2), t2.viewErrored = true; } }), e.on("aftererror", function() { var i3, a2, n2, o2, s; (i3 = e.data) === null || i3 === void 0 || delete i3.player_error_code, (a2 = e.data) === null || a2 === void 0 || delete a2.player_error_message, (n2 = e.data) === null || n2 === void 0 || delete n2.player_error_context, (o2 = e.data) === null || o2 === void 0 || delete o2.player_error_severity, (s = e.data) === null || s === void 0 || delete s.player_error_business_exception; }); }; var Bt = fa; var pa = function() { "use strict"; function r9(e) { D(this, r9), l(this, "_watchTimeTrackerLastCheckedTime", void 0), l(this, "pm", void 0), this.pm = e, this._watchTimeTrackerLastCheckedTime = null, e.on("playbackheartbeat", this._updateWatchTime.bind(this)), e.on("playbackheartbeatend", this._clearWatchTimeState.bind(this)); } return L(r9, [{ key: "_updateWatchTime", value: function(t2, i3) { var a2 = i3.viewer_time; this._watchTimeTrackerLastCheckedTime === null && (this._watchTimeTrackerLastCheckedTime = a2), O(this.pm.data, "view_watch_time", a2 - this._watchTimeTrackerLastCheckedTime), this._watchTimeTrackerLastCheckedTime = a2; } }, { key: "_clearWatchTimeState", value: function(t2, i3) { this._updateWatchTime(t2, i3), this._watchTimeTrackerLastCheckedTime = null; } }]), r9; }(); var Ut = pa; var va = function() { "use strict"; function r9(e) { var t2 = this; D(this, r9), l(this, "_playbackTimeTrackerLastPlayheadPosition", void 0), l(this, "_lastTime", void 0), l(this, "_isAdPlaying", void 0), l(this, "_callbackUpdatePlaybackTime", void 0), l(this, "pm", void 0), this.pm = e, this._playbackTimeTrackerLastPlayheadPosition = -1, this._lastTime = A.now(), this._isAdPlaying = false, this._callbackUpdatePlaybackTime = null; var i3 = this._startPlaybackTimeTracking.bind(this); e.on("playing", i3), e.on("adplaying", i3), e.on("seeked", i3); var a2 = this._stopPlaybackTimeTracking.bind(this); e.on("playbackheartbeatend", a2), e.on("seeking", a2), e.on("adplaying", function() { t2._isAdPlaying = true; }), e.on("adended", function() { t2._isAdPlaying = false; }), e.on("adpause", function() { t2._isAdPlaying = false; }), e.on("adbreakstart", function() { t2._isAdPlaying = false; }), e.on("adbreakend", function() { t2._isAdPlaying = false; }), e.on("adplay", function() { t2._isAdPlaying = false; }), e.on("viewinit", function() { t2._playbackTimeTrackerLastPlayheadPosition = -1, t2._lastTime = A.now(), t2._isAdPlaying = false, t2._callbackUpdatePlaybackTime = null; }); } return L(r9, [{ key: "_startPlaybackTimeTracking", value: function() { this._callbackUpdatePlaybackTime === null && (this._callbackUpdatePlaybackTime = this._updatePlaybackTime.bind(this), this._playbackTimeTrackerLastPlayheadPosition = this.pm.data.player_playhead_time, this.pm.on("playbackheartbeat", this._callbackUpdatePlaybackTime)); } }, { key: "_stopPlaybackTimeTracking", value: function() { this._callbackUpdatePlaybackTime && (this._updatePlaybackTime(), this.pm.off("playbackheartbeat", this._callbackUpdatePlaybackTime), this._callbackUpdatePlaybackTime = null, this._playbackTimeTrackerLastPlayheadPosition = -1); } }, { key: "_updatePlaybackTime", value: function() { var t2 = this.pm.data.player_playhead_time, i3 = A.now(), a2 = -1; this._playbackTimeTrackerLastPlayheadPosition >= 0 && t2 > this._playbackTimeTrackerLastPlayheadPosition ? a2 = t2 - this._playbackTimeTrackerLastPlayheadPosition : this._isAdPlaying && (a2 = i3 - this._lastTime), a2 > 0 && a2 <= 1e3 && O(this.pm.data, "view_content_playback_time", a2), this._playbackTimeTrackerLastPlayheadPosition = t2, this._lastTime = i3; } }]), r9; }(); var Ft = va; var ma = function() { "use strict"; function r9(e) { D(this, r9), l(this, "pm", void 0), this.pm = e; var t2 = this._updatePlayheadTime.bind(this); e.on("playbackheartbeat", t2), e.on("playbackheartbeatend", t2), e.on("timeupdate", t2), e.on("destroy", function() { e.off("timeupdate", t2); }); } return L(r9, [{ key: "_updateMaxPlayheadPosition", value: function() { this.pm.data.view_max_playhead_position = typeof this.pm.data.view_max_playhead_position == "undefined" ? this.pm.data.player_playhead_time : Math.max(this.pm.data.view_max_playhead_position, this.pm.data.player_playhead_time); } }, { key: "_updatePlayheadTime", value: function(t2, i3) { var a2 = this, n2 = function() { a2.pm.currentFragmentPDT && a2.pm.currentFragmentStart && (a2.pm.data.player_program_time = a2.pm.currentFragmentPDT + a2.pm.data.player_playhead_time - a2.pm.currentFragmentStart); }; if (i3 && i3.player_playhead_time) this.pm.data.player_playhead_time = i3.player_playhead_time, n2(), this._updateMaxPlayheadPosition(); else if (this.pm.getPlayheadTime) { var o2 = this.pm.getPlayheadTime(); typeof o2 != "undefined" && (this.pm.data.player_playhead_time = o2, n2(), this._updateMaxPlayheadPosition()); } } }]), r9; }(); var Vt = ma; var Wt = 5 * 60 * 1e3; var ha = function r2(e) { "use strict"; if (D(this, r2), !e.disableRebufferTracking) { var t2, i3 = function(n2, o2) { a2(o2), t2 = void 0; }, a2 = function(n2) { if (t2) { var o2 = n2.viewer_time - t2; O(e.data, "view_rebuffer_duration", o2), t2 = n2.viewer_time, e.data.view_rebuffer_duration > Wt && (e.emit("viewend"), e.send("viewend"), e.mux.log.warn("Ending view after rebuffering for longer than ".concat(Wt, "ms, future events will be ignored unless a programchange or videochange occurs."))); } e.data.view_watch_time >= 0 && e.data.view_rebuffer_count > 0 && (e.data.view_rebuffer_frequency = e.data.view_rebuffer_count / e.data.view_watch_time, e.data.view_rebuffer_percentage = e.data.view_rebuffer_duration / e.data.view_watch_time); }; e.on("playbackheartbeat", function(n2, o2) { return a2(o2); }), e.on("rebufferstart", function(n2, o2) { t2 || (O(e.data, "view_rebuffer_count", 1), t2 = o2.viewer_time, e.one("rebufferend", i3)); }), e.on("viewinit", function() { t2 = void 0, e.off("rebufferend", i3); }); } }; var jt = ha; var ya = function() { "use strict"; function r9(e) { var t2 = this; D(this, r9), l(this, "_lastCheckedTime", void 0), l(this, "_lastPlayheadTime", void 0), l(this, "_lastPlayheadTimeUpdatedTime", void 0), l(this, "_rebuffering", void 0), l(this, "pm", void 0), this.pm = e, !(e.disableRebufferTracking || e.disablePlayheadRebufferTracking) && (this._lastCheckedTime = null, this._lastPlayheadTime = null, this._lastPlayheadTimeUpdatedTime = null, e.on("playbackheartbeat", this._checkIfRebuffering.bind(this)), e.on("playbackheartbeatend", this._cleanupRebufferTracker.bind(this)), e.on("seeking", function() { t2._cleanupRebufferTracker(null, { viewer_time: A.now() }); })); } return L(r9, [{ key: "_checkIfRebuffering", value: function(t2, i3) { if (this.pm.seekingTracker.isSeeking || this.pm.adTracker.isAdBreak || !this.pm.playbackHeartbeat._playheadShouldBeProgressing) { this._cleanupRebufferTracker(t2, i3); return; } if (this._lastCheckedTime === null) { this._prepareRebufferTrackerState(i3.viewer_time); return; } if (this._lastPlayheadTime !== this.pm.data.player_playhead_time) { this._cleanupRebufferTracker(t2, i3, true); return; } var a2 = i3.viewer_time - this._lastPlayheadTimeUpdatedTime; typeof this.pm.sustainedRebufferThreshold == "number" && a2 >= this.pm.sustainedRebufferThreshold && (this._rebuffering || (this._rebuffering = true, this.pm.emit("rebufferstart", { viewer_time: this._lastPlayheadTimeUpdatedTime }))), this._lastCheckedTime = i3.viewer_time; } }, { key: "_clearRebufferTrackerState", value: function() { this._lastCheckedTime = null, this._lastPlayheadTime = null, this._lastPlayheadTimeUpdatedTime = null; } }, { key: "_prepareRebufferTrackerState", value: function(t2) { this._lastCheckedTime = t2, this._lastPlayheadTime = this.pm.data.player_playhead_time, this._lastPlayheadTimeUpdatedTime = t2; } }, { key: "_cleanupRebufferTracker", value: function(t2, i3) { var a2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false; if (this._rebuffering) this._rebuffering = false, this.pm.emit("rebufferend", { viewer_time: i3.viewer_time }); else { if (this._lastCheckedTime === null) return; var n2 = this.pm.data.player_playhead_time - this._lastPlayheadTime, o2 = i3.viewer_time - this._lastPlayheadTimeUpdatedTime; typeof this.pm.minimumRebufferDuration == "number" && n2 > 0 && o2 - n2 > this.pm.minimumRebufferDuration && (this._lastCheckedTime = null, this.pm.emit("rebufferstart", { viewer_time: this._lastPlayheadTimeUpdatedTime }), this.pm.emit("rebufferend", { viewer_time: this._lastPlayheadTimeUpdatedTime + o2 - n2 })); } a2 ? this._prepareRebufferTrackerState(i3.viewer_time) : this._clearRebufferTrackerState(); } }]), r9; }(); var Gt = ya; var ga = function() { "use strict"; function r9(e) { var t2 = this; D(this, r9), l(this, "NAVIGATION_START", void 0), l(this, "pm", void 0), this.pm = e, e.on("viewinit", function() { var i3 = e.data, a2 = i3.view_id; if (!i3.view_program_changed) { var n2 = function(o2, s) { var u3 = s.viewer_time; o2.type === "playing" && typeof e.data.view_time_to_first_frame == "undefined" ? t2.calculateTimeToFirstFrame(u3 || A.now(), a2) : o2.type === "adplaying" && (typeof e.data.view_time_to_first_frame == "undefined" || t2._inPrerollPosition()) && t2.calculateTimeToFirstFrame(u3 || A.now(), a2); }; e.one("playing", n2), e.one("adplaying", n2), e.one("viewend", function() { e.off("playing", n2), e.off("adplaying", n2); }); } }); } return L(r9, [{ key: "_inPrerollPosition", value: function() { return typeof this.pm.data.view_content_playback_time == "undefined" || this.pm.data.view_content_playback_time <= 1e3; } }, { key: "calculateTimeToFirstFrame", value: function(t2, i3) { i3 === this.pm.data.view_id && (this.pm.watchTimeTracker._updateWatchTime(null, { viewer_time: t2 }), this.pm.data.view_time_to_first_frame = this.pm.data.view_watch_time, (this.pm.data.player_autoplay_on || this.pm.data.video_is_autoplay) && this.NAVIGATION_START && (this.pm.data.view_aggregate_startup_time = this.pm.data.view_start + this.pm.data.view_watch_time - this.NAVIGATION_START)); } }]), r9; }(); var Jt = ga; var ba = function r3(e) { "use strict"; var t2 = this; D(this, r3), l(this, "_lastPlayerHeight", void 0), l(this, "_lastPlayerWidth", void 0), l(this, "_lastPlayheadPosition", void 0), l(this, "_lastSourceHeight", void 0), l(this, "_lastSourceWidth", void 0), e.on("viewinit", function() { t2._lastPlayheadPosition = -1; }); var i3 = ["pause", "rebufferstart", "seeking", "error", "adbreakstart", "hb", "renditionchange", "orientationchange", "viewend"], a2 = ["playing", "hb", "renditionchange", "orientationchange"]; i3.forEach(function(n2) { e.on(n2, function() { if (t2._lastPlayheadPosition >= 0 && e.data.player_playhead_time >= 0 && t2._lastPlayerWidth >= 0 && t2._lastSourceWidth > 0 && t2._lastPlayerHeight >= 0 && t2._lastSourceHeight > 0) { var o2 = e.data.player_playhead_time - t2._lastPlayheadPosition; if (o2 < 0) { t2._lastPlayheadPosition = -1; return; } var s = Math.min(t2._lastPlayerWidth / t2._lastSourceWidth, t2._lastPlayerHeight / t2._lastSourceHeight), u3 = Math.max(0, s - 1), p3 = Math.max(0, 1 - s); e.data.view_max_upscale_percentage = Math.max(e.data.view_max_upscale_percentage || 0, u3), e.data.view_max_downscale_percentage = Math.max(e.data.view_max_downscale_percentage || 0, p3), O(e.data, "view_total_content_playback_time", o2), O(e.data, "view_total_upscaling", u3 * o2), O(e.data, "view_total_downscaling", p3 * o2); } t2._lastPlayheadPosition = -1; }); }), a2.forEach(function(n2) { e.on(n2, function() { t2._lastPlayheadPosition = e.data.player_playhead_time, t2._lastPlayerWidth = e.data.player_width, t2._lastPlayerHeight = e.data.player_height, t2._lastSourceWidth = e.data.video_source_width, t2._lastSourceHeight = e.data.video_source_height; }); }); }; var Qt = ba; var Ta = 2e3; var wa = function r4(e) { "use strict"; var t2 = this; D(this, r4), l(this, "isSeeking", void 0), this.isSeeking = false; var i3 = -1, a2 = function() { var n2 = A.now(), o2 = (e.data.viewer_time || n2) - (i3 || n2); O(e.data, "view_seek_duration", o2), e.data.view_max_seek_time = Math.max(e.data.view_max_seek_time || 0, o2), t2.isSeeking = false, i3 = -1; }; e.on("seeking", function(n2, o2) { if (Object.assign(e.data, o2), t2.isSeeking && o2.viewer_time - i3 <= Ta) { i3 = o2.viewer_time; return; } t2.isSeeking && a2(), t2.isSeeking = true, i3 = o2.viewer_time, O(e.data, "view_seek_count", 1), e.send("seeking"); }), e.on("seeked", function() { a2(); }), e.on("viewend", function() { t2.isSeeking && (a2(), e.send("seeked")), t2.isSeeking = false, i3 = -1; }); }; var zt = wa; var Kt = function(e, t2) { e.push(t2), e.sort(function(i3, a2) { return i3.viewer_time - a2.viewer_time; }); }; var Ea = ["adbreakstart", "adrequest", "adresponse", "adplay", "adplaying", "adpause", "adended", "adbreakend", "aderror", "adclicked", "adskipped"]; var ka = function() { "use strict"; function r9(e) { var t2 = this; D(this, r9), l(this, "_adHasPlayed", void 0), l(this, "_adRequests", void 0), l(this, "_adResponses", void 0), l(this, "_currentAdRequestNumber", void 0), l(this, "_currentAdResponseNumber", void 0), l(this, "_prerollPlayTime", void 0), l(this, "_wouldBeNewAdPlay", void 0), l(this, "isAdBreak", void 0), l(this, "pm", void 0), this.pm = e, e.on("viewinit", function() { t2.isAdBreak = false, t2._currentAdRequestNumber = 0, t2._currentAdResponseNumber = 0, t2._adRequests = [], t2._adResponses = [], t2._adHasPlayed = false, t2._wouldBeNewAdPlay = true, t2._prerollPlayTime = void 0; }), Ea.forEach(function(a2) { return e.on(a2, t2._updateAdData.bind(t2)); }); var i3 = function() { t2.isAdBreak = false; }; e.on("adbreakstart", function() { t2.isAdBreak = true; }), e.on("play", i3), e.on("playing", i3), e.on("viewend", i3), e.on("adrequest", function(a2, n2) { n2 = Object.assign({ ad_request_id: "generatedAdRequestId" + t2._currentAdRequestNumber++ }, n2), Kt(t2._adRequests, n2), O(e.data, "view_ad_request_count"), t2.inPrerollPosition() && (e.data.view_preroll_requested = true, t2._adHasPlayed || O(e.data, "view_preroll_request_count")); }), e.on("adresponse", function(a2, n2) { n2 = Object.assign({ ad_request_id: "generatedAdRequestId" + t2._currentAdResponseNumber++ }, n2), Kt(t2._adResponses, n2); var o2 = t2.findAdRequest(n2.ad_request_id); o2 && O(e.data, "view_ad_request_time", Math.max(0, n2.viewer_time - o2.viewer_time)); }), e.on("adplay", function(a2, n2) { t2._adHasPlayed = true, t2._wouldBeNewAdPlay && (t2._wouldBeNewAdPlay = false, O(e.data, "view_ad_played_count")), t2.inPrerollPosition() && !e.data.view_preroll_played && (e.data.view_preroll_played = true, t2._adRequests.length > 0 && (e.data.view_preroll_request_time = Math.max(0, n2.viewer_time - t2._adRequests[0].viewer_time)), e.data.view_start && (e.data.view_startup_preroll_request_time = Math.max(0, n2.viewer_time - e.data.view_start)), t2._prerollPlayTime = n2.viewer_time); }), e.on("adplaying", function(a2, n2) { t2.inPrerollPosition() && typeof e.data.view_preroll_load_time == "undefined" && typeof t2._prerollPlayTime != "undefined" && (e.data.view_preroll_load_time = n2.viewer_time - t2._prerollPlayTime, e.data.view_startup_preroll_load_time = n2.viewer_time - t2._prerollPlayTime); }), e.on("adclicked", function(a2, n2) { t2._wouldBeNewAdPlay || O(e.data, "view_ad_clicked_count"); }), e.on("adskipped", function(a2, n2) { t2._wouldBeNewAdPlay || O(e.data, "view_ad_skipped_count"); }), e.on("adended", function() { t2._wouldBeNewAdPlay = true; }), e.on("aderror", function() { t2._wouldBeNewAdPlay = true; }); } return L(r9, [{ key: "inPrerollPosition", value: function() { return typeof this.pm.data.view_content_playback_time == "undefined" || this.pm.data.view_content_playback_time <= 1e3; } }, { key: "findAdRequest", value: function(t2) { for (var i3 = 0; i3 < this._adRequests.length; i3++) if (this._adRequests[i3].ad_request_id === t2) return this._adRequests[i3]; } }, { key: "_updateAdData", value: function(t2, i3) { if (this.inPrerollPosition()) { if (!this.pm.data.view_preroll_ad_tag_hostname && i3.ad_tag_url) { var a2 = H(re(i3.ad_tag_url), 2), n2 = a2[0], o2 = a2[1]; this.pm.data.view_preroll_ad_tag_domain = o2, this.pm.data.view_preroll_ad_tag_hostname = n2; } if (!this.pm.data.view_preroll_ad_asset_hostname && i3.ad_asset_url) { var s = H(re(i3.ad_asset_url), 2), u3 = s[0], p3 = s[1]; this.pm.data.view_preroll_ad_asset_domain = p3, this.pm.data.view_preroll_ad_asset_hostname = u3; } } this.pm.data.ad_asset_url = i3 == null ? void 0 : i3.ad_asset_url, this.pm.data.ad_tag_url = i3 == null ? void 0 : i3.ad_tag_url, this.pm.data.ad_creative_id = i3 == null ? void 0 : i3.ad_creative_id, this.pm.data.ad_id = i3 == null ? void 0 : i3.ad_id, this.pm.data.ad_universal_id = i3 == null ? void 0 : i3.ad_universal_id; } }]), r9; }(); var Yt = ka; var Qe = V(J()); var xa = function r5(e) { "use strict"; D(this, r5); var t2, i3, a2 = function() { e.disableRebufferTracking || (O(e.data, "view_waiting_rebuffer_count", 1), t2 = A.now(), i3 = Qe.default.setInterval(function() { if (t2) { var p3 = A.now(); O(e.data, "view_waiting_rebuffer_duration", p3 - t2), t2 = p3; } }, 250)); }, n2 = function() { e.disableRebufferTracking || t2 && (O(e.data, "view_waiting_rebuffer_duration", A.now() - t2), t2 = false, Qe.default.clearInterval(i3)); }, o2 = false, s = function() { o2 = true; }, u3 = function() { o2 = false, n2(); }; e.on("waiting", function() { o2 && a2(); }), e.on("playing", function() { n2(), s(); }), e.on("pause", u3), e.on("seeking", u3); }; var Xt = xa; var Da = function r6(e) { "use strict"; var t2 = this; D(this, r6), l(this, "lastWallClockTime", void 0); var i3 = function() { t2.lastWallClockTime = A.now(), e.on("before*", a2); }, a2 = function(n2) { var o2 = A.now(), s = t2.lastWallClockTime; t2.lastWallClockTime = o2, o2 - s > 3e4 && (e.emit("devicesleep", { viewer_time: s }), Object.assign(e.data, { viewer_time: s }), e.send("devicesleep"), e.emit("devicewake", { viewer_time: o2 }), Object.assign(e.data, { viewer_time: o2 }), e.send("devicewake")); }; e.one("playbackheartbeat", i3), e.on("playbackheartbeatend", function() { e.off("before*", a2), e.one("playbackheartbeat", i3); }); }; var $t = Da; var Ue = V(J()); var ze = function(r9) { return r9(); }(function() { var r9 = function() { for (var i3 = 0, a2 = {}; i3 < arguments.length; i3++) { var n2 = arguments[i3]; for (var o2 in n2) a2[o2] = n2[o2]; } return a2; }; function e(t2) { function i3(a2, n2, o2) { var s; if (typeof document != "undefined") { if (arguments.length > 1) { if (o2 = r9({ path: "/" }, i3.defaults, o2), typeof o2.expires == "number") { var u3 = /* @__PURE__ */ new Date(); u3.setMilliseconds(u3.getMilliseconds() + o2.expires * 864e5), o2.expires = u3; } try { s = JSON.stringify(n2), /^[\{\[]/.test(s) && (n2 = s); } catch (T3) { } return t2.write ? n2 = t2.write(n2, a2) : n2 = encodeURIComponent(String(n2)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent), a2 = encodeURIComponent(String(a2)), a2 = a2.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent), a2 = a2.replace(/[\(\)]/g, escape), document.cookie = [a2, "=", n2, o2.expires ? "; expires=" + o2.expires.toUTCString() : "", o2.path ? "; path=" + o2.path : "", o2.domain ? "; domain=" + o2.domain : "", o2.secure ? "; secure" : ""].join(""); } a2 || (s = {}); for (var p3 = document.cookie ? document.cookie.split("; ") : [], b2 = /(%[0-9A-Z]{2})+/g, k3 = 0; k3 < p3.length; k3++) { var y4 = p3[k3].split("="), c3 = y4.slice(1).join("="); c3.charAt(0) === '"' && (c3 = c3.slice(1, -1)); try { var v2 = y4[0].replace(b2, decodeURIComponent); if (c3 = t2.read ? t2.read(c3, v2) : t2(c3, v2) || c3.replace(b2, decodeURIComponent), this.json) try { c3 = JSON.parse(c3); } catch (T3) { } if (a2 === v2) { s = c3; break; } a2 || (s[v2] = c3); } catch (T3) { } } return s; } } return i3.set = i3, i3.get = function(a2) { return i3.call(i3, a2); }, i3.getJSON = function() { return i3.apply({ json: true }, [].slice.call(arguments)); }, i3.defaults = {}, i3.remove = function(a2, n2) { i3(a2, "", r9(n2, { expires: -1 })); }, i3.withConverter = e, i3; } return e(function() { }); }); var Zt = "muxData"; var Sa = function(r9) { return Object.entries(r9).map(function(e) { var t2 = H(e, 2), i3 = t2[0], a2 = t2[1]; return "".concat(i3, "=").concat(a2); }).join("&"); }; var Ra = function(r9) { return r9.split("&").reduce(function(e, t2) { var i3 = H(t2.split("="), 2), a2 = i3[0], n2 = i3[1], o2 = +n2, s = n2 && o2 == n2 ? o2 : n2; return e[a2] = s, e; }, {}); }; var er = function() { var e; try { e = Ra(ze.get(Zt) || ""); } catch (t2) { e = {}; } return e; }; var tr = function(e) { try { ze.set(Zt, Sa(e), { expires: 365 }); } catch (t2) { } }; var rr = function() { var e = er(); return e.mux_viewer_id = e.mux_viewer_id || ee(), e.msn = e.msn || Math.random(), tr(e), { mux_viewer_id: e.mux_viewer_id, mux_sample_number: e.msn }; }; var ar = function() { var e = er(), t2 = A.now(); return e.session_start && (e.sst = e.session_start, delete e.session_start), e.session_id && (e.sid = e.session_id, delete e.session_id), e.session_expires && (e.sex = e.session_expires, delete e.session_expires), (!e.sex || e.sex < t2) && (e.sid = ee(), e.sst = t2), e.sex = t2 + 25 * 60 * 1e3, tr(e), { session_id: e.sid, session_start: e.sst, session_expires: e.sex }; }; function Ke(r9, e) { var t2 = e.beaconCollectionDomain, i3 = e.beaconDomain; if (t2) return "https://" + t2; r9 = r9 || "inferred"; var a2 = i3 || "litix.io"; return r9.match(/^[a-z0-9]+$/) ? "https://" + r9 + "." + a2 : "https://img.litix.io/a.gif"; } var ir = V(J()); var nr = function() { var e; switch (or()) { case "cellular": e = "cellular"; break; case "ethernet": e = "wired"; break; case "wifi": e = "wifi"; break; case void 0: break; default: e = "other"; } return e; }; var or = function() { var e = ir.default.navigator, t2 = e && (e.connection || e.mozConnection || e.webkitConnection); return t2 && t2.type; }; nr.getConnectionFromAPI = or; var sr = nr; var qa = { a: "env", b: "beacon", c: "custom", d: "ad", e: "event", f: "experiment", i: "internal", m: "mux", n: "response", p: "player", q: "request", r: "retry", s: "session", t: "timestamp", u: "viewer", v: "video", w: "page", x: "view", y: "sub" }; var Aa = dr(qa); var Oa = { ad: "ad", af: "affiliate", ag: "aggregate", ap: "api", al: "application", ao: "audio", ar: "architecture", as: "asset", au: "autoplay", av: "average", bi: "bitrate", bn: "brand", br: "break", bw: "browser", by: "bytes", bz: "business", ca: "cached", cb: "cancel", cc: "codec", cd: "code", cg: "category", ch: "changed", ci: "client", ck: "clicked", cl: "canceled", cn: "config", co: "count", ce: "counter", cp: "complete", cq: "creator", cr: "creative", cs: "captions", ct: "content", cu: "current", cx: "connection", cz: "context", dg: "downscaling", dm: "domain", dn: "cdn", do: "downscale", dr: "drm", dp: "dropped", du: "duration", dv: "device", dy: "dynamic", eb: "enabled", ec: "encoding", ed: "edge", en: "end", eg: "engine", em: "embed", er: "error", ep: "experiments", es: "errorcode", et: "errortext", ee: "event", ev: "events", ex: "expires", ez: "exception", fa: "failed", fi: "first", fm: "family", ft: "format", fp: "fps", fq: "frequency", fr: "frame", fs: "fullscreen", ha: "has", hb: "holdback", he: "headers", ho: "host", hn: "hostname", ht: "height", id: "id", ii: "init", in: "instance", ip: "ip", is: "is", ke: "key", la: "language", lb: "labeled", le: "level", li: "live", ld: "loaded", lo: "load", ls: "lists", lt: "latency", ma: "max", md: "media", me: "message", mf: "manifest", mi: "mime", ml: "midroll", mm: "min", mn: "manufacturer", mo: "model", mx: "mux", ne: "newest", nm: "name", no: "number", on: "on", or: "origin", os: "os", pa: "paused", pb: "playback", pd: "producer", pe: "percentage", pf: "played", pg: "program", ph: "playhead", pi: "plugin", pl: "preroll", pn: "playing", po: "poster", pp: "pip", pr: "preload", ps: "position", pt: "part", py: "property", px: "pop", pz: "plan", ra: "rate", rd: "requested", re: "rebuffer", rf: "rendition", rg: "range", rm: "remote", ro: "ratio", rp: "response", rq: "request", rs: "requests", sa: "sample", sd: "skipped", se: "session", sh: "shift", sk: "seek", sm: "stream", so: "source", sq: "sequence", sr: "series", ss: "status", st: "start", su: "startup", sv: "server", sw: "software", sy: "severity", ta: "tag", tc: "tech", te: "text", tg: "target", th: "throughput", ti: "time", tl: "total", to: "to", tt: "title", ty: "type", ug: "upscaling", un: "universal", up: "upscale", ur: "url", us: "user", va: "variant", vd: "viewed", vi: "video", ve: "version", vw: "view", vr: "viewer", wd: "width", wa: "watch", wt: "waiting" }; var ur = dr(Oa); function dr(r9) { var e = {}; for (var t2 in r9) r9.hasOwnProperty(t2) && (e[r9[t2]] = t2); return e; } function ve(r9) { var e = {}, t2 = {}; return Object.keys(r9).forEach(function(i3) { var a2 = false; if (r9.hasOwnProperty(i3) && r9[i3] !== void 0) { var n2 = i3.split("_"), o2 = n2[0], s = Aa[o2]; s || (q.info("Data key word `" + n2[0] + "` not expected in " + i3), s = o2 + "_"), n2.splice(1).forEach(function(u3) { u3 === "url" && (a2 = true), ur[u3] ? s += ur[u3] : Number.isInteger(Number(u3)) ? s += u3 : (q.info("Data key word `" + u3 + "` not expected in " + i3), s += "_" + u3 + "_"); }), a2 ? t2[s] = r9[i3] : e[s] = r9[i3]; } }), Object.assign(e, t2); } var ie = V(J()); var Lr = V(nt2()); var ai = { maxBeaconSize: 300, maxQueueLength: 3600, baseTimeBetweenBeacons: 1e4, maxPayloadKBSize: 500 }; var ii = 56 * 1024; var ni = ["hb", "requestcompleted", "requestfailed", "requestcanceled"]; var oi = "https://img.litix.io"; var $ = function(e) { var t2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; this._beaconUrl = e || oi, this._eventQueue = [], this._postInFlight = false, this._resendAfterPost = false, this._failureCount = 0, this._sendTimeout = false, this._options = Object.assign({}, ai, t2); }; $.prototype.queueEvent = function(r9, e) { var t2 = Object.assign({}, e); return this._eventQueue.length <= this._options.maxQueueLength || r9 === "eventrateexceeded" ? (this._eventQueue.push(t2), this._sendTimeout || this._startBeaconSending(), this._eventQueue.length <= this._options.maxQueueLength) : false; }; $.prototype.flushEvents = function() { var r9 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false; if (r9 && this._eventQueue.length === 1) { this._eventQueue.pop(); return; } this._eventQueue.length && this._sendBeaconQueue(), this._startBeaconSending(); }; $.prototype.destroy = function() { var r9 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false; this.destroyed = true, r9 ? this._clearBeaconQueue() : this.flushEvents(), ie.default.clearTimeout(this._sendTimeout); }; $.prototype._clearBeaconQueue = function() { var r9 = this._eventQueue.length > this._options.maxBeaconSize ? this._eventQueue.length - this._options.maxBeaconSize : 0, e = this._eventQueue.slice(r9); r9 > 0 && Object.assign(e[e.length - 1], ve({ mux_view_message: "event queue truncated" })); var t2 = this._createPayload(e); Cr(this._beaconUrl, t2, true, function() { }); }; $.prototype._sendBeaconQueue = function() { var r9 = this; if (this._postInFlight) { this._resendAfterPost = true; return; } var e = this._eventQueue.slice(0, this._options.maxBeaconSize); this._eventQueue = this._eventQueue.slice(this._options.maxBeaconSize), this._postInFlight = true; var t2 = this._createPayload(e), i3 = A.now(); Cr(this._beaconUrl, t2, false, function(a2, n2) { n2 ? (r9._eventQueue = e.concat(r9._eventQueue), r9._failureCount += 1, q.info("Error sending beacon: " + n2)) : r9._failureCount = 0, r9._roundTripTime = A.now() - i3, r9._postInFlight = false, r9._resendAfterPost && (r9._resendAfterPost = false, r9._eventQueue.length > 0 && r9._sendBeaconQueue()); }); }; $.prototype._getNextBeaconTime = function() { if (!this._failureCount) return this._options.baseTimeBetweenBeacons; var r9 = Math.pow(2, this._failureCount - 1); return r9 = r9 * Math.random(), (1 + r9) * this._options.baseTimeBetweenBeacons; }; $.prototype._startBeaconSending = function() { var r9 = this; ie.default.clearTimeout(this._sendTimeout), !this.destroyed && (this._sendTimeout = ie.default.setTimeout(function() { r9._eventQueue.length && r9._sendBeaconQueue(), r9._startBeaconSending(); }, this._getNextBeaconTime())); }; $.prototype._createPayload = function(r9) { var e = this, t2 = { transmission_timestamp: Math.round(A.now()) }; this._roundTripTime && (t2.rtt_ms = Math.round(this._roundTripTime)); var i3, a2, n2, o2 = function() { i3 = JSON.stringify({ metadata: t2, events: a2 || r9 }), n2 = i3.length / 1024; }, s = function() { return n2 <= e._options.maxPayloadKBSize; }; return o2(), s() || (q.info("Payload size is too big (" + n2 + " kb). Removing unnecessary events."), a2 = r9.filter(function(u3) { return ni.indexOf(u3.e) === -1; }), o2()), s() || (q.info("Payload size still too big (" + n2 + " kb). Cropping fields.."), a2.forEach(function(u3) { for (var p3 in u3) { var b2 = u3[p3], k3 = 50 * 1024; typeof b2 == "string" && b2.length > k3 && (u3[p3] = b2.substring(0, k3)); } }), o2()), i3; }; var si = typeof Lr.default.exitPictureInPicture == "function" ? function(r9) { return r9.length <= ii; } : function(r9) { return false; }; var Cr = function(r9, e, t2, i3) { if (t2 && navigator && navigator.sendBeacon && navigator.sendBeacon(r9, e)) { i3(); return; } if (ie.default.fetch) { ie.default.fetch(r9, { method: "POST", body: e, headers: { "Content-Type": "text/plain" }, keepalive: si(e) }).then(function(n2) { return i3(null, n2.ok ? null : "Error"); }).catch(function(n2) { return i3(null, n2); }); return; } if (ie.default.XMLHttpRequest) { var a2 = new ie.default.XMLHttpRequest(); a2.onreadystatechange = function() { if (a2.readyState === 4) return i3(null, a2.status !== 200 ? "error" : void 0); }, a2.open("POST", r9), a2.setRequestHeader("Content-Type", "text/plain"), a2.send(e); return; } i3(); }; var Mr = $; var ui = ["env_key", "view_id", "view_sequence_number", "player_sequence_number", "beacon_domain", "player_playhead_time", "viewer_time", "mux_api_version", "event", "video_id", "player_instance_id", "player_error_code", "player_error_message", "player_error_context", "player_error_severity", "player_error_business_exception"]; var di = ["adplay", "adplaying", "adpause", "adfirstquartile", "admidpoint", "adthirdquartile", "adended", "adresponse", "adrequest"]; var li = ["ad_id", "ad_creative_id", "ad_universal_id"]; var ci = ["viewstart", "error", "ended", "viewend"]; var _i = 10 * 60 * 1e3; var Hr = function() { "use strict"; function r9(e, t2) { var i3 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; D(this, r9); var a2, n2, o2, s, u3, p3, b2, k3, y4, c3, v2, T3; l(this, "mux", void 0), l(this, "envKey", void 0), l(this, "options", void 0), l(this, "eventQueue", void 0), l(this, "sampleRate", void 0), l(this, "disableCookies", void 0), l(this, "respectDoNotTrack", void 0), l(this, "previousBeaconData", void 0), l(this, "lastEventTime", void 0), l(this, "rateLimited", void 0), l(this, "pageLevelData", void 0), l(this, "viewerData", void 0), this.mux = e, this.envKey = t2, this.options = i3, this.previousBeaconData = null, this.lastEventTime = 0, this.rateLimited = false, this.eventQueue = new Mr(Ke(this.envKey, this.options)); var x2; this.sampleRate = (x2 = this.options.sampleRate) !== null && x2 !== void 0 ? x2 : 1; var m2; this.disableCookies = (m2 = this.options.disableCookies) !== null && m2 !== void 0 ? m2 : false; var f; this.respectDoNotTrack = (f = this.options.respectDoNotTrack) !== null && f !== void 0 ? f : false, this.previousBeaconData = null, this.lastEventTime = 0, this.rateLimited = false, this.pageLevelData = { mux_api_version: this.mux.API_VERSION, mux_embed: this.mux.NAME, mux_embed_version: this.mux.VERSION, viewer_application_name: (a2 = this.options.platform) === null || a2 === void 0 ? void 0 : a2.name, viewer_application_version: (n2 = this.options.platform) === null || n2 === void 0 ? void 0 : n2.version, viewer_application_engine: (o2 = this.options.platform) === null || o2 === void 0 ? void 0 : o2.layout, viewer_device_name: (s = this.options.platform) === null || s === void 0 ? void 0 : s.product, viewer_device_category: "", viewer_device_manufacturer: (u3 = this.options.platform) === null || u3 === void 0 ? void 0 : u3.manufacturer, viewer_os_family: (b2 = this.options.platform) === null || b2 === void 0 || (p3 = b2.os) === null || p3 === void 0 ? void 0 : p3.family, viewer_os_architecture: (y4 = this.options.platform) === null || y4 === void 0 || (k3 = y4.os) === null || k3 === void 0 ? void 0 : k3.architecture, viewer_os_version: (v2 = this.options.platform) === null || v2 === void 0 || (c3 = v2.os) === null || c3 === void 0 ? void 0 : c3.version, viewer_connection_type: sr(), page_url: Ue.default === null || Ue.default === void 0 || (T3 = Ue.default.location) === null || T3 === void 0 ? void 0 : T3.href }, this.viewerData = this.disableCookies ? {} : rr(); } return L(r9, [{ key: "send", value: function(t2, i3) { if (!(!t2 || !(i3 != null && i3.view_id))) { if (this.respectDoNotTrack && ce()) return q.info("Not sending `" + t2 + "` because Do Not Track is enabled"); if (!i3 || typeof i3 != "object") return q.error("A data object was expected in send() but was not provided"); var a2 = this.disableCookies ? {} : ar(), n2 = fe(ue({}, this.pageLevelData, i3, a2, this.viewerData), { event: t2, env_key: this.envKey }); n2.user_id && (n2.viewer_user_id = n2.user_id, delete n2.user_id); var o2, s = ((o2 = n2.mux_sample_number) !== null && o2 !== void 0 ? o2 : 0) >= this.sampleRate, u3 = this._deduplicateBeaconData(t2, n2), p3 = ve(u3); if (this.lastEventTime = this.mux.utils.now(), s) return q.info("Not sending event due to sample rate restriction", t2, n2, p3); if (this.envKey || q.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL", t2, n2, p3), !this.rateLimited) { if (q.info("Sending event", t2, n2, p3), this.rateLimited = !this.eventQueue.queueEvent(t2, p3), this.mux.WINDOW_UNLOADING && t2 === "viewend") this.eventQueue.destroy(true); else if (this.mux.WINDOW_HIDDEN && t2 === "hb" ? this.eventQueue.flushEvents(true) : ci.indexOf(t2) >= 0 && this.eventQueue.flushEvents(), this.rateLimited) return n2.event = "eventrateexceeded", p3 = ve(n2), this.eventQueue.queueEvent(n2.event, p3), q.error("Beaconing disabled due to rate limit."); } } } }, { key: "destroy", value: function() { this.eventQueue.destroy(false); } }, { key: "_deduplicateBeaconData", value: function(t2, i3) { var a2 = this, n2 = {}, o2 = i3.view_id; if (o2 === "-1" || t2 === "viewstart" || t2 === "viewend" || !this.previousBeaconData || this.mux.utils.now() - this.lastEventTime >= _i) n2 = ue({}, i3), o2 && (this.previousBeaconData = n2), o2 && t2 === "viewend" && (this.previousBeaconData = null); else { var s = t2.indexOf("request") === 0; Object.entries(i3).forEach(function(u3) { var p3 = H(u3, 2), b2 = p3[0], k3 = p3[1]; a2.previousBeaconData && (k3 !== a2.previousBeaconData[b2] || ui.indexOf(b2) > -1 || a2.objectHasChanged(s, b2, k3, a2.previousBeaconData[b2]) || a2.eventRequiresKey(t2, b2)) && (n2[b2] = k3, a2.previousBeaconData[b2] = k3); }); } return n2; } }, { key: "objectHasChanged", value: function(t2, i3, a2, n2) { return !t2 || i3.indexOf("request_") !== 0 ? false : i3 === "request_response_headers" || typeof a2 != "object" || typeof n2 != "object" ? true : Object.keys(a2 || {}).length !== Object.keys(n2 || {}).length; } }, { key: "eventRequiresKey", value: function(t2, i3) { return !!(t2 === "renditionchange" && i3.indexOf("video_source_") === 0 || li.includes(i3) && di.includes(t2)); } }]), r9; }(); var fi = function r7(e) { "use strict"; D(this, r7); var t2 = 0, i3 = 0, a2 = 0, n2 = 0, o2 = 0, s = 0, u3 = 0, p3 = function(y4, c3) { var v2 = c3.request_start, T3 = c3.request_response_start, x2 = c3.request_response_end, m2 = c3.request_bytes_loaded; n2++; var f, _3; if (T3 ? (f = T3 - (v2 != null ? v2 : 0), _3 = (x2 != null ? x2 : 0) - T3) : _3 = (x2 != null ? x2 : 0) - (v2 != null ? v2 : 0), _3 > 0 && m2 && m2 > 0) { var d2 = m2 / _3 * 8e3; o2++, i3 += m2, a2 += _3, e.data.view_min_request_throughput = Math.min(e.data.view_min_request_throughput || 1 / 0, d2), e.data.view_average_request_throughput = i3 / a2 * 8e3, e.data.view_request_count = n2, f > 0 && (t2 += f, e.data.view_max_request_latency = Math.max(e.data.view_max_request_latency || 0, f), e.data.view_average_request_latency = t2 / o2); } }, b2 = function(y4, c3) { n2++, s++, e.data.view_request_count = n2, e.data.view_request_failed_count = s; }, k3 = function(y4, c3) { n2++, u3++, e.data.view_request_count = n2, e.data.view_request_canceled_count = u3; }; e.on("requestcompleted", p3), e.on("requestfailed", b2), e.on("requestcanceled", k3); }; var Br = fi; var pi = 60 * 60 * 1e3; var vi2 = function r8(e) { "use strict"; var t2 = this; D(this, r8), l(this, "_lastEventTime", void 0), e.on("before*", function(i3, a2) { var n2 = a2.viewer_time, o2 = A.now(), s = t2._lastEventTime; if (t2._lastEventTime = o2, s && o2 - s > pi) { var u3 = Object.keys(e.data).reduce(function(b2, k3) { return k3.indexOf("video_") === 0 ? Object.assign(b2, l({}, k3, e.data[k3])) : b2; }, {}); e.mux.log.info("Received event after at least an hour inactivity, creating a new view"); var p3 = e.playbackHeartbeat._playheadShouldBeProgressing; e._resetView(Object.assign({ viewer_time: n2 }, u3)), e.playbackHeartbeat._playheadShouldBeProgressing = p3, e.playbackHeartbeat._playheadShouldBeProgressing && i3.type !== "play" && i3.type !== "adbreakstart" && (e.emit("play", { viewer_time: n2 }), i3.type !== "playing" && e.emit("playing", { viewer_time: n2 })); } }); }; var Ur = vi2; var mi = ["viewstart", "ended", "loadstart", "pause", "play", "playing", "ratechange", "waiting", "adplay", "adpause", "adended", "aderror", "adplaying", "adrequest", "adresponse", "adbreakstart", "adbreakend", "adfirstquartile", "admidpoint", "adthirdquartile", "rebufferstart", "rebufferend", "seeked", "error", "hb", "requestcompleted", "requestfailed", "requestcanceled", "renditionchange"]; var hi = /* @__PURE__ */ new Set(["requestcompleted", "requestfailed", "requestcanceled"]); var yi = function(r9) { "use strict"; Dt(t2, r9); var e = qt(t2); function t2(i3, a2, n2) { D(this, t2); var o2; o2 = e.call(this), l(g(o2), "DOM_CONTENT_LOADED_EVENT_END", void 0), l(g(o2), "NAVIGATION_START", void 0), l(g(o2), "_destroyed", void 0), l(g(o2), "_heartBeatTimeout", void 0), l(g(o2), "adTracker", void 0), l(g(o2), "dashjs", void 0), l(g(o2), "data", void 0), l(g(o2), "disablePlayheadRebufferTracking", void 0), l(g(o2), "disableRebufferTracking", void 0), l(g(o2), "errorTracker", void 0), l(g(o2), "errorTranslator", void 0), l(g(o2), "emitTranslator", void 0), l(g(o2), "getAdData", void 0), l(g(o2), "getPlayheadTime", void 0), l(g(o2), "getStateData", void 0), l(g(o2), "stateDataTranslator", void 0), l(g(o2), "hlsjs", void 0), l(g(o2), "id", void 0), l(g(o2), "longResumeTracker", void 0), l(g(o2), "minimumRebufferDuration", void 0), l(g(o2), "mux", void 0), l(g(o2), "playbackEventDispatcher", void 0), l(g(o2), "playbackHeartbeat", void 0), l(g(o2), "playbackHeartbeatTime", void 0), l(g(o2), "playheadTime", void 0), l(g(o2), "seekingTracker", void 0), l(g(o2), "sustainedRebufferThreshold", void 0), l(g(o2), "watchTimeTracker", void 0), l(g(o2), "currentFragmentPDT", void 0), l(g(o2), "currentFragmentStart", void 0), o2.DOM_CONTENT_LOADED_EVENT_END = _e.domContentLoadedEventEnd(), o2.NAVIGATION_START = _e.navigationStart(); var s = { debug: false, minimumRebufferDuration: 250, sustainedRebufferThreshold: 1e3, playbackHeartbeatTime: 25, beaconDomain: "litix.io", sampleRate: 1, disableCookies: false, respectDoNotTrack: false, disableRebufferTracking: false, disablePlayheadRebufferTracking: false, errorTranslator: function(y4) { return y4; }, emitTranslator: function() { for (var y4 = arguments.length, c3 = new Array(y4), v2 = 0; v2 < y4; v2++) c3[v2] = arguments[v2]; return c3; }, stateDataTranslator: function(y4) { return y4; } }; o2.mux = i3, o2.id = a2, n2 != null && n2.beaconDomain && o2.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."), n2 = Object.assign(s, n2), n2.data = n2.data || {}, n2.data.property_key && (n2.data.env_key = n2.data.property_key, delete n2.data.property_key), q.level = n2.debug ? Y.DEBUG : Y.WARN, o2.getPlayheadTime = n2.getPlayheadTime, o2.getStateData = n2.getStateData || function() { return {}; }, o2.getAdData = n2.getAdData || function() { }, o2.minimumRebufferDuration = n2.minimumRebufferDuration, o2.sustainedRebufferThreshold = n2.sustainedRebufferThreshold, o2.playbackHeartbeatTime = n2.playbackHeartbeatTime, o2.disableRebufferTracking = n2.disableRebufferTracking, o2.disableRebufferTracking && o2.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."), o2.disablePlayheadRebufferTracking = n2.disablePlayheadRebufferTracking, o2.errorTranslator = n2.errorTranslator, o2.emitTranslator = n2.emitTranslator, o2.stateDataTranslator = n2.stateDataTranslator, o2.playbackEventDispatcher = new Hr(i3, n2.data.env_key, n2), o2.data = { player_instance_id: ee(), mux_sample_rate: n2.sampleRate, beacon_domain: n2.beaconCollectionDomain || n2.beaconDomain }, o2.data.view_sequence_number = 1, o2.data.player_sequence_number = 1; var u3 = (function() { typeof this.data.view_start == "undefined" && (this.data.view_start = this.mux.utils.now(), this.emit("viewstart")); }).bind(g(o2)); if (o2.on("viewinit", function(y4, c3) { this._resetVideoData(), this._resetViewData(), this._resetErrorData(), this._updateStateData(), Object.assign(this.data, c3), this._initializeViewData(), this.one("play", u3), this.one("adbreakstart", u3); }), o2.on("videochange", function(y4, c3) { this._resetView(c3); }), o2.on("programchange", function(y4, c3) { this.data.player_is_paused && this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."), this._resetView(Object.assign(c3, { view_program_changed: true })), u3(), this.emit("play"), this.emit("playing"); }), o2.on("fragmentchange", function(y4, c3) { this.currentFragmentPDT = c3.currentFragmentPDT, this.currentFragmentStart = c3.currentFragmentStart; }), o2.on("destroy", o2.destroy), typeof window != "undefined" && typeof window.addEventListener == "function" && typeof window.removeEventListener == "function") { var p3 = function() { var y4 = typeof o2.data.view_start != "undefined"; o2.mux.WINDOW_HIDDEN = document.visibilityState === "hidden", y4 && o2.mux.WINDOW_HIDDEN && (o2.data.player_is_paused || o2.emit("hb")); }; window.addEventListener("visibilitychange", p3, false); var b2 = function(y4) { y4.persisted || o2.destroy(); }; window.addEventListener("pagehide", b2, false), o2.on("destroy", function() { window.removeEventListener("visibilitychange", p3), window.removeEventListener("pagehide", b2); }); } o2.on("playerready", function(y4, c3) { Object.assign(this.data, c3); }), mi.forEach(function(y4) { o2.on(y4, function(c3, v2) { y4.indexOf("ad") !== 0 && this._updateStateData(), Object.assign(this.data, v2), this._sanitizeData(); }), o2.on("after" + y4, function() { (y4 !== "error" || this.errorTracker.viewErrored) && this.send(y4); }); }), o2.on("viewend", function(y4, c3) { Object.assign(o2.data, c3); }); var k3 = function(c3) { var v2 = this.mux.utils.now(); this.data.player_init_time && (this.data.player_startup_time = v2 - this.data.player_init_time), !this.mux.PLAYER_TRACKED && this.NAVIGATION_START && (this.mux.PLAYER_TRACKED = true, (this.data.player_init_time || this.DOM_CONTENT_LOADED_EVENT_END) && (this.data.page_load_time = Math.min(this.data.player_init_time || 1 / 0, this.DOM_CONTENT_LOADED_EVENT_END || 1 / 0) - this.NAVIGATION_START)), this.send("playerready"), delete this.data.player_startup_time, delete this.data.page_load_time; }; return o2.one("playerready", k3), o2.longResumeTracker = new Ur(g(o2)), o2.errorTracker = new Bt(g(o2)), new $t(g(o2)), o2.seekingTracker = new zt(g(o2)), o2.playheadTime = new Vt(g(o2)), o2.playbackHeartbeat = new Ht(g(o2)), new Qt(g(o2)), o2.watchTimeTracker = new Ut(g(o2)), new Ft(g(o2)), o2.adTracker = new Yt(g(o2)), new Gt(g(o2)), new jt(g(o2)), new Jt(g(o2)), new Xt(g(o2)), new Br(g(o2)), n2.hlsjs && o2.addHLSJS(n2), n2.dashjs && o2.addDashJS(n2), o2.emit("viewinit", n2.data), o2; } return L(t2, [{ key: "emit", value: function(a2, n2) { var o2, s = Object.assign({ viewer_time: this.mux.utils.now() }, n2), u3 = [a2, s]; if (this.emitTranslator) try { u3 = this.emitTranslator(a2, s); } catch (p3) { this.mux.log.warn("Exception in emit translator callback.", p3); } u3 != null && u3.length && (o2 = De(X(t2.prototype), "emit", this)).call.apply(o2, [this].concat(W(u3))); } }, { key: "destroy", value: function() { this._destroyed || (this._destroyed = true, typeof this.data.view_start != "undefined" && (this.emit("viewend"), this.send("viewend")), this.playbackEventDispatcher.destroy(), this.removeHLSJS(), this.removeDashJS(), window.clearTimeout(this._heartBeatTimeout)); } }, { key: "send", value: function(a2) { if (this.data.view_id) { var n2 = Object.assign({}, this.data), o2 = ["player_program_time", "player_manifest_newest_program_time", "player_live_edge_program_time", "player_program_time", "video_holdback", "video_part_holdback", "video_target_duration", "video_part_target_duration"]; if (n2.video_source_is_live === void 0 && (n2.player_source_duration === 1 / 0 || n2.video_source_duration === 1 / 0 ? n2.video_source_is_live = true : (n2.player_source_duration > 0 || n2.video_source_duration > 0) && (n2.video_source_is_live = false)), n2.video_source_is_live || o2.forEach(function(b2) { n2[b2] = void 0; }), n2.video_source_url = n2.video_source_url || n2.player_source_url, n2.video_source_url) { var s = H(re(n2.video_source_url), 2), u3 = s[0], p3 = s[1]; n2.video_source_domain = p3, n2.video_source_hostname = u3; } delete n2.ad_request_id, this.playbackEventDispatcher.send(a2, n2), this.data.view_sequence_number++, this.data.player_sequence_number++, hi.has(a2) || this._restartHeartBeat(), a2 === "viewend" && delete this.data.view_id; } } }, { key: "_resetView", value: function(a2) { this.emit("viewend"), this.send("viewend"), this.emit("viewinit", a2); } }, { key: "_updateStateData", value: function() { var a2 = this.getStateData(); if (typeof this.stateDataTranslator == "function") try { a2 = this.stateDataTranslator(a2); } catch (n2) { this.mux.log.warn("Exception in stateDataTranslator translator callback.", n2); } Object.assign(this.data, a2), this.playheadTime._updatePlayheadTime(), this._sanitizeData(); } }, { key: "_sanitizeData", value: function() { var a2 = this, n2 = ["player_width", "player_height", "video_source_width", "video_source_height", "player_playhead_time", "video_source_bitrate"]; n2.forEach(function(s) { var u3 = parseInt(a2.data[s], 10); a2.data[s] = isNaN(u3) ? void 0 : u3; }); var o2 = ["player_source_url", "video_source_url"]; o2.forEach(function(s) { if (a2.data[s]) { var u3 = a2.data[s].toLowerCase(); (u3.indexOf("data:") === 0 || u3.indexOf("blob:") === 0) && (a2.data[s] = "MSE style URL"); } }); } }, { key: "_resetVideoData", value: function() { var a2 = this; Object.keys(this.data).forEach(function(n2) { n2.indexOf("video_") === 0 && delete a2.data[n2]; }); } }, { key: "_resetViewData", value: function() { var a2 = this; Object.keys(this.data).forEach(function(n2) { n2.indexOf("view_") === 0 && delete a2.data[n2]; }), this.data.view_sequence_number = 1; } }, { key: "_resetErrorData", value: function() { delete this.data.player_error_code, delete this.data.player_error_message, delete this.data.player_error_context, delete this.data.player_error_severity, delete this.data.player_error_business_exception; } }, { key: "_initializeViewData", value: function() { var a2 = this, n2 = this.data.view_id = ee(), o2 = function() { n2 === a2.data.view_id && O(a2.data, "player_view_count", 1); }; this.data.player_is_paused ? this.one("play", o2) : o2(); } }, { key: "_restartHeartBeat", value: function() { var a2 = this; window.clearTimeout(this._heartBeatTimeout), this._heartBeatTimeout = window.setTimeout(function() { a2.data.player_is_paused || a2.emit("hb"); }, 1e4); } }, { key: "addHLSJS", value: function(a2) { if (!a2.hlsjs) { this.mux.log.warn("You must pass a valid hlsjs instance in order to track it."); return; } if (this.hlsjs) { this.mux.log.warn("An instance of HLS.js is already being monitored for this player."); return; } this.hlsjs = a2.hlsjs, Ot(this.mux, this.id, a2.hlsjs, {}, a2.Hls || window.Hls); } }, { key: "removeHLSJS", value: function() { this.hlsjs && (Pt(this.hlsjs), this.hlsjs = void 0); } }, { key: "addDashJS", value: function(a2) { if (!a2.dashjs) { this.mux.log.warn("You must pass a valid dashjs instance in order to track it."); return; } if (this.dashjs) { this.mux.log.warn("An instance of Dash.js is already being monitored for this player."); return; } this.dashjs = a2.dashjs, Nt(this.mux, this.id, a2.dashjs); } }, { key: "removeDashJS", value: function() { this.dashjs && (Lt(this.dashjs), this.dashjs = void 0); } }]), t2; }(Mt); var Fr = yi; var he = V(nt2()); function ot() { return he.default && !!(he.default.fullscreenElement || he.default.webkitFullscreenElement || he.default.mozFullScreenElement || he.default.msFullscreenElement); } var gi = ["loadstart", "pause", "play", "playing", "seeking", "seeked", "timeupdate", "ratechange", "stalled", "waiting", "error", "ended"]; var bi = { 1: "MEDIA_ERR_ABORTED", 2: "MEDIA_ERR_NETWORK", 3: "MEDIA_ERR_DECODE", 4: "MEDIA_ERR_SRC_NOT_SUPPORTED" }; function st(r9, e, t2) { var i3 = H(se(e), 3), a2 = i3[0], n2 = i3[1], o2 = i3[2], s = r9.log, u3 = r9.utils.getComputedStyle, p3 = r9.utils.secondsToMs, b2 = { automaticErrorTracking: true }; if (a2) { if (o2 !== "video" && o2 !== "audio") return s.error("The element of `" + n2 + "` was not a media element."); } else return s.error("No element was found with the `" + n2 + "` query selector."); a2.mux && (a2.mux.destroy(), delete a2.mux, s.warn("Already monitoring this video element, replacing existing event listeners")); var k3 = { getPlayheadTime: function() { return p3(a2.currentTime); }, getStateData: function() { var v2, T3, x2, m2 = ((v2 = (T3 = this).getPlayheadTime) === null || v2 === void 0 ? void 0 : v2.call(T3)) || p3(a2.currentTime), f = this.hlsjs && this.hlsjs.url, _3 = this.dashjs && typeof this.dashjs.getSource == "function" && this.dashjs.getSource(), d2 = { player_is_paused: a2.paused, player_width: parseInt(u3(a2, "width")), player_height: parseInt(u3(a2, "height")), player_autoplay_on: a2.autoplay, player_preload_on: a2.preload, player_language_code: a2.lang, player_is_fullscreen: ot(), video_poster_url: a2.poster, video_source_url: f || _3 || a2.currentSrc, video_source_duration: p3(a2.duration), video_source_height: a2.videoHeight, video_source_width: a2.videoWidth, view_dropped_frame_count: a2 == null || (x2 = a2.getVideoPlaybackQuality) === null || x2 === void 0 ? void 0 : x2.call(a2).droppedVideoFrames }; if (a2.getStartDate && m2 > 0) { var h3 = a2.getStartDate(); if (h3 && typeof h3.getTime == "function" && h3.getTime()) { var w4 = h3.getTime(); if (d2.player_program_time = w4 + m2, a2.seekable.length > 0) { var E5 = w4 + a2.seekable.end(a2.seekable.length - 1); d2.player_live_edge_program_time = E5; } } } return d2; } }; t2 = Object.assign(b2, t2, k3), t2.data = Object.assign({ player_software: "HTML5 Video Element", player_mux_plugin_name: "VideoElementMonitor", player_mux_plugin_version: r9.VERSION }, t2.data), a2.mux = a2.mux || {}, a2.mux.deleted = false, a2.mux.emit = function(c3, v2) { r9.emit(n2, c3, v2); }, a2.mux.updateData = function(c3) { a2.mux.emit("hb", c3); }; var y4 = function() { s.error("The monitor for this video element has already been destroyed."); }; a2.mux.destroy = function() { Object.keys(a2.mux.listeners).forEach(function(c3) { a2.removeEventListener(c3, a2.mux.listeners[c3], false); }), delete a2.mux.listeners, a2.mux.destroy = y4, a2.mux.swapElement = y4, a2.mux.emit = y4, a2.mux.addHLSJS = y4, a2.mux.addDashJS = y4, a2.mux.removeHLSJS = y4, a2.mux.removeDashJS = y4, a2.mux.updateData = y4, a2.mux.setEmitTranslator = y4, a2.mux.setStateDataTranslator = y4, a2.mux.setGetPlayheadTime = y4, a2.mux.deleted = true, r9.emit(n2, "destroy"); }, a2.mux.swapElement = function(c3) { var v2 = H(se(c3), 3), T3 = v2[0], x2 = v2[1], m2 = v2[2]; if (T3) { if (m2 !== "video" && m2 !== "audio") return r9.log.error("The element of `" + x2 + "` was not a media element."); } else return r9.log.error("No element was found with the `" + x2 + "` query selector."); T3.muxId = a2.muxId, delete a2.muxId, T3.mux = T3.mux || {}, T3.mux.listeners = Object.assign({}, a2.mux.listeners), delete a2.mux.listeners, Object.keys(T3.mux.listeners).forEach(function(f) { a2.removeEventListener(f, T3.mux.listeners[f], false), T3.addEventListener(f, T3.mux.listeners[f], false); }), T3.mux.swapElement = a2.mux.swapElement, T3.mux.destroy = a2.mux.destroy, delete a2.mux, a2 = T3; }, a2.mux.addHLSJS = function(c3) { r9.addHLSJS(n2, c3); }, a2.mux.addDashJS = function(c3) { r9.addDashJS(n2, c3); }, a2.mux.removeHLSJS = function() { r9.removeHLSJS(n2); }, a2.mux.removeDashJS = function() { r9.removeDashJS(n2); }, a2.mux.setEmitTranslator = function(c3) { r9.setEmitTranslator(n2, c3); }, a2.mux.setStateDataTranslator = function(c3) { r9.setStateDataTranslator(n2, c3); }, a2.mux.setGetPlayheadTime = function(c3) { c3 || (c3 = t2.getPlayheadTime), r9.setGetPlayheadTime(n2, c3); }, r9.init(n2, t2), r9.emit(n2, "playerready"), a2.paused || (r9.emit(n2, "play"), a2.readyState > 2 && r9.emit(n2, "playing")), a2.mux.listeners = {}, gi.forEach(function(c3) { c3 === "error" && !t2.automaticErrorTracking || (a2.mux.listeners[c3] = function() { var v2 = {}; if (c3 === "error") { if (!a2.error || a2.error.code === 1) return; v2.player_error_code = a2.error.code, v2.player_error_message = bi[a2.error.code] || a2.error.message; } r9.emit(n2, c3, v2); }, a2.addEventListener(c3, a2.mux.listeners[c3], false)); }); } function ut(r9, e, t2, i3) { var a2 = i3; if (r9 && typeof r9[e] == "function") try { a2 = r9[e].apply(r9, t2); } catch (n2) { q.info("safeCall error", n2); } return a2; } var ge = V(J()); var ye; ge.default && ge.default.WeakMap && (ye = /* @__PURE__ */ new WeakMap()); function dt2(r9, e) { if (!r9 || !e || !ge.default || typeof ge.default.getComputedStyle != "function") return ""; var t2; return ye && ye.has(r9) && (t2 = ye.get(r9)), t2 || (t2 = ge.default.getComputedStyle(r9, null), ye && ye.set(r9, t2)), t2.getPropertyValue(e); } function lt(r9) { return Math.floor(r9 * 1e3); } var le = { TARGET_DURATION: "#EXT-X-TARGETDURATION", PART_INF: "#EXT-X-PART-INF", SERVER_CONTROL: "#EXT-X-SERVER-CONTROL", INF: "#EXTINF", PROGRAM_DATE_TIME: "#EXT-X-PROGRAM-DATE-TIME", VERSION: "#EXT-X-VERSION", SESSION_DATA: "#EXT-X-SESSION-DATA" }; var Fe = function(e) { return this.buffer = "", this.manifest = { segments: [], serverControl: {}, sessionData: {} }, this.currentUri = {}, this.process(e), this.manifest; }; Fe.prototype.process = function(r9) { var e; for (this.buffer += r9, e = this.buffer.indexOf("\n"); e > -1; e = this.buffer.indexOf("\n")) this.processLine(this.buffer.substring(0, e)), this.buffer = this.buffer.substring(e + 1); }; Fe.prototype.processLine = function(r9) { var e = r9.indexOf(":"), t2 = ki(r9, e), i3 = t2[0], a2 = t2.length === 2 ? _t(t2[1]) : void 0; if (i3[0] !== "#") this.currentUri.uri = i3, this.manifest.segments.push(this.currentUri), this.manifest.targetDuration && !("duration" in this.currentUri) && (this.currentUri.duration = this.manifest.targetDuration), this.currentUri = {}; else switch (i3) { case le.TARGET_DURATION: { if (!isFinite(a2) || a2 < 0) return; this.manifest.targetDuration = a2, this.setHoldBack(); break; } case le.PART_INF: { ct(this.manifest, t2), this.manifest.partInf.partTarget && (this.manifest.partTargetDuration = this.manifest.partInf.partTarget), this.setHoldBack(); break; } case le.SERVER_CONTROL: { ct(this.manifest, t2), this.setHoldBack(); break; } case le.INF: { a2 === 0 ? this.currentUri.duration = 0.01 : a2 > 0 && (this.currentUri.duration = a2); break; } case le.PROGRAM_DATE_TIME: { var n2 = a2, o2 = new Date(n2); this.manifest.dateTimeString || (this.manifest.dateTimeString = n2, this.manifest.dateTimeObject = o2), this.currentUri.dateTimeString = n2, this.currentUri.dateTimeObject = o2; break; } case le.VERSION: { ct(this.manifest, t2); break; } case le.SESSION_DATA: { var s = xi(t2[1]), u3 = Ce(s); Object.assign(this.manifest.sessionData, u3); } } }; Fe.prototype.setHoldBack = function() { var r9 = this.manifest, e = r9.serverControl, t2 = r9.targetDuration, i3 = r9.partTargetDuration; if (e) { var a2 = "holdBack", n2 = "partHoldBack", o2 = t2 && t2 * 3, s = i3 && i3 * 2; t2 && !e.hasOwnProperty(a2) && (e[a2] = o2), o2 && e[a2] < o2 && (e[a2] = o2), i3 && !e.hasOwnProperty(n2) && (e[n2] = i3 * 3), i3 && e[n2] < s && (e[n2] = s); } }; var ct = function(r9, e) { var t2 = Vr(e[0].replace("#EXT-X-", "")), i3; Ei(e[1]) ? (i3 = {}, i3 = Object.assign(wi(e[1]), i3)) : i3 = _t(e[1]), r9[t2] = i3; }; var Vr = function(r9) { return r9.toLowerCase().replace(/-(\w)/g, function(e) { return e[1].toUpperCase(); }); }; var _t = function(r9) { if (r9.toLowerCase() === "yes" || r9.toLowerCase() === "no") return r9.toLowerCase() === "yes"; var e = r9.indexOf(":") !== -1 ? r9 : parseFloat(r9); return isNaN(e) ? r9 : e; }; var Ti = function(r9) { var e = {}, t2 = r9.split("="); if (t2.length > 1) { var i3 = Vr(t2[0]); e[i3] = _t(t2[1]); } return e; }; var wi = function(r9) { for (var e = r9.split(","), t2 = {}, i3 = 0; e.length > i3; i3++) { var a2 = e[i3], n2 = Ti(a2); t2 = Object.assign(n2, t2); } return t2; }; var Ei = function(r9) { return r9.indexOf("=") > -1; }; var ki = function(r9, e) { return e === -1 ? [r9] : [r9.substring(0, e), r9.substring(e + 1)]; }; var xi = function(r9) { var e = {}; if (r9) { var t2 = r9.search(","), i3 = r9.slice(0, t2), a2 = r9.slice(t2 + 1), n2 = [i3, a2]; return n2.forEach(function(o2, s) { for (var u3 = o2.replace(/['"]+/g, "").split("="), p3 = 0; p3 < u3.length; p3++) u3[p3] === "DATA-ID" && (e["DATA-ID"] = u3[1 - p3]), u3[p3] === "VALUE" && (e.VALUE = u3[1 - p3]); }), { data: e }; } }; var Wr = Fe; var Di = { safeCall: ut, safeIncrement: O, getComputedStyle: dt2, secondsToMs: lt, assign: Object.assign, headersStringToObject: pe, cdnHeadersToRequestId: de, extractHostnameAndDomain: re, extractHostname: F, manifestParser: Wr, generateShortID: Oe, generateUUID: ee, now: A.now, findMediaElement: se }; var jr = Di; var Si = { PLAYER_READY: "playerready", VIEW_INIT: "viewinit", VIDEO_CHANGE: "videochange", PLAY: "play", PAUSE: "pause", PLAYING: "playing", TIME_UPDATE: "timeupdate", SEEKING: "seeking", SEEKED: "seeked", REBUFFER_START: "rebufferstart", REBUFFER_END: "rebufferend", ERROR: "error", ENDED: "ended", RENDITION_CHANGE: "renditionchange", ORIENTATION_CHANGE: "orientationchange", AD_REQUEST: "adrequest", AD_RESPONSE: "adresponse", AD_BREAK_START: "adbreakstart", AD_PLAY: "adplay", AD_PLAYING: "adplaying", AD_PAUSE: "adpause", AD_FIRST_QUARTILE: "adfirstquartile", AD_MID_POINT: "admidpoint", AD_THIRD_QUARTILE: "adthirdquartile", AD_ENDED: "adended", AD_BREAK_END: "adbreakend", AD_ERROR: "aderror", REQUEST_COMPLETED: "requestcompleted", REQUEST_FAILED: "requestfailed", REQUEST_CANCELLED: "requestcanceled", HEARTBEAT: "hb", DESTROY: "destroy" }; var Gr = Si; var Ri = "mux-embed"; var qi = "5.9.0"; var Ai = "2.1"; var C = {}; var ne = function(e) { var t2 = arguments; typeof e == "string" ? ne.hasOwnProperty(e) ? be.default.setTimeout(function() { t2 = Array.prototype.splice.call(t2, 1), ne[e].apply(null, t2); }, 0) : q.warn("`" + e + "` is an unknown task") : typeof e == "function" ? be.default.setTimeout(function() { e(ne); }, 0) : q.warn("`" + e + "` is invalid."); }; var Oi = { loaded: A.now(), NAME: Ri, VERSION: qi, API_VERSION: Ai, PLAYER_TRACKED: false, monitor: function(e, t2) { return st(ne, e, t2); }, destroyMonitor: function(e) { var t2 = H(se(e), 1), i3 = t2[0]; i3 && i3.mux && typeof i3.mux.destroy == "function" ? i3.mux.destroy() : q.error("A video element monitor for `" + e + "` has not been initialized via `mux.monitor`."); }, addHLSJS: function(e, t2) { var i3 = Q(e); C[i3] ? C[i3].addHLSJS(t2) : q.error("A monitor for `" + i3 + "` has not been initialized."); }, addDashJS: function(e, t2) { var i3 = Q(e); C[i3] ? C[i3].addDashJS(t2) : q.error("A monitor for `" + i3 + "` has not been initialized."); }, removeHLSJS: function(e) { var t2 = Q(e); C[t2] ? C[t2].removeHLSJS() : q.error("A monitor for `" + t2 + "` has not been initialized."); }, removeDashJS: function(e) { var t2 = Q(e); C[t2] ? C[t2].removeDashJS() : q.error("A monitor for `" + t2 + "` has not been initialized."); }, init: function(e, t2) { ce() && t2 && t2.respectDoNotTrack && q.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled."); var i3 = Q(e); C[i3] = new Fr(ne, i3, t2); }, emit: function(e, t2, i3) { var a2 = Q(e); C[a2] ? (C[a2].emit(t2, i3), t2 === "destroy" && delete C[a2]) : q.error("A monitor for `" + a2 + "` has not been initialized."); }, updateData: function(e, t2) { var i3 = Q(e); C[i3] ? C[i3].emit("hb", t2) : q.error("A monitor for `" + i3 + "` has not been initialized."); }, setEmitTranslator: function(e, t2) { var i3 = Q(e); C[i3] ? C[i3].emitTranslator = t2 : q.error("A monitor for `" + i3 + "` has not been initialized."); }, setStateDataTranslator: function(e, t2) { var i3 = Q(e); C[i3] ? C[i3].stateDataTranslator = t2 : q.error("A monitor for `" + i3 + "` has not been initialized."); }, setGetPlayheadTime: function(e, t2) { var i3 = Q(e); C[i3] ? C[i3].getPlayheadTime = t2 : q.error("A monitor for `" + i3 + "` has not been initialized."); }, checkDoNotTrack: ce, log: q, utils: jr, events: Gr, WINDOW_HIDDEN: false, WINDOW_UNLOADING: false }; Object.assign(ne, Oi); typeof be.default != "undefined" && typeof be.default.addEventListener == "function" && be.default.addEventListener("pagehide", function(r9) { r9.persisted || (ne.WINDOW_UNLOADING = true); }, false); var Ed = ne; // node_modules/hls.js/dist/hls.mjs function getDefaultExportFromCjs(x2) { return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2; } var urlToolkit = { exports: {} }; (function(module, exports) { (function(root) { var URL_REGEX = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/; var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/; var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g; var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g; var URLToolkit = { // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or // // E.g // With opts.alwaysNormalize = false (default, spec compliant) // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g // With opts.alwaysNormalize = true (not spec compliant) // http://a.com/b/cd + /e/f/../g => http://a.com/e/g buildAbsoluteURL: function(baseURL, relativeURL, opts) { opts = opts || {}; baseURL = baseURL.trim(); relativeURL = relativeURL.trim(); if (!relativeURL) { if (!opts.alwaysNormalize) { return baseURL; } var basePartsForNormalise = URLToolkit.parseURL(baseURL); if (!basePartsForNormalise) { throw new Error("Error trying to parse base URL."); } basePartsForNormalise.path = URLToolkit.normalizePath( basePartsForNormalise.path ); return URLToolkit.buildURLFromParts(basePartsForNormalise); } var relativeParts = URLToolkit.parseURL(relativeURL); if (!relativeParts) { throw new Error("Error trying to parse relative URL."); } if (relativeParts.scheme) { if (!opts.alwaysNormalize) { return relativeURL; } relativeParts.path = URLToolkit.normalizePath(relativeParts.path); return URLToolkit.buildURLFromParts(relativeParts); } var baseParts = URLToolkit.parseURL(baseURL); if (!baseParts) { throw new Error("Error trying to parse base URL."); } if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== "/") { var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path); baseParts.netLoc = pathParts[1]; baseParts.path = pathParts[2]; } if (baseParts.netLoc && !baseParts.path) { baseParts.path = "/"; } var builtParts = { // 2c) Otherwise, the embedded URL inherits the scheme of // the base URL. scheme: baseParts.scheme, netLoc: relativeParts.netLoc, path: null, params: relativeParts.params, query: relativeParts.query, fragment: relativeParts.fragment }; if (!relativeParts.netLoc) { builtParts.netLoc = baseParts.netLoc; if (relativeParts.path[0] !== "/") { if (!relativeParts.path) { builtParts.path = baseParts.path; if (!relativeParts.params) { builtParts.params = baseParts.params; if (!relativeParts.query) { builtParts.query = baseParts.query; } } } else { var baseURLPath = baseParts.path; var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf("/") + 1) + relativeParts.path; builtParts.path = URLToolkit.normalizePath(newPath); } } } if (builtParts.path === null) { builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path; } return URLToolkit.buildURLFromParts(builtParts); }, parseURL: function(url) { var parts = URL_REGEX.exec(url); if (!parts) { return null; } return { scheme: parts[1] || "", netLoc: parts[2] || "", path: parts[3] || "", params: parts[4] || "", query: parts[5] || "", fragment: parts[6] || "" }; }, normalizePath: function(path) { path = path.split("").reverse().join("").replace(SLASH_DOT_REGEX, ""); while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, "")).length) { } return path.split("").reverse().join(""); }, buildURLFromParts: function(parts) { return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment; } }; module.exports = URLToolkit; })(); })(urlToolkit); var urlToolkitExports = urlToolkit.exports; function ownKeys2(e, r9) { var t2 = Object.keys(e); if (Object.getOwnPropertySymbols) { var o2 = Object.getOwnPropertySymbols(e); r9 && (o2 = o2.filter(function(r10) { return Object.getOwnPropertyDescriptor(e, r10).enumerable; })), t2.push.apply(t2, o2); } return t2; } function _objectSpread23(e) { for (var r9 = 1; r9 < arguments.length; r9++) { var t2 = null != arguments[r9] ? arguments[r9] : {}; r9 % 2 ? ownKeys2(Object(t2), true).forEach(function(r10) { _defineProperty3(e, r10, t2[r10]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t2)) : ownKeys2(Object(t2)).forEach(function(r10) { Object.defineProperty(e, r10, Object.getOwnPropertyDescriptor(t2, r10)); }); } return e; } function _toPrimitive2(t2, r9) { if ("object" != typeof t2 || !t2) return t2; var e = t2[Symbol.toPrimitive]; if (void 0 !== e) { var i3 = e.call(t2, r9 || "default"); if ("object" != typeof i3) return i3; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r9 ? String : Number)(t2); } function _toPropertyKey2(t2) { var i3 = _toPrimitive2(t2, "string"); return "symbol" == typeof i3 ? i3 : String(i3); } function _defineProperty3(obj, key, value) { key = _toPropertyKey2(key); if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _extends2() { _extends2 = Object.assign ? Object.assign.bind() : function(target) { for (var i3 = 1; i3 < arguments.length; i3++) { var source = arguments[i3]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends2.apply(this, arguments); } var isFiniteNumber = Number.isFinite || function(value) { return typeof value === "number" && isFinite(value); }; var isSafeInteger = Number.isSafeInteger || function(value) { return typeof value === "number" && Math.abs(value) <= MAX_SAFE_INTEGER; }; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; var Events = function(Events2) { Events2["MEDIA_ATTACHING"] = "hlsMediaAttaching"; Events2["MEDIA_ATTACHED"] = "hlsMediaAttached"; Events2["MEDIA_DETACHING"] = "hlsMediaDetaching"; Events2["MEDIA_DETACHED"] = "hlsMediaDetached"; Events2["BUFFER_RESET"] = "hlsBufferReset"; Events2["BUFFER_CODECS"] = "hlsBufferCodecs"; Events2["BUFFER_CREATED"] = "hlsBufferCreated"; Events2["BUFFER_APPENDING"] = "hlsBufferAppending"; Events2["BUFFER_APPENDED"] = "hlsBufferAppended"; Events2["BUFFER_EOS"] = "hlsBufferEos"; Events2["BUFFER_FLUSHING"] = "hlsBufferFlushing"; Events2["BUFFER_FLUSHED"] = "hlsBufferFlushed"; Events2["MANIFEST_LOADING"] = "hlsManifestLoading"; Events2["MANIFEST_LOADED"] = "hlsManifestLoaded"; Events2["MANIFEST_PARSED"] = "hlsManifestParsed"; Events2["LEVEL_SWITCHING"] = "hlsLevelSwitching"; Events2["LEVEL_SWITCHED"] = "hlsLevelSwitched"; Events2["LEVEL_LOADING"] = "hlsLevelLoading"; Events2["LEVEL_LOADED"] = "hlsLevelLoaded"; Events2["LEVEL_UPDATED"] = "hlsLevelUpdated"; Events2["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated"; Events2["LEVELS_UPDATED"] = "hlsLevelsUpdated"; Events2["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated"; Events2["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching"; Events2["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched"; Events2["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading"; Events2["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded"; Events2["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated"; Events2["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared"; Events2["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch"; Events2["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading"; Events2["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded"; Events2["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed"; Events2["CUES_PARSED"] = "hlsCuesParsed"; Events2["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound"; Events2["INIT_PTS_FOUND"] = "hlsInitPtsFound"; Events2["FRAG_LOADING"] = "hlsFragLoading"; Events2["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted"; Events2["FRAG_LOADED"] = "hlsFragLoaded"; Events2["FRAG_DECRYPTED"] = "hlsFragDecrypted"; Events2["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment"; Events2["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata"; Events2["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata"; Events2["FRAG_PARSED"] = "hlsFragParsed"; Events2["FRAG_BUFFERED"] = "hlsFragBuffered"; Events2["FRAG_CHANGED"] = "hlsFragChanged"; Events2["FPS_DROP"] = "hlsFpsDrop"; Events2["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping"; Events2["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated"; Events2["ERROR"] = "hlsError"; Events2["DESTROYING"] = "hlsDestroying"; Events2["KEY_LOADING"] = "hlsKeyLoading"; Events2["KEY_LOADED"] = "hlsKeyLoaded"; Events2["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached"; Events2["BACK_BUFFER_REACHED"] = "hlsBackBufferReached"; Events2["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded"; return Events2; }({}); var ErrorTypes = function(ErrorTypes2) { ErrorTypes2["NETWORK_ERROR"] = "networkError"; ErrorTypes2["MEDIA_ERROR"] = "mediaError"; ErrorTypes2["KEY_SYSTEM_ERROR"] = "keySystemError"; ErrorTypes2["MUX_ERROR"] = "muxError"; ErrorTypes2["OTHER_ERROR"] = "otherError"; return ErrorTypes2; }({}); var ErrorDetails = function(ErrorDetails2) { ErrorDetails2["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys"; ErrorDetails2["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess"; ErrorDetails2["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession"; ErrorDetails2["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense"; ErrorDetails2["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed"; ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed"; ErrorDetails2["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed"; ErrorDetails2["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed"; ErrorDetails2["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted"; ErrorDetails2["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError"; ErrorDetails2["MANIFEST_LOAD_ERROR"] = "manifestLoadError"; ErrorDetails2["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut"; ErrorDetails2["MANIFEST_PARSING_ERROR"] = "manifestParsingError"; ErrorDetails2["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError"; ErrorDetails2["LEVEL_EMPTY_ERROR"] = "levelEmptyError"; ErrorDetails2["LEVEL_LOAD_ERROR"] = "levelLoadError"; ErrorDetails2["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut"; ErrorDetails2["LEVEL_PARSING_ERROR"] = "levelParsingError"; ErrorDetails2["LEVEL_SWITCH_ERROR"] = "levelSwitchError"; ErrorDetails2["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError"; ErrorDetails2["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut"; ErrorDetails2["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError"; ErrorDetails2["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut"; ErrorDetails2["FRAG_LOAD_ERROR"] = "fragLoadError"; ErrorDetails2["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut"; ErrorDetails2["FRAG_DECRYPT_ERROR"] = "fragDecryptError"; ErrorDetails2["FRAG_PARSING_ERROR"] = "fragParsingError"; ErrorDetails2["FRAG_GAP"] = "fragGap"; ErrorDetails2["REMUX_ALLOC_ERROR"] = "remuxAllocError"; ErrorDetails2["KEY_LOAD_ERROR"] = "keyLoadError"; ErrorDetails2["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut"; ErrorDetails2["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError"; ErrorDetails2["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError"; ErrorDetails2["BUFFER_APPEND_ERROR"] = "bufferAppendError"; ErrorDetails2["BUFFER_APPENDING_ERROR"] = "bufferAppendingError"; ErrorDetails2["BUFFER_STALLED_ERROR"] = "bufferStalledError"; ErrorDetails2["BUFFER_FULL_ERROR"] = "bufferFullError"; ErrorDetails2["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole"; ErrorDetails2["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall"; ErrorDetails2["INTERNAL_EXCEPTION"] = "internalException"; ErrorDetails2["INTERNAL_ABORTED"] = "aborted"; ErrorDetails2["UNKNOWN"] = "unknown"; return ErrorDetails2; }({}); var noop3 = function noop4() { }; var fakeLogger = { trace: noop3, debug: noop3, log: noop3, warn: noop3, info: noop3, error: noop3 }; var exportedLogger = fakeLogger; function consolePrintFn(type) { const func = self.console[type]; if (func) { return func.bind(self.console, `[${type}] >`); } return noop3; } function exportLoggerFunctions(debugConfig, ...functions) { functions.forEach(function(type) { exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type); }); } function enableLogs(debugConfig, id) { if (typeof console === "object" && debugConfig === true || typeof debugConfig === "object") { exportLoggerFunctions( debugConfig, // Remove out from list here to hard-disable a log-level // 'trace', "debug", "log", "info", "warn", "error" ); try { exportedLogger.log(`Debug logs enabled for "${id}" in hls.js version ${"1.5.20"}`); } catch (e) { exportedLogger = fakeLogger; } } else { exportedLogger = fakeLogger; } } var logger = exportedLogger; var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g; var AttrList = class _AttrList { constructor(attrs) { if (typeof attrs === "string") { attrs = _AttrList.parseAttrList(attrs); } _extends2(this, attrs); } get clientAttrs() { return Object.keys(this).filter((attr) => attr.substring(0, 2) === "X-"); } decimalInteger(attrName) { const intValue = parseInt(this[attrName], 10); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; } hexadecimalInteger(attrName) { if (this[attrName]) { let stringValue = (this[attrName] || "0x").slice(2); stringValue = (stringValue.length & 1 ? "0" : "") + stringValue; const value = new Uint8Array(stringValue.length / 2); for (let i3 = 0; i3 < stringValue.length / 2; i3++) { value[i3] = parseInt(stringValue.slice(i3 * 2, i3 * 2 + 2), 16); } return value; } else { return null; } } hexadecimalIntegerAsNumber(attrName) { const intValue = parseInt(this[attrName], 16); if (intValue > Number.MAX_SAFE_INTEGER) { return Infinity; } return intValue; } decimalFloatingPoint(attrName) { return parseFloat(this[attrName]); } optionalFloat(attrName, defaultValue) { const value = this[attrName]; return value ? parseFloat(value) : defaultValue; } enumeratedString(attrName) { return this[attrName]; } bool(attrName) { return this[attrName] === "YES"; } decimalResolution(attrName) { const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]); if (res === null) { return void 0; } return { width: parseInt(res[1], 10), height: parseInt(res[2], 10) }; } static parseAttrList(input) { let match2; const attrs = {}; const quote = '"'; ATTR_LIST_REGEX.lastIndex = 0; while ((match2 = ATTR_LIST_REGEX.exec(input)) !== null) { let value = match2[2]; if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) { value = value.slice(1, -1); } const name = match2[1].trim(); attrs[name] = value; } return attrs; } }; function isDateRangeCueAttribute(attrName) { return attrName !== "ID" && attrName !== "CLASS" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT"; } function isSCTE35Attribute(attrName) { return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN"; } var DateRange = class { constructor(dateRangeAttr, dateRangeWithSameId) { this.attr = void 0; this._startDate = void 0; this._endDate = void 0; this._badValueForSameId = void 0; if (dateRangeWithSameId) { const previousAttr = dateRangeWithSameId.attr; for (const key in previousAttr) { if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) { logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`); this._badValueForSameId = key; break; } } dateRangeAttr = _extends2(new AttrList({}), previousAttr, dateRangeAttr); } this.attr = dateRangeAttr; this._startDate = new Date(dateRangeAttr["START-DATE"]); if ("END-DATE" in this.attr) { const endDate = new Date(this.attr["END-DATE"]); if (isFiniteNumber(endDate.getTime())) { this._endDate = endDate; } } } get id() { return this.attr.ID; } get class() { return this.attr.CLASS; } get startDate() { return this._startDate; } get endDate() { if (this._endDate) { return this._endDate; } const duration = this.duration; if (duration !== null) { return new Date(this._startDate.getTime() + duration * 1e3); } return null; } get duration() { if ("DURATION" in this.attr) { const duration = this.attr.decimalFloatingPoint("DURATION"); if (isFiniteNumber(duration)) { return duration; } } else if (this._endDate) { return (this._endDate.getTime() - this._startDate.getTime()) / 1e3; } return null; } get plannedDuration() { if ("PLANNED-DURATION" in this.attr) { return this.attr.decimalFloatingPoint("PLANNED-DURATION"); } return null; } get endOnNext() { return this.attr.bool("END-ON-NEXT"); } get isValid() { return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class); } }; var LoadStats = class { constructor() { this.aborted = false; this.loaded = 0; this.retry = 0; this.total = 0; this.chunkCount = 0; this.bwEstimate = 0; this.loading = { start: 0, first: 0, end: 0 }; this.parsing = { start: 0, end: 0 }; this.buffering = { start: 0, first: 0, end: 0 }; } }; var ElementaryStreamTypes = { AUDIO: "audio", VIDEO: "video", AUDIOVIDEO: "audiovideo" }; var BaseSegment = class { constructor(baseurl) { this._byteRange = null; this._url = null; this.baseurl = void 0; this.relurl = void 0; this.elementaryStreams = { [ElementaryStreamTypes.AUDIO]: null, [ElementaryStreamTypes.VIDEO]: null, [ElementaryStreamTypes.AUDIOVIDEO]: null }; this.baseurl = baseurl; } // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array setByteRange(value, previous) { const params = value.split("@", 2); let start; if (params.length === 1) { start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0; } else { start = parseInt(params[1]); } this._byteRange = [start, parseInt(params[0]) + start]; } get byteRange() { if (!this._byteRange) { return []; } return this._byteRange; } get byteRangeStartOffset() { return this.byteRange[0]; } get byteRangeEndOffset() { return this.byteRange[1]; } get url() { if (!this._url && this.baseurl && this.relurl) { this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true }); } return this._url || ""; } set url(value) { this._url = value; } }; var Fragment4 = class extends BaseSegment { constructor(type, baseurl) { super(baseurl); this._decryptdata = null; this.rawProgramDateTime = null; this.programDateTime = null; this.tagList = []; this.duration = 0; this.sn = 0; this.levelkeys = void 0; this.type = void 0; this.loader = null; this.keyLoader = null; this.level = -1; this.cc = 0; this.startPTS = void 0; this.endPTS = void 0; this.startDTS = void 0; this.endDTS = void 0; this.start = 0; this.deltaPTS = void 0; this.maxStartPTS = void 0; this.minEndPTS = void 0; this.stats = new LoadStats(); this.data = void 0; this.bitrateTest = false; this.title = null; this.initSegment = null; this.endList = void 0; this.gap = void 0; this.urlId = 0; this.type = type; } get decryptdata() { const { levelkeys } = this; if (!levelkeys && !this._decryptdata) { return null; } if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) { const key = this.levelkeys.identity; if (key) { this._decryptdata = key.getDecryptData(this.sn); } else { const keyFormats = Object.keys(this.levelkeys); if (keyFormats.length === 1) { return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn); } } } return this._decryptdata; } get end() { return this.start + this.duration; } get endProgramDateTime() { if (this.programDateTime === null) { return null; } if (!isFiniteNumber(this.programDateTime)) { return null; } const duration = !isFiniteNumber(this.duration) ? 0 : this.duration; return this.programDateTime + duration * 1e3; } get encrypted() { var _this$_decryptdata; if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) { return true; } else if (this.levelkeys) { const keyFormats = Object.keys(this.levelkeys); const len = keyFormats.length; if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) { return true; } } return false; } setKeyFormat(keyFormat) { if (this.levelkeys) { const key = this.levelkeys[keyFormat]; if (key && !this._decryptdata) { this._decryptdata = key.getDecryptData(this.sn); } } } abortRequests() { var _this$loader, _this$keyLoader; (_this$loader = this.loader) == null ? void 0 : _this$loader.abort(); (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort(); } setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) { const { elementaryStreams } = this; const info = elementaryStreams[type]; if (!info) { elementaryStreams[type] = { startPTS, endPTS, startDTS, endDTS, partial }; return; } info.startPTS = Math.min(info.startPTS, startPTS); info.endPTS = Math.max(info.endPTS, endPTS); info.startDTS = Math.min(info.startDTS, startDTS); info.endDTS = Math.max(info.endDTS, endDTS); } clearElementaryStreamInfo() { const { elementaryStreams } = this; elementaryStreams[ElementaryStreamTypes.AUDIO] = null; elementaryStreams[ElementaryStreamTypes.VIDEO] = null; elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null; } }; var Part = class extends BaseSegment { constructor(partAttrs, frag, baseurl, index2, previous) { super(baseurl); this.fragOffset = 0; this.duration = 0; this.gap = false; this.independent = false; this.relurl = void 0; this.fragment = void 0; this.index = void 0; this.stats = new LoadStats(); this.duration = partAttrs.decimalFloatingPoint("DURATION"); this.gap = partAttrs.bool("GAP"); this.independent = partAttrs.bool("INDEPENDENT"); this.relurl = partAttrs.enumeratedString("URI"); this.fragment = frag; this.index = index2; const byteRange = partAttrs.enumeratedString("BYTERANGE"); if (byteRange) { this.setByteRange(byteRange, previous); } if (previous) { this.fragOffset = previous.fragOffset + previous.duration; } } get start() { return this.fragment.start + this.fragOffset; } get end() { return this.start + this.duration; } get loaded() { const { elementaryStreams } = this; return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo); } }; var DEFAULT_TARGET_DURATION = 10; var LevelDetails = class { constructor(baseUrl) { this.PTSKnown = false; this.alignedSliding = false; this.averagetargetduration = void 0; this.endCC = 0; this.endSN = 0; this.fragments = void 0; this.fragmentHint = void 0; this.partList = null; this.dateRanges = void 0; this.live = true; this.ageHeader = 0; this.advancedDateTime = void 0; this.updated = true; this.advanced = true; this.availabilityDelay = void 0; this.misses = 0; this.startCC = 0; this.startSN = 0; this.startTimeOffset = null; this.targetduration = 0; this.totalduration = 0; this.type = null; this.url = void 0; this.m3u8 = ""; this.version = null; this.canBlockReload = false; this.canSkipUntil = 0; this.canSkipDateRanges = false; this.skippedSegments = 0; this.recentlyRemovedDateranges = void 0; this.partHoldBack = 0; this.holdBack = 0; this.partTarget = 0; this.preloadHint = void 0; this.renditionReports = void 0; this.tuneInGoal = 0; this.deltaUpdateFailed = void 0; this.driftStartTime = 0; this.driftEndTime = 0; this.driftStart = 0; this.driftEnd = 0; this.encryptedFragments = void 0; this.playlistParsingError = null; this.variableList = null; this.hasVariableRefs = false; this.fragments = []; this.encryptedFragments = []; this.dateRanges = {}; this.url = baseUrl; } reloaded(previous) { if (!previous) { this.advanced = true; this.updated = true; return; } const partSnDiff = this.lastPartSn - previous.lastPartSn; const partIndexDiff = this.lastPartIndex - previous.lastPartIndex; this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live; this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0; if (this.updated || this.advanced) { this.misses = Math.floor(previous.misses * 0.6); } else { this.misses = previous.misses + 1; } this.availabilityDelay = previous.availabilityDelay; } get hasProgramDateTime() { if (this.fragments.length) { return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime); } return false; } get levelTargetDuration() { return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION; } get drift() { const runTime = this.driftEndTime - this.driftStartTime; if (runTime > 0) { const runDuration = this.driftEnd - this.driftStart; return runDuration * 1e3 / runTime; } return 1; } get edge() { return this.partEnd || this.fragmentEnd; } get partEnd() { var _this$partList; if ((_this$partList = this.partList) != null && _this$partList.length) { return this.partList[this.partList.length - 1].end; } return this.fragmentEnd; } get fragmentEnd() { var _this$fragments; if ((_this$fragments = this.fragments) != null && _this$fragments.length) { return this.fragments[this.fragments.length - 1].end; } return 0; } get age() { if (this.advancedDateTime) { return Math.max(Date.now() - this.advancedDateTime, 0) / 1e3; } return 0; } get lastPartIndex() { var _this$partList2; if ((_this$partList2 = this.partList) != null && _this$partList2.length) { return this.partList[this.partList.length - 1].index; } return -1; } get lastPartSn() { var _this$partList3; if ((_this$partList3 = this.partList) != null && _this$partList3.length) { return this.partList[this.partList.length - 1].fragment.sn; } return this.endSN; } }; function base64Decode(base64encodedStr) { return Uint8Array.from(atob(base64encodedStr), (c3) => c3.charCodeAt(0)); } function getKeyIdBytes(str) { const keyIdbytes = strToUtf8array(str).subarray(0, 16); const paddedkeyIdbytes = new Uint8Array(16); paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length); return paddedkeyIdbytes; } function changeEndianness(keyId) { const swap = function swap2(array, from2, to) { const cur = array[from2]; array[from2] = array[to]; array[to] = cur; }; swap(keyId, 0, 3); swap(keyId, 1, 2); swap(keyId, 4, 5); swap(keyId, 6, 7); } function convertDataUriToArrayBytes(uri) { const colonsplit = uri.split(":"); let keydata = null; if (colonsplit[0] === "data" && colonsplit.length === 2) { const semicolonsplit = colonsplit[1].split(";"); const commasplit = semicolonsplit[semicolonsplit.length - 1].split(","); if (commasplit.length === 2) { const isbase64 = commasplit[0] === "base64"; const data = commasplit[1]; if (isbase64) { semicolonsplit.splice(-1, 1); keydata = base64Decode(data); } else { keydata = getKeyIdBytes(data); } } } return keydata; } function strToUtf8array(str) { return Uint8Array.from(unescape(encodeURIComponent(str)), (c3) => c3.charCodeAt(0)); } var optionalSelf = typeof self !== "undefined" ? self : void 0; var KeySystems = { CLEARKEY: "org.w3.clearkey", FAIRPLAY: "com.apple.fps", PLAYREADY: "com.microsoft.playready", WIDEVINE: "com.widevine.alpha" }; var KeySystemFormats = { CLEARKEY: "org.w3.clearkey", FAIRPLAY: "com.apple.streamingkeydelivery", PLAYREADY: "com.microsoft.playready", WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed" }; function keySystemFormatToKeySystemDomain(format2) { switch (format2) { case KeySystemFormats.FAIRPLAY: return KeySystems.FAIRPLAY; case KeySystemFormats.PLAYREADY: return KeySystems.PLAYREADY; case KeySystemFormats.WIDEVINE: return KeySystems.WIDEVINE; case KeySystemFormats.CLEARKEY: return KeySystems.CLEARKEY; } } var KeySystemIds = { CENC: "1077efecc0b24d02ace33c1e52e2fb4b", CLEARKEY: "e2719d58a985b3c9781ab030af78d30e", FAIRPLAY: "94ce86fb07ff4f43adb893d2fa968ca2", PLAYREADY: "9a04f07998404286ab92e65be0885f95", WIDEVINE: "edef8ba979d64acea3c827dcd51d21ed" }; function keySystemIdToKeySystemDomain(systemId) { if (systemId === KeySystemIds.WIDEVINE) { return KeySystems.WIDEVINE; } else if (systemId === KeySystemIds.PLAYREADY) { return KeySystems.PLAYREADY; } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) { return KeySystems.CLEARKEY; } } function keySystemDomainToKeySystemFormat(keySystem) { switch (keySystem) { case KeySystems.FAIRPLAY: return KeySystemFormats.FAIRPLAY; case KeySystems.PLAYREADY: return KeySystemFormats.PLAYREADY; case KeySystems.WIDEVINE: return KeySystemFormats.WIDEVINE; case KeySystems.CLEARKEY: return KeySystemFormats.CLEARKEY; } } function getKeySystemsForConfig(config) { const { drmSystems, widevineLicenseUrl } = config; const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter((keySystem) => !!drmSystems[keySystem]) : []; if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) { keySystemsToAttempt.push(KeySystems.WIDEVINE); } return keySystemsToAttempt; } var requestMediaKeySystemAccess = function(_optionalSelf$navigat) { if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) { return self.navigator.requestMediaKeySystemAccess.bind(self.navigator); } else { return null; } }(); function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) { let initDataTypes; switch (keySystem) { case KeySystems.FAIRPLAY: initDataTypes = ["cenc", "sinf"]; break; case KeySystems.WIDEVINE: case KeySystems.PLAYREADY: initDataTypes = ["cenc"]; break; case KeySystems.CLEARKEY: initDataTypes = ["cenc", "keyids"]; break; default: throw new Error(`Unknown key-system: ${keySystem}`); } return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions); } function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) { const baseConfig = { initDataTypes, persistentState: drmSystemOptions.persistentState || "optional", distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || "optional", sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || "temporary"], audioCapabilities: audioCodecs.map((codec) => ({ contentType: `audio/mp4; codecs="${codec}"`, robustness: drmSystemOptions.audioRobustness || "", encryptionScheme: drmSystemOptions.audioEncryptionScheme || null })), videoCapabilities: videoCodecs.map((codec) => ({ contentType: `video/mp4; codecs="${codec}"`, robustness: drmSystemOptions.videoRobustness || "", encryptionScheme: drmSystemOptions.videoEncryptionScheme || null })) }; return [baseConfig]; } function parsePlayReadyWRM(keyBytes) { const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2); const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16)); const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf("<"), keyByteStr.length); const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlKeyBytes, "text/xml"); const keyData = xmlDoc.getElementsByTagName("KID")[0]; if (keyData) { const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute("VALUE"); if (keyId) { const keyIdArray = base64Decode(keyId).subarray(0, 16); changeEndianness(keyIdArray); return keyIdArray; } } return null; } function sliceUint8(array, start, end) { return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end)); } var isHeader$2 = (data, offset) => { if (offset + 10 <= data.length) { if (data[offset] === 73 && data[offset + 1] === 68 && data[offset + 2] === 51) { if (data[offset + 3] < 255 && data[offset + 4] < 255) { if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) { return true; } } } } return false; }; var isFooter = (data, offset) => { if (offset + 10 <= data.length) { if (data[offset] === 51 && data[offset + 1] === 68 && data[offset + 2] === 73) { if (data[offset + 3] < 255 && data[offset + 4] < 255) { if (data[offset + 6] < 128 && data[offset + 7] < 128 && data[offset + 8] < 128 && data[offset + 9] < 128) { return true; } } } } return false; }; var getID3Data = (data, offset) => { const front = offset; let length2 = 0; while (isHeader$2(data, offset)) { length2 += 10; const size = readSize(data, offset + 6); length2 += size; if (isFooter(data, offset + 10)) { length2 += 10; } offset += length2; } if (length2 > 0) { return data.subarray(front, front + length2); } return void 0; }; var readSize = (data, offset) => { let size = 0; size = (data[offset] & 127) << 21; size |= (data[offset + 1] & 127) << 14; size |= (data[offset + 2] & 127) << 7; size |= data[offset + 3] & 127; return size; }; var canParse$2 = (data, offset) => { return isHeader$2(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset; }; var getTimeStamp = (data) => { const frames = getID3Frames(data); for (let i3 = 0; i3 < frames.length; i3++) { const frame = frames[i3]; if (isTimeStampFrame(frame)) { return readTimeStamp(frame); } } return void 0; }; var isTimeStampFrame = (frame) => { return frame && frame.key === "PRIV" && frame.info === "com.apple.streaming.transportStreamTimestamp"; }; var getFrameData = (data) => { const type = String.fromCharCode(data[0], data[1], data[2], data[3]); const size = readSize(data, 4); const offset = 10; return { type, size, data: data.subarray(offset, offset + size) }; }; var getID3Frames = (id3Data) => { let offset = 0; const frames = []; while (isHeader$2(id3Data, offset)) { const size = readSize(id3Data, offset + 6); offset += 10; const end = offset + size; while (offset + 8 < end) { const frameData = getFrameData(id3Data.subarray(offset)); const frame = decodeFrame(frameData); if (frame) { frames.push(frame); } offset += frameData.size + 10; } if (isFooter(id3Data, offset)) { offset += 10; } } return frames; }; var decodeFrame = (frame) => { if (frame.type === "PRIV") { return decodePrivFrame(frame); } else if (frame.type[0] === "W") { return decodeURLFrame(frame); } return decodeTextFrame(frame); }; var decodePrivFrame = (frame) => { if (frame.size < 2) { return void 0; } const owner = utf8ArrayToStr(frame.data, true); const privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); return { key: frame.type, info: owner, data: privateData.buffer }; }; var decodeTextFrame = (frame) => { if (frame.size < 2) { return void 0; } if (frame.type === "TXXX") { let index2 = 1; const description = utf8ArrayToStr(frame.data.subarray(index2), true); index2 += description.length + 1; const value = utf8ArrayToStr(frame.data.subarray(index2)); return { key: frame.type, info: description, data: value }; } const text = utf8ArrayToStr(frame.data.subarray(1)); return { key: frame.type, data: text }; }; var decodeURLFrame = (frame) => { if (frame.type === "WXXX") { if (frame.size < 2) { return void 0; } let index2 = 1; const description = utf8ArrayToStr(frame.data.subarray(index2), true); index2 += description.length + 1; const value = utf8ArrayToStr(frame.data.subarray(index2)); return { key: frame.type, info: description, data: value }; } const url = utf8ArrayToStr(frame.data); return { key: frame.type, data: url }; }; var readTimeStamp = (timeStampFrame) => { if (timeStampFrame.data.byteLength === 8) { const data = new Uint8Array(timeStampFrame.data); const pts33Bit = data[3] & 1; let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7]; timestamp /= 45; if (pts33Bit) { timestamp += 4772185884e-2; } return Math.round(timestamp); } return void 0; }; var utf8ArrayToStr = (array, exitOnNull = false) => { const decoder2 = getTextDecoder(); if (decoder2) { const decoded = decoder2.decode(array); if (exitOnNull) { const idx = decoded.indexOf("\0"); return idx !== -1 ? decoded.substring(0, idx) : decoded; } return decoded.replace(/\0/g, ""); } const len = array.length; let c3; let char2; let char3; let out = ""; let i3 = 0; while (i3 < len) { c3 = array[i3++]; if (c3 === 0 && exitOnNull) { return out; } else if (c3 === 0 || c3 === 3) { continue; } switch (c3 >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: out += String.fromCharCode(c3); break; case 12: case 13: char2 = array[i3++]; out += String.fromCharCode((c3 & 31) << 6 | char2 & 63); break; case 14: char2 = array[i3++]; char3 = array[i3++]; out += String.fromCharCode((c3 & 15) << 12 | (char2 & 63) << 6 | (char3 & 63) << 0); break; } } return out; }; var decoder; function getTextDecoder() { if (navigator.userAgent.includes("PlayStation 4")) { return; } if (!decoder && typeof self.TextDecoder !== "undefined") { decoder = new self.TextDecoder("utf-8"); } return decoder; } var Hex = { hexDump: function(array) { let str = ""; for (let i3 = 0; i3 < array.length; i3++) { let h3 = array[i3].toString(16); if (h3.length < 2) { h3 = "0" + h3; } str += h3; } return str; } }; var UINT32_MAX$1 = Math.pow(2, 32) - 1; var push = [].push; var RemuxerTrackIdConfig = { video: 1, audio: 2, id3: 3, text: 4 }; function bin2str(data) { return String.fromCharCode.apply(null, data); } function readUint16(buffer, offset) { const val = buffer[offset] << 8 | buffer[offset + 1]; return val < 0 ? 65536 + val : val; } function readUint32(buffer, offset) { const val = readSint32(buffer, offset); return val < 0 ? 4294967296 + val : val; } function readUint64(buffer, offset) { let result = readUint32(buffer, offset); result *= Math.pow(2, 32); result += readUint32(buffer, offset + 4); return result; } function readSint32(buffer, offset) { return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3]; } function writeUint32(buffer, offset, value) { buffer[offset] = value >> 24; buffer[offset + 1] = value >> 16 & 255; buffer[offset + 2] = value >> 8 & 255; buffer[offset + 3] = value & 255; } function hasMoofData(data) { const end = data.byteLength; for (let i3 = 0; i3 < end; ) { const size = readUint32(data, i3); if (size > 8 && data[i3 + 4] === 109 && data[i3 + 5] === 111 && data[i3 + 6] === 111 && data[i3 + 7] === 102) { return true; } i3 = size > 1 ? i3 + size : end; } return false; } function findBox(data, path) { const results = []; if (!path.length) { return results; } const end = data.byteLength; for (let i3 = 0; i3 < end; ) { const size = readUint32(data, i3); const type = bin2str(data.subarray(i3 + 4, i3 + 8)); const endbox = size > 1 ? i3 + size : end; if (type === path[0]) { if (path.length === 1) { results.push(data.subarray(i3 + 8, endbox)); } else { const subresults = findBox(data.subarray(i3 + 8, endbox), path.slice(1)); if (subresults.length) { push.apply(results, subresults); } } } i3 = endbox; } return results; } function parseSegmentIndex(sidx) { const references = []; const version = sidx[0]; let index2 = 8; const timescale = readUint32(sidx, index2); index2 += 4; let earliestPresentationTime = 0; let firstOffset = 0; if (version === 0) { earliestPresentationTime = readUint32(sidx, index2); firstOffset = readUint32(sidx, index2 + 4); index2 += 8; } else { earliestPresentationTime = readUint64(sidx, index2); firstOffset = readUint64(sidx, index2 + 8); index2 += 16; } index2 += 2; let startByte = sidx.length + firstOffset; const referencesCount = readUint16(sidx, index2); index2 += 2; for (let i3 = 0; i3 < referencesCount; i3++) { let referenceIndex = index2; const referenceInfo = readUint32(sidx, referenceIndex); referenceIndex += 4; const referenceSize = referenceInfo & 2147483647; const referenceType = (referenceInfo & 2147483648) >>> 31; if (referenceType === 1) { logger.warn("SIDX has hierarchical references (not supported)"); return null; } const subsegmentDuration = readUint32(sidx, referenceIndex); referenceIndex += 4; references.push({ referenceSize, subsegmentDuration, // unscaled info: { duration: subsegmentDuration / timescale, start: startByte, end: startByte + referenceSize - 1 } }); startByte += referenceSize; referenceIndex += 4; index2 = referenceIndex; } return { earliestPresentationTime, timescale, version, referencesCount, references }; } function parseInitSegment(initSegment) { const result = []; const traks = findBox(initSegment, ["moov", "trak"]); for (let i3 = 0; i3 < traks.length; i3++) { const trak = traks[i3]; const tkhd = findBox(trak, ["tkhd"])[0]; if (tkhd) { let version = tkhd[0]; const trackId = readUint32(tkhd, version === 0 ? 12 : 20); const mdhd = findBox(trak, ["mdia", "mdhd"])[0]; if (mdhd) { version = mdhd[0]; const timescale = readUint32(mdhd, version === 0 ? 12 : 20); const hdlr = findBox(trak, ["mdia", "hdlr"])[0]; if (hdlr) { const hdlrType = bin2str(hdlr.subarray(8, 12)); const type = { soun: ElementaryStreamTypes.AUDIO, vide: ElementaryStreamTypes.VIDEO }[hdlrType]; if (type) { const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0]; const stsdData = parseStsd(stsd); result[trackId] = { timescale, type }; result[type] = _objectSpread23({ timescale, id: trackId }, stsdData); } } } } } const trex = findBox(initSegment, ["moov", "mvex", "trex"]); trex.forEach((trex2) => { const trackId = readUint32(trex2, 4); const track = result[trackId]; if (track) { track.default = { duration: readUint32(trex2, 12), flags: readUint32(trex2, 20) }; } }); return result; } function parseStsd(stsd) { const sampleEntries = stsd.subarray(8); const sampleEntriesEnd = sampleEntries.subarray(8 + 78); const fourCC = bin2str(sampleEntries.subarray(4, 8)); let codec = fourCC; const encrypted = fourCC === "enca" || fourCC === "encv"; if (encrypted) { const encBox = findBox(sampleEntries, [fourCC])[0]; const encBoxChildren = encBox.subarray(fourCC === "enca" ? 28 : 78); const sinfs = findBox(encBoxChildren, ["sinf"]); sinfs.forEach((sinf) => { const schm = findBox(sinf, ["schm"])[0]; if (schm) { const scheme = bin2str(schm.subarray(4, 8)); if (scheme === "cbcs" || scheme === "cenc") { const frma = findBox(sinf, ["frma"])[0]; if (frma) { codec = bin2str(frma); } } } }); } switch (codec) { case "avc1": case "avc2": case "avc3": case "avc4": { const avcCBox = findBox(sampleEntriesEnd, ["avcC"])[0]; codec += "." + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]); break; } case "mp4a": { const codecBox = findBox(sampleEntries, [fourCC])[0]; const esdsBox = findBox(codecBox.subarray(28), ["esds"])[0]; if (esdsBox && esdsBox.length > 12) { let i3 = 4; if (esdsBox[i3++] !== 3) { break; } i3 = skipBERInteger(esdsBox, i3); i3 += 2; const flags = esdsBox[i3++]; if (flags & 128) { i3 += 2; } if (flags & 64) { i3 += esdsBox[i3++]; } if (esdsBox[i3++] !== 4) { break; } i3 = skipBERInteger(esdsBox, i3); const objectType = esdsBox[i3++]; if (objectType === 64) { codec += "." + toHex(objectType); } else { break; } i3 += 12; if (esdsBox[i3++] !== 5) { break; } i3 = skipBERInteger(esdsBox, i3); const firstByte = esdsBox[i3++]; let audioObjectType = (firstByte & 248) >> 3; if (audioObjectType === 31) { audioObjectType += 1 + ((firstByte & 7) << 3) + ((esdsBox[i3] & 224) >> 5); } codec += "." + audioObjectType; } break; } case "hvc1": case "hev1": { const hvcCBox = findBox(sampleEntriesEnd, ["hvcC"])[0]; const profileByte = hvcCBox[1]; const profileSpace = ["", "A", "B", "C"][profileByte >> 6]; const generalProfileIdc = profileByte & 31; const profileCompat = readUint32(hvcCBox, 2); const tierFlag = (profileByte & 32) >> 5 ? "H" : "L"; const levelIDC = hvcCBox[12]; const constraintIndicator = hvcCBox.subarray(6, 12); codec += "." + profileSpace + generalProfileIdc; codec += "." + profileCompat.toString(16).toUpperCase(); codec += "." + tierFlag + levelIDC; let constraintString = ""; for (let i3 = constraintIndicator.length; i3--; ) { const byte = constraintIndicator[i3]; if (byte || constraintString) { const encodedByte = byte.toString(16).toUpperCase(); constraintString = "." + encodedByte + constraintString; } } codec += constraintString; break; } case "dvh1": case "dvhe": { const dvcCBox = findBox(sampleEntriesEnd, ["dvcC"])[0]; const profile = dvcCBox[2] >> 1 & 127; const level = dvcCBox[2] << 5 & 32 | dvcCBox[3] >> 3 & 31; codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level); break; } case "vp09": { const vpcCBox = findBox(sampleEntriesEnd, ["vpcC"])[0]; const profile = vpcCBox[4]; const level = vpcCBox[5]; const bitDepth = vpcCBox[6] >> 4 & 15; codec += "." + addLeadingZero(profile) + "." + addLeadingZero(level) + "." + addLeadingZero(bitDepth); break; } case "av01": { const av1CBox = findBox(sampleEntriesEnd, ["av1C"])[0]; const profile = av1CBox[1] >>> 5; const level = av1CBox[1] & 31; const tierFlag = av1CBox[2] >>> 7 ? "H" : "M"; const highBitDepth = (av1CBox[2] & 64) >> 6; const twelveBit = (av1CBox[2] & 32) >> 5; const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8; const monochrome = (av1CBox[2] & 16) >> 4; const chromaSubsamplingX = (av1CBox[2] & 8) >> 3; const chromaSubsamplingY = (av1CBox[2] & 4) >> 2; const chromaSamplePosition = av1CBox[2] & 3; const colorPrimaries = 1; const transferCharacteristics = 1; const matrixCoefficients = 1; const videoFullRangeFlag = 0; codec += "." + profile + "." + addLeadingZero(level) + tierFlag + "." + addLeadingZero(bitDepth) + "." + monochrome + "." + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + "." + addLeadingZero(colorPrimaries) + "." + addLeadingZero(transferCharacteristics) + "." + addLeadingZero(matrixCoefficients) + "." + videoFullRangeFlag; break; } } return { codec, encrypted }; } function skipBERInteger(bytes, i3) { const limit = i3 + 5; while (bytes[i3++] & 128 && i3 < limit) { } return i3; } function toHex(x2) { return ("0" + x2.toString(16).toUpperCase()).slice(-2); } function addLeadingZero(num) { return (num < 10 ? "0" : "") + num; } function patchEncyptionData(initSegment, decryptdata) { if (!initSegment || !decryptdata) { return initSegment; } const keyId = decryptdata.keyId; if (keyId && decryptdata.isCommonEncryption) { const traks = findBox(initSegment, ["moov", "trak"]); traks.forEach((trak) => { const stsd = findBox(trak, ["mdia", "minf", "stbl", "stsd"])[0]; const sampleEntries = stsd.subarray(8); let encBoxes = findBox(sampleEntries, ["enca"]); const isAudio = encBoxes.length > 0; if (!isAudio) { encBoxes = findBox(sampleEntries, ["encv"]); } encBoxes.forEach((enc) => { const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78); const sinfBoxes = findBox(encBoxChildren, ["sinf"]); sinfBoxes.forEach((sinf) => { const tenc = parseSinf(sinf); if (tenc) { const tencKeyId = tenc.subarray(8, 24); if (!tencKeyId.some((b2) => b2 !== 0)) { logger.log(`[eme] Patching keyId in 'enc${isAudio ? "a" : "v"}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`); tenc.set(keyId, 8); } } }); }); }); } return initSegment; } function parseSinf(sinf) { const schm = findBox(sinf, ["schm"])[0]; if (schm) { const scheme = bin2str(schm.subarray(4, 8)); if (scheme === "cbcs" || scheme === "cenc") { return findBox(sinf, ["schi", "tenc"])[0]; } } return null; } function getStartDTS(initData, fmp4) { return findBox(fmp4, ["moof", "traf"]).reduce((result, traf) => { const tfdt = findBox(traf, ["tfdt"])[0]; const version = tfdt[0]; const start = findBox(traf, ["tfhd"]).reduce((result2, tfhd) => { const id = readUint32(tfhd, 4); const track = initData[id]; if (track) { let baseTime = readUint32(tfdt, 4); if (version === 1) { if (baseTime === UINT32_MAX$1) { logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`); return result2; } baseTime *= UINT32_MAX$1 + 1; baseTime += readUint32(tfdt, 8); } const scale2 = track.timescale || 9e4; const startTime = baseTime / scale2; if (isFiniteNumber(startTime) && (result2 === null || startTime < result2)) { return startTime; } } return result2; }, null); if (start !== null && isFiniteNumber(start) && (result === null || start < result)) { return start; } return result; }, null); } function getDuration(data, initData) { let rawDuration = 0; let videoDuration = 0; let audioDuration = 0; const trafs = findBox(data, ["moof", "traf"]); for (let i3 = 0; i3 < trafs.length; i3++) { const traf = trafs[i3]; const tfhd = findBox(traf, ["tfhd"])[0]; const id = readUint32(tfhd, 4); const track = initData[id]; if (!track) { continue; } const trackDefault = track.default; const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags); let sampleDuration = trackDefault == null ? void 0 : trackDefault.duration; if (tfhdFlags & 8) { if (tfhdFlags & 2) { sampleDuration = readUint32(tfhd, 12); } else { sampleDuration = readUint32(tfhd, 8); } } const timescale = track.timescale || 9e4; const truns = findBox(traf, ["trun"]); for (let j3 = 0; j3 < truns.length; j3++) { rawDuration = computeRawDurationFromSamples(truns[j3]); if (!rawDuration && sampleDuration) { const sampleCount = readUint32(truns[j3], 4); rawDuration = sampleDuration * sampleCount; } if (track.type === ElementaryStreamTypes.VIDEO) { videoDuration += rawDuration / timescale; } else if (track.type === ElementaryStreamTypes.AUDIO) { audioDuration += rawDuration / timescale; } } } if (videoDuration === 0 && audioDuration === 0) { let sidxMinStart = Infinity; let sidxMaxEnd = 0; let sidxDuration = 0; const sidxs = findBox(data, ["sidx"]); for (let i3 = 0; i3 < sidxs.length; i3++) { const sidx = parseSegmentIndex(sidxs[i3]); if (sidx != null && sidx.references) { sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale); const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0); sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale); sidxDuration = sidxMaxEnd - sidxMinStart; } } if (sidxDuration && isFiniteNumber(sidxDuration)) { return sidxDuration; } } if (videoDuration) { return videoDuration; } return audioDuration; } function computeRawDurationFromSamples(trun) { const flags = readUint32(trun, 0); let offset = 8; if (flags & 1) { offset += 4; } if (flags & 4) { offset += 4; } let duration = 0; const sampleCount = readUint32(trun, 4); for (let i3 = 0; i3 < sampleCount; i3++) { if (flags & 256) { const sampleDuration = readUint32(trun, offset); duration += sampleDuration; offset += 4; } if (flags & 512) { offset += 4; } if (flags & 1024) { offset += 4; } if (flags & 2048) { offset += 4; } } return duration; } function offsetStartDTS(initData, fmp4, timeOffset) { findBox(fmp4, ["moof", "traf"]).forEach((traf) => { findBox(traf, ["tfhd"]).forEach((tfhd) => { const id = readUint32(tfhd, 4); const track = initData[id]; if (!track) { return; } const timescale = track.timescale || 9e4; findBox(traf, ["tfdt"]).forEach((tfdt) => { const version = tfdt[0]; const offset = timeOffset * timescale; if (offset) { let baseMediaDecodeTime = readUint32(tfdt, 4); if (version === 0) { baseMediaDecodeTime -= offset; baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0); writeUint32(tfdt, 4, baseMediaDecodeTime); } else { baseMediaDecodeTime *= Math.pow(2, 32); baseMediaDecodeTime += readUint32(tfdt, 8); baseMediaDecodeTime -= offset; baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0); const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1)); const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1)); writeUint32(tfdt, 4, upper); writeUint32(tfdt, 8, lower); } } }); }); }); } function segmentValidRange(data) { const segmentedRange = { valid: null, remainder: null }; const moofs = findBox(data, ["moof"]); if (moofs.length < 2) { segmentedRange.remainder = data; return segmentedRange; } const last = moofs[moofs.length - 1]; segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8); segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8); return segmentedRange; } function appendUint8Array(data1, data2) { const temp = new Uint8Array(data1.length + data2.length); temp.set(data1); temp.set(data2, data1.length); return temp; } function parseSamples(timeOffset, track) { const seiSamples = []; const videoData = track.samples; const timescale = track.timescale; const trackId = track.id; let isHEVCFlavor = false; const moofs = findBox(videoData, ["moof"]); moofs.map((moof) => { const moofOffset = moof.byteOffset - 8; const trafs = findBox(moof, ["traf"]); trafs.map((traf) => { const baseTime = findBox(traf, ["tfdt"]).map((tfdt) => { const version = tfdt[0]; let result = readUint32(tfdt, 4); if (version === 1) { result *= Math.pow(2, 32); result += readUint32(tfdt, 8); } return result / timescale; })[0]; if (baseTime !== void 0) { timeOffset = baseTime; } return findBox(traf, ["tfhd"]).map((tfhd) => { const id = readUint32(tfhd, 4); const tfhdFlags = readUint32(tfhd, 0) & 16777215; const baseDataOffsetPresent = (tfhdFlags & 1) !== 0; const sampleDescriptionIndexPresent = (tfhdFlags & 2) !== 0; const defaultSampleDurationPresent = (tfhdFlags & 8) !== 0; let defaultSampleDuration = 0; const defaultSampleSizePresent = (tfhdFlags & 16) !== 0; let defaultSampleSize = 0; const defaultSampleFlagsPresent = (tfhdFlags & 32) !== 0; let tfhdOffset = 8; if (id === trackId) { if (baseDataOffsetPresent) { tfhdOffset += 8; } if (sampleDescriptionIndexPresent) { tfhdOffset += 4; } if (defaultSampleDurationPresent) { defaultSampleDuration = readUint32(tfhd, tfhdOffset); tfhdOffset += 4; } if (defaultSampleSizePresent) { defaultSampleSize = readUint32(tfhd, tfhdOffset); tfhdOffset += 4; } if (defaultSampleFlagsPresent) { tfhdOffset += 4; } if (track.type === "video") { isHEVCFlavor = isHEVC(track.codec); } findBox(traf, ["trun"]).map((trun) => { const version = trun[0]; const flags = readUint32(trun, 0) & 16777215; const dataOffsetPresent = (flags & 1) !== 0; let dataOffset = 0; const firstSampleFlagsPresent = (flags & 4) !== 0; const sampleDurationPresent = (flags & 256) !== 0; let sampleDuration = 0; const sampleSizePresent = (flags & 512) !== 0; let sampleSize = 0; const sampleFlagsPresent = (flags & 1024) !== 0; const sampleCompositionOffsetsPresent = (flags & 2048) !== 0; let compositionOffset = 0; const sampleCount = readUint32(trun, 4); let trunOffset = 8; if (dataOffsetPresent) { dataOffset = readUint32(trun, trunOffset); trunOffset += 4; } if (firstSampleFlagsPresent) { trunOffset += 4; } let sampleOffset = dataOffset + moofOffset; for (let ix = 0; ix < sampleCount; ix++) { if (sampleDurationPresent) { sampleDuration = readUint32(trun, trunOffset); trunOffset += 4; } else { sampleDuration = defaultSampleDuration; } if (sampleSizePresent) { sampleSize = readUint32(trun, trunOffset); trunOffset += 4; } else { sampleSize = defaultSampleSize; } if (sampleFlagsPresent) { trunOffset += 4; } if (sampleCompositionOffsetsPresent) { if (version === 0) { compositionOffset = readUint32(trun, trunOffset); } else { compositionOffset = readSint32(trun, trunOffset); } trunOffset += 4; } if (track.type === ElementaryStreamTypes.VIDEO) { let naluTotalSize = 0; while (naluTotalSize < sampleSize) { const naluSize = readUint32(videoData, sampleOffset); sampleOffset += 4; if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) { const data = videoData.subarray(sampleOffset, sampleOffset + naluSize); parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples); } sampleOffset += naluSize; naluTotalSize += naluSize + 4; } } timeOffset += sampleDuration / timescale; } }); } }); }); }); return seiSamples; } function isHEVC(codec) { if (!codec) { return false; } const delimit2 = codec.indexOf("."); const baseCodec = delimit2 < 0 ? codec : codec.substring(0, delimit2); return baseCodec === "hvc1" || baseCodec === "hev1" || // Dolby Vision baseCodec === "dvh1" || baseCodec === "dvhe"; } function isSEIMessage(isHEVCFlavor, naluHeader) { if (isHEVCFlavor) { const naluType = naluHeader >> 1 & 63; return naluType === 39 || naluType === 40; } else { const naluType = naluHeader & 31; return naluType === 6; } } function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) { const data = discardEPB(unescapedData); let seiPtr = 0; seiPtr += headerSize; let payloadType = 0; let payloadSize = 0; let b2 = 0; while (seiPtr < data.length) { payloadType = 0; do { if (seiPtr >= data.length) { break; } b2 = data[seiPtr++]; payloadType += b2; } while (b2 === 255); payloadSize = 0; do { if (seiPtr >= data.length) { break; } b2 = data[seiPtr++]; payloadSize += b2; } while (b2 === 255); const leftOver = data.length - seiPtr; let payPtr = seiPtr; if (payloadSize < leftOver) { seiPtr += payloadSize; } else if (payloadSize > leftOver) { logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`); break; } if (payloadType === 4) { const countryCode = data[payPtr++]; if (countryCode === 181) { const providerCode = readUint16(data, payPtr); payPtr += 2; if (providerCode === 49) { const userStructure = readUint32(data, payPtr); payPtr += 4; if (userStructure === 1195456820) { const userDataType = data[payPtr++]; if (userDataType === 3) { const firstByte = data[payPtr++]; const totalCCs = 31 & firstByte; const enabled = 64 & firstByte; const totalBytes = enabled ? 2 + totalCCs * 3 : 0; const byteArray = new Uint8Array(totalBytes); if (enabled) { byteArray[0] = firstByte; for (let i3 = 1; i3 < totalBytes; i3++) { byteArray[i3] = data[payPtr++]; } } samples.push({ type: userDataType, payloadType, pts, bytes: byteArray }); } } } } } else if (payloadType === 5) { if (payloadSize > 16) { const uuidStrArray = []; for (let i3 = 0; i3 < 16; i3++) { const _b = data[payPtr++].toString(16); uuidStrArray.push(_b.length == 1 ? "0" + _b : _b); if (i3 === 3 || i3 === 5 || i3 === 7 || i3 === 9) { uuidStrArray.push("-"); } } const length2 = payloadSize - 16; const userDataBytes = new Uint8Array(length2); for (let i3 = 0; i3 < length2; i3++) { userDataBytes[i3] = data[payPtr++]; } samples.push({ payloadType, pts, uuid: uuidStrArray.join(""), userData: utf8ArrayToStr(userDataBytes), userDataBytes }); } } } } function discardEPB(data) { const length2 = data.byteLength; const EPBPositions = []; let i3 = 1; while (i3 < length2 - 2) { if (data[i3] === 0 && data[i3 + 1] === 0 && data[i3 + 2] === 3) { EPBPositions.push(i3 + 2); i3 += 2; } else { i3++; } } if (EPBPositions.length === 0) { return data; } const newLength = length2 - EPBPositions.length; const newData = new Uint8Array(newLength); let sourceIndex = 0; for (i3 = 0; i3 < newLength; sourceIndex++, i3++) { if (sourceIndex === EPBPositions[0]) { sourceIndex++; EPBPositions.shift(); } newData[i3] = data[sourceIndex]; } return newData; } function parseEmsg(data) { const version = data[0]; let schemeIdUri = ""; let value = ""; let timeScale = 0; let presentationTimeDelta = 0; let presentationTime = 0; let eventDuration = 0; let id = 0; let offset = 0; if (version === 0) { while (bin2str(data.subarray(offset, offset + 1)) !== "\0") { schemeIdUri += bin2str(data.subarray(offset, offset + 1)); offset += 1; } schemeIdUri += bin2str(data.subarray(offset, offset + 1)); offset += 1; while (bin2str(data.subarray(offset, offset + 1)) !== "\0") { value += bin2str(data.subarray(offset, offset + 1)); offset += 1; } value += bin2str(data.subarray(offset, offset + 1)); offset += 1; timeScale = readUint32(data, 12); presentationTimeDelta = readUint32(data, 16); eventDuration = readUint32(data, 20); id = readUint32(data, 24); offset = 28; } else if (version === 1) { offset += 4; timeScale = readUint32(data, offset); offset += 4; const leftPresentationTime = readUint32(data, offset); offset += 4; const rightPresentationTime = readUint32(data, offset); offset += 4; presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime; if (!isSafeInteger(presentationTime)) { presentationTime = Number.MAX_SAFE_INTEGER; logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box"); } eventDuration = readUint32(data, offset); offset += 4; id = readUint32(data, offset); offset += 4; while (bin2str(data.subarray(offset, offset + 1)) !== "\0") { schemeIdUri += bin2str(data.subarray(offset, offset + 1)); offset += 1; } schemeIdUri += bin2str(data.subarray(offset, offset + 1)); offset += 1; while (bin2str(data.subarray(offset, offset + 1)) !== "\0") { value += bin2str(data.subarray(offset, offset + 1)); offset += 1; } value += bin2str(data.subarray(offset, offset + 1)); offset += 1; } const payload = data.subarray(offset, data.byteLength); return { schemeIdUri, value, timeScale, presentationTime, presentationTimeDelta, eventDuration, id, payload }; } function mp4Box(type, ...payload) { const len = payload.length; let size = 8; let i3 = len; while (i3--) { size += payload[i3].byteLength; } const result = new Uint8Array(size); result[0] = size >> 24 & 255; result[1] = size >> 16 & 255; result[2] = size >> 8 & 255; result[3] = size & 255; result.set(type, 4); for (i3 = 0, size = 8; i3 < len; i3++) { result.set(payload[i3], size); size += payload[i3].byteLength; } return result; } function mp4pssh(systemId, keyids, data) { if (systemId.byteLength !== 16) { throw new RangeError("Invalid system id"); } let version; let kids; if (keyids) { version = 1; kids = new Uint8Array(keyids.length * 16); for (let ix = 0; ix < keyids.length; ix++) { const k3 = keyids[ix]; if (k3.byteLength !== 16) { throw new RangeError("Invalid key"); } kids.set(k3, ix * 16); } } else { version = 0; kids = new Uint8Array(); } let kidCount; if (version > 0) { kidCount = new Uint8Array(4); if (keyids.length > 0) { new DataView(kidCount.buffer).setUint32(0, keyids.length, false); } } else { kidCount = new Uint8Array(); } const dataSize = new Uint8Array(4); if (data && data.byteLength > 0) { new DataView(dataSize.buffer).setUint32(0, data.byteLength, false); } return mp4Box( [112, 115, 115, 104], new Uint8Array([ version, 0, 0, 0 // Flags ]), systemId, // 16 bytes kidCount, kids, dataSize, data || new Uint8Array() ); } function parseMultiPssh(initData) { const results = []; if (initData instanceof ArrayBuffer) { const length2 = initData.byteLength; let offset = 0; while (offset + 32 < length2) { const view = new DataView(initData, offset); const pssh = parsePssh(view); results.push(pssh); offset += pssh.size; } } return results; } function parsePssh(view) { const size = view.getUint32(0); const offset = view.byteOffset; const length2 = view.byteLength; if (length2 < size) { return { offset, size: length2 }; } const type = view.getUint32(4); if (type !== 1886614376) { return { offset, size }; } const version = view.getUint32(8) >>> 24; if (version !== 0 && version !== 1) { return { offset, size }; } const buffer = view.buffer; const systemId = Hex.hexDump(new Uint8Array(buffer, offset + 12, 16)); const dataSizeOrKidCount = view.getUint32(28); let kids = null; let data = null; if (version === 0) { if (size - 32 < dataSizeOrKidCount || dataSizeOrKidCount < 22) { return { offset, size }; } data = new Uint8Array(buffer, offset + 32, dataSizeOrKidCount); } else if (version === 1) { if (!dataSizeOrKidCount || length2 < offset + 32 + dataSizeOrKidCount * 16 + 16) { return { offset, size }; } kids = []; for (let i3 = 0; i3 < dataSizeOrKidCount; i3++) { kids.push(new Uint8Array(buffer, offset + 32 + i3 * 16, 16)); } } return { version, systemId, kids, data, offset, size }; } var keyUriToKeyIdMap = {}; var LevelKey = class _LevelKey { static clearKeyUriToKeyIdMap() { keyUriToKeyIdMap = {}; } constructor(method, uri, format2, formatversions = [1], iv = null) { this.uri = void 0; this.method = void 0; this.keyFormat = void 0; this.keyFormatVersions = void 0; this.encrypted = void 0; this.isCommonEncryption = void 0; this.iv = null; this.key = null; this.keyId = null; this.pssh = null; this.method = method; this.uri = uri; this.keyFormat = format2; this.keyFormatVersions = formatversions; this.iv = iv; this.encrypted = method ? method !== "NONE" : false; this.isCommonEncryption = this.encrypted && method !== "AES-128"; } isSupported() { if (this.method) { if (this.method === "AES-128" || this.method === "NONE") { return true; } if (this.keyFormat === "identity") { return this.method === "SAMPLE-AES"; } else { switch (this.keyFormat) { case KeySystemFormats.FAIRPLAY: case KeySystemFormats.WIDEVINE: case KeySystemFormats.PLAYREADY: case KeySystemFormats.CLEARKEY: return ["ISO-23001-7", "SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1; } } } return false; } getDecryptData(sn) { if (!this.encrypted || !this.uri) { return null; } if (this.method === "AES-128" && this.uri && !this.iv) { if (typeof sn !== "number") { if (this.method === "AES-128" && !this.iv) { logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`); } sn = 0; } const iv = createInitializationVector(sn); const decryptdata = new _LevelKey(this.method, this.uri, "identity", this.keyFormatVersions, iv); return decryptdata; } const keyBytes = convertDataUriToArrayBytes(this.uri); if (keyBytes) { switch (this.keyFormat) { case KeySystemFormats.WIDEVINE: this.pssh = keyBytes; if (keyBytes.length >= 22) { this.keyId = keyBytes.subarray(keyBytes.length - 22, keyBytes.length - 6); } break; case KeySystemFormats.PLAYREADY: { const PlayReadyKeySystemUUID = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]); this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes); this.keyId = parsePlayReadyWRM(keyBytes); break; } default: { let keydata = keyBytes.subarray(0, 16); if (keydata.length !== 16) { const padded = new Uint8Array(16); padded.set(keydata, 16 - keydata.length); keydata = padded; } this.keyId = keydata; break; } } } if (!this.keyId || this.keyId.byteLength !== 16) { let keyId = keyUriToKeyIdMap[this.uri]; if (!keyId) { const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER; keyId = new Uint8Array(16); const dv = new DataView(keyId.buffer, 12, 4); dv.setUint32(0, val); keyUriToKeyIdMap[this.uri] = keyId; } this.keyId = keyId; } return this; } }; function createInitializationVector(segmentNumber) { const uint8View = new Uint8Array(16); for (let i3 = 12; i3 < 16; i3++) { uint8View[i3] = segmentNumber >> 8 * (15 - i3) & 255; } return uint8View; } var VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g; function hasVariableReferences(str) { return VARIABLE_REPLACEMENT_REGEX.test(str); } function substituteVariablesInAttributes(parsed, attr, attributeNames) { if (parsed.variableList !== null || parsed.hasVariableRefs) { for (let i3 = attributeNames.length; i3--; ) { const name = attributeNames[i3]; const value = attr[name]; if (value) { attr[name] = substituteVariables(parsed, value); } } } } function substituteVariables(parsed, value) { if (parsed.variableList !== null || parsed.hasVariableRefs) { const variableList = parsed.variableList; return value.replace(VARIABLE_REPLACEMENT_REGEX, (variableReference) => { const variableName = variableReference.substring(2, variableReference.length - 1); const variableValue = variableList == null ? void 0 : variableList[variableName]; if (variableValue === void 0) { parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`)); return variableReference; } return variableValue; }); } return value; } function addVariableDefinition(parsed, attr, parentUrl) { let variableList = parsed.variableList; if (!variableList) { parsed.variableList = variableList = {}; } let NAME; let VALUE; if ("QUERYPARAM" in attr) { NAME = attr.QUERYPARAM; try { const searchParams = new self.URL(parentUrl).searchParams; if (searchParams.has(NAME)) { VALUE = searchParams.get(NAME); } else { throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`); } } catch (error) { parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`)); } } else { NAME = attr.NAME; VALUE = attr.VALUE; } if (NAME in variableList) { parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`)); } else { variableList[NAME] = VALUE || ""; } } function importVariableDefinition(parsed, attr, sourceVariableList) { const IMPORT2 = attr.IMPORT; if (sourceVariableList && IMPORT2 in sourceVariableList) { let variableList = parsed.variableList; if (!variableList) { parsed.variableList = variableList = {}; } variableList[IMPORT2] = sourceVariableList[IMPORT2]; } else { parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT2}"`)); } } function getMediaSource(preferManagedMediaSource = true) { if (typeof self === "undefined") return void 0; const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource; return mms || self.MediaSource || self.WebKitMediaSource; } function isManagedMediaSource(source) { return typeof self !== "undefined" && source === self.ManagedMediaSource; } var sampleEntryCodesISO = { audio: { a3ds: 1, "ac-3": 0.95, "ac-4": 1, alac: 0.9, alaw: 1, dra1: 1, "dts+": 1, "dts-": 1, dtsc: 1, dtse: 1, dtsh: 1, "ec-3": 0.9, enca: 1, fLaC: 0.9, // MP4-RA listed codec entry for FLAC flac: 0.9, // legacy browser codec name for FLAC FLAC: 0.9, // some manifests may list "FLAC" with Apple's tools g719: 1, g726: 1, m4ae: 1, mha1: 1, mha2: 1, mhm1: 1, mhm2: 1, mlpa: 1, mp4a: 1, "raw ": 1, Opus: 1, opus: 1, // browsers expect this to be lowercase despite MP4RA says 'Opus' samr: 1, sawb: 1, sawp: 1, sevc: 1, sqcp: 1, ssmv: 1, twos: 1, ulaw: 1 }, video: { avc1: 1, avc2: 1, avc3: 1, avc4: 1, avcp: 1, av01: 0.8, drac: 1, dva1: 1, dvav: 1, dvh1: 0.7, dvhe: 0.7, encv: 1, hev1: 0.75, hvc1: 0.75, mjp2: 1, mp4v: 1, mvc1: 1, mvc2: 1, mvc3: 1, mvc4: 1, resv: 1, rv60: 1, s263: 1, svc1: 1, svc2: 1, "vc-1": 1, vp08: 1, vp09: 0.9 }, text: { stpp: 1, wvtt: 1 } }; function isCodecType(codec, type) { const typeCodes = sampleEntryCodesISO[type]; return !!typeCodes && !!typeCodes[codec.slice(0, 4)]; } function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) { return !codecs.split(",").some((codec) => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource)); } function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) { var _MediaSource$isTypeSu; const MediaSource = getMediaSource(preferManagedMediaSource); return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false; } function mimeTypeForCodec(codec, type) { return `${type}/mp4;codecs="${codec}"`; } function videoCodecPreferenceValue(videoCodec) { if (videoCodec) { const fourCC = videoCodec.substring(0, 4); return sampleEntryCodesISO.video[fourCC]; } return 2; } function codecsSetSelectionPreferenceValue(codecSet) { return codecSet.split(",").reduce((num, fourCC) => { const preferenceValue = sampleEntryCodesISO.video[fourCC]; if (preferenceValue) { return (preferenceValue * 2 + num) / (num ? 3 : 2); } return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1); }, 0); } var CODEC_COMPATIBLE_NAMES = {}; function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) { if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) { return CODEC_COMPATIBLE_NAMES[lowerCaseCodec]; } const codecsToCheck = { flac: ["flac", "fLaC", "FLAC"], opus: ["opus", "Opus"] }[lowerCaseCodec]; for (let i3 = 0; i3 < codecsToCheck.length; i3++) { if (isCodecMediaSourceSupported(codecsToCheck[i3], "audio", preferManagedMediaSource)) { CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i3]; return codecsToCheck[i3]; } } return lowerCaseCodec; } var AUDIO_CODEC_REGEXP = /flac|opus/i; function getCodecCompatibleName(codec, preferManagedMediaSource = true) { return codec.replace(AUDIO_CODEC_REGEXP, (m2) => getCodecCompatibleNameLower(m2.toLowerCase(), preferManagedMediaSource)); } function pickMostCompleteCodecName(parsedCodec, levelCodec) { if (parsedCodec && parsedCodec !== "mp4a") { return parsedCodec; } return levelCodec ? levelCodec.split(",")[0] : levelCodec; } function convertAVC1ToAVCOTI(codec) { const codecs = codec.split(","); for (let i3 = 0; i3 < codecs.length; i3++) { const avcdata = codecs[i3].split("."); if (avcdata.length > 2) { let result = avcdata.shift() + "."; result += parseInt(avcdata.shift()).toString(16); result += ("000" + parseInt(avcdata.shift()).toString(16)).slice(-4); codecs[i3] = result; } } return codecs.join(","); } var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g; var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g; var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([ /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:,), group 1 => duration, group 2 => title /(?!#) *(\S[^\r\n]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten) /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y) /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec /#.*/.source // All other non-segment oriented tags will match with all groups empty ].join("|"), "g"); var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join("|")); var M3U8Parser = class _M3U8Parser { static findGroup(groups, mediaGroupId) { for (let i3 = 0; i3 < groups.length; i3++) { const group = groups[i3]; if (group.id === mediaGroupId) { return group; } } } static resolve(url, baseUrl) { return urlToolkitExports.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true }); } static isMediaPlaylist(str) { return IS_MEDIA_PLAYLIST.test(str); } static parseMasterPlaylist(string, baseurl) { const hasVariableRefs = hasVariableReferences(string); const parsed = { contentSteering: null, levels: [], playlistParsingError: null, sessionData: null, sessionKeys: null, startTimeOffset: null, variableList: null, hasVariableRefs }; const levelsWithKnownCodecs = []; MASTER_PLAYLIST_REGEX.lastIndex = 0; let result; while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) { if (result[1]) { var _level$unknownCodecs; const attrs = new AttrList(result[1]); { substituteVariablesInAttributes(parsed, attrs, ["CODECS", "SUPPLEMENTAL-CODECS", "ALLOWED-CPC", "PATHWAY-ID", "STABLE-VARIANT-ID", "AUDIO", "VIDEO", "SUBTITLES", "CLOSED-CAPTIONS", "NAME"]); } const uri = substituteVariables(parsed, result[2]); const level = { attrs, bitrate: attrs.decimalInteger("BANDWIDTH") || attrs.decimalInteger("AVERAGE-BANDWIDTH"), name: attrs.NAME, url: _M3U8Parser.resolve(uri, baseurl) }; const resolution = attrs.decimalResolution("RESOLUTION"); if (resolution) { level.width = resolution.width; level.height = resolution.height; } setCodecs(attrs.CODECS, level); if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) { levelsWithKnownCodecs.push(level); } parsed.levels.push(level); } else if (result[3]) { const tag = result[3]; const attributes = result[4]; switch (tag) { case "SESSION-DATA": { const sessionAttrs = new AttrList(attributes); { substituteVariablesInAttributes(parsed, sessionAttrs, ["DATA-ID", "LANGUAGE", "VALUE", "URI"]); } const dataId = sessionAttrs["DATA-ID"]; if (dataId) { if (parsed.sessionData === null) { parsed.sessionData = {}; } parsed.sessionData[dataId] = sessionAttrs; } break; } case "SESSION-KEY": { const sessionKey = parseKey(attributes, baseurl, parsed); if (sessionKey.encrypted && sessionKey.isSupported()) { if (parsed.sessionKeys === null) { parsed.sessionKeys = []; } parsed.sessionKeys.push(sessionKey); } else { logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`); } break; } case "DEFINE": { { const variableAttributes = new AttrList(attributes); substituteVariablesInAttributes(parsed, variableAttributes, ["NAME", "VALUE", "QUERYPARAM"]); addVariableDefinition(parsed, variableAttributes, baseurl); } break; } case "CONTENT-STEERING": { const contentSteeringAttributes = new AttrList(attributes); { substituteVariablesInAttributes(parsed, contentSteeringAttributes, ["SERVER-URI", "PATHWAY-ID"]); } parsed.contentSteering = { uri: _M3U8Parser.resolve(contentSteeringAttributes["SERVER-URI"], baseurl), pathwayId: contentSteeringAttributes["PATHWAY-ID"] || "." }; break; } case "START": { parsed.startTimeOffset = parseStartTimeOffset(attributes); break; } } } } const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length; parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels; if (parsed.levels.length === 0) { parsed.playlistParsingError = new Error("no levels found in manifest"); } return parsed; } static parseMasterPlaylistMedia(string, baseurl, parsed) { let result; const results = {}; const levels = parsed.levels; const groupsByType = { AUDIO: levels.map((level) => ({ id: level.attrs.AUDIO, audioCodec: level.audioCodec })), SUBTITLES: levels.map((level) => ({ id: level.attrs.SUBTITLES, textCodec: level.textCodec })), "CLOSED-CAPTIONS": [] }; let id = 0; MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0; while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) { const attrs = new AttrList(result[1]); const type = attrs.TYPE; if (type) { const groups = groupsByType[type]; const medias = results[type] || []; results[type] = medias; { substituteVariablesInAttributes(parsed, attrs, ["URI", "GROUP-ID", "LANGUAGE", "ASSOC-LANGUAGE", "STABLE-RENDITION-ID", "NAME", "INSTREAM-ID", "CHARACTERISTICS", "CHANNELS"]); } const lang = attrs.LANGUAGE; const assocLang = attrs["ASSOC-LANGUAGE"]; const channels = attrs.CHANNELS; const characteristics = attrs.CHARACTERISTICS; const instreamId = attrs["INSTREAM-ID"]; const media = { attrs, bitrate: 0, id: id++, groupId: attrs["GROUP-ID"] || "", name: attrs.NAME || lang || "", type, default: attrs.bool("DEFAULT"), autoselect: attrs.bool("AUTOSELECT"), forced: attrs.bool("FORCED"), lang, url: attrs.URI ? _M3U8Parser.resolve(attrs.URI, baseurl) : "" }; if (assocLang) { media.assocLang = assocLang; } if (channels) { media.channels = channels; } if (characteristics) { media.characteristics = characteristics; } if (instreamId) { media.instreamId = instreamId; } if (groups != null && groups.length) { const groupCodec = _M3U8Parser.findGroup(groups, media.groupId) || groups[0]; assignCodec(media, groupCodec, "audioCodec"); assignCodec(media, groupCodec, "textCodec"); } medias.push(media); } } return results; } static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) { const level = new LevelDetails(baseurl); const fragments = level.fragments; let currentInitSegment = null; let currentSN = 0; let currentPart = 0; let totalduration = 0; let discontinuityCounter = 0; let prevFrag = null; let frag = new Fragment4(type, baseurl); let result; let i3; let levelkeys; let firstPdtIndex = -1; let createNextFrag = false; let nextByteRange = null; LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0; level.m3u8 = string; level.hasVariableRefs = hasVariableReferences(string); while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) { if (createNextFrag) { createNextFrag = false; frag = new Fragment4(type, baseurl); frag.start = totalduration; frag.sn = currentSN; frag.cc = discontinuityCounter; frag.level = id; if (currentInitSegment) { frag.initSegment = currentInitSegment; frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime; currentInitSegment.rawProgramDateTime = null; if (nextByteRange) { frag.setByteRange(nextByteRange); nextByteRange = null; } } } const duration = result[1]; if (duration) { frag.duration = parseFloat(duration); const title = (" " + result[2]).slice(1); frag.title = title || null; frag.tagList.push(title ? ["INF", duration, title] : ["INF", duration]); } else if (result[3]) { if (isFiniteNumber(frag.duration)) { frag.start = totalduration; if (levelkeys) { setFragLevelKeys(frag, levelkeys, level); } frag.sn = currentSN; frag.level = id; frag.cc = discontinuityCounter; fragments.push(frag); const uri = (" " + result[3]).slice(1); frag.relurl = substituteVariables(level, uri); assignProgramDateTime(frag, prevFrag); prevFrag = frag; totalduration += frag.duration; currentSN++; currentPart = 0; createNextFrag = true; } } else if (result[4]) { const data = (" " + result[4]).slice(1); if (prevFrag) { frag.setByteRange(data, prevFrag); } else { frag.setByteRange(data); } } else if (result[5]) { frag.rawProgramDateTime = (" " + result[5]).slice(1); frag.tagList.push(["PROGRAM-DATE-TIME", frag.rawProgramDateTime]); if (firstPdtIndex === -1) { firstPdtIndex = fragments.length; } } else { result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW); if (!result) { logger.warn("No matches on slow regex match for level playlist!"); continue; } for (i3 = 1; i3 < result.length; i3++) { if (typeof result[i3] !== "undefined") { break; } } const tag = (" " + result[i3]).slice(1); const value1 = (" " + result[i3 + 1]).slice(1); const value2 = result[i3 + 2] ? (" " + result[i3 + 2]).slice(1) : ""; switch (tag) { case "PLAYLIST-TYPE": level.type = value1.toUpperCase(); break; case "MEDIA-SEQUENCE": currentSN = level.startSN = parseInt(value1); break; case "SKIP": { const skipAttrs = new AttrList(value1); { substituteVariablesInAttributes(level, skipAttrs, ["RECENTLY-REMOVED-DATERANGES"]); } const skippedSegments = skipAttrs.decimalInteger("SKIPPED-SEGMENTS"); if (isFiniteNumber(skippedSegments)) { level.skippedSegments = skippedSegments; for (let _i2 = skippedSegments; _i2--; ) { fragments.unshift(null); } currentSN += skippedSegments; } const recentlyRemovedDateranges = skipAttrs.enumeratedString("RECENTLY-REMOVED-DATERANGES"); if (recentlyRemovedDateranges) { level.recentlyRemovedDateranges = recentlyRemovedDateranges.split(" "); } break; } case "TARGETDURATION": level.targetduration = Math.max(parseInt(value1), 1); break; case "VERSION": level.version = parseInt(value1); break; case "INDEPENDENT-SEGMENTS": case "EXTM3U": break; case "ENDLIST": level.live = false; break; case "#": if (value1 || value2) { frag.tagList.push(value2 ? [value1, value2] : [value1]); } break; case "DISCONTINUITY": discontinuityCounter++; frag.tagList.push(["DIS"]); break; case "GAP": frag.gap = true; frag.tagList.push([tag]); break; case "BITRATE": frag.tagList.push([tag, value1]); break; case "DATERANGE": { const dateRangeAttr = new AttrList(value1); { substituteVariablesInAttributes(level, dateRangeAttr, ["ID", "CLASS", "START-DATE", "END-DATE", "SCTE35-CMD", "SCTE35-OUT", "SCTE35-IN"]); substituteVariablesInAttributes(level, dateRangeAttr, dateRangeAttr.clientAttrs); } const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]); if (dateRange.isValid || level.skippedSegments) { level.dateRanges[dateRange.id] = dateRange; } else { logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`); } frag.tagList.push(["EXT-X-DATERANGE", value1]); break; } case "DEFINE": { { const variableAttributes = new AttrList(value1); substituteVariablesInAttributes(level, variableAttributes, ["NAME", "VALUE", "IMPORT", "QUERYPARAM"]); if ("IMPORT" in variableAttributes) { importVariableDefinition(level, variableAttributes, multivariantVariableList); } else { addVariableDefinition(level, variableAttributes, baseurl); } } break; } case "DISCONTINUITY-SEQUENCE": discontinuityCounter = parseInt(value1); break; case "KEY": { const levelKey = parseKey(value1, baseurl, level); if (levelKey.isSupported()) { if (levelKey.method === "NONE") { levelkeys = void 0; break; } if (!levelkeys) { levelkeys = {}; } if (levelkeys[levelKey.keyFormat]) { levelkeys = _extends2({}, levelkeys); } levelkeys[levelKey.keyFormat] = levelKey; } else { logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`); } break; } case "START": level.startTimeOffset = parseStartTimeOffset(value1); break; case "MAP": { const mapAttrs = new AttrList(value1); { substituteVariablesInAttributes(level, mapAttrs, ["BYTERANGE", "URI"]); } if (frag.duration) { const init = new Fragment4(type, baseurl); setInitSegment(init, mapAttrs, id, levelkeys); currentInitSegment = init; frag.initSegment = currentInitSegment; if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) { frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime; } } else { const end = frag.byteRangeEndOffset; if (end) { const start = frag.byteRangeStartOffset; nextByteRange = `${end - start}@${start}`; } else { nextByteRange = null; } setInitSegment(frag, mapAttrs, id, levelkeys); currentInitSegment = frag; createNextFrag = true; } break; } case "SERVER-CONTROL": { const serverControlAttrs = new AttrList(value1); level.canBlockReload = serverControlAttrs.bool("CAN-BLOCK-RELOAD"); level.canSkipUntil = serverControlAttrs.optionalFloat("CAN-SKIP-UNTIL", 0); level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool("CAN-SKIP-DATERANGES"); level.partHoldBack = serverControlAttrs.optionalFloat("PART-HOLD-BACK", 0); level.holdBack = serverControlAttrs.optionalFloat("HOLD-BACK", 0); break; } case "PART-INF": { const partInfAttrs = new AttrList(value1); level.partTarget = partInfAttrs.decimalFloatingPoint("PART-TARGET"); break; } case "PART": { let partList = level.partList; if (!partList) { partList = level.partList = []; } const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : void 0; const index2 = currentPart++; const partAttrs = new AttrList(value1); { substituteVariablesInAttributes(level, partAttrs, ["BYTERANGE", "URI"]); } const part = new Part(partAttrs, frag, baseurl, index2, previousFragmentPart); partList.push(part); frag.duration += part.duration; break; } case "PRELOAD-HINT": { const preloadHintAttrs = new AttrList(value1); { substituteVariablesInAttributes(level, preloadHintAttrs, ["URI"]); } level.preloadHint = preloadHintAttrs; break; } case "RENDITION-REPORT": { const renditionReportAttrs = new AttrList(value1); { substituteVariablesInAttributes(level, renditionReportAttrs, ["URI"]); } level.renditionReports = level.renditionReports || []; level.renditionReports.push(renditionReportAttrs); break; } default: logger.warn(`line parsed but not handled: ${result}`); break; } } } if (prevFrag && !prevFrag.relurl) { fragments.pop(); totalduration -= prevFrag.duration; if (level.partList) { level.fragmentHint = prevFrag; } } else if (level.partList) { assignProgramDateTime(frag, prevFrag); frag.cc = discontinuityCounter; level.fragmentHint = frag; if (levelkeys) { setFragLevelKeys(frag, levelkeys, level); } } const fragmentLength = fragments.length; const firstFragment = fragments[0]; const lastFragment = fragments[fragmentLength - 1]; totalduration += level.skippedSegments * level.targetduration; if (totalduration > 0 && fragmentLength && lastFragment) { level.averagetargetduration = totalduration / fragmentLength; const lastSn = lastFragment.sn; level.endSN = lastSn !== "initSegment" ? lastSn : 0; if (!level.live) { lastFragment.endList = true; } if (firstFragment) { level.startCC = firstFragment.cc; } } else { level.endSN = 0; level.startCC = 0; } if (level.fragmentHint) { totalduration += level.fragmentHint.duration; } level.totalduration = totalduration; level.endCC = discontinuityCounter; if (firstPdtIndex > 0) { backfillProgramDateTimes(fragments, firstPdtIndex); } return level; } }; function parseKey(keyTagAttributes, baseurl, parsed) { var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT; const keyAttrs = new AttrList(keyTagAttributes); { substituteVariablesInAttributes(parsed, keyAttrs, ["KEYFORMAT", "KEYFORMATVERSIONS", "URI", "IV", "URI"]); } const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : ""; const decrypturi = keyAttrs.URI; const decryptiv = keyAttrs.hexadecimalInteger("IV"); const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS; const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : "identity"; if (decrypturi && keyAttrs.IV && !decryptiv) { logger.error(`Invalid IV: ${keyAttrs.IV}`); } const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : ""; const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : "1").split("/").map(Number).filter(Number.isFinite); return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv); } function parseStartTimeOffset(startAttributes) { const startAttrs = new AttrList(startAttributes); const startTimeOffset = startAttrs.decimalFloatingPoint("TIME-OFFSET"); if (isFiniteNumber(startTimeOffset)) { return startTimeOffset; } return null; } function setCodecs(codecsAttributeValue, level) { let codecs = (codecsAttributeValue || "").split(/[ ,]+/).filter((c3) => c3); ["video", "audio", "text"].forEach((type) => { const filtered = codecs.filter((codec) => isCodecType(codec, type)); if (filtered.length) { level[`${type}Codec`] = filtered.join(","); codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1); } }); level.unknownCodecs = codecs; } function assignCodec(media, groupItem, codecProperty) { const codecValue = groupItem[codecProperty]; if (codecValue) { media[codecProperty] = codecValue; } } function backfillProgramDateTimes(fragments, firstPdtIndex) { let fragPrev = fragments[firstPdtIndex]; for (let i3 = firstPdtIndex; i3--; ) { const frag = fragments[i3]; if (!frag) { return; } frag.programDateTime = fragPrev.programDateTime - frag.duration * 1e3; fragPrev = frag; } } function assignProgramDateTime(frag, prevFrag) { if (frag.rawProgramDateTime) { frag.programDateTime = Date.parse(frag.rawProgramDateTime); } else if (prevFrag != null && prevFrag.programDateTime) { frag.programDateTime = prevFrag.endProgramDateTime; } if (!isFiniteNumber(frag.programDateTime)) { frag.programDateTime = null; frag.rawProgramDateTime = null; } } function setInitSegment(frag, mapAttrs, id, levelkeys) { frag.relurl = mapAttrs.URI; if (mapAttrs.BYTERANGE) { frag.setByteRange(mapAttrs.BYTERANGE); } frag.level = id; frag.sn = "initSegment"; if (levelkeys) { frag.levelkeys = levelkeys; } frag.initSegment = null; } function setFragLevelKeys(frag, levelkeys, level) { frag.levelkeys = levelkeys; const { encryptedFragments } = level; if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some((format2) => levelkeys[format2].isCommonEncryption)) { encryptedFragments.push(frag); } } var PlaylistContextType = { MANIFEST: "manifest", LEVEL: "level", AUDIO_TRACK: "audioTrack", SUBTITLE_TRACK: "subtitleTrack" }; var PlaylistLevelType = { MAIN: "main", AUDIO: "audio", SUBTITLE: "subtitle" }; function mapContextToLevelType(context) { const { type } = context; switch (type) { case PlaylistContextType.AUDIO_TRACK: return PlaylistLevelType.AUDIO; case PlaylistContextType.SUBTITLE_TRACK: return PlaylistLevelType.SUBTITLE; default: return PlaylistLevelType.MAIN; } } function getResponseUrl(response, context) { let url = response.url; if (url === void 0 || url.indexOf("data:") === 0) { url = context.url; } return url; } var PlaylistLoader = class { constructor(hls) { this.hls = void 0; this.loaders = /* @__PURE__ */ Object.create(null); this.variableList = null; this.hls = hls; this.registerListeners(); } startLoad(startPosition) { } stopLoad() { this.destroyInternalLoaders(); } registerListeners() { const { hls } = this; hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this); hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this); } unregisterListeners() { const { hls } = this; hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this); hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this); } /** * Returns defaults or configured loader-type overloads (pLoader and loader config params) */ createInternalLoader(context) { const config = this.hls.config; const PLoader = config.pLoader; const Loader2 = config.loader; const InternalLoader = PLoader || Loader2; const loader = new InternalLoader(config); this.loaders[context.type] = loader; return loader; } getInternalLoader(context) { return this.loaders[context.type]; } resetInternalLoader(contextType) { if (this.loaders[contextType]) { delete this.loaders[contextType]; } } /** * Call `destroy` on all internal loader instances mapped (one per context type) */ destroyInternalLoaders() { for (const contextType in this.loaders) { const loader = this.loaders[contextType]; if (loader) { loader.destroy(); } this.resetInternalLoader(contextType); } } destroy() { this.variableList = null; this.unregisterListeners(); this.destroyInternalLoaders(); } onManifestLoading(event, data) { const { url } = data; this.variableList = null; this.load({ id: null, level: 0, responseType: "text", type: PlaylistContextType.MANIFEST, url, deliveryDirectives: null }); } onLevelLoading(event, data) { const { id, level, pathwayId, url, deliveryDirectives } = data; this.load({ id, level, pathwayId, responseType: "text", type: PlaylistContextType.LEVEL, url, deliveryDirectives }); } onAudioTrackLoading(event, data) { const { id, groupId, url, deliveryDirectives } = data; this.load({ id, groupId, level: null, responseType: "text", type: PlaylistContextType.AUDIO_TRACK, url, deliveryDirectives }); } onSubtitleTrackLoading(event, data) { const { id, groupId, url, deliveryDirectives } = data; this.load({ id, groupId, level: null, responseType: "text", type: PlaylistContextType.SUBTITLE_TRACK, url, deliveryDirectives }); } load(context) { var _context$deliveryDire; const config = this.hls.config; let loader = this.getInternalLoader(context); if (loader) { const loaderContext = loader.context; if (loaderContext && loaderContext.url === context.url && loaderContext.level === context.level) { logger.trace("[playlist-loader]: playlist request ongoing"); return; } logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`); loader.abort(); } let loadPolicy; if (context.type === PlaylistContextType.MANIFEST) { loadPolicy = config.manifestLoadPolicy.default; } else { loadPolicy = _extends2({}, config.playlistLoadPolicy.default, { timeoutRetry: null, errorRetry: null }); } loader = this.createInternalLoader(context); if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) { let levelDetails; if (context.type === PlaylistContextType.LEVEL && context.level !== null) { levelDetails = this.hls.levels[context.level].details; } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) { levelDetails = this.hls.audioTracks[context.id].details; } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) { levelDetails = this.hls.subtitleTracks[context.id].details; } if (levelDetails) { const partTarget = levelDetails.partTarget; const targetDuration = levelDetails.targetduration; if (partTarget && targetDuration) { const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1e3; loadPolicy = _extends2({}, loadPolicy, { maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs), maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs) }); } } } const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {}; const loaderConfig = { loadPolicy, timeout: loadPolicy.maxLoadTimeMs, maxRetry: legacyRetryCompatibility.maxNumRetry || 0, retryDelay: legacyRetryCompatibility.retryDelayMs || 0, maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0 }; const loaderCallbacks = { onSuccess: (response, stats, context2, networkDetails) => { const loader2 = this.getInternalLoader(context2); this.resetInternalLoader(context2.type); const string = response.data; if (string.indexOf("#EXTM3U") !== 0) { this.handleManifestParsingError(response, context2, new Error("no EXTM3U delimiter"), networkDetails || null, stats); return; } stats.parsing.start = performance.now(); if (M3U8Parser.isMediaPlaylist(string)) { this.handleTrackOrLevelPlaylist(response, stats, context2, networkDetails || null, loader2); } else { this.handleMasterPlaylist(response, stats, context2, networkDetails); } }, onError: (response, context2, networkDetails, stats) => { this.handleNetworkError(context2, networkDetails, false, response, stats); }, onTimeout: (stats, context2, networkDetails) => { this.handleNetworkError(context2, networkDetails, true, void 0, stats); } }; loader.load(context, loaderConfig, loaderCallbacks); } handleMasterPlaylist(response, stats, context, networkDetails) { const hls = this.hls; const string = response.data; const url = getResponseUrl(response, context); const parsedResult = M3U8Parser.parseMasterPlaylist(string, url); if (parsedResult.playlistParsingError) { this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats); return; } const { contentSteering, levels, sessionData, sessionKeys, startTimeOffset, variableList } = parsedResult; this.variableList = variableList; const { AUDIO: audioTracks = [], SUBTITLES: subtitles, "CLOSED-CAPTIONS": captions } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult); if (audioTracks.length) { const embeddedAudioFound = audioTracks.some((audioTrack) => !audioTrack.url); if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) { logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"); audioTracks.unshift({ type: "main", name: "main", groupId: "main", default: false, autoselect: false, forced: false, id: -1, attrs: new AttrList({}), bitrate: 0, url: "" }); } } hls.trigger(Events.MANIFEST_LOADED, { levels, audioTracks, subtitles, captions, contentSteering, url, stats, networkDetails, sessionData, sessionKeys, startTimeOffset, variableList }); } handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) { const hls = this.hls; const { id, level, type } = context; const url = getResponseUrl(response, context); const levelUrlId = 0; const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0; const levelType = mapContextToLevelType(context); const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId, this.variableList); if (type === PlaylistContextType.MANIFEST) { const singleLevel = { attrs: new AttrList({}), bitrate: 0, details: levelDetails, name: "", url }; hls.trigger(Events.MANIFEST_LOADED, { levels: [singleLevel], audioTracks: [], url, stats, networkDetails, sessionData: null, sessionKeys: null, contentSteering: null, startTimeOffset: null, variableList: null }); } stats.parsing.end = performance.now(); context.levelDetails = levelDetails; this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader); } handleManifestParsingError(response, context, error, networkDetails, stats) { this.hls.trigger(Events.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: context.type === PlaylistContextType.MANIFEST, url: response.url, err: error, error, reason: error.message, response, context, networkDetails, stats }); } handleNetworkError(context, networkDetails, timeout = false, response, stats) { let message = `A network ${timeout ? "timeout" : "error" + (response ? " (status " + response.code + ")" : "")} occurred while loading ${context.type}`; if (context.type === PlaylistContextType.LEVEL) { message += `: ${context.level} id: ${context.id}`; } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) { message += ` id: ${context.id} group-id: "${context.groupId}"`; } const error = new Error(message); logger.warn(`[playlist-loader]: ${message}`); let details = ErrorDetails.UNKNOWN; let fatal = false; const loader = this.getInternalLoader(context); switch (context.type) { case PlaylistContextType.MANIFEST: details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR; fatal = true; break; case PlaylistContextType.LEVEL: details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR; fatal = false; break; case PlaylistContextType.AUDIO_TRACK: details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR; fatal = false; break; case PlaylistContextType.SUBTITLE_TRACK: details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR; fatal = false; break; } if (loader) { this.resetInternalLoader(context.type); } const errorData = { type: ErrorTypes.NETWORK_ERROR, details, fatal, url: context.url, loader, context, error, networkDetails, stats }; if (response) { const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url; errorData.response = _objectSpread23({ url, data: void 0 }, response); } this.hls.trigger(Events.ERROR, errorData); } handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) { const hls = this.hls; const { type, level, id, groupId, deliveryDirectives } = context; const url = getResponseUrl(response, context); const parent = mapContextToLevelType(context); const levelIndex = typeof context.level === "number" && parent === PlaylistLevelType.MAIN ? level : void 0; if (!levelDetails.fragments.length) { const _error = new Error("No Segments found in Playlist"); hls.trigger(Events.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.LEVEL_EMPTY_ERROR, fatal: false, url, error: _error, reason: _error.message, response, context, level: levelIndex, parent, networkDetails, stats }); return; } if (!levelDetails.targetduration) { levelDetails.playlistParsingError = new Error("Missing Target Duration"); } const error = levelDetails.playlistParsingError; if (error) { hls.trigger(Events.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.LEVEL_PARSING_ERROR, fatal: false, url, error, reason: error.message, response, context, level: levelIndex, parent, networkDetails, stats }); return; } if (levelDetails.live && loader) { if (loader.getCacheAge) { levelDetails.ageHeader = loader.getCacheAge() || 0; } if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) { levelDetails.ageHeader = 0; } } switch (type) { case PlaylistContextType.MANIFEST: case PlaylistContextType.LEVEL: hls.trigger(Events.LEVEL_LOADED, { details: levelDetails, level: levelIndex || 0, id: id || 0, stats, networkDetails, deliveryDirectives }); break; case PlaylistContextType.AUDIO_TRACK: hls.trigger(Events.AUDIO_TRACK_LOADED, { details: levelDetails, id: id || 0, groupId: groupId || "", stats, networkDetails, deliveryDirectives }); break; case PlaylistContextType.SUBTITLE_TRACK: hls.trigger(Events.SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id || 0, groupId: groupId || "", stats, networkDetails, deliveryDirectives }); break; } } }; function sendAddTrackEvent(track, videoEl) { let event; try { event = new Event("addtrack"); } catch (err) { event = document.createEvent("Event"); event.initEvent("addtrack", false, false); } event.track = track; videoEl.dispatchEvent(event); } function addCueToTrack(track, cue) { const mode = track.mode; if (mode === "disabled") { track.mode = "hidden"; } if (track.cues && !track.cues.getCueById(cue.id)) { try { track.addCue(cue); if (!track.cues.getCueById(cue.id)) { throw new Error(`addCue is failed for: ${cue}`); } } catch (err) { logger.debug(`[texttrack-utils]: ${err}`); try { const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text); textTrackCue.id = cue.id; track.addCue(textTrackCue); } catch (err2) { logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`); } } } if (mode === "disabled") { track.mode = mode; } } function clearCurrentCues(track) { const mode = track.mode; if (mode === "disabled") { track.mode = "hidden"; } if (track.cues) { for (let i3 = track.cues.length; i3--; ) { track.removeCue(track.cues[i3]); } } if (mode === "disabled") { track.mode = mode; } } function removeCuesInRange(track, start, end, predicate) { const mode = track.mode; if (mode === "disabled") { track.mode = "hidden"; } if (track.cues && track.cues.length > 0) { const cues = getCuesInRange(track.cues, start, end); for (let i3 = 0; i3 < cues.length; i3++) { if (!predicate || predicate(cues[i3])) { track.removeCue(cues[i3]); } } } if (mode === "disabled") { track.mode = mode; } } function getFirstCueIndexAfterTime(cues, time) { if (time < cues[0].startTime) { return 0; } const len = cues.length - 1; if (time > cues[len].endTime) { return -1; } let left = 0; let right = len; while (left <= right) { const mid = Math.floor((right + left) / 2); if (time < cues[mid].startTime) { right = mid - 1; } else if (time > cues[mid].startTime && left < len) { left = mid + 1; } else { return mid; } } return cues[left].startTime - time < time - cues[right].startTime ? left : right; } function getCuesInRange(cues, start, end) { const cuesFound = []; const firstCueInRange = getFirstCueIndexAfterTime(cues, start); if (firstCueInRange > -1) { for (let i3 = firstCueInRange, len = cues.length; i3 < len; i3++) { const cue = cues[i3]; if (cue.startTime >= start && cue.endTime <= end) { cuesFound.push(cue); } else if (cue.startTime > end) { return cuesFound; } } } return cuesFound; } function filterSubtitleTracks(textTrackList) { const tracks = []; for (let i3 = 0; i3 < textTrackList.length; i3++) { const track = textTrackList[i3]; if ((track.kind === "subtitles" || track.kind === "captions") && track.label) { tracks.push(textTrackList[i3]); } } return tracks; } var MetadataSchema = { audioId3: "org.id3", dateRange: "com.apple.quicktime.HLS", emsg: "https://aomedia.org/emsg/ID3" }; var MIN_CUE_DURATION = 0.25; function getCueClass() { if (typeof self === "undefined") return void 0; return self.VTTCue || self.TextTrackCue; } function createCueWithDataFields(Cue, startTime, endTime, data, type) { let cue = new Cue(startTime, endTime, ""); try { cue.value = data; if (type) { cue.type = type; } } catch (e) { cue = new Cue(startTime, endTime, JSON.stringify(type ? _objectSpread23({ type }, data) : data)); } return cue; } var MAX_CUE_ENDTIME = (() => { const Cue = getCueClass(); try { Cue && new Cue(0, Number.POSITIVE_INFINITY, ""); } catch (e) { return Number.MAX_VALUE; } return Number.POSITIVE_INFINITY; })(); function dateRangeDateToTimelineSeconds(date, offset) { return date.getTime() / 1e3 - offset; } function hexToArrayBuffer(str) { return Uint8Array.from(str.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer; } var ID3TrackController = class { constructor(hls) { this.hls = void 0; this.id3Track = null; this.media = null; this.dateRangeCuesAppended = {}; this.hls = hls; this._registerListeners(); } destroy() { this._unregisterListeners(); this.id3Track = null; this.media = null; this.dateRangeCuesAppended = {}; this.hls = null; } _registerListeners() { const { hls } = this; hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this); hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this); } _unregisterListeners() { const { hls } = this; hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this); hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this); } // Add ID3 metatadata text track. onMediaAttached(event, data) { this.media = data.media; } onMediaDetaching() { if (!this.id3Track) { return; } clearCurrentCues(this.id3Track); this.id3Track = null; this.media = null; this.dateRangeCuesAppended = {}; } onManifestLoading() { this.dateRangeCuesAppended = {}; } createTrack(media) { const track = this.getID3Track(media.textTracks); track.mode = "hidden"; return track; } getID3Track(textTracks) { if (!this.media) { return; } for (let i3 = 0; i3 < textTracks.length; i3++) { const textTrack = textTracks[i3]; if (textTrack.kind === "metadata" && textTrack.label === "id3") { sendAddTrackEvent(textTrack, this.media); return textTrack; } } return this.media.addTextTrack("metadata", "id3"); } onFragParsingMetadata(event, data) { if (!this.media) { return; } const { hls: { config: { enableEmsgMetadataCues, enableID3MetadataCues } } } = this; if (!enableEmsgMetadataCues && !enableID3MetadataCues) { return; } const { samples } = data; if (!this.id3Track) { this.id3Track = this.createTrack(this.media); } const Cue = getCueClass(); if (!Cue) { return; } for (let i3 = 0; i3 < samples.length; i3++) { const type = samples[i3].type; if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) { continue; } const frames = getID3Frames(samples[i3].data); if (frames) { const startTime = samples[i3].pts; let endTime = startTime + samples[i3].duration; if (endTime > MAX_CUE_ENDTIME) { endTime = MAX_CUE_ENDTIME; } const timeDiff = endTime - startTime; if (timeDiff <= 0) { endTime = startTime + MIN_CUE_DURATION; } for (let j3 = 0; j3 < frames.length; j3++) { const frame = frames[j3]; if (!isTimeStampFrame(frame)) { this.updateId3CueEnds(startTime, type); const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type); if (cue) { this.id3Track.addCue(cue); } } } } } } updateId3CueEnds(startTime, type) { var _this$id3Track; const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues; if (cues) { for (let i3 = cues.length; i3--; ) { const cue = cues[i3]; if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) { cue.endTime = startTime; } } } } onBufferFlushing(event, { startOffset, endOffset, type }) { const { id3Track, hls } = this; if (!hls) { return; } const { config: { enableEmsgMetadataCues, enableID3MetadataCues } } = hls; if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) { let predicate; if (type === "audio") { predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues; } else if (type === "video") { predicate = (cue) => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues; } else { predicate = (cue) => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues; } removeCuesInRange(id3Track, startOffset, endOffset, predicate); } } onLevelUpdated(event, { details }) { if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) { return; } const { dateRangeCuesAppended, id3Track } = this; const { dateRanges } = details; const ids = Object.keys(dateRanges); if (id3Track) { const idsToRemove = Object.keys(dateRangeCuesAppended).filter((id) => !ids.includes(id)); for (let i3 = idsToRemove.length; i3--; ) { const id = idsToRemove[i3]; Object.keys(dateRangeCuesAppended[id].cues).forEach((key) => { id3Track.removeCue(dateRangeCuesAppended[id].cues[key]); }); delete dateRangeCuesAppended[id]; } } const lastFragment = details.fragments[details.fragments.length - 1]; if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) { return; } if (!this.id3Track) { this.id3Track = this.createTrack(this.media); } const dateTimeOffset = lastFragment.programDateTime / 1e3 - lastFragment.start; const Cue = getCueClass(); for (let i3 = 0; i3 < ids.length; i3++) { const id = ids[i3]; const dateRange = dateRanges[id]; const startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset); const appendedDateRangeCues = dateRangeCuesAppended[id]; const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {}; let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false; let endTime = MAX_CUE_ENDTIME; const endDate = dateRange.endDate; if (endDate) { endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset); durationKnown = true; } else if (dateRange.endOnNext && !durationKnown) { const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id2) => { if (id2 !== dateRange.id) { const otherDateRange = dateRanges[id2]; if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) { return otherDateRange; } } return candidateDateRange; }, null); if (nextDateRangeWithSameClass) { endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset); durationKnown = true; } } const attributes = Object.keys(dateRange.attr); for (let j3 = 0; j3 < attributes.length; j3++) { const key = attributes[j3]; if (!isDateRangeCueAttribute(key)) { continue; } const cue = cues[key]; if (cue) { if (durationKnown && !appendedDateRangeCues.durationKnown) { cue.endTime = endTime; } } else if (Cue) { let data = dateRange.attr[key]; if (isSCTE35Attribute(key)) { data = hexToArrayBuffer(data); } const _cue = createCueWithDataFields(Cue, startTime, endTime, { key, data }, MetadataSchema.dateRange); if (_cue) { _cue.id = id; this.id3Track.addCue(_cue); cues[key] = _cue; } } } dateRangeCuesAppended[id] = { cues, dateRange, durationKnown }; } } }; var LatencyController = class { constructor(hls) { this.hls = void 0; this.config = void 0; this.media = null; this.levelDetails = null; this.currentTime = 0; this.stallCount = 0; this._latency = null; this.timeupdateHandler = () => this.timeupdate(); this.hls = hls; this.config = hls.config; this.registerListeners(); } get latency() { return this._latency || 0; } get maxLatency() { const { config, levelDetails } = this; if (config.liveMaxLatencyDuration !== void 0) { return config.liveMaxLatencyDuration; } return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0; } get targetLatency() { const { levelDetails } = this; if (levelDetails === null) { return null; } const { holdBack, partHoldBack, targetduration } = levelDetails; const { liveSyncDuration, liveSyncDurationCount, lowLatencyMode } = this.config; const userConfig = this.hls.userConfig; let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack; if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) { targetLatency = liveSyncDuration !== void 0 ? liveSyncDuration : liveSyncDurationCount * targetduration; } const maxLiveSyncOnStallIncrease = targetduration; const liveSyncOnStallIncrease = 1; return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease); } get liveSyncPosition() { const liveEdge = this.estimateLiveEdge(); const targetLatency = this.targetLatency; const levelDetails = this.levelDetails; if (liveEdge === null || targetLatency === null || levelDetails === null) { return null; } const edge = levelDetails.edge; const syncPosition = liveEdge - targetLatency - this.edgeStalled; const min = edge - levelDetails.totalduration; const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration); return Math.min(Math.max(min, syncPosition), max); } get drift() { const { levelDetails } = this; if (levelDetails === null) { return 1; } return levelDetails.drift; } get edgeStalled() { const { levelDetails } = this; if (levelDetails === null) { return 0; } const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3; return Math.max(levelDetails.age - maxLevelUpdateAge, 0); } get forwardBufferLength() { const { media, levelDetails } = this; if (!media || !levelDetails) { return 0; } const bufferedRanges = media.buffered.length; return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime; } destroy() { this.unregisterListeners(); this.onMediaDetaching(); this.levelDetails = null; this.hls = this.timeupdateHandler = null; } registerListeners() { this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this); this.hls.on(Events.ERROR, this.onError, this); } unregisterListeners() { this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this); this.hls.off(Events.ERROR, this.onError, this); } onMediaAttached(event, data) { this.media = data.media; this.media.addEventListener("timeupdate", this.timeupdateHandler); } onMediaDetaching() { if (this.media) { this.media.removeEventListener("timeupdate", this.timeupdateHandler); this.media = null; } } onManifestLoading() { this.levelDetails = null; this._latency = null; this.stallCount = 0; } onLevelUpdated(event, { details }) { this.levelDetails = details; if (details.advanced) { this.timeupdate(); } if (!details.live && this.media) { this.media.removeEventListener("timeupdate", this.timeupdateHandler); } } onError(event, data) { var _this$levelDetails; if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) { return; } this.stallCount++; if ((_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) { logger.warn("[playback-rate-controller]: Stall detected, adjusting target latency"); } } timeupdate() { const { media, levelDetails } = this; if (!media || !levelDetails) { return; } this.currentTime = media.currentTime; const latency = this.computeLatency(); if (latency === null) { return; } this._latency = latency; const { lowLatencyMode, maxLiveSyncPlaybackRate } = this.config; if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) { return; } const targetLatency = this.targetLatency; if (targetLatency === null) { return; } const distanceFromTarget = latency - targetLatency; const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration); const inLiveRange = distanceFromTarget < liveMinLatencyDuration; if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) { const max = Math.min(2, Math.max(1, maxLiveSyncPlaybackRate)); const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20; media.playbackRate = Math.min(max, Math.max(1, rate)); } else if (media.playbackRate !== 1 && media.playbackRate !== 0) { media.playbackRate = 1; } } estimateLiveEdge() { const { levelDetails } = this; if (levelDetails === null) { return null; } return levelDetails.edge + levelDetails.age; } computeLatency() { const liveEdge = this.estimateLiveEdge(); if (liveEdge === null) { return null; } return liveEdge - this.currentTime; } }; var HdcpLevels = ["NONE", "TYPE-0", "TYPE-1", null]; function isHdcpLevel(value) { return HdcpLevels.indexOf(value) > -1; } var VideoRangeValues = ["SDR", "PQ", "HLG"]; function isVideoRange(value) { return !!value && VideoRangeValues.indexOf(value) > -1; } var HlsSkip = { No: "", Yes: "YES", v2: "v2" }; function getSkipValue(details) { const { canSkipUntil, canSkipDateRanges, age } = details; const playlistRecentEnough = age < canSkipUntil / 2; if (canSkipUntil && playlistRecentEnough) { if (canSkipDateRanges) { return HlsSkip.v2; } return HlsSkip.Yes; } return HlsSkip.No; } var HlsUrlParameters = class { constructor(msn, part, skip) { this.msn = void 0; this.part = void 0; this.skip = void 0; this.msn = msn; this.part = part; this.skip = skip; } addDirectives(uri) { const url = new self.URL(uri); if (this.msn !== void 0) { url.searchParams.set("_HLS_msn", this.msn.toString()); } if (this.part !== void 0) { url.searchParams.set("_HLS_part", this.part.toString()); } if (this.skip) { url.searchParams.set("_HLS_skip", this.skip); } return url.href; } }; var Level = class { constructor(data) { this._attrs = void 0; this.audioCodec = void 0; this.bitrate = void 0; this.codecSet = void 0; this.url = void 0; this.frameRate = void 0; this.height = void 0; this.id = void 0; this.name = void 0; this.videoCodec = void 0; this.width = void 0; this.details = void 0; this.fragmentError = 0; this.loadError = 0; this.loaded = void 0; this.realBitrate = 0; this.supportedPromise = void 0; this.supportedResult = void 0; this._avgBitrate = 0; this._audioGroups = void 0; this._subtitleGroups = void 0; this._urlId = 0; this.url = [data.url]; this._attrs = [data.attrs]; this.bitrate = data.bitrate; if (data.details) { this.details = data.details; } this.id = data.id || 0; this.name = data.name; this.width = data.width || 0; this.height = data.height || 0; this.frameRate = data.attrs.optionalFloat("FRAME-RATE", 0); this._avgBitrate = data.attrs.decimalInteger("AVERAGE-BANDWIDTH"); this.audioCodec = data.audioCodec; this.videoCodec = data.videoCodec; this.codecSet = [data.videoCodec, data.audioCodec].filter((c3) => !!c3).map((s) => s.substring(0, 4)).join(","); this.addGroupId("audio", data.attrs.AUDIO); this.addGroupId("text", data.attrs.SUBTITLES); } get maxBitrate() { return Math.max(this.realBitrate, this.bitrate); } get averageBitrate() { return this._avgBitrate || this.realBitrate || this.bitrate; } get attrs() { return this._attrs[0]; } get codecs() { return this.attrs.CODECS || ""; } get pathwayId() { return this.attrs["PATHWAY-ID"] || "."; } get videoRange() { return this.attrs["VIDEO-RANGE"] || "SDR"; } get score() { return this.attrs.optionalFloat("SCORE", 0); } get uri() { return this.url[0] || ""; } hasAudioGroup(groupId) { return hasGroup(this._audioGroups, groupId); } hasSubtitleGroup(groupId) { return hasGroup(this._subtitleGroups, groupId); } get audioGroups() { return this._audioGroups; } get subtitleGroups() { return this._subtitleGroups; } addGroupId(type, groupId) { if (!groupId) { return; } if (type === "audio") { let audioGroups = this._audioGroups; if (!audioGroups) { audioGroups = this._audioGroups = []; } if (audioGroups.indexOf(groupId) === -1) { audioGroups.push(groupId); } } else if (type === "text") { let subtitleGroups = this._subtitleGroups; if (!subtitleGroups) { subtitleGroups = this._subtitleGroups = []; } if (subtitleGroups.indexOf(groupId) === -1) { subtitleGroups.push(groupId); } } } // Deprecated methods (retained for backwards compatibility) get urlId() { return 0; } set urlId(value) { } get audioGroupIds() { return this.audioGroups ? [this.audioGroupId] : void 0; } get textGroupIds() { return this.subtitleGroups ? [this.textGroupId] : void 0; } get audioGroupId() { var _this$audioGroups; return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0]; } get textGroupId() { var _this$subtitleGroups; return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0]; } addFallback() { } }; function hasGroup(groups, groupId) { if (!groupId || !groups) { return false; } return groups.indexOf(groupId) !== -1; } function updateFromToPTS(fragFrom, fragTo) { const fragToPTS = fragTo.startPTS; if (isFiniteNumber(fragToPTS)) { let duration = 0; let frag; if (fragTo.sn > fragFrom.sn) { duration = fragToPTS - fragFrom.start; frag = fragFrom; } else { duration = fragFrom.start - fragToPTS; frag = fragTo; } if (frag.duration !== duration) { frag.duration = duration; } } else if (fragTo.sn > fragFrom.sn) { const contiguous = fragFrom.cc === fragTo.cc; if (contiguous && fragFrom.minEndPTS) { fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start); } else { fragTo.start = fragFrom.start + fragFrom.duration; } } else { fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0); } } function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) { const parsedMediaDuration = endPTS - startPTS; if (parsedMediaDuration <= 0) { logger.warn("Fragment should have a positive duration", frag); endPTS = startPTS + frag.duration; endDTS = startDTS + frag.duration; } let maxStartPTS = startPTS; let minEndPTS = endPTS; const fragStartPts = frag.startPTS; const fragEndPts = frag.endPTS; if (isFiniteNumber(fragStartPts)) { const deltaPTS = Math.abs(fragStartPts - startPTS); if (!isFiniteNumber(frag.deltaPTS)) { frag.deltaPTS = deltaPTS; } else { frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS); } maxStartPTS = Math.max(startPTS, fragStartPts); startPTS = Math.min(startPTS, fragStartPts); startDTS = Math.min(startDTS, frag.startDTS); minEndPTS = Math.min(endPTS, fragEndPts); endPTS = Math.max(endPTS, fragEndPts); endDTS = Math.max(endDTS, frag.endDTS); } const drift = startPTS - frag.start; if (frag.start !== 0) { frag.start = startPTS; } frag.duration = endPTS - frag.start; frag.startPTS = startPTS; frag.maxStartPTS = maxStartPTS; frag.startDTS = startDTS; frag.endPTS = endPTS; frag.minEndPTS = minEndPTS; frag.endDTS = endDTS; const sn = frag.sn; if (!details || sn < details.startSN || sn > details.endSN) { return 0; } let i3; const fragIdx = sn - details.startSN; const fragments = details.fragments; fragments[fragIdx] = frag; for (i3 = fragIdx; i3 > 0; i3--) { updateFromToPTS(fragments[i3], fragments[i3 - 1]); } for (i3 = fragIdx; i3 < fragments.length - 1; i3++) { updateFromToPTS(fragments[i3], fragments[i3 + 1]); } if (details.fragmentHint) { updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint); } details.PTSKnown = details.alignedSliding = true; return drift; } function mergeDetails(oldDetails, newDetails) { let currentInitSegment = null; const oldFragments = oldDetails.fragments; for (let i3 = oldFragments.length - 1; i3 >= 0; i3--) { const oldInit = oldFragments[i3].initSegment; if (oldInit) { currentInitSegment = oldInit; break; } } if (oldDetails.fragmentHint) { delete oldDetails.fragmentHint.endPTS; } let PTSFrag; mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments2) => { if (newDetails.skippedSegments) { if (newFrag.cc !== oldFrag.cc) { const ccOffset = oldFrag.cc - newFrag.cc; for (let i3 = newFragIndex; i3 < newFragments2.length; i3++) { newFragments2[i3].cc += ccOffset; } } } if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) { newFrag.start = newFrag.startPTS = oldFrag.startPTS; newFrag.startDTS = oldFrag.startDTS; newFrag.maxStartPTS = oldFrag.maxStartPTS; newFrag.endPTS = oldFrag.endPTS; newFrag.endDTS = oldFrag.endDTS; newFrag.minEndPTS = oldFrag.minEndPTS; newFrag.duration = oldFrag.endPTS - oldFrag.startPTS; if (newFrag.duration) { PTSFrag = newFrag; } newDetails.PTSKnown = newDetails.alignedSliding = true; } newFrag.elementaryStreams = oldFrag.elementaryStreams; newFrag.loader = oldFrag.loader; newFrag.stats = oldFrag.stats; if (oldFrag.initSegment) { newFrag.initSegment = oldFrag.initSegment; currentInitSegment = oldFrag.initSegment; } }); const newFragments = newDetails.fragments; if (currentInitSegment) { const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments; fragmentsToCheck.forEach((frag) => { var _currentInitSegment; if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) { frag.initSegment = currentInitSegment; } }); } if (newDetails.skippedSegments) { newDetails.deltaUpdateFailed = newFragments.some((frag) => !frag); if (newDetails.deltaUpdateFailed) { logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist"); for (let i3 = newDetails.skippedSegments; i3--; ) { newFragments.shift(); } newDetails.startSN = newFragments[0].sn; } else { if (newDetails.canSkipDateRanges) { newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges); } } newDetails.startCC = newDetails.fragments[0].cc; newDetails.endCC = newFragments[newFragments.length - 1].cc; } mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => { newPart.elementaryStreams = oldPart.elementaryStreams; newPart.stats = oldPart.stats; }); if (PTSFrag) { updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS); } else { adjustSliding(oldDetails, newDetails); } if (newFragments.length) { newDetails.totalduration = newDetails.edge - newFragments[0].start; } newDetails.driftStartTime = oldDetails.driftStartTime; newDetails.driftStart = oldDetails.driftStart; const advancedDateTime = newDetails.advancedDateTime; if (newDetails.advanced && advancedDateTime) { const edge = newDetails.edge; if (!newDetails.driftStart) { newDetails.driftStartTime = advancedDateTime; newDetails.driftStart = edge; } newDetails.driftEndTime = advancedDateTime; newDetails.driftEnd = edge; } else { newDetails.driftEndTime = oldDetails.driftEndTime; newDetails.driftEnd = oldDetails.driftEnd; newDetails.advancedDateTime = oldDetails.advancedDateTime; } } function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) { const dateRanges = _extends2({}, oldDateRanges); if (recentlyRemovedDateranges) { recentlyRemovedDateranges.forEach((id) => { delete dateRanges[id]; }); } Object.keys(deltaDateRanges).forEach((id) => { const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]); if (dateRange.isValid) { dateRanges[id] = dateRange; } else { logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(deltaDateRanges[id].attr)}"`); } }); return dateRanges; } function mapPartIntersection(oldParts, newParts, intersectionFn) { if (oldParts && newParts) { let delta = 0; for (let i3 = 0, len = oldParts.length; i3 <= len; i3++) { const oldPart = oldParts[i3]; const newPart = newParts[i3 + delta]; if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) { intersectionFn(oldPart, newPart); } else { delta--; } } } } function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) { const skippedSegments = newDetails.skippedSegments; const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN; const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN; const delta = newDetails.startSN - oldDetails.startSN; const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments; const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments; for (let i3 = start; i3 <= end; i3++) { const oldFrag = oldFrags[delta + i3]; let newFrag = newFrags[i3]; if (skippedSegments && !newFrag && i3 < skippedSegments) { newFrag = newDetails.fragments[i3] = oldFrag; } if (oldFrag && newFrag) { intersectionFn(oldFrag, newFrag, i3, newFrags); } } } function adjustSliding(oldDetails, newDetails) { const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN; const oldFragments = oldDetails.fragments; if (delta < 0 || delta >= oldFragments.length) { return; } addSliding(newDetails, oldFragments[delta].start); } function addSliding(details, start) { if (start) { const fragments = details.fragments; for (let i3 = details.skippedSegments; i3 < fragments.length; i3++) { fragments[i3].start += start; } if (details.fragmentHint) { details.fragmentHint.start += start; } } } function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) { let reloadInterval = 1e3 * newDetails.targetduration; if (newDetails.updated) { const fragments = newDetails.fragments; const liveEdgeMaxTargetDurations = 4; if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) { const lastSegmentDuration = fragments[fragments.length - 1].duration * 1e3; if (lastSegmentDuration < reloadInterval) { reloadInterval = lastSegmentDuration; } } } else { reloadInterval /= 2; } return Math.round(reloadInterval); } function getFragmentWithSN(level, sn, fragCurrent) { if (!(level != null && level.details)) { return null; } const levelDetails = level.details; let fragment = levelDetails.fragments[sn - levelDetails.startSN]; if (fragment) { return fragment; } fragment = levelDetails.fragmentHint; if (fragment && fragment.sn === sn) { return fragment; } if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) { return fragCurrent; } return null; } function getPartWith(level, sn, partIndex) { var _level$details; if (!(level != null && level.details)) { return null; } return findPart((_level$details = level.details) == null ? void 0 : _level$details.partList, sn, partIndex); } function findPart(partList, sn, partIndex) { if (partList) { for (let i3 = partList.length; i3--; ) { const part = partList[i3]; if (part.index === partIndex && part.fragment.sn === sn) { return part; } } } return null; } function reassignFragmentLevelIndexes(levels) { levels.forEach((level, index2) => { const { details } = level; if (details != null && details.fragments) { details.fragments.forEach((fragment) => { fragment.level = index2; }); } }); } function isTimeoutError(error) { switch (error.details) { case ErrorDetails.FRAG_LOAD_TIMEOUT: case ErrorDetails.KEY_LOAD_TIMEOUT: case ErrorDetails.LEVEL_LOAD_TIMEOUT: case ErrorDetails.MANIFEST_LOAD_TIMEOUT: return true; } return false; } function getRetryConfig(loadPolicy, error) { const isTimeout = isTimeoutError(error); return loadPolicy.default[`${isTimeout ? "timeout" : "error"}Retry`]; } function getRetryDelay(retryConfig, retryCount) { const backoffFactor = retryConfig.backoff === "linear" ? 1 : Math.pow(2, retryCount); return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs); } function getLoaderConfigWithoutReties(loderConfig) { return _objectSpread23(_objectSpread23({}, loderConfig), { errorRetry: null, timeoutRetry: null }); } function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) { if (!retryConfig) { return false; } const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code; const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout); return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry; } function retryForHttpStatus(httpStatus) { return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499); } var BinarySearch = { /** * Searches for an item in an array which matches a certain condition. * This requires the condition to only match one item in the array, * and for the array to be ordered. * * @param list The array to search. * @param comparisonFn * Called and provided a candidate item as the first argument. * Should return: * > -1 if the item should be located at a lower index than the provided item. * > 1 if the item should be located at a higher index than the provided item. * > 0 if the item is the item you're looking for. * * @returns the object if found, otherwise returns null */ search: function(list, comparisonFn) { let minIndex = 0; let maxIndex = list.length - 1; let currentIndex = null; let currentElement = null; while (minIndex <= maxIndex) { currentIndex = (minIndex + maxIndex) / 2 | 0; currentElement = list[currentIndex]; const comparisonResult = comparisonFn(currentElement); if (comparisonResult > 0) { minIndex = currentIndex + 1; } else if (comparisonResult < 0) { maxIndex = currentIndex - 1; } else { return currentElement; } } return null; } }; function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) { if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) { return null; } const startPDT = fragments[0].programDateTime; if (PDTValue < (startPDT || 0)) { return null; } const endPDT = fragments[fragments.length - 1].endProgramDateTime; if (PDTValue >= (endPDT || 0)) { return null; } maxFragLookUpTolerance = maxFragLookUpTolerance || 0; for (let seg = 0; seg < fragments.length; ++seg) { const frag = fragments[seg]; if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) { return frag; } } return null; } function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 5e-3) { let fragNext = null; if (fragPrevious) { fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null; const bufferEdgeError = fragPrevious.endDTS - bufferEnd; if (bufferEdgeError > 0 && bufferEdgeError < 15e-7) { bufferEnd += 15e-7; } } else if (bufferEnd === 0 && fragments[0].start === 0) { fragNext = fragments[0]; } if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) { return fragNext; } const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)); if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) { return foundFragment; } return fragNext; } function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) { if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) { const firstDuration = fragPrevious.tagList.reduce((duration, tag) => { if (tag[0] === "INF") { duration += parseFloat(tag[1]); } return duration; }, nextFragLookupTolerance); return fragNext.start <= firstDuration; } return false; } function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) { if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) { return 0; } const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)); if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { return 1; } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { return -1; } return 0; } function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) { const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1e3; const endProgramDateTime = candidate.endProgramDateTime || 0; return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd; } function findFragWithCC(fragments, cc) { return BinarySearch.search(fragments, (candidate) => { if (candidate.cc < cc) { return 1; } else if (candidate.cc > cc) { return -1; } else { return 0; } }); } var NetworkErrorAction = { DoNothing: 0, SendEndCallback: 1, SendAlternateToPenaltyBox: 2, RemoveAlternatePermanently: 3, InsertDiscontinuity: 4, RetryRequest: 5 }; var ErrorActionFlags = { None: 0, MoveAllAlternatesMatchingHost: 1, MoveAllAlternatesMatchingHDCP: 2, SwitchToSDR: 4 }; var ErrorController = class { constructor(hls) { this.hls = void 0; this.playlistError = 0; this.penalizedRenditions = {}; this.log = void 0; this.warn = void 0; this.error = void 0; this.hls = hls; this.log = logger.log.bind(logger, `[info]:`); this.warn = logger.warn.bind(logger, `[warning]:`); this.error = logger.error.bind(logger, `[error]:`); this.registerListeners(); } registerListeners() { const hls = this.hls; hls.on(Events.ERROR, this.onError, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this); } unregisterListeners() { const hls = this.hls; if (!hls) { return; } hls.off(Events.ERROR, this.onError, this); hls.off(Events.ERROR, this.onErrorOut, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this); } destroy() { this.unregisterListeners(); this.hls = null; this.penalizedRenditions = {}; } startLoad(startPosition) { } stopLoad() { this.playlistError = 0; } getVariantLevelIndex(frag) { return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel; } onManifestLoading() { this.playlistError = 0; this.penalizedRenditions = {}; } onLevelUpdated() { this.playlistError = 0; } onError(event, data) { var _data$frag, _data$level; if (data.fatal) { return; } const hls = this.hls; const context = data.context; switch (data.details) { case ErrorDetails.FRAG_LOAD_ERROR: case ErrorDetails.FRAG_LOAD_TIMEOUT: case ErrorDetails.KEY_LOAD_ERROR: case ErrorDetails.KEY_LOAD_TIMEOUT: data.errorAction = this.getFragRetryOrSwitchAction(data); return; case ErrorDetails.FRAG_PARSING_ERROR: if ((_data$frag = data.frag) != null && _data$frag.gap) { data.errorAction = { action: NetworkErrorAction.DoNothing, flags: ErrorActionFlags.None }; return; } case ErrorDetails.FRAG_GAP: case ErrorDetails.FRAG_DECRYPT_ERROR: { data.errorAction = this.getFragRetryOrSwitchAction(data); data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox; return; } case ErrorDetails.LEVEL_EMPTY_ERROR: case ErrorDetails.LEVEL_PARSING_ERROR: { var _data$context, _data$context$levelDe; const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel; if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) { data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex); } else { data.levelRetry = false; data.errorAction = this.getLevelSwitchAction(data, levelIndex); } } return; case ErrorDetails.LEVEL_LOAD_ERROR: case ErrorDetails.LEVEL_LOAD_TIMEOUT: if (typeof (context == null ? void 0 : context.level) === "number") { data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level); } return; case ErrorDetails.AUDIO_TRACK_LOAD_ERROR: case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT: case ErrorDetails.SUBTITLE_LOAD_ERROR: case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT: if (context) { const level = hls.levels[hls.loadLevel]; if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) { data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel); data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox; data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost; return; } } return; case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED: { const level = hls.levels[hls.loadLevel]; const restrictedHdcpLevel = level == null ? void 0 : level.attrs["HDCP-LEVEL"]; if (restrictedHdcpLevel) { data.errorAction = { action: NetworkErrorAction.SendAlternateToPenaltyBox, flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP, hdcpLevel: restrictedHdcpLevel }; } else { this.keySystemError(data); } } return; case ErrorDetails.BUFFER_ADD_CODEC_ERROR: case ErrorDetails.REMUX_ALLOC_ERROR: case ErrorDetails.BUFFER_APPEND_ERROR: data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel); return; case ErrorDetails.INTERNAL_EXCEPTION: case ErrorDetails.BUFFER_APPENDING_ERROR: case ErrorDetails.BUFFER_FULL_ERROR: case ErrorDetails.LEVEL_SWITCH_ERROR: case ErrorDetails.BUFFER_STALLED_ERROR: case ErrorDetails.BUFFER_SEEK_OVER_HOLE: case ErrorDetails.BUFFER_NUDGE_ON_STALL: data.errorAction = { action: NetworkErrorAction.DoNothing, flags: ErrorActionFlags.None }; return; } if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) { this.keySystemError(data); } } keySystemError(data) { const levelIndex = this.getVariantLevelIndex(data.frag); data.levelRetry = false; data.errorAction = this.getLevelSwitchAction(data, levelIndex); } getPlaylistRetryOrSwitchAction(data, levelIndex) { const hls = this.hls; const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data); const retryCount = this.playlistError++; const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response); if (retry) { return { action: NetworkErrorAction.RetryRequest, flags: ErrorActionFlags.None, retryConfig, retryCount }; } const errorAction = this.getLevelSwitchAction(data, levelIndex); if (retryConfig) { errorAction.retryConfig = retryConfig; errorAction.retryCount = retryCount; } return errorAction; } getFragRetryOrSwitchAction(data) { const hls = this.hls; const variantLevelIndex = this.getVariantLevelIndex(data.frag); const level = hls.levels[variantLevelIndex]; const { fragLoadPolicy, keyLoadPolicy } = hls.config; const retryConfig = getRetryConfig(data.details.startsWith("key") ? keyLoadPolicy : fragLoadPolicy, data); const fragmentErrors = hls.levels.reduce((acc, level2) => acc + level2.fragmentError, 0); if (level) { if (data.details !== ErrorDetails.FRAG_GAP) { level.fragmentError++; } const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response); if (retry) { return { action: NetworkErrorAction.RetryRequest, flags: ErrorActionFlags.None, retryConfig, retryCount: fragmentErrors }; } } const errorAction = this.getLevelSwitchAction(data, variantLevelIndex); if (retryConfig) { errorAction.retryConfig = retryConfig; errorAction.retryCount = fragmentErrors; } return errorAction; } getLevelSwitchAction(data, levelIndex) { const hls = this.hls; if (levelIndex === null || levelIndex === void 0) { levelIndex = hls.loadLevel; } const level = this.hls.levels[levelIndex]; if (level) { var _data$frag2, _data$context2; const errorDetails = data.details; level.loadError++; if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) { level.fragmentError++; } let nextLevel = -1; const { levels, loadLevel, minAutoLevel, maxAutoLevel } = hls; if (!hls.autoLevelEnabled) { hls.loadLevel = -1; } const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type; const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === "audio" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR); const findAudioCodecAlternate = isAudioCodecError && levels.some(({ audioCodec }) => level.audioCodec !== audioCodec); const isVideoCodecError = data.sourceBufferName === "video" && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR); const findVideoCodecAlternate = isVideoCodecError && levels.some(({ codecSet, audioCodec }) => level.codecSet !== codecSet && level.audioCodec === audioCodec); const { type: playlistErrorType, groupId: playlistErrorGroupId } = (_data$context2 = data.context) != null ? _data$context2 : {}; for (let i3 = levels.length; i3--; ) { const candidate = (i3 + loadLevel) % levels.length; if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) { var _level$audioGroups, _level$subtitleGroups; const levelCandidate = levels[candidate]; if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) { const levelDetails = levels[candidate].details; if (levelDetails) { const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start); if (fragCandidate != null && fragCandidate.gap) { continue; } } } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) { continue; } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some((groupId) => levelCandidate.hasAudioGroup(groupId)) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some((groupId) => levelCandidate.hasSubtitleGroup(groupId)) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) { continue; } nextLevel = candidate; break; } } if (nextLevel > -1 && hls.loadLevel !== nextLevel) { data.levelRetry = true; this.playlistError = 0; return { action: NetworkErrorAction.SendAlternateToPenaltyBox, flags: ErrorActionFlags.None, nextAutoLevel: nextLevel }; } } return { action: NetworkErrorAction.SendAlternateToPenaltyBox, flags: ErrorActionFlags.MoveAllAlternatesMatchingHost }; } onErrorOut(event, data) { var _data$errorAction; switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) { case NetworkErrorAction.DoNothing: break; case NetworkErrorAction.SendAlternateToPenaltyBox: this.sendAlternateToPenaltyBox(data); if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) { data.fatal = true; } else if (/MediaSource readyState: ended/.test(data.error.message)) { this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`); this.hls.recoverMediaError(); } break; case NetworkErrorAction.RetryRequest: break; } if (data.fatal) { this.hls.stopLoad(); return; } } sendAlternateToPenaltyBox(data) { const hls = this.hls; const errorAction = data.errorAction; if (!errorAction) { return; } const { flags, hdcpLevel, nextAutoLevel } = errorAction; switch (flags) { case ErrorActionFlags.None: this.switchLevel(data, nextAutoLevel); break; case ErrorActionFlags.MoveAllAlternatesMatchingHDCP: if (hdcpLevel) { hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1]; errorAction.resolved = true; } this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`); break; } if (!errorAction.resolved) { this.switchLevel(data, nextAutoLevel); } } switchLevel(data, levelIndex) { if (levelIndex !== void 0 && data.errorAction) { this.warn(`switching to level ${levelIndex} after ${data.details}`); this.hls.nextAutoLevel = levelIndex; data.errorAction.resolved = true; this.hls.nextLoadLevel = this.hls.nextAutoLevel; } } }; var BasePlaylistController = class { constructor(hls, logPrefix) { this.hls = void 0; this.timer = -1; this.requestScheduled = -1; this.canLoad = false; this.log = void 0; this.warn = void 0; this.log = logger.log.bind(logger, `${logPrefix}:`); this.warn = logger.warn.bind(logger, `${logPrefix}:`); this.hls = hls; } destroy() { this.clearTimer(); this.hls = this.log = this.warn = null; } clearTimer() { if (this.timer !== -1) { self.clearTimeout(this.timer); this.timer = -1; } } startLoad() { this.canLoad = true; this.requestScheduled = -1; this.loadPlaylist(); } stopLoad() { this.canLoad = false; this.clearTimer(); } switchParams(playlistUri, previous, current) { const renditionReports = previous == null ? void 0 : previous.renditionReports; if (renditionReports) { let foundIndex = -1; for (let i3 = 0; i3 < renditionReports.length; i3++) { const attr = renditionReports[i3]; let uri; try { uri = new self.URL(attr.URI, previous.url).href; } catch (error) { logger.warn(`Could not construct new URL for Rendition Report: ${error}`); uri = attr.URI || ""; } if (uri === playlistUri) { foundIndex = i3; break; } else if (uri === playlistUri.substring(0, uri.length)) { foundIndex = i3; } } if (foundIndex !== -1) { const attr = renditionReports[foundIndex]; const msn = parseInt(attr["LAST-MSN"]) || (previous == null ? void 0 : previous.lastPartSn); let part = parseInt(attr["LAST-PART"]) || (previous == null ? void 0 : previous.lastPartIndex); if (this.hls.config.lowLatencyMode) { const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration); if (part >= 0 && currentGoal > previous.partTarget) { part += 1; } } const skip = current && getSkipValue(current); return new HlsUrlParameters(msn, part >= 0 ? part : void 0, skip); } } } loadPlaylist(hlsUrlParameters) { if (this.requestScheduled === -1) { this.requestScheduled = self.performance.now(); } } shouldLoadPlaylist(playlist) { return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live); } shouldReloadPlaylist(playlist) { return this.timer === -1 && this.requestScheduled === -1 && this.shouldLoadPlaylist(playlist); } playlistLoaded(index2, data, previousDetails) { const { details, stats } = data; const now2 = self.performance.now(); const elapsed = stats.loading.first ? Math.max(0, now2 - stats.loading.first) : 0; details.advancedDateTime = Date.now() - elapsed; if (details.live || previousDetails != null && previousDetails.live) { details.reloaded(previousDetails); if (previousDetails) { this.log(`live playlist ${index2} ${details.advanced ? "REFRESHED " + details.lastPartSn + "-" + details.lastPartIndex : details.updated ? "UPDATED" : "MISSED"}`); } if (previousDetails && details.fragments.length > 0) { mergeDetails(previousDetails, details); } if (!this.canLoad || !details.live) { return; } let deliveryDirectives; let msn = void 0; let part = void 0; if (details.canBlockReload && details.endSN && details.advanced) { const lowLatencyMode = this.hls.config.lowLatencyMode; const lastPartSn = details.lastPartSn; const endSn = details.endSN; const lastPartIndex = details.lastPartIndex; const hasParts = lastPartIndex !== -1; const lastPart = lastPartSn === endSn; const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex; if (hasParts) { msn = lastPart ? endSn + 1 : lastPartSn; part = lastPart ? nextSnStartIndex : lastPartIndex + 1; } else { msn = endSn + 1; } const lastAdvanced = details.age; const cdnAge = lastAdvanced + details.ageHeader; let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5); if (currentGoal > 0) { if (previousDetails && currentGoal > previousDetails.tuneInGoal) { this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`); currentGoal = 0; } else { const segments = Math.floor(currentGoal / details.targetduration); msn += segments; if (part !== void 0) { const parts = Math.round(currentGoal % details.targetduration / details.partTarget); part += parts; } this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`); } details.tuneInGoal = currentGoal; } deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part); if (lowLatencyMode || !lastPart) { this.loadPlaylist(deliveryDirectives); return; } } else if (details.canBlockReload || details.canSkipUntil) { deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part); } const bufferInfo = this.hls.mainForwardBufferInfo; const position2 = bufferInfo ? bufferInfo.end - bufferInfo.len : 0; const distanceToLiveEdgeMs = (details.edge - position2) * 1e3; const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs); if (details.updated && now2 > this.requestScheduled + reloadInterval) { this.requestScheduled = stats.loading.start; } if (msn !== void 0 && details.canBlockReload) { this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1e3 || 1e3); } else if (this.requestScheduled === -1 || this.requestScheduled + reloadInterval < now2) { this.requestScheduled = now2; } else if (this.requestScheduled - now2 <= 0) { this.requestScheduled += reloadInterval; } let estimatedTimeUntilUpdate = this.requestScheduled - now2; estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate); this.log(`reload live playlist ${index2} in ${Math.round(estimatedTimeUntilUpdate)} ms`); this.timer = self.setTimeout(() => this.loadPlaylist(deliveryDirectives), estimatedTimeUntilUpdate); } else { this.clearTimer(); } } getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) { let skip = getSkipValue(details); if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) { msn = previousDeliveryDirectives.msn; part = previousDeliveryDirectives.part; skip = HlsSkip.No; } return new HlsUrlParameters(msn, part, skip); } checkRetry(errorEvent) { const errorDetails = errorEvent.details; const isTimeout = isTimeoutError(errorEvent); const errorAction = errorEvent.errorAction; const { action, retryCount = 0, retryConfig } = errorAction || {}; const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox); if (retry) { var _errorEvent$context; this.requestScheduled = -1; if (retryCount >= retryConfig.maxNumRetry) { return false; } if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) { this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`); this.loadPlaylist(); } else { const delay2 = getRetryDelay(retryConfig, retryCount); this.timer = self.setTimeout(() => this.loadPlaylist(), delay2); this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay2}ms`); } errorEvent.levelRetry = true; errorAction.resolved = true; } return retry; } }; var EWMA = class { // About half of the estimated value will be from the last |halfLife| samples by weight. constructor(halfLife, estimate = 0, weight = 0) { this.halfLife = void 0; this.alpha_ = void 0; this.estimate_ = void 0; this.totalWeight_ = void 0; this.halfLife = halfLife; this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0; this.estimate_ = estimate; this.totalWeight_ = weight; } sample(weight, value) { const adjAlpha = Math.pow(this.alpha_, weight); this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_; this.totalWeight_ += weight; } getTotalWeight() { return this.totalWeight_; } getEstimate() { if (this.alpha_) { const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); if (zeroFactor) { return this.estimate_ / zeroFactor; } } return this.estimate_; } }; var EwmaBandWidthEstimator = class { constructor(slow, fast, defaultEstimate, defaultTTFB = 100) { this.defaultEstimate_ = void 0; this.minWeight_ = void 0; this.minDelayMs_ = void 0; this.slow_ = void 0; this.fast_ = void 0; this.defaultTTFB_ = void 0; this.ttfb_ = void 0; this.defaultEstimate_ = defaultEstimate; this.minWeight_ = 1e-3; this.minDelayMs_ = 50; this.slow_ = new EWMA(slow); this.fast_ = new EWMA(fast); this.defaultTTFB_ = defaultTTFB; this.ttfb_ = new EWMA(slow); } update(slow, fast) { const { slow_, fast_, ttfb_ } = this; if (slow_.halfLife !== slow) { this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight()); } if (fast_.halfLife !== fast) { this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight()); } if (ttfb_.halfLife !== slow) { this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight()); } } sample(durationMs, numBytes) { durationMs = Math.max(durationMs, this.minDelayMs_); const numBits = 8 * numBytes; const durationS = durationMs / 1e3; const bandwidthInBps = numBits / durationS; this.fast_.sample(durationS, bandwidthInBps); this.slow_.sample(durationS, bandwidthInBps); } sampleTTFB(ttfb) { const seconds = ttfb / 1e3; const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2); this.ttfb_.sample(weight, Math.max(ttfb, 5)); } canEstimate() { return this.fast_.getTotalWeight() >= this.minWeight_; } getEstimate() { if (this.canEstimate()) { return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate()); } else { return this.defaultEstimate_; } } getEstimateTTFB() { if (this.ttfb_.getTotalWeight() >= this.minWeight_) { return this.ttfb_.getEstimate(); } else { return this.defaultTTFB_; } } destroy() { } }; var SUPPORTED_INFO_DEFAULT = { supported: true, configurations: [], decodingInfoResults: [{ supported: true, powerEfficient: true, smooth: true }] }; var SUPPORTED_INFO_CACHE = {}; function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) { const audioGroups = level.audioCodec ? level.audioGroups : null; const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec; const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels; const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2; let audioChannels = null; if (audioGroups != null && audioGroups.length) { try { if (audioGroups.length === 1 && audioGroups[0]) { audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels; } else { audioChannels = audioGroups.reduce((acc, groupId) => { if (groupId) { const audioTrackGroup = audioTracksByGroup.groups[groupId]; if (!audioTrackGroup) { throw new Error(`Audio track group ${groupId} not found`); } Object.keys(audioTrackGroup.channels).forEach((key) => { acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key]; }); } return acc; }, { 2: 0 }); } } catch (error) { return true; } } return level.videoCodec !== void 0 && (level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== "SDR" && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some((channels) => parseInt(channels) > maxChannels); } function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities) { const videoCodecs = level.videoCodec; const audioCodecs = level.audioCodec; if (!videoCodecs || !audioCodecs || !mediaCapabilities) { return Promise.resolve(SUPPORTED_INFO_DEFAULT); } const baseVideoConfiguration = { width: level.width, height: level.height, bitrate: Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate)), // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0. framerate: level.frameRate || 30 }; const videoRange = level.videoRange; if (videoRange !== "SDR") { baseVideoConfiguration.transferFunction = videoRange.toLowerCase(); } const configurations = videoCodecs.split(",").map((videoCodec) => ({ type: "media-source", video: _objectSpread23(_objectSpread23({}, baseVideoConfiguration), {}, { contentType: mimeTypeForCodec(videoCodec, "video") }) })); if (audioCodecs && level.audioGroups) { level.audioGroups.forEach((audioGroupId) => { var _audioTracksByGroup$g; if (!audioGroupId) { return; } (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks.forEach((audioTrack) => { if (audioTrack.groupId === audioGroupId) { const channels = audioTrack.channels || ""; const channelsNumber = parseFloat(channels); if (isFiniteNumber(channelsNumber) && channelsNumber > 2) { configurations.push.apply(configurations, audioCodecs.split(",").map((audioCodec) => ({ type: "media-source", audio: { contentType: mimeTypeForCodec(audioCodec, "audio"), channels: "" + channelsNumber // spatialRendering: // audioCodec === 'ec-3' && channels.indexOf('JOC'), } }))); } } }); }); } return Promise.all(configurations.map((configuration) => { const decodingInfoKey = getMediaDecodingInfoKey(configuration); return SUPPORTED_INFO_CACHE[decodingInfoKey] || (SUPPORTED_INFO_CACHE[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration)); })).then((decodingInfoResults) => ({ supported: !decodingInfoResults.some((info) => !info.supported), configurations, decodingInfoResults })).catch((error) => ({ supported: false, configurations, decodingInfoResults: [], error })); } function getMediaDecodingInfoKey(config) { const { audio, video } = config; const mediaConfig = video || audio; if (mediaConfig) { const codec = mediaConfig.contentType.split('"')[1]; if (video) { return `r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || "sd"}_${codec}_${Math.ceil(video.bitrate / 1e5)}`; } if (audio) { return `c${audio.channels}${audio.spatialRendering ? "s" : "n"}_${codec}`; } } return ""; } function isHdrSupported() { if (typeof matchMedia === "function") { const mediaQueryList = matchMedia("(dynamic-range: high)"); const badQuery = matchMedia("bad query"); if (mediaQueryList.media !== badQuery.media) { return mediaQueryList.matches === true; } } return false; } function getVideoSelectionOptions(currentVideoRange, videoPreference) { let preferHDR = false; let allowedVideoRanges = []; if (currentVideoRange) { preferHDR = currentVideoRange !== "SDR"; allowedVideoRanges = [currentVideoRange]; } if (videoPreference) { allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0); preferHDR = videoPreference.preferHDR !== void 0 ? videoPreference.preferHDR : isHdrSupported(); if (preferHDR) { allowedVideoRanges = allowedVideoRanges.filter((range) => range !== "SDR"); } else { allowedVideoRanges = ["SDR"]; } } return { preferHDR, allowedVideoRanges }; } function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) { const codecSets = Object.keys(codecTiers); const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels; const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec; const preferStereo = channelsPreference && parseInt(channelsPreference) === 2; let hasStereo = true; let hasCurrentVideoRange = false; let minHeight = Infinity; let minFramerate = Infinity; let minBitrate = Infinity; let selectedScore = 0; let videoRanges = []; const { preferHDR, allowedVideoRanges } = getVideoSelectionOptions(currentVideoRange, videoPreference); for (let i3 = codecSets.length; i3--; ) { const tier = codecTiers[codecSets[i3]]; hasStereo = tier.channels[2] > 0; minHeight = Math.min(minHeight, tier.minHeight); minFramerate = Math.min(minFramerate, tier.minFramerate); minBitrate = Math.min(minBitrate, tier.minBitrate); const matchingVideoRanges = allowedVideoRanges.filter((range) => tier.videoRanges[range] > 0); if (matchingVideoRanges.length > 0) { hasCurrentVideoRange = true; videoRanges = matchingVideoRanges; } } minHeight = isFiniteNumber(minHeight) ? minHeight : 0; minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0; const maxHeight = Math.max(1080, minHeight); const maxFramerate = Math.max(30, minFramerate); minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw; currentBw = Math.max(minBitrate, currentBw); if (!hasCurrentVideoRange) { currentVideoRange = void 0; videoRanges = []; } const codecSet = codecSets.reduce((selected, candidate) => { const candidateTier = codecTiers[candidate]; if (candidate === selected) { return selected; } if (candidateTier.minBitrate > currentBw) { logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`); return selected; } if (!candidateTier.hasDefaultAudio) { logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`); return selected; } if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) { logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`); return selected; } if (channelsPreference && !preferStereo) { if (!candidateTier.channels[channelsPreference]) { logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`); return selected; } } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels["2"] === 0) { logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`); return selected; } if (candidateTier.minHeight > maxHeight) { logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`); return selected; } if (candidateTier.minFramerate > maxFramerate) { logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`); return selected; } if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) { logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${JSON.stringify(videoRanges)} found`); return selected; } if (candidateTier.maxScore < selectedScore) { logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`); return selected; } if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) { return selected; } selectedScore = candidateTier.maxScore; return candidate; }, void 0); return { codecSet, videoRanges, preferHDR, minFramerate, minBitrate }; } function logStartCodecCandidateIgnored(codeSet, reason) { logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`); } function getAudioTracksByGroup(allAudioTracks) { return allAudioTracks.reduce((audioTracksByGroup, track) => { let trackGroup = audioTracksByGroup.groups[track.groupId]; if (!trackGroup) { trackGroup = audioTracksByGroup.groups[track.groupId] = { tracks: [], channels: { 2: 0 }, hasDefault: false, hasAutoSelect: false }; } trackGroup.tracks.push(track); const channelsKey = track.channels || "2"; trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1; trackGroup.hasDefault = trackGroup.hasDefault || track.default; trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect; if (trackGroup.hasDefault) { audioTracksByGroup.hasDefaultAudio = true; } if (trackGroup.hasAutoSelect) { audioTracksByGroup.hasAutoSelectAudio = true; } return audioTracksByGroup; }, { hasDefaultAudio: false, hasAutoSelectAudio: false, groups: {} }); } function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) { return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level) => { if (!level.codecSet) { return tiers; } const audioGroups = level.audioGroups; let tier = tiers[level.codecSet]; if (!tier) { tiers[level.codecSet] = tier = { minBitrate: Infinity, minHeight: Infinity, minFramerate: Infinity, maxScore: 0, videoRanges: { SDR: 0 }, channels: { "2": 0 }, hasDefaultAudio: !audioGroups, fragmentError: 0 }; } tier.minBitrate = Math.min(tier.minBitrate, level.bitrate); const lesserWidthOrHeight = Math.min(level.height, level.width); tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight); tier.minFramerate = Math.min(tier.minFramerate, level.frameRate); tier.maxScore = Math.max(tier.maxScore, level.score); tier.fragmentError += level.fragmentError; tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1; if (audioGroups) { audioGroups.forEach((audioGroupId) => { if (!audioGroupId) { return; } const audioGroup = audioTracksByGroup.groups[audioGroupId]; if (!audioGroup) { return; } tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio; Object.keys(audioGroup.channels).forEach((channels) => { tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels]; }); }); } return tiers; }, {}); } function findMatchingOption(option, tracks, matchPredicate) { if ("attrs" in option) { const index2 = tracks.indexOf(option); if (index2 !== -1) { return index2; } } for (let i3 = 0; i3 < tracks.length; i3++) { const track = tracks[i3]; if (matchesOption(option, track, matchPredicate)) { return i3; } } return -1; } function matchesOption(option, track, matchPredicate) { const { groupId, name, lang, assocLang, default: isDefault } = option; const forced = option.forced; return (groupId === void 0 || track.groupId === groupId) && (name === void 0 || track.name === name) && (lang === void 0 || track.lang === lang) && (lang === void 0 || track.assocLang === assocLang) && (isDefault === void 0 || track.default === isDefault) && (forced === void 0 || track.forced === forced) && (!("characteristics" in option) || characteristicsMatch(option.characteristics || "", track.characteristics)) && (matchPredicate === void 0 || matchPredicate(option, track)); } function characteristicsMatch(characteristicsA, characteristicsB = "") { const arrA = characteristicsA.split(","); const arrB = characteristicsB.split(","); return arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1); } function audioMatchPredicate(option, track) { const { audioCodec, channels } = option; return (audioCodec === void 0 || (track.audioCodec || "").substring(0, 4) === audioCodec.substring(0, 4)) && (channels === void 0 || channels === (track.channels || "2")); } function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) { const currentLevel = levels[searchIndex]; const variants = levels.reduce((variantMap, level, index2) => { const uri = level.uri; const renditions2 = variantMap[uri] || (variantMap[uri] = []); renditions2.push(index2); return variantMap; }, {}); const renditions = variants[currentLevel.uri]; if (renditions.length > 1) { searchIndex = Math.max.apply(Math, renditions); } const currentVideoRange = currentLevel.videoRange; const currentFrameRate = currentLevel.frameRate; const currentVideoCodec = currentLevel.codecSet.substring(0, 4); const matchingVideo = searchDownAndUpList(levels, searchIndex, (level) => { if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) { return false; } const audioGroups = level.audioGroups; const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1); return findMatchingOption(option, tracks, matchPredicate) > -1; }); if (matchingVideo > -1) { return matchingVideo; } return searchDownAndUpList(levels, searchIndex, (level) => { const audioGroups = level.audioGroups; const tracks = allAudioTracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1); return findMatchingOption(option, tracks, matchPredicate) > -1; }); } function searchDownAndUpList(arr, searchIndex, predicate) { for (let i3 = searchIndex; i3 > -1; i3--) { if (predicate(arr[i3])) { return i3; } } for (let i3 = searchIndex + 1; i3 < arr.length; i3++) { if (predicate(arr[i3])) { return i3; } } return -1; } var AbrController = class { constructor(_hls) { this.hls = void 0; this.lastLevelLoadSec = 0; this.lastLoadedFragLevel = -1; this.firstSelection = -1; this._nextAutoLevel = -1; this.nextAutoLevelKey = ""; this.audioTracksByGroup = null; this.codecTiers = null; this.timer = -1; this.fragCurrent = null; this.partCurrent = null; this.bitrateTestDelay = 0; this.bwEstimator = void 0; this._abandonRulesCheck = () => { const { fragCurrent: frag, partCurrent: part, hls } = this; const { autoLevelEnabled, media } = hls; if (!frag || !media) { return; } const now2 = performance.now(); const stats = part ? part.stats : frag.stats; const duration = part ? part.duration : frag.duration; const timeLoading = now2 - stats.loading.start; const minAutoLevel = hls.minAutoLevel; if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level <= minAutoLevel) { this.clearTimer(); this._nextAutoLevel = -1; return; } if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) { return; } const bufferInfo = hls.mainForwardBufferInfo; if (bufferInfo === null) { return; } const ttfbEstimate = this.bwEstimator.getEstimateTTFB(); const playbackRate = Math.abs(media.playbackRate); if (timeLoading <= Math.max(ttfbEstimate, 1e3 * (duration / (playbackRate * 2)))) { return; } const bufferStarvationDelay = bufferInfo.len / playbackRate; const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1; const loadedFirstByte = stats.loaded && ttfb > -1; const bwEstimate = this.getBwEstimate(); const levels = hls.levels; const level = levels[frag.level]; const expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.averageBitrate / 8)); let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading; if (timeStreaming < 1 && loadedFirstByte) { timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate); } const loadRate = loadedFirstByte ? stats.loaded * 1e3 / timeStreaming : 0; const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbEstimate / 1e3; if (fragLoadedDelay <= bufferStarvationDelay) { return; } const bwe = loadRate ? loadRate * 8 : bwEstimate; let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY; let nextLoadLevel; for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) { const levelNextBitrate = levels[nextLoadLevel].maxBitrate; fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbEstimate / 1e3, bwe, duration * levelNextBitrate, !levels[nextLoadLevel].details); if (fragLevelNextLoadedDelay < bufferStarvationDelay) { break; } } if (fragLevelNextLoadedDelay >= fragLoadedDelay) { return; } if (fragLevelNextLoadedDelay > duration * 10) { return; } hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel; if (loadedFirstByte) { this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded); } else { this.bwEstimator.sampleTTFB(timeLoading); } const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate; if (this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor > nextLoadLevelBitrate) { this.resetEstimator(nextLoadLevelBitrate); } this.clearTimer(); logger.warn(`[abr] Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${frag.level} is loading too slowly; Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s TTFB estimate: ${ttfb | 0} ms Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : "Unknown"} bps New BW estimate: ${this.getBwEstimate() | 0} bps Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`); hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, { frag, part, stats }); }; this.hls = _hls; this.bwEstimator = this.initEstimator(); this.registerListeners(); } resetEstimator(abrEwmaDefaultEstimate) { if (abrEwmaDefaultEstimate) { logger.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`); this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate; } this.firstSelection = -1; this.bwEstimator = this.initEstimator(); } initEstimator() { const config = this.hls.config; return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate); } registerListeners() { const { hls } = this; hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.FRAG_LOADING, this.onFragLoading, this); hls.on(Events.FRAG_LOADED, this.onFragLoaded, this); hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this); hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this); hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this); hls.on(Events.ERROR, this.onError, this); } unregisterListeners() { const { hls } = this; if (!hls) { return; } hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.FRAG_LOADING, this.onFragLoading, this); hls.off(Events.FRAG_LOADED, this.onFragLoaded, this); hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this); hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this); hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this); hls.off(Events.ERROR, this.onError, this); } destroy() { this.unregisterListeners(); this.clearTimer(); this.hls = this._abandonRulesCheck = null; this.fragCurrent = this.partCurrent = null; } onManifestLoading(event, data) { this.lastLoadedFragLevel = -1; this.firstSelection = -1; this.lastLevelLoadSec = 0; this.fragCurrent = this.partCurrent = null; this.onLevelsUpdated(); this.clearTimer(); } onLevelsUpdated() { if (this.lastLoadedFragLevel > -1 && this.fragCurrent) { this.lastLoadedFragLevel = this.fragCurrent.level; } this._nextAutoLevel = -1; this.onMaxAutoLevelUpdated(); this.codecTiers = null; this.audioTracksByGroup = null; } onMaxAutoLevelUpdated() { this.firstSelection = -1; this.nextAutoLevelKey = ""; } onFragLoading(event, data) { const frag = data.frag; if (this.ignoreFragment(frag)) { return; } if (!frag.bitrateTest) { var _data$part; this.fragCurrent = frag; this.partCurrent = (_data$part = data.part) != null ? _data$part : null; } this.clearTimer(); this.timer = self.setInterval(this._abandonRulesCheck, 100); } onLevelSwitching(event, data) { this.clearTimer(); } onError(event, data) { if (data.fatal) { return; } switch (data.details) { case ErrorDetails.BUFFER_ADD_CODEC_ERROR: case ErrorDetails.BUFFER_APPEND_ERROR: this.lastLoadedFragLevel = -1; this.firstSelection = -1; break; case ErrorDetails.FRAG_LOAD_TIMEOUT: { const frag = data.frag; const { fragCurrent, partCurrent: part } = this; if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) { const now2 = performance.now(); const stats = part ? part.stats : frag.stats; const timeLoading = now2 - stats.loading.start; const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1; const loadedFirstByte = stats.loaded && ttfb > -1; if (loadedFirstByte) { const ttfbEstimate = this.bwEstimator.getEstimateTTFB(); this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded); } else { this.bwEstimator.sampleTTFB(timeLoading); } } break; } } } getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) { const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth; const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0; return fragLoadSec + playlistLoadSec; } onLevelLoaded(event, data) { const config = this.hls.config; const { loading } = data.stats; const timeLoadingMs = loading.end - loading.start; if (isFiniteNumber(timeLoadingMs)) { this.lastLevelLoadSec = timeLoadingMs / 1e3; } if (data.details.live) { this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive); } else { this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD); } } onFragLoaded(event, { frag, part }) { const stats = part ? part.stats : frag.stats; if (frag.type === PlaylistLevelType.MAIN) { this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start); } if (this.ignoreFragment(frag)) { return; } this.clearTimer(); if (frag.level === this._nextAutoLevel) { this._nextAutoLevel = -1; } this.firstSelection = -1; if (this.hls.config.abrMaxWithRealBitrate) { const duration = part ? part.duration : frag.duration; const level = this.hls.levels[frag.level]; const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded; const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration; level.loaded = { bytes: loadedBytes, duration: loadedDuration }; level.realBitrate = Math.round(8 * loadedBytes / loadedDuration); } if (frag.bitrateTest) { const fragBufferedData = { stats, frag, part, id: frag.type }; this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData); frag.bitrateTest = false; } else { this.lastLoadedFragLevel = frag.level; } } onFragBuffered(event, data) { const { frag, part } = data; const stats = part != null && part.stats.loaded ? part.stats : frag.stats; if (stats.aborted) { return; } if (this.ignoreFragment(frag)) { return; } const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB()); this.bwEstimator.sample(processingMs, stats.loaded); stats.bwEstimate = this.getBwEstimate(); if (frag.bitrateTest) { this.bitrateTestDelay = processingMs / 1e3; } else { this.bitrateTestDelay = 0; } } ignoreFragment(frag) { return frag.type !== PlaylistLevelType.MAIN || frag.sn === "initSegment"; } clearTimer() { if (this.timer > -1) { self.clearInterval(this.timer); this.timer = -1; } } get firstAutoLevel() { const { maxAutoLevel, minAutoLevel } = this.hls; const bwEstimate = this.getBwEstimate(); const maxStartDelay = this.hls.config.maxStarvationDelay; const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1); if (abrAutoLevel > -1) { return abrAutoLevel; } const firstLevel = this.hls.firstLevel; const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel); logger.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`); return clamped; } get forcedAutoLevel() { if (this.nextAutoLevelKey) { return -1; } return this._nextAutoLevel; } // return next auto level get nextAutoLevel() { const forcedAutoLevel = this.forcedAutoLevel; const bwEstimator = this.bwEstimator; const useEstimate = bwEstimator.canEstimate(); const loadedFirstFrag = this.lastLoadedFragLevel > -1; if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) { return forcedAutoLevel; } const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel; if (forcedAutoLevel !== -1) { const levels = this.hls.levels; if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) { return forcedAutoLevel; } } this._nextAutoLevel = nextABRAutoLevel; this.nextAutoLevelKey = this.getAutoLevelKey(); return nextABRAutoLevel; } getAutoLevelKey() { return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`; } getNextABRAutoLevel() { const { fragCurrent, partCurrent, hls } = this; const { maxAutoLevel, config, minAutoLevel } = hls; const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0; const avgbw = this.getBwEstimate(); const bufferStarvationDelay = this.getStarvationDelay(); let bwFactor = config.abrBandWidthFactor; let bwUpFactor = config.abrBandWidthUpFactor; if (bufferStarvationDelay) { const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor); if (_bestLevel >= 0) { return _bestLevel; } } let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay; if (!bufferStarvationDelay) { const bitrateTestDelay = this.bitrateTestDelay; if (bitrateTestDelay) { const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay; maxStarvationDelay = maxLoadingDelay - bitrateTestDelay; logger.info(`[abr] bitrate test took ${Math.round(1e3 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * maxStarvationDelay)} ms`); bwFactor = bwUpFactor = 1; } } const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor); logger.info(`[abr] ${bufferStarvationDelay ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${bestLevel}`); if (bestLevel > -1) { return bestLevel; } const minLevel = hls.levels[minAutoLevel]; const autoLevel = hls.levels[hls.loadLevel]; if ((minLevel == null ? void 0 : minLevel.bitrate) < (autoLevel == null ? void 0 : autoLevel.bitrate)) { return minAutoLevel; } return hls.loadLevel; } getStarvationDelay() { const hls = this.hls; const media = hls.media; if (!media) { return Infinity; } const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1; const bufferInfo = hls.mainForwardBufferInfo; return (bufferInfo ? bufferInfo.len : 0) / playbackRate; } getBwEstimate() { return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate; } findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) { var _level$details; const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay; const lastLoadedFragLevel = this.lastLoadedFragLevel; const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel; const { fragCurrent, partCurrent } = this; const { levels, allAudioTracks, loadLevel, config } = this.hls; if (levels.length === 1) { return 0; } const level = levels[selectionBaseLevel]; const live = !!(level != null && (_level$details = level.details) != null && _level$details.live); const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1; let currentCodecSet; let currentVideoRange = "SDR"; let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0; const { audioPreference, videoPreference } = config; const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks)); if (firstSelection) { if (this.firstSelection !== -1) { return this.firstSelection; } const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel)); const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference); const { codecSet, videoRanges, minFramerate, minBitrate, preferHDR } = startTier; currentCodecSet = codecSet; currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0]; currentFrameRate = minFramerate; currentBw = Math.max(currentBw, minBitrate); logger.log(`[abr] picked start tier ${JSON.stringify(startTier)}`); } else { currentCodecSet = level == null ? void 0 : level.codecSet; currentVideoRange = level == null ? void 0 : level.videoRange; } const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0; const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1e3; const levelsSkipped = []; for (let i3 = maxAutoLevel; i3 >= minAutoLevel; i3--) { var _levelInfo$supportedR; const levelInfo = levels[i3]; const upSwitch = i3 > selectionBaseLevel; if (!levelInfo) { continue; } if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) { const mediaCapabilities = navigator.mediaCapabilities; if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === "function" && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) { levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities); levelInfo.supportedPromise.then((decodingInfo) => { if (!this.hls) { return; } levelInfo.supportedResult = decodingInfo; const levels2 = this.hls.levels; const index2 = levels2.indexOf(levelInfo); if (decodingInfo.error) { logger.warn(`[abr] MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index2} ${JSON.stringify(decodingInfo)}`); } else if (!decodingInfo.supported) { logger.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${index2} ${JSON.stringify(decodingInfo)}`); if (index2 > -1 && levels2.length > 1) { logger.log(`[abr] Removing unsupported level ${index2}`); this.hls.removeLevel(index2); } } }); } else { levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT; } } if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || levelInfo.supportedResult && !((_levelInfo$supportedR = levelInfo.supportedResult.decodingInfoResults) != null && _levelInfo$supportedR[0].smooth)) { levelsSkipped.push(i3); continue; } const levelDetails = levelInfo.details; const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration; let adjustedbw; if (!upSwitch) { adjustedbw = bwFactor * currentBw; } else { adjustedbw = bwUpFactor * currentBw; } const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levels[i3].averageBitrate : levels[i3].maxBitrate; const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === void 0); const canSwitchWithinTolerance = ( // if adjusted bw is greater than level bitrate AND adjustedbw >= bitrate && // no level change, or new level has no error history (i3 === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ... // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1 (fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration) ); if (canSwitchWithinTolerance) { const forcedAutoLevel = this.forcedAutoLevel; if (i3 !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) { if (levelsSkipped.length) { logger.trace(`[abr] Skipped level(s) ${levelsSkipped.join(",")} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${level.codecs}" ${currentVideoRange}`); } logger.info(`[abr] switch candidate:${selectionBaseLevel}->${i3} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${currentCodecSet} videoRange:${currentVideoRange} hls.loadLevel:${loadLevel}`); } if (firstSelection) { this.firstSelection = i3; } return i3; } } return -1; } set nextAutoLevel(nextLevel) { const { maxAutoLevel, minAutoLevel } = this.hls; const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel); if (this._nextAutoLevel !== value) { this.nextAutoLevelKey = ""; this._nextAutoLevel = value; } } }; var TaskLoop = class { constructor() { this._boundTick = void 0; this._tickTimer = null; this._tickInterval = null; this._tickCallCount = 0; this._boundTick = this.tick.bind(this); } destroy() { this.onHandlerDestroying(); this.onHandlerDestroyed(); } onHandlerDestroying() { this.clearNextTick(); this.clearInterval(); } onHandlerDestroyed() { } hasInterval() { return !!this._tickInterval; } hasNextTick() { return !!this._tickTimer; } /** * @param millis - Interval time (ms) * @eturns True when interval has been scheduled, false when already scheduled (no effect) */ setInterval(millis) { if (!this._tickInterval) { this._tickCallCount = 0; this._tickInterval = self.setInterval(this._boundTick, millis); return true; } return false; } /** * @returns True when interval was cleared, false when none was set (no effect) */ clearInterval() { if (this._tickInterval) { self.clearInterval(this._tickInterval); this._tickInterval = null; return true; } return false; } /** * @returns True when timeout was cleared, false when none was set (no effect) */ clearNextTick() { if (this._tickTimer) { self.clearTimeout(this._tickTimer); this._tickTimer = null; return true; } return false; } /** * Will call the subclass doTick implementation in this main loop tick * or in the next one (via setTimeout(,0)) in case it has already been called * in this tick (in case this is a re-entrant call). */ tick() { this._tickCallCount++; if (this._tickCallCount === 1) { this.doTick(); if (this._tickCallCount > 1) { this.tickImmediate(); } this._tickCallCount = 0; } } tickImmediate() { this.clearNextTick(); this._tickTimer = self.setTimeout(this._boundTick, 0); } /** * For subclass to implement task logic * @abstract */ doTick() { } }; var FragmentState = { NOT_LOADED: "NOT_LOADED", APPENDING: "APPENDING", PARTIAL: "PARTIAL", OK: "OK" }; var FragmentTracker = class { constructor(hls) { this.activePartLists = /* @__PURE__ */ Object.create(null); this.endListFragments = /* @__PURE__ */ Object.create(null); this.fragments = /* @__PURE__ */ Object.create(null); this.timeRanges = /* @__PURE__ */ Object.create(null); this.bufferPadding = 0.2; this.hls = void 0; this.hasGaps = false; this.hls = hls; this._registerListeners(); } _registerListeners() { const { hls } = this; hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this); hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this); hls.on(Events.FRAG_LOADED, this.onFragLoaded, this); } _unregisterListeners() { const { hls } = this; hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this); hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this); hls.off(Events.FRAG_LOADED, this.onFragLoaded, this); } destroy() { this._unregisterListeners(); this.fragments = // @ts-ignore this.activePartLists = // @ts-ignore this.endListFragments = this.timeRanges = null; } /** * Return a Fragment or Part with an appended range that matches the position and levelType * Otherwise, return null */ getAppendedFrag(position2, levelType) { const activeParts = this.activePartLists[levelType]; if (activeParts) { for (let i3 = activeParts.length; i3--; ) { const activePart = activeParts[i3]; if (!activePart) { break; } const appendedPTS = activePart.end; if (activePart.start <= position2 && appendedPTS !== null && position2 <= appendedPTS) { return activePart; } } } return this.getBufferedFrag(position2, levelType); } /** * Return a buffered Fragment that matches the position and levelType. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted). * If not found any Fragment, return null */ getBufferedFrag(position2, levelType) { const { fragments } = this; const keys = Object.keys(fragments); for (let i3 = keys.length; i3--; ) { const fragmentEntity = fragments[keys[i3]]; if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) { const frag = fragmentEntity.body; if (frag.start <= position2 && position2 <= frag.end) { return frag; } } } return null; } /** * Partial fragments effected by coded frame eviction will be removed * The browser will unload parts of the buffer to free up memory for new buffer data * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable) */ detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart) { if (this.timeRanges) { this.timeRanges[elementaryStream] = timeRange; } const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1; Object.keys(this.fragments).forEach((key) => { const fragmentEntity = this.fragments[key]; if (!fragmentEntity) { return; } if (appendedPartSn >= fragmentEntity.body.sn) { return; } if (!fragmentEntity.buffered && !fragmentEntity.loaded) { if (fragmentEntity.body.type === playlistType) { this.removeFragment(fragmentEntity.body); } return; } const esData = fragmentEntity.range[elementaryStream]; if (!esData) { return; } esData.time.some((time) => { const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange); if (isNotBuffered) { this.removeFragment(fragmentEntity.body); } return isNotBuffered; }); }); } /** * Checks if the fragment passed in is loaded in the buffer properly * Partially loaded fragments will be registered as a partial fragment */ detectPartialFragments(data) { const timeRanges = this.timeRanges; const { frag, part } = data; if (!timeRanges || frag.sn === "initSegment") { return; } const fragKey = getFragmentKey(frag); const fragmentEntity = this.fragments[fragKey]; if (!fragmentEntity || fragmentEntity.buffered && frag.gap) { return; } const isFragHint = !frag.relurl; Object.keys(timeRanges).forEach((elementaryStream) => { const streamInfo = frag.elementaryStreams[elementaryStream]; if (!streamInfo) { return; } const timeRange = timeRanges[elementaryStream]; const partial = isFragHint || streamInfo.partial === true; fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, part, partial, timeRange); }); fragmentEntity.loaded = null; if (Object.keys(fragmentEntity.range).length) { fragmentEntity.buffered = true; const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList; if (endList) { this.endListFragments[fragmentEntity.body.type] = fragmentEntity; } if (!isPartial(fragmentEntity)) { this.removeParts(frag.sn - 1, frag.type); } } else { this.removeFragment(fragmentEntity.body); } } removeParts(snToKeep, levelType) { const activeParts = this.activePartLists[levelType]; if (!activeParts) { return; } this.activePartLists[levelType] = activeParts.filter((part) => part.fragment.sn >= snToKeep); } fragBuffered(frag, force) { const fragKey = getFragmentKey(frag); let fragmentEntity = this.fragments[fragKey]; if (!fragmentEntity && force) { fragmentEntity = this.fragments[fragKey] = { body: frag, appendedPTS: null, loaded: null, buffered: false, range: /* @__PURE__ */ Object.create(null) }; if (frag.gap) { this.hasGaps = true; } } if (fragmentEntity) { fragmentEntity.loaded = null; fragmentEntity.buffered = true; } } getBufferedTimes(fragment, part, partial, timeRange) { const buffered = { time: [], partial }; const startPTS = fragment.start; const endPTS = fragment.end; const minEndPTS = fragment.minEndPTS || endPTS; const maxStartPTS = fragment.maxStartPTS || startPTS; for (let i3 = 0; i3 < timeRange.length; i3++) { const startTime = timeRange.start(i3) - this.bufferPadding; const endTime = timeRange.end(i3) + this.bufferPadding; if (maxStartPTS >= startTime && minEndPTS <= endTime) { buffered.time.push({ startPTS: Math.max(startPTS, timeRange.start(i3)), endPTS: Math.min(endPTS, timeRange.end(i3)) }); break; } else if (startPTS < endTime && endPTS > startTime) { const start = Math.max(startPTS, timeRange.start(i3)); const end = Math.min(endPTS, timeRange.end(i3)); if (end > start) { buffered.partial = true; buffered.time.push({ startPTS: start, endPTS: end }); } } else if (endPTS <= startTime) { break; } } return buffered; } /** * Gets the partial fragment for a certain time */ getPartialFragment(time) { let bestFragment = null; let timePadding; let startTime; let endTime; let bestOverlap = 0; const { bufferPadding, fragments } = this; Object.keys(fragments).forEach((key) => { const fragmentEntity = fragments[key]; if (!fragmentEntity) { return; } if (isPartial(fragmentEntity)) { startTime = fragmentEntity.body.start - bufferPadding; endTime = fragmentEntity.body.end + bufferPadding; if (time >= startTime && time <= endTime) { timePadding = Math.min(time - startTime, endTime - time); if (bestOverlap <= timePadding) { bestFragment = fragmentEntity.body; bestOverlap = timePadding; } } } }); return bestFragment; } isEndListAppended(type) { const lastFragmentEntity = this.endListFragments[type]; return lastFragmentEntity !== void 0 && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity)); } getState(fragment) { const fragKey = getFragmentKey(fragment); const fragmentEntity = this.fragments[fragKey]; if (fragmentEntity) { if (!fragmentEntity.buffered) { return FragmentState.APPENDING; } else if (isPartial(fragmentEntity)) { return FragmentState.PARTIAL; } else { return FragmentState.OK; } } return FragmentState.NOT_LOADED; } isTimeBuffered(startPTS, endPTS, timeRange) { let startTime; let endTime; for (let i3 = 0; i3 < timeRange.length; i3++) { startTime = timeRange.start(i3) - this.bufferPadding; endTime = timeRange.end(i3) + this.bufferPadding; if (startPTS >= startTime && endPTS <= endTime) { return true; } if (endPTS <= startTime) { return false; } } return false; } onFragLoaded(event, data) { const { frag, part } = data; if (frag.sn === "initSegment" || frag.bitrateTest) { return; } const loaded = part ? null : data; const fragKey = getFragmentKey(frag); this.fragments[fragKey] = { body: frag, appendedPTS: null, loaded, buffered: false, range: /* @__PURE__ */ Object.create(null) }; } onBufferAppended(event, data) { const { frag, part, timeRanges } = data; if (frag.sn === "initSegment") { return; } const playlistType = frag.type; if (part) { let activeParts = this.activePartLists[playlistType]; if (!activeParts) { this.activePartLists[playlistType] = activeParts = []; } activeParts.push(part); } this.timeRanges = timeRanges; Object.keys(timeRanges).forEach((elementaryStream) => { const timeRange = timeRanges[elementaryStream]; this.detectEvictedFragments(elementaryStream, timeRange, playlistType, part); }); } onFragBuffered(event, data) { this.detectPartialFragments(data); } hasFragment(fragment) { const fragKey = getFragmentKey(fragment); return !!this.fragments[fragKey]; } hasParts(type) { var _this$activePartLists; return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length); } removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) { if (withGapOnly && !this.hasGaps) { return; } Object.keys(this.fragments).forEach((key) => { const fragmentEntity = this.fragments[key]; if (!fragmentEntity) { return; } const frag = fragmentEntity.body; if (frag.type !== playlistType || withGapOnly && !frag.gap) { return; } if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) { this.removeFragment(frag); } }); } removeFragment(fragment) { const fragKey = getFragmentKey(fragment); fragment.stats.loaded = 0; fragment.clearElementaryStreamInfo(); const activeParts = this.activePartLists[fragment.type]; if (activeParts) { const snToRemove = fragment.sn; this.activePartLists[fragment.type] = activeParts.filter((part) => part.fragment.sn !== snToRemove); } delete this.fragments[fragKey]; if (fragment.endList) { delete this.endListFragments[fragment.type]; } } removeAllFragments() { this.fragments = /* @__PURE__ */ Object.create(null); this.endListFragments = /* @__PURE__ */ Object.create(null); this.activePartLists = /* @__PURE__ */ Object.create(null); this.hasGaps = false; } }; function isPartial(fragmentEntity) { var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3; return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial)); } function getFragmentKey(fragment) { return `${fragment.type}_${fragment.level}_${fragment.sn}`; } var noopBuffered = { length: 0, start: () => 0, end: () => 0 }; var BufferHelper = class _BufferHelper { /** * Return true if `media`'s buffered include `position` */ static isBuffered(media, position2) { try { if (media) { const buffered = _BufferHelper.getBuffered(media); for (let i3 = 0; i3 < buffered.length; i3++) { if (position2 >= buffered.start(i3) && position2 <= buffered.end(i3)) { return true; } } } } catch (error) { } return false; } static bufferInfo(media, pos, maxHoleDuration) { try { if (media) { const vbuffered = _BufferHelper.getBuffered(media); const buffered = []; let i3; for (i3 = 0; i3 < vbuffered.length; i3++) { buffered.push({ start: vbuffered.start(i3), end: vbuffered.end(i3) }); } return this.bufferedInfo(buffered, pos, maxHoleDuration); } } catch (error) { } return { len: 0, start: pos, end: pos, nextStart: void 0 }; } static bufferedInfo(buffered, pos, maxHoleDuration) { pos = Math.max(0, pos); buffered.sort(function(a2, b2) { const diff = a2.start - b2.start; if (diff) { return diff; } else { return b2.end - a2.end; } }); let buffered2 = []; if (maxHoleDuration) { for (let i3 = 0; i3 < buffered.length; i3++) { const buf2len = buffered2.length; if (buf2len) { const buf2end = buffered2[buf2len - 1].end; if (buffered[i3].start - buf2end < maxHoleDuration) { if (buffered[i3].end > buf2end) { buffered2[buf2len - 1].end = buffered[i3].end; } } else { buffered2.push(buffered[i3]); } } else { buffered2.push(buffered[i3]); } } } else { buffered2 = buffered; } let bufferLen = 0; let bufferStartNext; let bufferStart = pos; let bufferEnd = pos; for (let i3 = 0; i3 < buffered2.length; i3++) { const start = buffered2[i3].start; const end = buffered2[i3].end; if (pos + maxHoleDuration >= start && pos < end) { bufferStart = start; bufferEnd = end; bufferLen = bufferEnd - pos; } else if (pos + maxHoleDuration < start) { bufferStartNext = start; break; } } return { len: bufferLen, start: bufferStart || 0, end: bufferEnd || 0, nextStart: bufferStartNext }; } /** * Safe method to get buffered property. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource */ static getBuffered(media) { try { return media.buffered; } catch (e) { logger.log("failed to get media.buffered", e); return noopBuffered; } } }; var ChunkMetadata = class { constructor(level, sn, id, size = 0, part = -1, partial = false) { this.level = void 0; this.sn = void 0; this.part = void 0; this.id = void 0; this.size = void 0; this.partial = void 0; this.transmuxing = getNewPerformanceTiming(); this.buffering = { audio: getNewPerformanceTiming(), video: getNewPerformanceTiming(), audiovideo: getNewPerformanceTiming() }; this.level = level; this.sn = sn; this.id = id; this.size = size; this.part = part; this.partial = partial; } }; function getNewPerformanceTiming() { return { start: 0, executeStart: 0, executeEnd: 0, end: 0 }; } function findFirstFragWithCC(fragments, cc) { for (let i3 = 0, len = fragments.length; i3 < len; i3++) { var _fragments$i; if (((_fragments$i = fragments[i3]) == null ? void 0 : _fragments$i.cc) === cc) { return fragments[i3]; } } return null; } function shouldAlignOnDiscontinuities(lastFrag, switchDetails, details) { if (switchDetails) { if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) { return true; } } return false; } function findDiscontinuousReferenceFrag(prevDetails, curDetails) { const prevFrags = prevDetails.fragments; const curFrags = curDetails.fragments; if (!curFrags.length || !prevFrags.length) { logger.log("No fragments to align"); return; } const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc); if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) { logger.log("No frag in previous level to align on"); return; } return prevStartFrag; } function adjustFragmentStart(frag, sliding) { if (frag) { const start = frag.start + sliding; frag.start = frag.startPTS = start; frag.endPTS = start + frag.duration; } } function adjustSlidingStart(sliding, details) { const fragments = details.fragments; for (let i3 = 0, len = fragments.length; i3 < len; i3++) { adjustFragmentStart(fragments[i3], sliding); } if (details.fragmentHint) { adjustFragmentStart(details.fragmentHint, sliding); } details.alignedSliding = true; } function alignStream(lastFrag, switchDetails, details) { if (!switchDetails) { return; } alignDiscontinuities(lastFrag, details, switchDetails); if (!details.alignedSliding && switchDetails) { alignMediaPlaylistByPDT(details, switchDetails); } if (!details.alignedSliding && switchDetails && !details.skippedSegments) { adjustSliding(switchDetails, details); } } function alignDiscontinuities(lastFrag, details, switchDetails) { if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) { const referenceFrag = findDiscontinuousReferenceFrag(switchDetails, details); if (referenceFrag && isFiniteNumber(referenceFrag.start)) { logger.log(`Adjusting PTS using last level due to CC increase within current level ${details.url}`); adjustSlidingStart(referenceFrag.start, details); } } } function alignMediaPlaylistByPDT(details, refDetails) { if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) { return; } const fragments = details.fragments; const refFragments = refDetails.fragments; if (!fragments.length || !refFragments.length) { return; } let refFrag; let frag; const targetCC = Math.min(refDetails.endCC, details.endCC); if (refDetails.startCC < targetCC && details.startCC < targetCC) { refFrag = findFirstFragWithCC(refFragments, targetCC); frag = findFirstFragWithCC(fragments, targetCC); } if (!refFrag || !frag) { refFrag = refFragments[Math.floor(refFragments.length / 2)]; frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)]; } const refPDT = refFrag.programDateTime; const targetPDT = frag.programDateTime; if (!refPDT || !targetPDT) { return; } const delta = (targetPDT - refPDT) / 1e3 - (frag.start - refFrag.start); adjustSlidingStart(delta, details); } var MIN_CHUNK_SIZE = Math.pow(2, 17); var FragmentLoader = class { constructor(config) { this.config = void 0; this.loader = null; this.partLoadTimeout = -1; this.config = config; } destroy() { if (this.loader) { this.loader.destroy(); this.loader = null; } } abort() { if (this.loader) { this.loader.abort(); } } load(frag, onProgress) { const url = frag.url; if (!url) { return Promise.reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag, error: new Error(`Fragment does not have a ${url ? "part list" : "url"}`), networkDetails: null })); } this.abort(); const config = this.config; const FragmentILoader = config.fLoader; const DefaultILoader = config.loader; return new Promise((resolve, reject) => { if (this.loader) { this.loader.destroy(); } if (frag.gap) { if (frag.tagList.some((tags) => tags[0] === "GAP")) { reject(createGapLoadError(frag)); return; } else { frag.gap = false; } } const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config); const loaderContext = createLoaderContext(frag); const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default); const loaderConfig = { loadPolicy, timeout: loadPolicy.maxLoadTimeMs, maxRetry: 0, retryDelay: 0, maxRetryDelay: 0, highWaterMark: frag.sn === "initSegment" ? Infinity : MIN_CHUNK_SIZE }; frag.stats = loader.stats; loader.load(loaderContext, loaderConfig, { onSuccess: (response, stats, context, networkDetails) => { this.resetLoader(frag, loader); let payload = response.data; if (context.resetIV && frag.decryptdata) { frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16)); payload = payload.slice(16); } resolve({ frag, part: null, payload, networkDetails }); }, onError: (response, context, networkDetails, stats) => { this.resetLoader(frag, loader); reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag, response: _objectSpread23({ url, data: void 0 }, response), error: new Error(`HTTP Error ${response.code} ${response.text}`), networkDetails, stats })); }, onAbort: (stats, context, networkDetails) => { this.resetLoader(frag, loader); reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.INTERNAL_ABORTED, fatal: false, frag, error: new Error("Aborted"), networkDetails, stats })); }, onTimeout: (stats, context, networkDetails) => { this.resetLoader(frag, loader); reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag, error: new Error(`Timeout after ${loaderConfig.timeout}ms`), networkDetails, stats })); }, onProgress: (stats, context, data, networkDetails) => { if (onProgress) { onProgress({ frag, part: null, payload: data, networkDetails }); } } }); }); } loadPart(frag, part, onProgress) { this.abort(); const config = this.config; const FragmentILoader = config.fLoader; const DefaultILoader = config.loader; return new Promise((resolve, reject) => { if (this.loader) { this.loader.destroy(); } if (frag.gap || part.gap) { reject(createGapLoadError(frag, part)); return; } const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config); const loaderContext = createLoaderContext(frag, part); const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default); const loaderConfig = { loadPolicy, timeout: loadPolicy.maxLoadTimeMs, maxRetry: 0, retryDelay: 0, maxRetryDelay: 0, highWaterMark: MIN_CHUNK_SIZE }; part.stats = loader.stats; loader.load(loaderContext, loaderConfig, { onSuccess: (response, stats, context, networkDetails) => { this.resetLoader(frag, loader); this.updateStatsFromPart(frag, part); const partLoadedData = { frag, part, payload: response.data, networkDetails }; onProgress(partLoadedData); resolve(partLoadedData); }, onError: (response, context, networkDetails, stats) => { this.resetLoader(frag, loader); reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag, part, response: _objectSpread23({ url: loaderContext.url, data: void 0 }, response), error: new Error(`HTTP Error ${response.code} ${response.text}`), networkDetails, stats })); }, onAbort: (stats, context, networkDetails) => { frag.stats.aborted = part.stats.aborted; this.resetLoader(frag, loader); reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.INTERNAL_ABORTED, fatal: false, frag, part, error: new Error("Aborted"), networkDetails, stats })); }, onTimeout: (stats, context, networkDetails) => { this.resetLoader(frag, loader); reject(new LoadError({ type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag, part, error: new Error(`Timeout after ${loaderConfig.timeout}ms`), networkDetails, stats })); } }); }); } updateStatsFromPart(frag, part) { const fragStats = frag.stats; const partStats = part.stats; const partTotal = partStats.total; fragStats.loaded += partStats.loaded; if (partTotal) { const estTotalParts = Math.round(frag.duration / part.duration); const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts); const estRemainingParts = estTotalParts - estLoadedParts; const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts); fragStats.total = fragStats.loaded + estRemainingBytes; } else { fragStats.total = Math.max(fragStats.loaded, fragStats.total); } const fragLoading = fragStats.loading; const partLoading = partStats.loading; if (fragLoading.start) { fragLoading.first += partLoading.first - partLoading.start; } else { fragLoading.start = partLoading.start; fragLoading.first = partLoading.first; } fragLoading.end = partLoading.end; } resetLoader(frag, loader) { frag.loader = null; if (this.loader === loader) { self.clearTimeout(this.partLoadTimeout); this.loader = null; } loader.destroy(); } }; function createLoaderContext(frag, part = null) { const segment = part || frag; const loaderContext = { frag, part, responseType: "arraybuffer", url: segment.url, headers: {}, rangeStart: 0, rangeEnd: 0 }; const start = segment.byteRangeStartOffset; const end = segment.byteRangeEndOffset; if (isFiniteNumber(start) && isFiniteNumber(end)) { var _frag$decryptdata; let byteRangeStart = start; let byteRangeEnd = end; if (frag.sn === "initSegment" && ((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method) === "AES-128") { const fragmentLen = end - start; if (fragmentLen % 16) { byteRangeEnd = end + (16 - fragmentLen % 16); } if (start !== 0) { loaderContext.resetIV = true; byteRangeStart = start - 16; } } loaderContext.rangeStart = byteRangeStart; loaderContext.rangeEnd = byteRangeEnd; } return loaderContext; } function createGapLoadError(frag, part) { const error = new Error(`GAP ${frag.gap ? "tag" : "attribute"} found`); const errorData = { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_GAP, fatal: false, frag, error, networkDetails: null }; if (part) { errorData.part = part; } (part ? part : frag).stats.aborted = true; return new LoadError(errorData); } var LoadError = class extends Error { constructor(data) { super(data.error.message); this.data = void 0; this.data = data; } }; var AESCrypto = class { constructor(subtle, iv) { this.subtle = void 0; this.aesIV = void 0; this.subtle = subtle; this.aesIV = iv; } decrypt(data, key) { return this.subtle.decrypt({ name: "AES-CBC", iv: this.aesIV }, key, data); } }; var FastAESKey = class { constructor(subtle, key) { this.subtle = void 0; this.key = void 0; this.subtle = subtle; this.key = key; } expandKey() { return this.subtle.importKey("raw", this.key, { name: "AES-CBC" }, false, ["encrypt", "decrypt"]); } }; function removePadding(array) { const outputBytes = array.byteLength; const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1); if (paddingBytes) { return sliceUint8(array, 0, outputBytes - paddingBytes); } return array; } var AESDecryptor = class { constructor() { this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; this.sBox = new Uint32Array(256); this.invSBox = new Uint32Array(256); this.key = new Uint32Array(0); this.ksRows = 0; this.keySize = 0; this.keySchedule = void 0; this.invKeySchedule = void 0; this.initTable(); } // Using view.getUint32() also swaps the byte order. uint8ArrayToUint32Array_(arrayBuffer) { const view = new DataView(arrayBuffer); const newArray = new Uint32Array(4); for (let i3 = 0; i3 < 4; i3++) { newArray[i3] = view.getUint32(i3 * 4); } return newArray; } initTable() { const sBox = this.sBox; const invSBox = this.invSBox; const subMix = this.subMix; const subMix0 = subMix[0]; const subMix1 = subMix[1]; const subMix2 = subMix[2]; const subMix3 = subMix[3]; const invSubMix = this.invSubMix; const invSubMix0 = invSubMix[0]; const invSubMix1 = invSubMix[1]; const invSubMix2 = invSubMix[2]; const invSubMix3 = invSubMix[3]; const d2 = new Uint32Array(256); let x2 = 0; let xi2 = 0; let i3 = 0; for (i3 = 0; i3 < 256; i3++) { if (i3 < 128) { d2[i3] = i3 << 1; } else { d2[i3] = i3 << 1 ^ 283; } } for (i3 = 0; i3 < 256; i3++) { let sx = xi2 ^ xi2 << 1 ^ xi2 << 2 ^ xi2 << 3 ^ xi2 << 4; sx = sx >>> 8 ^ sx & 255 ^ 99; sBox[x2] = sx; invSBox[sx] = x2; const x22 = d2[x2]; const x4 = d2[x22]; const x8 = d2[x4]; let t2 = d2[sx] * 257 ^ sx * 16843008; subMix0[x2] = t2 << 24 | t2 >>> 8; subMix1[x2] = t2 << 16 | t2 >>> 16; subMix2[x2] = t2 << 8 | t2 >>> 24; subMix3[x2] = t2; t2 = x8 * 16843009 ^ x4 * 65537 ^ x22 * 257 ^ x2 * 16843008; invSubMix0[sx] = t2 << 24 | t2 >>> 8; invSubMix1[sx] = t2 << 16 | t2 >>> 16; invSubMix2[sx] = t2 << 8 | t2 >>> 24; invSubMix3[sx] = t2; if (!x2) { x2 = xi2 = 1; } else { x2 = x22 ^ d2[d2[d2[x8 ^ x22]]]; xi2 ^= d2[d2[xi2]]; } } } expandKey(keyBuffer) { const key = this.uint8ArrayToUint32Array_(keyBuffer); let sameKey = true; let offset = 0; while (offset < key.length && sameKey) { sameKey = key[offset] === this.key[offset]; offset++; } if (sameKey) { return; } this.key = key; const keySize = this.keySize = key.length; if (keySize !== 4 && keySize !== 6 && keySize !== 8) { throw new Error("Invalid aes key size=" + keySize); } const ksRows = this.ksRows = (keySize + 6 + 1) * 4; let ksRow; let invKsRow; const keySchedule = this.keySchedule = new Uint32Array(ksRows); const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows); const sbox = this.sBox; const rcon = this.rcon; const invSubMix = this.invSubMix; const invSubMix0 = invSubMix[0]; const invSubMix1 = invSubMix[1]; const invSubMix2 = invSubMix[2]; const invSubMix3 = invSubMix[3]; let prev2; let t2; for (ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { prev2 = keySchedule[ksRow] = key[ksRow]; continue; } t2 = prev2; if (ksRow % keySize === 0) { t2 = t2 << 8 | t2 >>> 24; t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255]; t2 ^= rcon[ksRow / keySize | 0] << 24; } else if (keySize > 6 && ksRow % keySize === 4) { t2 = sbox[t2 >>> 24] << 24 | sbox[t2 >>> 16 & 255] << 16 | sbox[t2 >>> 8 & 255] << 8 | sbox[t2 & 255]; } keySchedule[ksRow] = prev2 = (keySchedule[ksRow - keySize] ^ t2) >>> 0; } for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { ksRow = ksRows - invKsRow; if (invKsRow & 3) { t2 = keySchedule[ksRow]; } else { t2 = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t2; } else { invKeySchedule[invKsRow] = invSubMix0[sbox[t2 >>> 24]] ^ invSubMix1[sbox[t2 >>> 16 & 255]] ^ invSubMix2[sbox[t2 >>> 8 & 255]] ^ invSubMix3[sbox[t2 & 255]]; } invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0; } } // Adding this as a method greatly improves performance. networkToHostOrderSwap(word) { return word << 24 | (word & 65280) << 8 | (word & 16711680) >> 8 | word >>> 24; } decrypt(inputArrayBuffer, offset, aesIV) { const nRounds = this.keySize + 6; const invKeySchedule = this.invKeySchedule; const invSBOX = this.invSBox; const invSubMix = this.invSubMix; const invSubMix0 = invSubMix[0]; const invSubMix1 = invSubMix[1]; const invSubMix2 = invSubMix[2]; const invSubMix3 = invSubMix[3]; const initVector = this.uint8ArrayToUint32Array_(aesIV); let initVector0 = initVector[0]; let initVector1 = initVector[1]; let initVector2 = initVector[2]; let initVector3 = initVector[3]; const inputInt32 = new Int32Array(inputArrayBuffer); const outputInt32 = new Int32Array(inputInt32.length); let t0, t1, t2, t3; let s0, s1, s2, s3; let inputWords0, inputWords1, inputWords2, inputWords3; let ksRow, i3; const swapWord = this.networkToHostOrderSwap; while (offset < inputInt32.length) { inputWords0 = swapWord(inputInt32[offset]); inputWords1 = swapWord(inputInt32[offset + 1]); inputWords2 = swapWord(inputInt32[offset + 2]); inputWords3 = swapWord(inputInt32[offset + 3]); s0 = inputWords0 ^ invKeySchedule[0]; s1 = inputWords3 ^ invKeySchedule[1]; s2 = inputWords2 ^ invKeySchedule[2]; s3 = inputWords1 ^ invKeySchedule[3]; ksRow = 4; for (i3 = 1; i3 < nRounds; i3++) { t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 255] ^ invSubMix2[s2 >> 8 & 255] ^ invSubMix3[s3 & 255] ^ invKeySchedule[ksRow]; t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 255] ^ invSubMix2[s3 >> 8 & 255] ^ invSubMix3[s0 & 255] ^ invKeySchedule[ksRow + 1]; t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 255] ^ invSubMix2[s0 >> 8 & 255] ^ invSubMix3[s1 & 255] ^ invKeySchedule[ksRow + 2]; t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 255] ^ invSubMix2[s1 >> 8 & 255] ^ invSubMix3[s2 & 255] ^ invKeySchedule[ksRow + 3]; s0 = t0; s1 = t1; s2 = t2; s3 = t3; ksRow = ksRow + 4; } t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 255] << 16 ^ invSBOX[s2 >> 8 & 255] << 8 ^ invSBOX[s3 & 255] ^ invKeySchedule[ksRow]; t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 255] << 16 ^ invSBOX[s3 >> 8 & 255] << 8 ^ invSBOX[s0 & 255] ^ invKeySchedule[ksRow + 1]; t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 255] << 16 ^ invSBOX[s0 >> 8 & 255] << 8 ^ invSBOX[s1 & 255] ^ invKeySchedule[ksRow + 2]; t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 255] << 16 ^ invSBOX[s1 >> 8 & 255] << 8 ^ invSBOX[s2 & 255] ^ invKeySchedule[ksRow + 3]; outputInt32[offset] = swapWord(t0 ^ initVector0); outputInt32[offset + 1] = swapWord(t3 ^ initVector1); outputInt32[offset + 2] = swapWord(t2 ^ initVector2); outputInt32[offset + 3] = swapWord(t1 ^ initVector3); initVector0 = inputWords0; initVector1 = inputWords1; initVector2 = inputWords2; initVector3 = inputWords3; offset = offset + 4; } return outputInt32.buffer; } }; var CHUNK_SIZE = 16; var Decrypter = class { constructor(config, { removePKCS7Padding = true } = {}) { this.logEnabled = true; this.removePKCS7Padding = void 0; this.subtle = null; this.softwareDecrypter = null; this.key = null; this.fastAesKey = null; this.remainderData = null; this.currentIV = null; this.currentResult = null; this.useSoftware = void 0; this.useSoftware = config.enableSoftwareAES; this.removePKCS7Padding = removePKCS7Padding; if (removePKCS7Padding) { try { const browserCrypto = self.crypto; if (browserCrypto) { this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; } } catch (e) { } } this.useSoftware = !this.subtle; } destroy() { this.subtle = null; this.softwareDecrypter = null; this.key = null; this.fastAesKey = null; this.remainderData = null; this.currentIV = null; this.currentResult = null; } isSync() { return this.useSoftware; } flush() { const { currentResult, remainderData } = this; if (!currentResult || remainderData) { this.reset(); return null; } const data = new Uint8Array(currentResult); this.reset(); if (this.removePKCS7Padding) { return removePadding(data); } return data; } reset() { this.currentResult = null; this.currentIV = null; this.remainderData = null; if (this.softwareDecrypter) { this.softwareDecrypter = null; } } decrypt(data, key, iv) { if (this.useSoftware) { return new Promise((resolve, reject) => { this.softwareDecrypt(new Uint8Array(data), key, iv); const decryptResult = this.flush(); if (decryptResult) { resolve(decryptResult.buffer); } else { reject(new Error("[softwareDecrypt] Failed to decrypt data")); } }); } return this.webCryptoDecrypt(new Uint8Array(data), key, iv); } // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached // data is handled in the flush() call softwareDecrypt(data, key, iv) { const { currentIV, currentResult, remainderData } = this; this.logOnce("JS AES decrypt"); if (remainderData) { data = appendUint8Array(remainderData, data); this.remainderData = null; } const currentChunk = this.getValidChunk(data); if (!currentChunk.length) { return null; } if (currentIV) { iv = currentIV; } let softwareDecrypter = this.softwareDecrypter; if (!softwareDecrypter) { softwareDecrypter = this.softwareDecrypter = new AESDecryptor(); } softwareDecrypter.expandKey(key); const result = currentResult; this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv); this.currentIV = sliceUint8(currentChunk, -16).buffer; if (!result) { return null; } return result; } webCryptoDecrypt(data, key, iv) { if (this.key !== key || !this.fastAesKey) { if (!this.subtle) { return Promise.resolve(this.onWebCryptoError(data, key, iv)); } this.key = key; this.fastAesKey = new FastAESKey(this.subtle, key); } return this.fastAesKey.expandKey().then((aesKey) => { if (!this.subtle) { return Promise.reject(new Error("web crypto not initialized")); } this.logOnce("WebCrypto AES decrypt"); const crypto2 = new AESCrypto(this.subtle, new Uint8Array(iv)); return crypto2.decrypt(data.buffer, aesKey); }).catch((err) => { logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`); return this.onWebCryptoError(data, key, iv); }); } onWebCryptoError(data, key, iv) { this.useSoftware = true; this.logEnabled = true; this.softwareDecrypt(data, key, iv); const decryptResult = this.flush(); if (decryptResult) { return decryptResult.buffer; } throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data"); } getValidChunk(data) { let currentChunk = data; const splitPoint = data.length - data.length % CHUNK_SIZE; if (splitPoint !== data.length) { currentChunk = sliceUint8(data, 0, splitPoint); this.remainderData = sliceUint8(data, splitPoint); } return currentChunk; } logOnce(msg) { if (!this.logEnabled) { return; } logger.log(`[decrypter]: ${msg}`); this.logEnabled = false; } }; var TimeRanges = { toString: function(r9) { let log = ""; const len = r9.length; for (let i3 = 0; i3 < len; i3++) { log += `[${r9.start(i3).toFixed(3)}-${r9.end(i3).toFixed(3)}]`; } return log; } }; var State = { STOPPED: "STOPPED", IDLE: "IDLE", KEY_LOADING: "KEY_LOADING", FRAG_LOADING: "FRAG_LOADING", FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY", WAITING_TRACK: "WAITING_TRACK", PARSING: "PARSING", PARSED: "PARSED", ENDED: "ENDED", ERROR: "ERROR", WAITING_INIT_PTS: "WAITING_INIT_PTS", WAITING_LEVEL: "WAITING_LEVEL" }; var BaseStreamController = class extends TaskLoop { constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) { super(); this.hls = void 0; this.fragPrevious = null; this.fragCurrent = null; this.fragmentTracker = void 0; this.transmuxer = null; this._state = State.STOPPED; this.playlistType = void 0; this.media = null; this.mediaBuffer = null; this.config = void 0; this.bitrateTest = false; this.lastCurrentTime = 0; this.nextLoadPosition = 0; this.startPosition = 0; this.startTimeOffset = null; this.loadedmetadata = false; this.retryDate = 0; this.levels = null; this.fragmentLoader = void 0; this.keyLoader = void 0; this.levelLastLoaded = null; this.startFragRequested = false; this.decrypter = void 0; this.initPTS = []; this.buffering = true; this.onvseeking = null; this.onvended = null; this.logPrefix = ""; this.log = void 0; this.warn = void 0; this.playlistType = playlistType; this.logPrefix = logPrefix; this.log = logger.log.bind(logger, `${logPrefix}:`); this.warn = logger.warn.bind(logger, `${logPrefix}:`); this.hls = hls; this.fragmentLoader = new FragmentLoader(hls.config); this.keyLoader = keyLoader; this.fragmentTracker = fragmentTracker; this.config = hls.config; this.decrypter = new Decrypter(hls.config); hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this); } doTick() { this.onTickEnd(); } onTickEnd() { } // eslint-disable-next-line @typescript-eslint/no-unused-vars startLoad(startPosition) { } stopLoad() { this.fragmentLoader.abort(); this.keyLoader.abort(this.playlistType); const frag = this.fragCurrent; if (frag != null && frag.loader) { frag.abortRequests(); this.fragmentTracker.removeFragment(frag); } this.resetTransmuxer(); this.fragCurrent = null; this.fragPrevious = null; this.clearInterval(); this.clearNextTick(); this.state = State.STOPPED; } pauseBuffering() { this.buffering = false; } resumeBuffering() { this.buffering = true; } _streamEnded(bufferInfo, levelDetails) { if (levelDetails.live || bufferInfo.nextStart || !bufferInfo.end || !this.media) { return false; } const partList = levelDetails.partList; if (partList != null && partList.length) { const lastPart = partList[partList.length - 1]; const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2); return lastPartBuffered; } const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type; return this.fragmentTracker.isEndListAppended(playlistType); } getLevelDetails() { if (this.levels && this.levelLastLoaded !== null) { var _this$levelLastLoaded; return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details; } } onMediaAttached(event, data) { const media = this.media = this.mediaBuffer = data.media; this.onvseeking = this.onMediaSeeking.bind(this); this.onvended = this.onMediaEnded.bind(this); media.addEventListener("seeking", this.onvseeking); media.addEventListener("ended", this.onvended); const config = this.config; if (this.levels && config.autoStartLoad && this.state === State.STOPPED) { this.startLoad(config.startPosition); } } onMediaDetaching() { const media = this.media; if (media != null && media.ended) { this.log("MSE detaching and video ended, reset startPosition"); this.startPosition = this.lastCurrentTime = 0; } if (media && this.onvseeking && this.onvended) { media.removeEventListener("seeking", this.onvseeking); media.removeEventListener("ended", this.onvended); this.onvseeking = this.onvended = null; } if (this.keyLoader) { this.keyLoader.detach(); } this.media = this.mediaBuffer = null; this.loadedmetadata = false; this.fragmentTracker.removeAllFragments(); this.stopLoad(); } onMediaSeeking() { const { config, fragCurrent, media, mediaBuffer, state } = this; const currentTime = media ? media.currentTime : 0; const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole); this.log(`media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}`); if (this.state === State.ENDED) { this.resetLoadingState(); } else if (fragCurrent) { const tolerance = config.maxFragLookUpTolerance; const fragStartOffset = fragCurrent.start - tolerance; const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) { const pastFragment = currentTime > fragEndOffset; if (currentTime < fragStartOffset || pastFragment) { if (pastFragment && fragCurrent.loader) { this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"); fragCurrent.abortRequests(); this.resetLoadingState(); } this.fragPrevious = null; } } } if (media) { this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true); this.lastCurrentTime = currentTime; } if (!this.loadedmetadata && !bufferInfo.len) { this.nextLoadPosition = this.startPosition = currentTime; } this.tickImmediate(); } onMediaEnded() { this.startPosition = this.lastCurrentTime = 0; } onManifestLoaded(event, data) { this.startTimeOffset = data.startTimeOffset; this.initPTS = []; } onHandlerDestroying() { this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this); this.stopLoad(); super.onHandlerDestroying(); this.hls = null; } onHandlerDestroyed() { this.state = State.STOPPED; if (this.fragmentLoader) { this.fragmentLoader.destroy(); } if (this.keyLoader) { this.keyLoader.destroy(); } if (this.decrypter) { this.decrypter.destroy(); } this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null; super.onHandlerDestroyed(); } loadFragment(frag, level, targetBufferTime) { this._loadFragForPlayback(frag, level, targetBufferTime); } _loadFragForPlayback(frag, level, targetBufferTime) { const progressCallback = (data) => { if (this.fragContextChanged(frag)) { this.warn(`Fragment ${frag.sn}${data.part ? " p: " + data.part.index : ""} of level ${frag.level} was dropped during download.`); this.fragmentTracker.removeFragment(frag); return; } frag.stats.chunkCount++; this._handleFragmentLoadProgress(data); }; this._doFragLoad(frag, level, targetBufferTime, progressCallback).then((data) => { if (!data) { return; } const state = this.state; if (this.fragContextChanged(frag)) { if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) { this.fragmentTracker.removeFragment(frag); this.state = State.IDLE; } return; } if ("payload" in data) { this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`); this.hls.trigger(Events.FRAG_LOADED, data); } this._handleFragmentLoadComplete(data); }).catch((reason) => { if (this.state === State.STOPPED || this.state === State.ERROR) { return; } this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`); this.resetFragmentLoading(frag); }); } clearTrackerIfNeeded(frag) { var _this$mediaBuffer; const { fragmentTracker } = this; const fragState = fragmentTracker.getState(frag); if (fragState === FragmentState.APPENDING) { const playlistType = frag.type; const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType); const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength); const backtrackFragment = this.backtrackFragment; const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0; if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) { fragmentTracker.removeFragment(frag); } } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) { fragmentTracker.removeAllFragments(); } else if (fragmentTracker.hasParts(frag.type)) { fragmentTracker.detectPartialFragments({ frag, part: null, stats: frag.stats, id: frag.type }); if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) { fragmentTracker.removeFragment(frag); } } } checkLiveUpdate(details) { if (details.updated && !details.live) { const lastFragment = details.fragments[details.fragments.length - 1]; this.fragmentTracker.detectPartialFragments({ frag: lastFragment, part: null, stats: lastFragment.stats, id: lastFragment.type }); } if (!details.fragments[0]) { details.deltaUpdateFailed = true; } } flushMainBuffer(startOffset, endOffset, type = null) { if (!(startOffset - endOffset)) { return; } const flushScope = { startOffset, endOffset, type }; this.hls.trigger(Events.BUFFER_FLUSHING, flushScope); } _loadInitSegment(frag, level) { this._doFragLoad(frag, level).then((data) => { if (!data || this.fragContextChanged(frag) || !this.levels) { throw new Error("init load aborted"); } return data; }).then((data) => { const { hls } = this; const { payload } = data; const decryptData = frag.decryptdata; if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === "AES-128") { const startTime = self.performance.now(); return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch((err) => { hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_DECRYPT_ERROR, fatal: false, error: err, reason: err.message, frag }); throw err; }).then((decryptedData) => { const endTime = self.performance.now(); hls.trigger(Events.FRAG_DECRYPTED, { frag, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); data.payload = decryptedData; return this.completeInitSegmentLoad(data); }); } return this.completeInitSegmentLoad(data); }).catch((reason) => { if (this.state === State.STOPPED || this.state === State.ERROR) { return; } this.warn(reason); this.resetFragmentLoading(frag); }); } completeInitSegmentLoad(data) { const { levels } = this; if (!levels) { throw new Error("init load aborted, missing levels"); } const stats = data.frag.stats; this.state = State.IDLE; data.frag.data = new Uint8Array(data.payload); stats.parsing.start = stats.buffering.start = self.performance.now(); stats.parsing.end = stats.buffering.end = self.performance.now(); this.tick(); } fragContextChanged(frag) { const { fragCurrent } = this; return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level; } fragBufferedComplete(frag, part) { var _frag$startPTS, _frag$endPTS, _this$fragCurrent, _this$fragPrevious; const media = this.mediaBuffer ? this.mediaBuffer : this.media; this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? " part: " + part.index : ""} of ${this.playlistType === PlaylistLevelType.MAIN ? "level" : "track"} ${frag.level} (frag:[${((_frag$startPTS = frag.startPTS) != null ? _frag$startPTS : NaN).toFixed(3)}-${((_frag$endPTS = frag.endPTS) != null ? _frag$endPTS : NaN).toFixed(3)}] > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : "(detached)"})`); if (frag.sn !== "initSegment") { var _this$levels; if (frag.type !== PlaylistLevelType.SUBTITLE) { const el = frag.elementaryStreams; if (!Object.keys(el).some((type) => !!el[type])) { this.state = State.IDLE; return; } } const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level]; if (level != null && level.fragmentError) { this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`); level.fragmentError = 0; } } this.state = State.IDLE; if (!media) { return; } if (!this.loadedmetadata && frag.type == PlaylistLevelType.MAIN && media.buffered.length && ((_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.sn) === ((_this$fragPrevious = this.fragPrevious) == null ? void 0 : _this$fragPrevious.sn)) { this.loadedmetadata = true; this.seekToStartPos(); } this.tick(); } seekToStartPos() { } _handleFragmentLoadComplete(fragLoadedEndData) { const { transmuxer } = this; if (!transmuxer) { return; } const { frag, part, partsLoaded } = fragLoadedEndData; const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some((fragLoaded) => !fragLoaded); const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete); transmuxer.flush(chunkMeta); } // eslint-disable-next-line @typescript-eslint/no-unused-vars _handleFragmentLoadProgress(frag) { } _doFragLoad(frag, level, targetBufferTime = null, progressCallback) { var _frag$decryptdata; const details = level == null ? void 0 : level.details; if (!this.levels || !details) { throw new Error(`frag load aborted, missing level${details ? "" : " detail"}s`); } let keyLoadingPromise = null; if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) { this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.logPrefix === "[stream-controller]" ? "level" : "track"} ${frag.level}`); this.state = State.KEY_LOADING; this.fragCurrent = frag; keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => { if (!this.fragContextChanged(keyLoadedData.frag)) { this.hls.trigger(Events.KEY_LOADED, keyLoadedData); if (this.state === State.KEY_LOADING) { this.state = State.IDLE; } return keyLoadedData; } }); this.hls.trigger(Events.KEY_LOADING, { frag }); if (this.fragCurrent === null) { keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`)); } } else if (!frag.encrypted && details.encryptedFragments.length) { this.keyLoader.loadClear(frag, details.encryptedFragments); } targetBufferTime = Math.max(frag.start, targetBufferTime || 0); if (this.config.lowLatencyMode && frag.sn !== "initSegment") { const partList = details.partList; if (partList && progressCallback) { if (targetBufferTime > frag.end && details.fragmentHint) { frag = details.fragmentHint; } const partIndex = this.getNextPart(partList, frag, targetBufferTime); if (partIndex > -1) { const part = partList[partIndex]; this.log(`Loading part sn: ${frag.sn} p: ${part.index} cc: ${frag.cc} of playlist [${details.startSN}-${details.endSN}] parts [0-${partIndex}-${partList.length - 1}] ${this.logPrefix === "[stream-controller]" ? "level" : "track"}: ${frag.level}, target: ${parseFloat(targetBufferTime.toFixed(3))}`); this.nextLoadPosition = part.start + part.duration; this.state = State.FRAG_LOADING; let _result; if (keyLoadingPromise) { _result = keyLoadingPromise.then((keyLoadedData) => { if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) { return null; } return this.doFragPartsLoad(frag, part, level, progressCallback); }).catch((error) => this.handleFragLoadError(error)); } else { _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch((error) => this.handleFragLoadError(error)); } this.hls.trigger(Events.FRAG_LOADING, { frag, part, targetBufferTime }); if (this.fragCurrent === null) { return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`)); } return _result; } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) { return Promise.resolve(null); } } } this.log(`Loading fragment ${frag.sn} cc: ${frag.cc} ${details ? "of [" + details.startSN + "-" + details.endSN + "] " : ""}${this.logPrefix === "[stream-controller]" ? "level" : "track"}: ${frag.level}, target: ${parseFloat(targetBufferTime.toFixed(3))}`); if (isFiniteNumber(frag.sn) && !this.bitrateTest) { this.nextLoadPosition = frag.start + frag.duration; } this.state = State.FRAG_LOADING; const dataOnProgress = this.config.progressive; let result; if (dataOnProgress && keyLoadingPromise) { result = keyLoadingPromise.then((keyLoadedData) => { if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) { return null; } return this.fragmentLoader.load(frag, progressCallback); }).catch((error) => this.handleFragLoadError(error)); } else { result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : void 0), keyLoadingPromise]).then(([fragLoadedData]) => { if (!dataOnProgress && fragLoadedData && progressCallback) { progressCallback(fragLoadedData); } return fragLoadedData; }).catch((error) => this.handleFragLoadError(error)); } this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime }); if (this.fragCurrent === null) { return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`)); } return result; } doFragPartsLoad(frag, fromPart, level, progressCallback) { return new Promise((resolve, reject) => { var _level$details; const partsLoaded = []; const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList; const loadPart = (part) => { this.fragmentLoader.loadPart(frag, part, progressCallback).then((partLoadedData) => { partsLoaded[part.index] = partLoadedData; const loadedPart = partLoadedData.part; this.hls.trigger(Events.FRAG_LOADED, partLoadedData); const nextPart = getPartWith(level, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1); if (nextPart) { loadPart(nextPart); } else { return resolve({ frag, part: loadedPart, partsLoaded }); } }).catch(reject); }; loadPart(fromPart); }); } handleFragLoadError(error) { if ("data" in error) { const data = error.data; if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) { this.handleFragLoadAborted(data.frag, data.part); } else { this.hls.trigger(Events.ERROR, data); } } else { this.hls.trigger(Events.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, err: error, error, fatal: true }); } return null; } _handleTransmuxerFlush(chunkMeta) { const context = this.getCurrentContext(chunkMeta); if (!context || this.state !== State.PARSING) { if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) { this.state = State.IDLE; } return; } const { frag, part, level } = context; const now2 = self.performance.now(); frag.stats.parsing.end = now2; if (part) { part.stats.parsing.end = now2; } this.updateLevelTiming(frag, part, level, chunkMeta.partial); } getCurrentContext(chunkMeta) { const { levels, fragCurrent } = this; const { level: levelIndex, sn, part: partIndex } = chunkMeta; if (!(levels != null && levels[levelIndex])) { this.warn(`Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`); return null; } const level = levels[levelIndex]; const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null; const frag = part ? part.fragment : getFragmentWithSN(level, sn, fragCurrent); if (!frag) { return null; } if (fragCurrent && fragCurrent !== frag) { frag.stats = fragCurrent.stats; } return { frag, part, level }; } bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) { var _buffer; if (!data || this.state !== State.PARSING) { return; } const { data1, data2 } = data; let buffer = data1; if (data1 && data2) { buffer = appendUint8Array(data1, data2); } if (!((_buffer = buffer) != null && _buffer.length)) { return; } const segment = { type: data.type, frag, part, chunkMeta, parent: frag.type, data: buffer }; this.hls.trigger(Events.BUFFER_APPENDING, segment); if (data.dropped && data.independent && !part) { if (noBacktracking) { return; } this.flushBufferGap(frag); } } flushBufferGap(frag) { const media = this.media; if (!media) { return; } if (!BufferHelper.isBuffered(media, media.currentTime)) { this.flushMainBuffer(0, frag.start); return; } const currentTime = media.currentTime; const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0); const fragDuration = frag.duration; const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25); const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction); if (frag.start - start > segmentFraction) { this.flushMainBuffer(start, frag.start); } } getFwdBufferInfo(bufferable, type) { const pos = this.getLoadPosition(); if (!isFiniteNumber(pos)) { return null; } return this.getFwdBufferInfoAtPos(bufferable, pos, type); } getFwdBufferInfoAtPos(bufferable, pos, type) { const { config: { maxBufferHole } } = this; const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole); if (bufferInfo.len === 0 && bufferInfo.nextStart !== void 0) { const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type); if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) { return BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, maxBufferHole)); } } return bufferInfo; } getMaxBufferLength(levelBitrate) { const { config } = this; let maxBufLen; if (levelBitrate) { maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength); } else { maxBufLen = config.maxBufferLength; } return Math.min(maxBufLen, config.maxMaxBufferLength); } reduceMaxBufferLength(threshold, fragDuration) { const config = this.config; const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration); const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength); if (reducedLength >= minLength) { config.maxMaxBufferLength = reducedLength; this.warn(`Reduce max buffer length to ${reducedLength}s`); return true; } return false; } getAppendedFrag(position2, playlistType = PlaylistLevelType.MAIN) { const fragOrPart = this.fragmentTracker.getAppendedFrag(position2, PlaylistLevelType.MAIN); if (fragOrPart && "fragment" in fragOrPart) { return fragOrPart.fragment; } return fragOrPart; } getNextFragment(pos, levelDetails) { const fragments = levelDetails.fragments; const fragLen = fragments.length; if (!fragLen) { return null; } const { config } = this; const start = fragments[0].start; let frag; if (levelDetails.live) { const initialLiveManifestSize = config.initialLiveManifestSize; if (fragLen < initialLiveManifestSize) { this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`); return null; } if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) { frag = this.getInitialLiveFragment(levelDetails, fragments); this.startPosition = this.nextLoadPosition = frag ? this.hls.liveSyncPosition || frag.start : pos; } } else if (pos <= start) { frag = fragments[0]; } if (!frag) { const end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd; frag = this.getFragmentAtPosition(pos, end, levelDetails); } return this.mapToInitFragWhenRequired(frag); } isLoopLoading(frag, targetBufferTime) { const trackerState = this.fragmentTracker.getState(frag); return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime; } getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) { const gapStart = frag.gap; const nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails); if (nextFragment === null) { return nextFragment; } frag = nextFragment; if (gapStart && frag && !frag.gap && bufferInfo.nextStart) { const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType); if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) { this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${frag.sn}`); return null; } } return frag; } mapToInitFragWhenRequired(frag) { if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) { return frag.initSegment; } return frag; } getNextPart(partList, frag, targetBufferTime) { let nextPart = -1; let contiguous = false; let independentAttrOmitted = true; for (let i3 = 0, len = partList.length; i3 < len; i3++) { const part = partList[i3]; independentAttrOmitted = independentAttrOmitted && !part.independent; if (nextPart > -1 && targetBufferTime < part.start) { break; } const loaded = part.loaded; if (loaded) { nextPart = -1; } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) { nextPart = i3; } contiguous = loaded; } return nextPart; } loadedEndOfParts(partList, targetBufferTime) { const lastPart = partList[partList.length - 1]; return lastPart && targetBufferTime > lastPart.start && lastPart.loaded; } /* This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real start and end times for each fragment in the playlist (after which this method will not need to be called). */ getInitialLiveFragment(levelDetails, fragments) { const fragPrevious = this.fragPrevious; let frag = null; if (fragPrevious) { if (levelDetails.hasProgramDateTime) { this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`); frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance); } if (!frag) { const targetSN = fragPrevious.sn + 1; if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) { const fragNext = fragments[targetSN - levelDetails.startSN]; if (fragPrevious.cc === fragNext.cc) { frag = fragNext; this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`); } } if (!frag) { frag = findFragWithCC(fragments, fragPrevious.cc); if (frag) { this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`); } } } } else { const liveStart = this.hls.liveSyncPosition; if (liveStart !== null) { frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails); } } return frag; } /* This method finds the best matching fragment given the provided position. */ getFragmentAtPosition(bufferEnd, end, levelDetails) { const { config } = this; let { fragPrevious } = this; let { fragments, endSN } = levelDetails; const { fragmentHint } = levelDetails; const { maxFragLookUpTolerance } = config; const partList = levelDetails.partList; const loadingParts = !!(config.lowLatencyMode && partList != null && partList.length && fragmentHint); if (loadingParts && fragmentHint && !this.bitrateTest) { fragments = fragments.concat(fragmentHint); endSN = fragmentHint.sn; } let frag; if (bufferEnd < end) { const lookupTolerance = bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance; frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance); } else { frag = fragments[fragments.length - 1]; } if (frag) { const curSNIdx = frag.sn - levelDetails.startSN; const fragState = this.fragmentTracker.getState(frag); if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) { fragPrevious = frag; } if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn)) { const sameLevel = fragPrevious && frag.level === fragPrevious.level; if (sameLevel) { const nextFrag = fragments[curSNIdx + 1]; if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) { frag = nextFrag; } else { frag = null; } } } } return frag; } synchronizeToLiveEdge(levelDetails) { const { config, media } = this; if (!media) { return; } const liveSyncPosition = this.hls.liveSyncPosition; const currentTime = media.currentTime; const start = levelDetails.fragments[0].start; const end = levelDetails.edge; const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) { const maxLatency = config.liveMaxLatencyDuration !== void 0 ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration; if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) { if (!this.loadedmetadata) { this.nextLoadPosition = liveSyncPosition; } if (media.readyState) { this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`); media.currentTime = liveSyncPosition; } } } } alignPlaylists(details, previousDetails, switchDetails) { const length2 = details.fragments.length; if (!length2) { this.warn(`No fragments in live playlist`); return 0; } const slidingStart = details.fragments[0].start; const firstLevelLoad = !previousDetails; const aligned = details.alignedSliding && isFiniteNumber(slidingStart); if (firstLevelLoad || !aligned && !slidingStart) { const { fragPrevious } = this; alignStream(fragPrevious, switchDetails, details); const alignedSlidingStart = details.fragments[0].start; this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : "na"}->${details.startSN} prev-sn: ${fragPrevious ? fragPrevious.sn : "na"} fragments: ${length2}`); return alignedSlidingStart; } return slidingStart; } waitForCdnTuneIn(details) { const advancePartLimit = 3; return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit); } setStartPosition(details, sliding) { let startPosition = this.startPosition; if (startPosition < sliding) { startPosition = -1; } if (startPosition === -1 || this.lastCurrentTime === -1) { const offsetInMultivariantPlaylist = this.startTimeOffset !== null; const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset; if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) { startPosition = sliding + startTimeOffset; if (startTimeOffset < 0) { startPosition += details.totalduration; } startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration); this.log(`Start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? "multivariant" : "media"} playlist, adjust startPosition to ${startPosition}`); this.startPosition = startPosition; } else if (details.live) { startPosition = this.hls.liveSyncPosition || sliding; } else { this.startPosition = startPosition = 0; } this.lastCurrentTime = startPosition; } this.nextLoadPosition = startPosition; } getLoadPosition() { const { media } = this; let pos = 0; if (this.loadedmetadata && media) { pos = media.currentTime; } else if (this.nextLoadPosition) { pos = this.nextLoadPosition; } return pos; } handleFragLoadAborted(frag, part) { if (this.transmuxer && frag.sn !== "initSegment" && frag.stats.aborted) { this.warn(`Fragment ${frag.sn}${part ? " part " + part.index : ""} of level ${frag.level} was aborted`); this.resetFragmentLoading(frag); } } resetFragmentLoading(frag) { if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) { this.state = State.IDLE; } } onFragmentOrKeyLoadError(filterType, data) { if (data.chunkMeta && !data.frag) { const context = this.getCurrentContext(data.chunkMeta); if (context) { data.frag = context.frag; } } const frag = data.frag; if (!frag || frag.type !== filterType || !this.levels) { return; } if (this.fragContextChanged(frag)) { var _this$fragCurrent2; this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent2 = this.fragCurrent) == null ? void 0 : _this$fragCurrent2.url}`); return; } const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP; if (gapTagEncountered) { this.fragmentTracker.fragBuffered(frag, true); } const errorAction = data.errorAction; const { action, retryCount = 0, retryConfig } = errorAction || {}; if (errorAction && action === NetworkErrorAction.RetryRequest && retryConfig) { this.resetStartWhenNotLoaded(this.levelLastLoaded); const delay2 = getRetryDelay(retryConfig, retryCount); this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay2}ms`); errorAction.resolved = true; this.retryDate = self.performance.now() + delay2; this.state = State.FRAG_LOADING_WAITING_RETRY; } else if (retryConfig && errorAction) { this.resetFragmentErrors(filterType); if (retryCount < retryConfig.maxNumRetry) { if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) { errorAction.resolved = true; } } else { logger.warn(`${data.details} reached or exceeded max retry (${retryCount})`); return; } } else if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox) { this.state = State.WAITING_LEVEL; } else { this.state = State.ERROR; } this.tickImmediate(); } reduceLengthAndFlushBuffer(data) { if (this.state === State.PARSING || this.state === State.PARSED) { const frag = data.frag; const playlistType = data.parent; const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType); const buffered = bufferedInfo && bufferedInfo.len > 0.5; if (buffered) { this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10); } const flushBuffer = !buffered; if (flushBuffer) { this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`); } if (frag) { this.fragmentTracker.removeFragment(frag); this.nextLoadPosition = frag.start; } this.resetLoadingState(); return flushBuffer; } return false; } resetFragmentErrors(filterType) { if (filterType === PlaylistLevelType.AUDIO) { this.fragCurrent = null; } if (!this.loadedmetadata) { this.startFragRequested = false; } if (this.state !== State.STOPPED) { this.state = State.IDLE; } } afterBufferFlushed(media, bufferType, playlistType) { if (!media) { return; } const bufferedTimeRanges = BufferHelper.getBuffered(media); this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType); if (this.state === State.ENDED) { this.resetLoadingState(); } } resetLoadingState() { this.log("Reset loading state"); this.fragCurrent = null; this.fragPrevious = null; this.state = State.IDLE; } resetStartWhenNotLoaded(level) { if (!this.loadedmetadata) { this.startFragRequested = false; const details = level ? level.details : null; if (details != null && details.live) { this.startPosition = -1; this.setStartPosition(details, 0); this.resetLoadingState(); } else { this.nextLoadPosition = this.startPosition; } } } resetWhenMissingContext(chunkMeta) { this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`); this.removeUnbufferedFrags(); this.resetStartWhenNotLoaded(this.levelLastLoaded); this.resetLoadingState(); } removeUnbufferedFrags(start = 0) { this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true); } updateLevelTiming(frag, part, level, partial) { var _this$transmuxer; const details = level.details; if (!details) { this.warn("level.details undefined"); return; } const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => { const info = frag.elementaryStreams[type]; if (info) { const parsedDuration = info.endPTS - info.startPTS; if (parsedDuration <= 0) { this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`); return result || false; } const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS); this.hls.trigger(Events.LEVEL_PTS_UPDATED, { details, level, drift, type, frag, start: info.startPTS, end: info.endPTS }); return true; } return result; }, false); if (!parsed && ((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) { const error = new Error(`Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`); if (level.fragmentError === 0) { level.fragmentError++; frag.gap = true; this.fragmentTracker.removeFragment(frag); this.fragmentTracker.fragBuffered(frag, true); } this.warn(error.message); this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, error, frag, reason: `Found no media in msn ${frag.sn} of level "${level.url}"` }); if (!this.hls) { return; } this.resetTransmuxer(); } this.state = State.PARSED; this.hls.trigger(Events.FRAG_PARSED, { frag, part }); } resetTransmuxer() { if (this.transmuxer) { this.transmuxer.destroy(); this.transmuxer = null; } } recoverWorkerError(data) { if (data.event === "demuxerWorker") { this.fragmentTracker.removeAllFragments(); this.resetTransmuxer(); this.resetStartWhenNotLoaded(this.levelLastLoaded); this.resetLoadingState(); } } set state(nextState) { const previousState = this._state; if (previousState !== nextState) { this._state = nextState; this.log(`${previousState}->${nextState}`); } } get state() { return this._state; } }; var ChunkCache = class { constructor() { this.chunks = []; this.dataLength = 0; } push(chunk) { this.chunks.push(chunk); this.dataLength += chunk.length; } flush() { const { chunks, dataLength } = this; let result; if (!chunks.length) { return new Uint8Array(0); } else if (chunks.length === 1) { result = chunks[0]; } else { result = concatUint8Arrays(chunks, dataLength); } this.reset(); return result; } reset() { this.chunks.length = 0; this.dataLength = 0; } }; function concatUint8Arrays(chunks, dataLength) { const result = new Uint8Array(dataLength); let offset = 0; for (let i3 = 0; i3 < chunks.length; i3++) { const chunk = chunks[i3]; result.set(chunk, offset); offset += chunk.length; } return result; } function hasUMDWorker() { return typeof __HLS_WORKER_BUNDLE__ === "function"; } function injectWorker() { const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], { type: "text/javascript" }); const objectURL = self.URL.createObjectURL(blob); const worker = new self.Worker(objectURL); return { worker, objectURL }; } function loadWorker(path) { const scriptURL = new self.URL(path, self.location.href).href; const worker = new self.Worker(scriptURL); return { worker, scriptURL }; } function dummyTrack(type = "", inputTimeScale = 9e4) { return { type, id: -1, pid: -1, inputTimeScale, sequenceNumber: -1, samples: [], dropped: 0 }; } var BaseAudioDemuxer = class { constructor() { this._audioTrack = void 0; this._id3Track = void 0; this.frameIndex = 0; this.cachedData = null; this.basePTS = null; this.initPTS = null; this.lastPTS = null; } resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) { this._id3Track = { type: "id3", id: 3, pid: -1, inputTimeScale: 9e4, sequenceNumber: 0, samples: [], dropped: 0 }; } resetTimeStamp(deaultTimestamp) { this.initPTS = deaultTimestamp; this.resetContiguity(); } resetContiguity() { this.basePTS = null; this.lastPTS = null; this.frameIndex = 0; } canParse(data, offset) { return false; } appendFrame(track, data, offset) { } // feed incoming data to the front of the parsing pipeline demux(data, timeOffset) { if (this.cachedData) { data = appendUint8Array(this.cachedData, data); this.cachedData = null; } let id3Data = getID3Data(data, 0); let offset = id3Data ? id3Data.length : 0; let lastDataIndex; const track = this._audioTrack; const id3Track = this._id3Track; const timestamp = id3Data ? getTimeStamp(id3Data) : void 0; const length2 = data.length; if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) { this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS); this.lastPTS = this.basePTS; } if (this.lastPTS === null) { this.lastPTS = this.basePTS; } if (id3Data && id3Data.length > 0) { id3Track.samples.push({ pts: this.lastPTS, dts: this.lastPTS, data: id3Data, type: MetadataSchema.audioId3, duration: Number.POSITIVE_INFINITY }); } while (offset < length2) { if (this.canParse(data, offset)) { const frame = this.appendFrame(track, data, offset); if (frame) { this.frameIndex++; this.lastPTS = frame.sample.pts; offset += frame.length; lastDataIndex = offset; } else { offset = length2; } } else if (canParse$2(data, offset)) { id3Data = getID3Data(data, offset); id3Track.samples.push({ pts: this.lastPTS, dts: this.lastPTS, data: id3Data, type: MetadataSchema.audioId3, duration: Number.POSITIVE_INFINITY }); offset += id3Data.length; lastDataIndex = offset; } else { offset++; } if (offset === length2 && lastDataIndex !== length2) { const partialData = sliceUint8(data, lastDataIndex); if (this.cachedData) { this.cachedData = appendUint8Array(this.cachedData, partialData); } else { this.cachedData = partialData; } } } return { audioTrack: track, videoTrack: dummyTrack(), id3Track, textTrack: dummyTrack() }; } demuxSampleAes(data, keyData, timeOffset) { return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`)); } flush(timeOffset) { const cachedData = this.cachedData; if (cachedData) { this.cachedData = null; this.demux(cachedData, 0); } return { audioTrack: this._audioTrack, videoTrack: dummyTrack(), id3Track: this._id3Track, textTrack: dummyTrack() }; } destroy() { } }; var initPTSFn = (timestamp, timeOffset, initPTS) => { if (isFiniteNumber(timestamp)) { return timestamp * 90; } const init90kHz = initPTS ? initPTS.baseTime * 9e4 / initPTS.timescale : 0; return timeOffset * 9e4 + init90kHz; }; function getAudioConfig(observer2, data, offset, audioCodec) { let adtsObjectType; let adtsExtensionSamplingIndex; let adtsChannelConfig; let config; const userAgent = navigator.userAgent.toLowerCase(); const manifestCodec = audioCodec; const adtsSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350]; adtsObjectType = ((data[offset + 2] & 192) >>> 6) + 1; const adtsSamplingIndex = (data[offset + 2] & 60) >>> 2; if (adtsSamplingIndex > adtsSamplingRates.length - 1) { const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`); observer2.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, error, reason: error.message }); return; } adtsChannelConfig = (data[offset + 2] & 1) << 2; adtsChannelConfig |= (data[offset + 3] & 192) >>> 6; logger.log(`manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`); if (/firefox/i.test(userAgent)) { if (adtsSamplingIndex >= 6) { adtsObjectType = 5; config = new Array(4); adtsExtensionSamplingIndex = adtsSamplingIndex - 3; } else { adtsObjectType = 2; config = new Array(2); adtsExtensionSamplingIndex = adtsSamplingIndex; } } else if (userAgent.indexOf("android") !== -1) { adtsObjectType = 2; config = new Array(2); adtsExtensionSamplingIndex = adtsSamplingIndex; } else { adtsObjectType = 5; config = new Array(4); if (audioCodec && (audioCodec.indexOf("mp4a.40.29") !== -1 || audioCodec.indexOf("mp4a.40.5") !== -1) || !audioCodec && adtsSamplingIndex >= 6) { adtsExtensionSamplingIndex = adtsSamplingIndex - 3; } else { if (audioCodec && audioCodec.indexOf("mp4a.40.2") !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) { adtsObjectType = 2; config = new Array(2); } adtsExtensionSamplingIndex = adtsSamplingIndex; } } config[0] = adtsObjectType << 3; config[0] |= (adtsSamplingIndex & 14) >> 1; config[1] |= (adtsSamplingIndex & 1) << 7; config[1] |= adtsChannelConfig << 3; if (adtsObjectType === 5) { config[1] |= (adtsExtensionSamplingIndex & 14) >> 1; config[2] = (adtsExtensionSamplingIndex & 1) << 7; config[2] |= 2 << 2; config[3] = 0; } return { config, samplerate: adtsSamplingRates[adtsSamplingIndex], channelCount: adtsChannelConfig, codec: "mp4a.40." + adtsObjectType, manifestCodec }; } function isHeaderPattern$1(data, offset) { return data[offset] === 255 && (data[offset + 1] & 246) === 240; } function getHeaderLength(data, offset) { return data[offset + 1] & 1 ? 7 : 9; } function getFullFrameLength(data, offset) { return (data[offset + 3] & 3) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 224) >>> 5; } function canGetFrameLength(data, offset) { return offset + 5 < data.length; } function isHeader$1(data, offset) { return offset + 1 < data.length && isHeaderPattern$1(data, offset); } function canParse$1(data, offset) { return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset; } function probe$1(data, offset) { if (isHeader$1(data, offset)) { const headerLength = getHeaderLength(data, offset); if (offset + headerLength >= data.length) { return false; } const frameLength = getFullFrameLength(data, offset); if (frameLength <= headerLength) { return false; } const newOffset = offset + frameLength; return newOffset === data.length || isHeader$1(data, newOffset); } return false; } function initTrackConfig(track, observer2, data, offset, audioCodec) { if (!track.samplerate) { const config = getAudioConfig(observer2, data, offset, audioCodec); if (!config) { return; } track.config = config.config; track.samplerate = config.samplerate; track.channelCount = config.channelCount; track.codec = config.codec; track.manifestCodec = config.manifestCodec; logger.log(`parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`); } } function getFrameDuration(samplerate) { return 1024 * 9e4 / samplerate; } function parseFrameHeader(data, offset) { const headerLength = getHeaderLength(data, offset); if (offset + headerLength <= data.length) { const frameLength = getFullFrameLength(data, offset) - headerLength; if (frameLength > 0) { return { headerLength, frameLength }; } } } function appendFrame$2(track, data, offset, pts, frameIndex) { const frameDuration = getFrameDuration(track.samplerate); const stamp = pts + frameIndex * frameDuration; const header = parseFrameHeader(data, offset); let unit; if (header) { const { frameLength, headerLength } = header; const _length = headerLength + frameLength; const missing = Math.max(0, offset + _length - data.length); if (missing) { unit = new Uint8Array(_length - headerLength); unit.set(data.subarray(offset + headerLength, data.length), 0); } else { unit = data.subarray(offset + headerLength, offset + _length); } const _sample = { unit, pts: stamp }; if (!missing) { track.samples.push(_sample); } return { sample: _sample, length: _length, missing }; } const length2 = data.length - offset; unit = new Uint8Array(length2); unit.set(data.subarray(offset, data.length), 0); const sample = { unit, pts: stamp }; return { sample, length: length2, missing: -1 }; } var chromeVersion$1 = null; var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; var SamplingRateMap = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3]; var SamplesCoefficients = [ // MPEG 2.5 [ 0, // Reserved 72, // Layer3 144, // Layer2 12 // Layer1 ], // Reserved [ 0, // Reserved 0, // Layer3 0, // Layer2 0 // Layer1 ], // MPEG 2 [ 0, // Reserved 72, // Layer3 144, // Layer2 12 // Layer1 ], // MPEG 1 [ 0, // Reserved 144, // Layer3 144, // Layer2 12 // Layer1 ] ]; var BytesInSlot = [ 0, // Reserved 1, // Layer3 1, // Layer2 4 // Layer1 ]; function appendFrame$1(track, data, offset, pts, frameIndex) { if (offset + 24 > data.length) { return; } const header = parseHeader(data, offset); if (header && offset + header.frameLength <= data.length) { const frameDuration = header.samplesPerFrame * 9e4 / header.sampleRate; const stamp = pts + frameIndex * frameDuration; const sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp }; track.config = []; track.channelCount = header.channelCount; track.samplerate = header.sampleRate; track.samples.push(sample); return { sample, length: header.frameLength, missing: 0 }; } } function parseHeader(data, offset) { const mpegVersion = data[offset + 1] >> 3 & 3; const mpegLayer = data[offset + 1] >> 1 & 3; const bitRateIndex = data[offset + 2] >> 4 & 15; const sampleRateIndex = data[offset + 2] >> 2 & 3; if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) { const paddingBit = data[offset + 2] >> 1 & 1; const channelMode = data[offset + 3] >> 6; const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4; const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1e3; const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2; const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex]; const channelCount = channelMode === 3 ? 1 : 2; const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer]; const bytesInSlot = BytesInSlot[mpegLayer]; const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot; const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot; if (chromeVersion$1 === null) { const userAgent = navigator.userAgent || ""; const result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion$1 = result ? parseInt(result[1]) : 0; } const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87; if (needChromeFix && mpegLayer === 2 && bitRate >= 224e3 && channelMode === 0) { data[offset + 3] = data[offset + 3] | 128; } return { sampleRate, channelCount, frameLength, samplesPerFrame }; } } function isHeaderPattern(data, offset) { return data[offset] === 255 && (data[offset + 1] & 224) === 224 && (data[offset + 1] & 6) !== 0; } function isHeader(data, offset) { return offset + 1 < data.length && isHeaderPattern(data, offset); } function canParse(data, offset) { const headerSize = 4; return isHeaderPattern(data, offset) && headerSize <= data.length - offset; } function probe(data, offset) { if (offset + 1 < data.length && isHeaderPattern(data, offset)) { const headerLength = 4; const header = parseHeader(data, offset); let frameLength = headerLength; if (header != null && header.frameLength) { frameLength = header.frameLength; } const newOffset = offset + frameLength; return newOffset === data.length || isHeader(data, newOffset); } return false; } var AACDemuxer = class extends BaseAudioDemuxer { constructor(observer2, config) { super(); this.observer = void 0; this.config = void 0; this.observer = observer2; this.config = config; } resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) { super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration); this._audioTrack = { container: "audio/adts", type: "audio", id: 2, pid: -1, sequenceNumber: 0, segmentCodec: "aac", samples: [], manifestCodec: audioCodec, duration: trackDuration, inputTimeScale: 9e4, dropped: 0 }; } // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS static probe(data) { if (!data) { return false; } const id3Data = getID3Data(data, 0); let offset = (id3Data == null ? void 0 : id3Data.length) || 0; if (probe(data, offset)) { return false; } for (let length2 = data.length; offset < length2; offset++) { if (probe$1(data, offset)) { logger.log("ADTS sync word found !"); return true; } } return false; } canParse(data, offset) { return canParse$1(data, offset); } appendFrame(track, data, offset) { initTrackConfig(track, this.observer, data, offset, track.manifestCodec); const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex); if (frame && frame.missing === 0) { return frame; } } }; var emsgSchemePattern = /\/emsg[-/]ID3/i; var MP4Demuxer = class { constructor(observer2, config) { this.remainderData = null; this.timeOffset = 0; this.config = void 0; this.videoTrack = void 0; this.audioTrack = void 0; this.id3Track = void 0; this.txtTrack = void 0; this.config = config; } resetTimeStamp() { } resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) { const videoTrack = this.videoTrack = dummyTrack("video", 1); const audioTrack = this.audioTrack = dummyTrack("audio", 1); const captionTrack = this.txtTrack = dummyTrack("text", 1); this.id3Track = dummyTrack("id3", 1); this.timeOffset = 0; if (!(initSegment != null && initSegment.byteLength)) { return; } const initData = parseInitSegment(initSegment); if (initData.video) { const { id, timescale, codec } = initData.video; videoTrack.id = id; videoTrack.timescale = captionTrack.timescale = timescale; videoTrack.codec = codec; } if (initData.audio) { const { id, timescale, codec } = initData.audio; audioTrack.id = id; audioTrack.timescale = timescale; audioTrack.codec = codec; } captionTrack.id = RemuxerTrackIdConfig.text; videoTrack.sampleDuration = 0; videoTrack.duration = audioTrack.duration = trackDuration; } resetContiguity() { this.remainderData = null; } static probe(data) { return hasMoofData(data); } demux(data, timeOffset) { this.timeOffset = timeOffset; let videoSamples = data; const videoTrack = this.videoTrack; const textTrack = this.txtTrack; if (this.config.progressive) { if (this.remainderData) { videoSamples = appendUint8Array(this.remainderData, data); } const segmentedData = segmentValidRange(videoSamples); this.remainderData = segmentedData.remainder; videoTrack.samples = segmentedData.valid || new Uint8Array(); } else { videoTrack.samples = videoSamples; } const id3Track = this.extractID3Track(videoTrack, timeOffset); textTrack.samples = parseSamples(timeOffset, videoTrack); return { videoTrack, audioTrack: this.audioTrack, id3Track, textTrack: this.txtTrack }; } flush() { const timeOffset = this.timeOffset; const videoTrack = this.videoTrack; const textTrack = this.txtTrack; videoTrack.samples = this.remainderData || new Uint8Array(); this.remainderData = null; const id3Track = this.extractID3Track(videoTrack, this.timeOffset); textTrack.samples = parseSamples(timeOffset, videoTrack); return { videoTrack, audioTrack: dummyTrack(), id3Track, textTrack: dummyTrack() }; } extractID3Track(videoTrack, timeOffset) { const id3Track = this.id3Track; if (videoTrack.samples.length) { const emsgs = findBox(videoTrack.samples, ["emsg"]); if (emsgs) { emsgs.forEach((data) => { const emsgInfo = parseEmsg(data); if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) { const pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale; let duration = emsgInfo.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale; if (duration <= 1e-3) { duration = Number.POSITIVE_INFINITY; } const payload = emsgInfo.payload; id3Track.samples.push({ data: payload, len: payload.byteLength, dts: pts, pts, type: MetadataSchema.emsg, duration }); } }); } } return id3Track; } demuxSampleAes(data, keyData, timeOffset) { return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption")); } destroy() { } }; var getAudioBSID = (data, offset) => { let bsid = 0; let numBits = 5; offset += numBits; const temp = new Uint32Array(1); const mask = new Uint32Array(1); const byte = new Uint8Array(1); while (numBits > 0) { byte[0] = data[offset]; const bits = Math.min(numBits, 8); const shift = 8 - bits; mask[0] = 4278190080 >>> 24 + shift << shift; temp[0] = (byte[0] & mask[0]) >> shift; bsid = !bsid ? temp[0] : bsid << bits | temp[0]; offset += 1; numBits -= bits; } return bsid; }; var AC3Demuxer = class extends BaseAudioDemuxer { constructor(observer2) { super(); this.observer = void 0; this.observer = observer2; } resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) { super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration); this._audioTrack = { container: "audio/ac-3", type: "audio", id: 2, pid: -1, sequenceNumber: 0, segmentCodec: "ac3", samples: [], manifestCodec: audioCodec, duration: trackDuration, inputTimeScale: 9e4, dropped: 0 }; } canParse(data, offset) { return offset + 64 < data.length; } appendFrame(track, data, offset) { const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex); if (frameLength !== -1) { const sample = track.samples[track.samples.length - 1]; return { sample, length: frameLength, missing: 0 }; } } static probe(data) { if (!data) { return false; } const id3Data = getID3Data(data, 0); if (!id3Data) { return false; } const offset = id3Data.length; if (data[offset] === 11 && data[offset + 1] === 119 && getTimeStamp(id3Data) !== void 0 && // check the bsid to confirm ac-3 getAudioBSID(data, offset) < 16) { return true; } return false; } }; function appendFrame(track, data, start, pts, frameIndex) { if (start + 8 > data.length) { return -1; } if (data[start] !== 11 || data[start + 1] !== 119) { return -1; } const samplingRateCode = data[start + 4] >> 6; if (samplingRateCode >= 3) { return -1; } const samplingRateMap = [48e3, 44100, 32e3]; const sampleRate = samplingRateMap[samplingRateCode]; const frameSizeCode = data[start + 4] & 63; const frameSizeMap = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920]; const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2; if (start + frameLength > data.length) { return -1; } const channelMode = data[start + 6] >> 5; let skipCount = 0; if (channelMode === 2) { skipCount += 2; } else { if (channelMode & 1 && channelMode !== 1) { skipCount += 2; } if (channelMode & 4) { skipCount += 2; } } const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1; const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5]; const channelCount = channelsMap[channelMode] + lfeon; const bsid = data[start + 5] >> 3; const bsmod = data[start + 5] & 7; const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 224]); const frameDuration = 1536 / sampleRate * 9e4; const stamp = pts + frameIndex * frameDuration; const unit = data.subarray(start, start + frameLength); track.config = config; track.channelCount = channelCount; track.samplerate = sampleRate; track.samples.push({ unit, pts: stamp }); return frameLength; } var BaseVideoParser = class { constructor() { this.VideoSample = null; } createVideoSample(key, pts, dts, debug) { return { key, frame: false, pts, dts, units: [], debug, length: 0 }; } getLastNalUnit(samples) { var _VideoSample; let VideoSample = this.VideoSample; let lastUnit; if (!VideoSample || VideoSample.units.length === 0) { VideoSample = samples[samples.length - 1]; } if ((_VideoSample = VideoSample) != null && _VideoSample.units) { const units = VideoSample.units; lastUnit = units[units.length - 1]; } return lastUnit; } pushAccessUnit(VideoSample, videoTrack) { if (VideoSample.units.length && VideoSample.frame) { if (VideoSample.pts === void 0) { const samples = videoTrack.samples; const nbSamples = samples.length; if (nbSamples) { const lastSample = samples[nbSamples - 1]; VideoSample.pts = lastSample.pts; VideoSample.dts = lastSample.dts; } else { videoTrack.dropped++; return; } } videoTrack.samples.push(VideoSample); } if (VideoSample.debug.length) { logger.log(VideoSample.pts + "/" + VideoSample.dts + ":" + VideoSample.debug); } } }; var ExpGolomb = class { constructor(data) { this.data = void 0; this.bytesAvailable = void 0; this.word = void 0; this.bitsAvailable = void 0; this.data = data; this.bytesAvailable = data.byteLength; this.word = 0; this.bitsAvailable = 0; } // ():void loadWord() { const data = this.data; const bytesAvailable = this.bytesAvailable; const position2 = data.byteLength - bytesAvailable; const workingBytes = new Uint8Array(4); const availableBytes = Math.min(4, bytesAvailable); if (availableBytes === 0) { throw new Error("no bytes available"); } workingBytes.set(data.subarray(position2, position2 + availableBytes)); this.word = new DataView(workingBytes.buffer).getUint32(0); this.bitsAvailable = availableBytes * 8; this.bytesAvailable -= availableBytes; } // (count:int):void skipBits(count) { let skipBytes; count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable); if (this.bitsAvailable > count) { this.word <<= count; this.bitsAvailable -= count; } else { count -= this.bitsAvailable; skipBytes = count >> 3; count -= skipBytes << 3; this.bytesAvailable -= skipBytes; this.loadWord(); this.word <<= count; this.bitsAvailable -= count; } } // (size:int):uint readBits(size) { let bits = Math.min(this.bitsAvailable, size); const valu = this.word >>> 32 - bits; if (size > 32) { logger.error("Cannot read more than 32 bits at a time"); } this.bitsAvailable -= bits; if (this.bitsAvailable > 0) { this.word <<= bits; } else if (this.bytesAvailable > 0) { this.loadWord(); } else { throw new Error("no bits available"); } bits = size - bits; if (bits > 0 && this.bitsAvailable) { return valu << bits | this.readBits(bits); } else { return valu; } } // ():uint skipLZ() { let leadingZeroCount; for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { if ((this.word & 2147483648 >>> leadingZeroCount) !== 0) { this.word <<= leadingZeroCount; this.bitsAvailable -= leadingZeroCount; return leadingZeroCount; } } this.loadWord(); return leadingZeroCount + this.skipLZ(); } // ():void skipUEG() { this.skipBits(1 + this.skipLZ()); } // ():void skipEG() { this.skipBits(1 + this.skipLZ()); } // ():uint readUEG() { const clz = this.skipLZ(); return this.readBits(clz + 1) - 1; } // ():int readEG() { const valu = this.readUEG(); if (1 & valu) { return 1 + valu >>> 1; } else { return -1 * (valu >>> 1); } } // Some convenience functions // :Boolean readBoolean() { return this.readBits(1) === 1; } // ():int readUByte() { return this.readBits(8); } // ():int readUShort() { return this.readBits(16); } // ():int readUInt() { return this.readBits(32); } /** * Advance the ExpGolomb decoder past a scaling list. The scaling * list is optionally transmitted as part of a sequence parameter * set and is not relevant to transmuxing. * @param count the number of entries in this scaling list * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 */ skipScalingList(count) { let lastScale = 8; let nextScale = 8; let deltaScale; for (let j3 = 0; j3 < count; j3++) { if (nextScale !== 0) { deltaScale = this.readEG(); nextScale = (lastScale + deltaScale + 256) % 256; } lastScale = nextScale === 0 ? lastScale : nextScale; } } /** * Read a sequence parameter set and return some interesting video * properties. A sequence parameter set is the H264 metadata that * describes the properties of upcoming video frames. * @returns an object with configuration parsed from the * sequence parameter set, including the dimensions of the * associated video frames. */ readSPS() { let frameCropLeftOffset = 0; let frameCropRightOffset = 0; let frameCropTopOffset = 0; let frameCropBottomOffset = 0; let numRefFramesInPicOrderCntCycle; let scalingListCount; let i3; const readUByte = this.readUByte.bind(this); const readBits = this.readBits.bind(this); const readUEG = this.readUEG.bind(this); const readBoolean = this.readBoolean.bind(this); const skipBits = this.skipBits.bind(this); const skipEG = this.skipEG.bind(this); const skipUEG = this.skipUEG.bind(this); const skipScalingList = this.skipScalingList.bind(this); readUByte(); const profileIdc = readUByte(); readBits(5); skipBits(3); readUByte(); skipUEG(); if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) { const chromaFormatIdc = readUEG(); if (chromaFormatIdc === 3) { skipBits(1); } skipUEG(); skipUEG(); skipBits(1); if (readBoolean()) { scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; for (i3 = 0; i3 < scalingListCount; i3++) { if (readBoolean()) { if (i3 < 6) { skipScalingList(16); } else { skipScalingList(64); } } } } } skipUEG(); const picOrderCntType = readUEG(); if (picOrderCntType === 0) { readUEG(); } else if (picOrderCntType === 1) { skipBits(1); skipEG(); skipEG(); numRefFramesInPicOrderCntCycle = readUEG(); for (i3 = 0; i3 < numRefFramesInPicOrderCntCycle; i3++) { skipEG(); } } skipUEG(); skipBits(1); const picWidthInMbsMinus1 = readUEG(); const picHeightInMapUnitsMinus1 = readUEG(); const frameMbsOnlyFlag = readBits(1); if (frameMbsOnlyFlag === 0) { skipBits(1); } skipBits(1); if (readBoolean()) { frameCropLeftOffset = readUEG(); frameCropRightOffset = readUEG(); frameCropTopOffset = readUEG(); frameCropBottomOffset = readUEG(); } let pixelRatio = [1, 1]; if (readBoolean()) { if (readBoolean()) { const aspectRatioIdc = readUByte(); switch (aspectRatioIdc) { case 1: pixelRatio = [1, 1]; break; case 2: pixelRatio = [12, 11]; break; case 3: pixelRatio = [10, 11]; break; case 4: pixelRatio = [16, 11]; break; case 5: pixelRatio = [40, 33]; break; case 6: pixelRatio = [24, 11]; break; case 7: pixelRatio = [20, 11]; break; case 8: pixelRatio = [32, 11]; break; case 9: pixelRatio = [80, 33]; break; case 10: pixelRatio = [18, 11]; break; case 11: pixelRatio = [15, 11]; break; case 12: pixelRatio = [64, 33]; break; case 13: pixelRatio = [160, 99]; break; case 14: pixelRatio = [4, 3]; break; case 15: pixelRatio = [3, 2]; break; case 16: pixelRatio = [2, 1]; break; case 255: { pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()]; break; } } } } return { width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2), height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset), pixelRatio }; } readSliceType() { this.readUByte(); this.readUEG(); return this.readUEG(); } }; var AvcVideoParser = class extends BaseVideoParser { parseAVCPES(track, textTrack, pes, last, duration) { const units = this.parseAVCNALu(track, pes.data); let VideoSample = this.VideoSample; let push2; let spsfound = false; pes.data = null; if (VideoSample && units.length && !track.audFound) { this.pushAccessUnit(VideoSample, track); VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, ""); } units.forEach((unit) => { var _VideoSample2; switch (unit.type) { case 1: { let iskey = false; push2 = true; const data = unit.data; if (spsfound && data.length > 4) { const sliceType = new ExpGolomb(data).readSliceType(); if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) { iskey = true; } } if (iskey) { var _VideoSample; if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) { this.pushAccessUnit(VideoSample, track); VideoSample = this.VideoSample = null; } } if (!VideoSample) { VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, ""); } VideoSample.frame = true; VideoSample.key = iskey; break; } case 5: push2 = true; if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) { this.pushAccessUnit(VideoSample, track); VideoSample = this.VideoSample = null; } if (!VideoSample) { VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, ""); } VideoSample.key = true; VideoSample.frame = true; break; case 6: { push2 = true; parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples); break; } case 7: { var _track$pixelRatio, _track$pixelRatio2; push2 = true; spsfound = true; const sps = unit.data; const expGolombDecoder = new ExpGolomb(sps); const config = expGolombDecoder.readSPS(); if (!track.sps || track.width !== config.width || track.height !== config.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) { track.width = config.width; track.height = config.height; track.pixelRatio = config.pixelRatio; track.sps = [sps]; track.duration = duration; const codecarray = sps.subarray(1, 4); let codecstring = "avc1."; for (let i3 = 0; i3 < 3; i3++) { let h3 = codecarray[i3].toString(16); if (h3.length < 2) { h3 = "0" + h3; } codecstring += h3; } track.codec = codecstring; } break; } case 8: push2 = true; track.pps = [unit.data]; break; case 9: push2 = true; track.audFound = true; if (VideoSample) { this.pushAccessUnit(VideoSample, track); } VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, ""); break; case 12: push2 = true; break; default: push2 = false; if (VideoSample) { VideoSample.debug += "unknown NAL " + unit.type + " "; } break; } if (VideoSample && push2) { const units2 = VideoSample.units; units2.push(unit); } }); if (last && VideoSample) { this.pushAccessUnit(VideoSample, track); this.VideoSample = null; } } parseAVCNALu(track, array) { const len = array.byteLength; let state = track.naluState || 0; const lastState = state; const units = []; let i3 = 0; let value; let overflow; let unitType; let lastUnitStart = -1; let lastUnitType = 0; if (state === -1) { lastUnitStart = 0; lastUnitType = array[0] & 31; state = 0; i3 = 1; } while (i3 < len) { value = array[i3++]; if (!state) { state = value ? 0 : 1; continue; } if (state === 1) { state = value ? 0 : 2; continue; } if (!value) { state = 3; } else if (value === 1) { overflow = i3 - state - 1; if (lastUnitStart >= 0) { const unit = { data: array.subarray(lastUnitStart, overflow), type: lastUnitType }; units.push(unit); } else { const lastUnit = this.getLastNalUnit(track.samples); if (lastUnit) { if (lastState && i3 <= 4 - lastState) { if (lastUnit.state) { lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState); } } if (overflow > 0) { lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow)); lastUnit.state = 0; } } } if (i3 < len) { unitType = array[i3] & 31; lastUnitStart = i3; lastUnitType = unitType; state = 0; } else { state = -1; } } else { state = 0; } } if (lastUnitStart >= 0 && state >= 0) { const unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state }; units.push(unit); } if (units.length === 0) { const lastUnit = this.getLastNalUnit(track.samples); if (lastUnit) { lastUnit.data = appendUint8Array(lastUnit.data, array); } } track.naluState = state; return units; } }; var SampleAesDecrypter = class { constructor(observer2, config, keyData) { this.keyData = void 0; this.decrypter = void 0; this.keyData = keyData; this.decrypter = new Decrypter(config, { removePKCS7Padding: false }); } decryptBuffer(encryptedData) { return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer); } // AAC - encrypt all full 16 bytes blocks starting from offset 16 decryptAacSample(samples, sampleIndex, callback) { const curUnit = samples[sampleIndex].unit; if (curUnit.length <= 16) { return; } const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16); const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length); this.decryptBuffer(encryptedBuffer).then((decryptedBuffer) => { const decryptedData = new Uint8Array(decryptedBuffer); curUnit.set(decryptedData, 16); if (!this.decrypter.isSync()) { this.decryptAacSamples(samples, sampleIndex + 1, callback); } }); } decryptAacSamples(samples, sampleIndex, callback) { for (; ; sampleIndex++) { if (sampleIndex >= samples.length) { callback(); return; } if (samples[sampleIndex].unit.length < 32) { continue; } this.decryptAacSample(samples, sampleIndex, callback); if (!this.decrypter.isSync()) { return; } } } // AVC - encrypt one 16 bytes block out of ten, starting from offset 32 getAvcEncryptedData(decodedData) { const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16; const encryptedData = new Int8Array(encryptedDataLen); let outputPos = 0; for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) { encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos); } return encryptedData; } getAvcDecryptedUnit(decodedData, decryptedData) { const uint8DecryptedData = new Uint8Array(decryptedData); let inputPos = 0; for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) { decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos); } return decodedData; } decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) { const decodedData = discardEPB(curUnit.data); const encryptedData = this.getAvcEncryptedData(decodedData); this.decryptBuffer(encryptedData.buffer).then((decryptedBuffer) => { curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer); if (!this.decrypter.isSync()) { this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback); } }); } decryptAvcSamples(samples, sampleIndex, unitIndex, callback) { if (samples instanceof Uint8Array) { throw new Error("Cannot decrypt samples of type Uint8Array"); } for (; ; sampleIndex++, unitIndex = 0) { if (sampleIndex >= samples.length) { callback(); return; } const curUnits = samples[sampleIndex].units; for (; ; unitIndex++) { if (unitIndex >= curUnits.length) { break; } const curUnit = curUnits[unitIndex]; if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) { continue; } this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit); if (!this.decrypter.isSync()) { return; } } } } }; var PACKET_LENGTH = 188; var TSDemuxer = class _TSDemuxer { constructor(observer2, config, typeSupported) { this.observer = void 0; this.config = void 0; this.typeSupported = void 0; this.sampleAes = null; this.pmtParsed = false; this.audioCodec = void 0; this.videoCodec = void 0; this._duration = 0; this._pmtId = -1; this._videoTrack = void 0; this._audioTrack = void 0; this._id3Track = void 0; this._txtTrack = void 0; this.aacOverFlow = null; this.remainderData = null; this.videoParser = void 0; this.observer = observer2; this.config = config; this.typeSupported = typeSupported; this.videoParser = new AvcVideoParser(); } static probe(data) { const syncOffset = _TSDemuxer.syncOffset(data); if (syncOffset > 0) { logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`); } return syncOffset !== -1; } static syncOffset(data) { const length2 = data.length; let scanwindow = Math.min(PACKET_LENGTH * 5, length2 - PACKET_LENGTH) + 1; let i3 = 0; while (i3 < scanwindow) { let foundPat = false; let packetStart = -1; let tsPackets = 0; for (let j3 = i3; j3 < length2; j3 += PACKET_LENGTH) { if (data[j3] === 71 && (length2 - j3 === PACKET_LENGTH || data[j3 + PACKET_LENGTH] === 71)) { tsPackets++; if (packetStart === -1) { packetStart = j3; if (packetStart !== 0) { scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1; } } if (!foundPat) { foundPat = parsePID(data, j3) === 0; } if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j3 + PACKET_LENGTH > scanwindow)) { return packetStart; } } else if (tsPackets) { return -1; } else { break; } } i3++; } return -1; } /** * Creates a track model internal to demuxer used to drive remuxing input */ static createTrack(type, duration) { return { container: type === "video" || type === "audio" ? "video/mp2t" : void 0, type, id: RemuxerTrackIdConfig[type], pid: -1, inputTimeScale: 9e4, sequenceNumber: 0, samples: [], dropped: 0, duration: type === "audio" ? duration : void 0 }; } /** * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start) * Resets all internal track instances of the demuxer. */ resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) { this.pmtParsed = false; this._pmtId = -1; this._videoTrack = _TSDemuxer.createTrack("video"); this._audioTrack = _TSDemuxer.createTrack("audio", trackDuration); this._id3Track = _TSDemuxer.createTrack("id3"); this._txtTrack = _TSDemuxer.createTrack("text"); this._audioTrack.segmentCodec = "aac"; this.aacOverFlow = null; this.remainderData = null; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this._duration = trackDuration; } resetTimeStamp() { } resetContiguity() { const { _audioTrack, _videoTrack, _id3Track } = this; if (_audioTrack) { _audioTrack.pesData = null; } if (_videoTrack) { _videoTrack.pesData = null; } if (_id3Track) { _id3Track.pesData = null; } this.aacOverFlow = null; this.remainderData = null; } demux(data, timeOffset, isSampleAes = false, flush = false) { if (!isSampleAes) { this.sampleAes = null; } let pes; const videoTrack = this._videoTrack; const audioTrack = this._audioTrack; const id3Track = this._id3Track; const textTrack = this._txtTrack; let videoPid = videoTrack.pid; let videoData = videoTrack.pesData; let audioPid = audioTrack.pid; let id3Pid = id3Track.pid; let audioData = audioTrack.pesData; let id3Data = id3Track.pesData; let unknownPID = null; let pmtParsed = this.pmtParsed; let pmtId = this._pmtId; let len = data.length; if (this.remainderData) { data = appendUint8Array(this.remainderData, data); len = data.length; this.remainderData = null; } if (len < PACKET_LENGTH && !flush) { this.remainderData = data; return { audioTrack, videoTrack, id3Track, textTrack }; } const syncOffset = Math.max(0, _TSDemuxer.syncOffset(data)); len -= (len - syncOffset) % PACKET_LENGTH; if (len < data.byteLength && !flush) { this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len); } let tsPacketErrors = 0; for (let start = syncOffset; start < len; start += PACKET_LENGTH) { if (data[start] === 71) { const stt = !!(data[start + 1] & 64); const pid = parsePID(data, start); const atf = (data[start + 3] & 48) >> 4; let offset; if (atf > 1) { offset = start + 5 + data[start + 4]; if (offset === start + PACKET_LENGTH) { continue; } } else { offset = start + 4; } switch (pid) { case videoPid: if (stt) { if (videoData && (pes = parsePES(videoData))) { this.videoParser.parseAVCPES(videoTrack, textTrack, pes, false, this._duration); } videoData = { data: [], size: 0 }; } if (videoData) { videoData.data.push(data.subarray(offset, start + PACKET_LENGTH)); videoData.size += start + PACKET_LENGTH - offset; } break; case audioPid: if (stt) { if (audioData && (pes = parsePES(audioData))) { switch (audioTrack.segmentCodec) { case "aac": this.parseAACPES(audioTrack, pes); break; case "mp3": this.parseMPEGPES(audioTrack, pes); break; case "ac3": { this.parseAC3PES(audioTrack, pes); } break; } } audioData = { data: [], size: 0 }; } if (audioData) { audioData.data.push(data.subarray(offset, start + PACKET_LENGTH)); audioData.size += start + PACKET_LENGTH - offset; } break; case id3Pid: if (stt) { if (id3Data && (pes = parsePES(id3Data))) { this.parseID3PES(id3Track, pes); } id3Data = { data: [], size: 0 }; } if (id3Data) { id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH)); id3Data.size += start + PACKET_LENGTH - offset; } break; case 0: if (stt) { offset += data[offset] + 1; } pmtId = this._pmtId = parsePAT(data, offset); break; case pmtId: { if (stt) { offset += data[offset] + 1; } const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer); videoPid = parsedPIDs.videoPid; if (videoPid > 0) { videoTrack.pid = videoPid; videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec; } audioPid = parsedPIDs.audioPid; if (audioPid > 0) { audioTrack.pid = audioPid; audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec; } id3Pid = parsedPIDs.id3Pid; if (id3Pid > 0) { id3Track.pid = id3Pid; } if (unknownPID !== null && !pmtParsed) { logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`); unknownPID = null; start = syncOffset - 188; } pmtParsed = this.pmtParsed = true; break; } case 17: case 8191: break; default: unknownPID = pid; break; } } else { tsPacketErrors++; } } if (tsPacketErrors > 0) { emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`)); } videoTrack.pesData = videoData; audioTrack.pesData = audioData; id3Track.pesData = id3Data; const demuxResult = { audioTrack, videoTrack, id3Track, textTrack }; if (flush) { this.extractRemainingSamples(demuxResult); } return demuxResult; } flush() { const { remainderData } = this; this.remainderData = null; let result; if (remainderData) { result = this.demux(remainderData, -1, false, true); } else { result = { videoTrack: this._videoTrack, audioTrack: this._audioTrack, id3Track: this._id3Track, textTrack: this._txtTrack }; } this.extractRemainingSamples(result); if (this.sampleAes) { return this.decrypt(result, this.sampleAes); } return result; } extractRemainingSamples(demuxResult) { const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult; const videoData = videoTrack.pesData; const audioData = audioTrack.pesData; const id3Data = id3Track.pesData; let pes; if (videoData && (pes = parsePES(videoData))) { this.videoParser.parseAVCPES(videoTrack, textTrack, pes, true, this._duration); videoTrack.pesData = null; } else { videoTrack.pesData = videoData; } if (audioData && (pes = parsePES(audioData))) { switch (audioTrack.segmentCodec) { case "aac": this.parseAACPES(audioTrack, pes); break; case "mp3": this.parseMPEGPES(audioTrack, pes); break; case "ac3": { this.parseAC3PES(audioTrack, pes); } break; } audioTrack.pesData = null; } else { if (audioData != null && audioData.size) { logger.log("last AAC PES packet truncated,might overlap between fragments"); } audioTrack.pesData = audioData; } if (id3Data && (pes = parsePES(id3Data))) { this.parseID3PES(id3Track, pes); id3Track.pesData = null; } else { id3Track.pesData = id3Data; } } demuxSampleAes(data, keyData, timeOffset) { const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive); const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData); return this.decrypt(demuxResult, sampleAes); } decrypt(demuxResult, sampleAes) { return new Promise((resolve) => { const { audioTrack, videoTrack } = demuxResult; if (audioTrack.samples && audioTrack.segmentCodec === "aac") { sampleAes.decryptAacSamples(audioTrack.samples, 0, () => { if (videoTrack.samples) { sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => { resolve(demuxResult); }); } else { resolve(demuxResult); } }); } else if (videoTrack.samples) { sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => { resolve(demuxResult); }); } }); } destroy() { this._duration = 0; } parseAACPES(track, pes) { let startOffset = 0; const aacOverFlow = this.aacOverFlow; let data = pes.data; if (aacOverFlow) { this.aacOverFlow = null; const frameMissingBytes = aacOverFlow.missing; const sampleLength = aacOverFlow.sample.unit.byteLength; if (frameMissingBytes === -1) { data = appendUint8Array(aacOverFlow.sample.unit, data); } else { const frameOverflowBytes = sampleLength - frameMissingBytes; aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes); track.samples.push(aacOverFlow.sample); startOffset = aacOverFlow.missing; } } let offset; let len; for (offset = startOffset, len = data.length; offset < len - 1; offset++) { if (isHeader$1(data, offset)) { break; } } if (offset !== startOffset) { let reason; const recoverable = offset < len - 1; if (recoverable) { reason = `AAC PES did not start with ADTS header,offset:${offset}`; } else { reason = "No ADTS header found in AAC PES"; } emitParsingError(this.observer, new Error(reason), recoverable); if (!recoverable) { return; } } initTrackConfig(track, this.observer, data, offset, this.audioCodec); let pts; if (pes.pts !== void 0) { pts = pes.pts; } else if (aacOverFlow) { const frameDuration = getFrameDuration(track.samplerate); pts = aacOverFlow.sample.pts + frameDuration; } else { logger.warn("[tsdemuxer]: AAC PES unknown PTS"); return; } let frameIndex = 0; let frame; while (offset < len) { frame = appendFrame$2(track, data, offset, pts, frameIndex); offset += frame.length; if (!frame.missing) { frameIndex++; for (; offset < len - 1; offset++) { if (isHeader$1(data, offset)) { break; } } } else { this.aacOverFlow = frame; break; } } } parseMPEGPES(track, pes) { const data = pes.data; const length2 = data.length; let frameIndex = 0; let offset = 0; const pts = pes.pts; if (pts === void 0) { logger.warn("[tsdemuxer]: MPEG PES unknown PTS"); return; } while (offset < length2) { if (isHeader(data, offset)) { const frame = appendFrame$1(track, data, offset, pts, frameIndex); if (frame) { offset += frame.length; frameIndex++; } else { break; } } else { offset++; } } } parseAC3PES(track, pes) { { const data = pes.data; const pts = pes.pts; if (pts === void 0) { logger.warn("[tsdemuxer]: AC3 PES unknown PTS"); return; } const length2 = data.length; let frameIndex = 0; let offset = 0; let parsed; while (offset < length2 && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) { offset += parsed; } } } parseID3PES(id3Track, pes) { if (pes.pts === void 0) { logger.warn("[tsdemuxer]: ID3 PES unknown PTS"); return; } const id3Sample = _extends2({}, pes, { type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3, duration: Number.POSITIVE_INFINITY }); id3Track.samples.push(id3Sample); } }; function parsePID(data, offset) { return ((data[offset + 1] & 31) << 8) + data[offset + 2]; } function parsePAT(data, offset) { return (data[offset + 10] & 31) << 8 | data[offset + 11]; } function parsePMT(data, offset, typeSupported, isSampleAes, observer2) { const result = { audioPid: -1, videoPid: -1, id3Pid: -1, segmentVideoCodec: "avc", segmentAudioCodec: "aac" }; const sectionLength = (data[offset + 1] & 15) << 8 | data[offset + 2]; const tableEnd = offset + 3 + sectionLength - 4; const programInfoLength = (data[offset + 10] & 15) << 8 | data[offset + 11]; offset += 12 + programInfoLength; while (offset < tableEnd) { const pid = parsePID(data, offset); const esInfoLength = (data[offset + 3] & 15) << 8 | data[offset + 4]; switch (data[offset]) { case 207: if (!isSampleAes) { logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC"); break; } case 15: if (result.audioPid === -1) { result.audioPid = pid; } break; case 21: if (result.id3Pid === -1) { result.id3Pid = pid; } break; case 219: if (!isSampleAes) { logEncryptedSamplesFoundInUnencryptedStream("H.264"); break; } case 27: if (result.videoPid === -1) { result.videoPid = pid; result.segmentVideoCodec = "avc"; } break; case 3: case 4: if (!typeSupported.mpeg && !typeSupported.mp3) { logger.log("MPEG audio found, not supported in this browser"); } else if (result.audioPid === -1) { result.audioPid = pid; result.segmentAudioCodec = "mp3"; } break; case 193: if (!isSampleAes) { logEncryptedSamplesFoundInUnencryptedStream("AC-3"); break; } case 129: { if (!typeSupported.ac3) { logger.log("AC-3 audio found, not supported in this browser"); } else if (result.audioPid === -1) { result.audioPid = pid; result.segmentAudioCodec = "ac3"; } } break; case 6: if (result.audioPid === -1 && esInfoLength > 0) { let parsePos = offset + 5; let remaining = esInfoLength; while (remaining > 2) { const descriptorId = data[parsePos]; switch (descriptorId) { case 106: { if (typeSupported.ac3 !== true) { logger.log("AC-3 audio found, not supported in this browser for now"); } else { result.audioPid = pid; result.segmentAudioCodec = "ac3"; } } break; } const descriptorLen = data[parsePos + 1] + 2; parsePos += descriptorLen; remaining -= descriptorLen; } } break; case 194: case 135: emitParsingError(observer2, new Error("Unsupported EC-3 in M2TS found")); return result; case 36: emitParsingError(observer2, new Error("Unsupported HEVC in M2TS found")); return result; } offset += esInfoLength + 5; } return result; } function emitParsingError(observer2, error, levelRetry) { logger.warn(`parsing error: ${error.message}`); observer2.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, levelRetry, error, reason: error.message }); } function logEncryptedSamplesFoundInUnencryptedStream(type) { logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`); } function parsePES(stream) { let i3 = 0; let frag; let pesLen; let pesHdrLen; let pesPts; let pesDts; const data = stream.data; if (!stream || stream.size === 0) { return null; } while (data[0].length < 19 && data.length > 1) { data[0] = appendUint8Array(data[0], data[1]); data.splice(1, 1); } frag = data[0]; const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2]; if (pesPrefix === 1) { pesLen = (frag[4] << 8) + frag[5]; if (pesLen && pesLen > stream.size - 6) { return null; } const pesFlags = frag[7]; if (pesFlags & 192) { pesPts = (frag[9] & 14) * 536870912 + // 1 << 29 (frag[10] & 255) * 4194304 + // 1 << 22 (frag[11] & 254) * 16384 + // 1 << 14 (frag[12] & 255) * 128 + // 1 << 7 (frag[13] & 254) / 2; if (pesFlags & 64) { pesDts = (frag[14] & 14) * 536870912 + // 1 << 29 (frag[15] & 255) * 4194304 + // 1 << 22 (frag[16] & 254) * 16384 + // 1 << 14 (frag[17] & 255) * 128 + // 1 << 7 (frag[18] & 254) / 2; if (pesPts - pesDts > 60 * 9e4) { logger.warn(`${Math.round((pesPts - pesDts) / 9e4)}s delta between PTS and DTS, align them`); pesPts = pesDts; } } else { pesDts = pesPts; } } pesHdrLen = frag[8]; let payloadStartOffset = pesHdrLen + 9; if (stream.size <= payloadStartOffset) { return null; } stream.size -= payloadStartOffset; const pesData = new Uint8Array(stream.size); for (let j3 = 0, dataLen = data.length; j3 < dataLen; j3++) { frag = data[j3]; let len = frag.byteLength; if (payloadStartOffset) { if (payloadStartOffset > len) { payloadStartOffset -= len; continue; } else { frag = frag.subarray(payloadStartOffset); len -= payloadStartOffset; payloadStartOffset = 0; } } pesData.set(frag, i3); i3 += len; } if (pesLen) { pesLen -= pesHdrLen + 3; } return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen }; } return null; } var MP3Demuxer = class extends BaseAudioDemuxer { resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) { super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration); this._audioTrack = { container: "audio/mpeg", type: "audio", id: 2, pid: -1, sequenceNumber: 0, segmentCodec: "mp3", samples: [], manifestCodec: audioCodec, duration: trackDuration, inputTimeScale: 9e4, dropped: 0 }; } static probe(data) { if (!data) { return false; } const id3Data = getID3Data(data, 0); let offset = (id3Data == null ? void 0 : id3Data.length) || 0; if (id3Data && data[offset] === 11 && data[offset + 1] === 119 && getTimeStamp(id3Data) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3) getAudioBSID(data, offset) <= 16) { return false; } for (let length2 = data.length; offset < length2; offset++) { if (probe(data, offset)) { logger.log("MPEG Audio sync word found !"); return true; } } return false; } canParse(data, offset) { return canParse(data, offset); } appendFrame(track, data, offset) { if (this.basePTS === null) { return; } return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex); } }; var AAC = class { static getSilentFrame(codec, channelCount) { switch (codec) { case "mp4a.40.2": if (channelCount === 1) { return new Uint8Array([0, 200, 0, 128, 35, 128]); } else if (channelCount === 2) { return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]); } else if (channelCount === 3) { return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]); } else if (channelCount === 4) { return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]); } else if (channelCount === 5) { return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]); } else if (channelCount === 6) { return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]); } break; default: if (channelCount === 1) { return new Uint8Array([1, 64, 34, 128, 163, 78, 230, 128, 186, 8, 0, 0, 0, 28, 6, 241, 193, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]); } else if (channelCount === 2) { return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]); } else if (channelCount === 3) { return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]); } break; } return void 0; } }; var UINT32_MAX = Math.pow(2, 32) - 1; var MP4 = class _MP4 { static init() { _MP4.types = { avc1: [], // codingname avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], ".mp3": [], dac3: [], "ac-3": [], mvex: [], mvhd: [], pasp: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [] }; let i3; for (i3 in _MP4.types) { if (_MP4.types.hasOwnProperty(i3)) { _MP4.types[i3] = [i3.charCodeAt(0), i3.charCodeAt(1), i3.charCodeAt(2), i3.charCodeAt(3)]; } } const videoHdlr = new Uint8Array([ 0, // version 0 0, 0, 0, // flags 0, 0, 0, 0, // pre_defined 118, 105, 100, 101, // handler_type: 'vide' 0, 0, 0, 0, // reserved 0, 0, 0, 0, // reserved 0, 0, 0, 0, // reserved 86, 105, 100, 101, 111, 72, 97, 110, 100, 108, 101, 114, 0 // name: 'VideoHandler' ]); const audioHdlr = new Uint8Array([ 0, // version 0 0, 0, 0, // flags 0, 0, 0, 0, // pre_defined 115, 111, 117, 110, // handler_type: 'soun' 0, 0, 0, 0, // reserved 0, 0, 0, 0, // reserved 0, 0, 0, 0, // reserved 83, 111, 117, 110, 100, 72, 97, 110, 100, 108, 101, 114, 0 // name: 'SoundHandler' ]); _MP4.HDLR_TYPES = { video: videoHdlr, audio: audioHdlr }; const dref = new Uint8Array([ 0, // version 0 0, 0, 0, // flags 0, 0, 0, 1, // entry_count 0, 0, 0, 12, // entry_size 117, 114, 108, 32, // 'url' type 0, // version 0 0, 0, 1 // entry_flags ]); const stco = new Uint8Array([ 0, // version 0, 0, 0, // flags 0, 0, 0, 0 // entry_count ]); _MP4.STTS = _MP4.STSC = _MP4.STCO = stco; _MP4.STSZ = new Uint8Array([ 0, // version 0, 0, 0, // flags 0, 0, 0, 0, // sample_size 0, 0, 0, 0 // sample_count ]); _MP4.VMHD = new Uint8Array([ 0, // version 0, 0, 1, // flags 0, 0, // graphicsmode 0, 0, 0, 0, 0, 0 // opcolor ]); _MP4.SMHD = new Uint8Array([ 0, // version 0, 0, 0, // flags 0, 0, // balance 0, 0 // reserved ]); _MP4.STSD = new Uint8Array([ 0, // version 0 0, 0, 0, // flags 0, 0, 0, 1 ]); const majorBrand = new Uint8Array([105, 115, 111, 109]); const avc1Brand = new Uint8Array([97, 118, 99, 49]); const minorVersion = new Uint8Array([0, 0, 0, 1]); _MP4.FTYP = _MP4.box(_MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand); _MP4.DINF = _MP4.box(_MP4.types.dinf, _MP4.box(_MP4.types.dref, dref)); } static box(type, ...payload) { let size = 8; let i3 = payload.length; const len = i3; while (i3--) { size += payload[i3].byteLength; } const result = new Uint8Array(size); result[0] = size >> 24 & 255; result[1] = size >> 16 & 255; result[2] = size >> 8 & 255; result[3] = size & 255; result.set(type, 4); for (i3 = 0, size = 8; i3 < len; i3++) { result.set(payload[i3], size); size += payload[i3].byteLength; } return result; } static hdlr(type) { return _MP4.box(_MP4.types.hdlr, _MP4.HDLR_TYPES[type]); } static mdat(data) { return _MP4.box(_MP4.types.mdat, data); } static mdhd(timescale, duration) { duration *= timescale; const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); return _MP4.box(_MP4.types.mdhd, new Uint8Array([ 1, // version 1 0, 0, 0, // flags 0, 0, 0, 0, 0, 0, 0, 2, // creation_time 0, 0, 0, 0, 0, 0, 0, 3, // modification_time timescale >> 24 & 255, timescale >> 16 & 255, timescale >> 8 & 255, timescale & 255, // timescale upperWordDuration >> 24, upperWordDuration >> 16 & 255, upperWordDuration >> 8 & 255, upperWordDuration & 255, lowerWordDuration >> 24, lowerWordDuration >> 16 & 255, lowerWordDuration >> 8 & 255, lowerWordDuration & 255, 85, 196, // 'und' language (undetermined) 0, 0 ])); } static mdia(track) { return _MP4.box(_MP4.types.mdia, _MP4.mdhd(track.timescale, track.duration), _MP4.hdlr(track.type), _MP4.minf(track)); } static mfhd(sequenceNumber) { return _MP4.box(_MP4.types.mfhd, new Uint8Array([ 0, 0, 0, 0, // flags sequenceNumber >> 24, sequenceNumber >> 16 & 255, sequenceNumber >> 8 & 255, sequenceNumber & 255 // sequence_number ])); } static minf(track) { if (track.type === "audio") { return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.smhd, _MP4.SMHD), _MP4.DINF, _MP4.stbl(track)); } else { return _MP4.box(_MP4.types.minf, _MP4.box(_MP4.types.vmhd, _MP4.VMHD), _MP4.DINF, _MP4.stbl(track)); } } static moof(sn, baseMediaDecodeTime, track) { return _MP4.box(_MP4.types.moof, _MP4.mfhd(sn), _MP4.traf(track, baseMediaDecodeTime)); } static moov(tracks) { let i3 = tracks.length; const boxes = []; while (i3--) { boxes[i3] = _MP4.trak(tracks[i3]); } return _MP4.box.apply(null, [_MP4.types.moov, _MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(_MP4.mvex(tracks))); } static mvex(tracks) { let i3 = tracks.length; const boxes = []; while (i3--) { boxes[i3] = _MP4.trex(tracks[i3]); } return _MP4.box.apply(null, [_MP4.types.mvex, ...boxes]); } static mvhd(timescale, duration) { duration *= timescale; const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); const bytes = new Uint8Array([ 1, // version 1 0, 0, 0, // flags 0, 0, 0, 0, 0, 0, 0, 2, // creation_time 0, 0, 0, 0, 0, 0, 0, 3, // modification_time timescale >> 24 & 255, timescale >> 16 & 255, timescale >> 8 & 255, timescale & 255, // timescale upperWordDuration >> 24, upperWordDuration >> 16 & 255, upperWordDuration >> 8 & 255, upperWordDuration & 255, lowerWordDuration >> 24, lowerWordDuration >> 16 & 255, lowerWordDuration >> 8 & 255, lowerWordDuration & 255, 0, 1, 0, 0, // 1.0 rate 1, 0, // 1.0 volume 0, 0, // reserved 0, 0, 0, 0, // reserved 0, 0, 0, 0, // reserved 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, // transformation: unity matrix 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // pre_defined 255, 255, 255, 255 // next_track_ID ]); return _MP4.box(_MP4.types.mvhd, bytes); } static sdtp(track) { const samples = track.samples || []; const bytes = new Uint8Array(4 + samples.length); let i3; let flags; for (i3 = 0; i3 < samples.length; i3++) { flags = samples[i3].flags; bytes[i3 + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy; } return _MP4.box(_MP4.types.sdtp, bytes); } static stbl(track) { return _MP4.box(_MP4.types.stbl, _MP4.stsd(track), _MP4.box(_MP4.types.stts, _MP4.STTS), _MP4.box(_MP4.types.stsc, _MP4.STSC), _MP4.box(_MP4.types.stsz, _MP4.STSZ), _MP4.box(_MP4.types.stco, _MP4.STCO)); } static avc1(track) { let sps = []; let pps = []; let i3; let data; let len; for (i3 = 0; i3 < track.sps.length; i3++) { data = track.sps[i3]; len = data.byteLength; sps.push(len >>> 8 & 255); sps.push(len & 255); sps = sps.concat(Array.prototype.slice.call(data)); } for (i3 = 0; i3 < track.pps.length; i3++) { data = track.pps[i3]; len = data.byteLength; pps.push(len >>> 8 & 255); pps.push(len & 255); pps = pps.concat(Array.prototype.slice.call(data)); } const avcc = _MP4.box(_MP4.types.avcC, new Uint8Array([ 1, // version sps[3], // profile sps[4], // profile compat sps[5], // level 252 | 3, // lengthSizeMinusOne, hard-coded to 4 bytes 224 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets ].concat(sps).concat([ track.pps.length // numOfPictureParameterSets ]).concat(pps))); const width = track.width; const height = track.height; const hSpacing = track.pixelRatio[0]; const vSpacing = track.pixelRatio[1]; return _MP4.box( _MP4.types.avc1, new Uint8Array([ 0, 0, 0, // reserved 0, 0, 0, // reserved 0, 1, // data_reference_index 0, 0, // pre_defined 0, 0, // reserved 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // pre_defined width >> 8 & 255, width & 255, // width height >> 8 & 255, height & 255, // height 0, 72, 0, 0, // horizresolution 0, 72, 0, 0, // vertresolution 0, 0, 0, 0, // reserved 0, 1, // frame_count 18, 100, 97, 105, 108, // dailymotion/hls.js 121, 109, 111, 116, 105, 111, 110, 47, 104, 108, 115, 46, 106, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // compressorname 0, 24, // depth = 24 17, 17 ]), // pre_defined = -1 avcc, _MP4.box(_MP4.types.btrt, new Uint8Array([ 0, 28, 156, 128, // bufferSizeDB 0, 45, 198, 192, // maxBitrate 0, 45, 198, 192 ])), // avgBitrate _MP4.box(_MP4.types.pasp, new Uint8Array([ hSpacing >> 24, // hSpacing hSpacing >> 16 & 255, hSpacing >> 8 & 255, hSpacing & 255, vSpacing >> 24, // vSpacing vSpacing >> 16 & 255, vSpacing >> 8 & 255, vSpacing & 255 ])) ); } static esds(track) { const configlen = track.config.length; return new Uint8Array([ 0, // version 0 0, 0, 0, // flags 3, // descriptor_type 23 + configlen, // length 0, 1, // es_id 0, // stream_priority 4, // descriptor_type 15 + configlen, // length 64, // codec : mpeg4_audio 21, // stream_type 0, 0, 0, // buffer_size 0, 0, 0, 0, // maxBitrate 0, 0, 0, 0, // avgBitrate 5 // descriptor_type ].concat([configlen]).concat(track.config).concat([6, 1, 2])); } static audioStsd(track) { const samplerate = track.samplerate; return new Uint8Array([ 0, 0, 0, // reserved 0, 0, 0, // reserved 0, 1, // data_reference_index 0, 0, 0, 0, 0, 0, 0, 0, // reserved 0, track.channelCount, // channelcount 0, 16, // sampleSize:16bits 0, 0, 0, 0, // reserved2 samplerate >> 8 & 255, samplerate & 255, // 0, 0 ]); } static mp4a(track) { return _MP4.box(_MP4.types.mp4a, _MP4.audioStsd(track), _MP4.box(_MP4.types.esds, _MP4.esds(track))); } static mp3(track) { return _MP4.box(_MP4.types[".mp3"], _MP4.audioStsd(track)); } static ac3(track) { return _MP4.box(_MP4.types["ac-3"], _MP4.audioStsd(track), _MP4.box(_MP4.types.dac3, track.config)); } static stsd(track) { if (track.type === "audio") { if (track.segmentCodec === "mp3" && track.codec === "mp3") { return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp3(track)); } if (track.segmentCodec === "ac3") { return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.ac3(track)); } return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.mp4a(track)); } else { return _MP4.box(_MP4.types.stsd, _MP4.STSD, _MP4.avc1(track)); } } static tkhd(track) { const id = track.id; const duration = track.duration * track.timescale; const width = track.width; const height = track.height; const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)); const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1)); return _MP4.box(_MP4.types.tkhd, new Uint8Array([ 1, // version 1 0, 0, 7, // flags 0, 0, 0, 0, 0, 0, 0, 2, // creation_time 0, 0, 0, 0, 0, 0, 0, 3, // modification_time id >> 24 & 255, id >> 16 & 255, id >> 8 & 255, id & 255, // track_ID 0, 0, 0, 0, // reserved upperWordDuration >> 24, upperWordDuration >> 16 & 255, upperWordDuration >> 8 & 255, upperWordDuration & 255, lowerWordDuration >> 24, lowerWordDuration >> 16 & 255, lowerWordDuration >> 8 & 255, lowerWordDuration & 255, 0, 0, 0, 0, 0, 0, 0, 0, // reserved 0, 0, // layer 0, 0, // alternate_group 0, 0, // non-audio track volume 0, 0, // reserved 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, // transformation: unity matrix width >> 8 & 255, width & 255, 0, 0, // width height >> 8 & 255, height & 255, 0, 0 // height ])); } static traf(track, baseMediaDecodeTime) { const sampleDependencyTable = _MP4.sdtp(track); const id = track.id; const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); return _MP4.box( _MP4.types.traf, _MP4.box(_MP4.types.tfhd, new Uint8Array([ 0, // version 0 0, 0, 0, // flags id >> 24, id >> 16 & 255, id >> 8 & 255, id & 255 // track_ID ])), _MP4.box(_MP4.types.tfdt, new Uint8Array([ 1, // version 1 0, 0, 0, // flags upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 255, upperWordBaseMediaDecodeTime >> 8 & 255, upperWordBaseMediaDecodeTime & 255, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 255, lowerWordBaseMediaDecodeTime >> 8 & 255, lowerWordBaseMediaDecodeTime & 255 ])), _MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd 20 + // tfdt 8 + // traf header 16 + // mfhd 8 + // moof header 8), // mdat header sampleDependencyTable ); } /** * Generate a track box. * @param track a track definition */ static trak(track) { track.duration = track.duration || 4294967295; return _MP4.box(_MP4.types.trak, _MP4.tkhd(track), _MP4.mdia(track)); } static trex(track) { const id = track.id; return _MP4.box(_MP4.types.trex, new Uint8Array([ 0, // version 0 0, 0, 0, // flags id >> 24, id >> 16 & 255, id >> 8 & 255, id & 255, // track_ID 0, 0, 0, 1, // default_sample_description_index 0, 0, 0, 0, // default_sample_duration 0, 0, 0, 0, // default_sample_size 0, 1, 0, 1 // default_sample_flags ])); } static trun(track, offset) { const samples = track.samples || []; const len = samples.length; const arraylen = 12 + 16 * len; const array = new Uint8Array(arraylen); let i3; let sample; let duration; let size; let flags; let cts; offset += 8 + arraylen; array.set([ track.type === "video" ? 1 : 0, // version 1 for video with signed-int sample_composition_time_offset 0, 15, 1, // flags len >>> 24 & 255, len >>> 16 & 255, len >>> 8 & 255, len & 255, // sample_count offset >>> 24 & 255, offset >>> 16 & 255, offset >>> 8 & 255, offset & 255 // data_offset ], 0); for (i3 = 0; i3 < len; i3++) { sample = samples[i3]; duration = sample.duration; size = sample.size; flags = sample.flags; cts = sample.cts; array.set([ duration >>> 24 & 255, duration >>> 16 & 255, duration >>> 8 & 255, duration & 255, // sample_duration size >>> 24 & 255, size >>> 16 & 255, size >>> 8 & 255, size & 255, // sample_size flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 240 << 8, flags.degradPrio & 15, // sample_flags cts >>> 24 & 255, cts >>> 16 & 255, cts >>> 8 & 255, cts & 255 // sample_composition_time_offset ], 12 + 16 * i3); } return _MP4.box(_MP4.types.trun, array); } static initSegment(tracks) { if (!_MP4.types) { _MP4.init(); } const movie = _MP4.moov(tracks); const result = appendUint8Array(_MP4.FTYP, movie); return result; } }; MP4.types = void 0; MP4.HDLR_TYPES = void 0; MP4.STTS = void 0; MP4.STSC = void 0; MP4.STCO = void 0; MP4.STSZ = void 0; MP4.VMHD = void 0; MP4.SMHD = void 0; MP4.STSD = void 0; MP4.FTYP = void 0; MP4.DINF = void 0; var MPEG_TS_CLOCK_FREQ_HZ = 9e4; function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) { const result = baseTime * destScale * srcBase; return round ? Math.round(result) : result; } function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) { return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round); } function toMsFromMpegTsClock(baseTime, round = false) { return toTimescaleFromBase(baseTime, 1e3, 1 / MPEG_TS_CLOCK_FREQ_HZ, round); } function toMpegTsClockFromTimescale(baseTime, srcScale = 1) { return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale); } var MAX_SILENT_FRAME_DURATION = 10 * 1e3; var AAC_SAMPLES_PER_FRAME = 1024; var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152; var AC3_SAMPLES_PER_FRAME = 1536; var chromeVersion = null; var safariWebkitVersion = null; var MP4Remuxer = class { constructor(observer2, config, typeSupported, vendor = "") { this.observer = void 0; this.config = void 0; this.typeSupported = void 0; this.ISGenerated = false; this._initPTS = null; this._initDTS = null; this.nextAvcDts = null; this.nextAudioPts = null; this.videoSampleDuration = null; this.isAudioContiguous = false; this.isVideoContiguous = false; this.videoTrackConfig = void 0; this.observer = observer2; this.config = config; this.typeSupported = typeSupported; this.ISGenerated = false; if (chromeVersion === null) { const userAgent = navigator.userAgent || ""; const result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion = result ? parseInt(result[1]) : 0; } if (safariWebkitVersion === null) { const result = navigator.userAgent.match(/Safari\/(\d+)/i); safariWebkitVersion = result ? parseInt(result[1]) : 0; } } destroy() { this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null; } resetTimeStamp(defaultTimeStamp) { logger.log("[mp4-remuxer]: initPTS & initDTS reset"); this._initPTS = this._initDTS = defaultTimeStamp; } resetNextTimestamp() { logger.log("[mp4-remuxer]: reset next timestamp"); this.isVideoContiguous = false; this.isAudioContiguous = false; } resetInitSegment() { logger.log("[mp4-remuxer]: ISGenerated flag reset"); this.ISGenerated = false; this.videoTrackConfig = void 0; } getVideoStartPts(videoSamples) { let rolloverDetected = false; const firstPts = videoSamples[0].pts; const startPTS = videoSamples.reduce((minPTS, sample) => { let pts = sample.pts; let delta = pts - minPTS; if (delta < -4294967296) { rolloverDetected = true; pts = normalizePts(pts, firstPts); delta = pts - minPTS; } if (delta > 0) { return minPTS; } return pts; }, firstPts); if (rolloverDetected) { logger.debug("PTS rollover detected"); } return startPTS; } remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) { let video; let audio; let initSegment; let text; let id3; let independent; let audioTimeOffset = timeOffset; let videoTimeOffset = timeOffset; const hasAudio = audioTrack.pid > -1; const hasVideo = videoTrack.pid > -1; const length2 = videoTrack.samples.length; const enoughAudioSamples = audioTrack.samples.length > 0; const enoughVideoSamples = flush && length2 > 0 || length2 > 1; const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush; if (canRemuxAvc) { if (this.ISGenerated) { var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2; const config = this.videoTrackConfig; if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1]))) { this.resetInitSegment(); } } else { initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset); } const isVideoContiguous = this.isVideoContiguous; let firstKeyFrameIndex = -1; let firstKeyFramePTS; if (enoughVideoSamples) { firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples); if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) { independent = true; if (firstKeyFrameIndex > 0) { logger.warn(`[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length2} video samples due to a missing keyframe`); const startPTS = this.getVideoStartPts(videoTrack.samples); videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex); videoTrack.dropped += firstKeyFrameIndex; videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale; firstKeyFramePTS = videoTimeOffset; } else if (firstKeyFrameIndex === -1) { logger.warn(`[mp4-remuxer]: No keyframe found out of ${length2} video samples`); independent = false; } } } if (this.ISGenerated) { if (enoughAudioSamples && enoughVideoSamples) { const startPTS = this.getVideoStartPts(videoTrack.samples); const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS; const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale; audioTimeOffset += Math.max(0, audiovideoTimestampDelta); videoTimeOffset += Math.max(0, -audiovideoTimestampDelta); } if (enoughAudioSamples) { if (!audioTrack.samplerate) { logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset); } audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : void 0); if (enoughVideoSamples) { const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; if (!videoTrack.inputTimeScale) { logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset); } video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength); } } else if (enoughVideoSamples) { video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0); } if (video) { video.firstKeyFrame = firstKeyFrameIndex; video.independent = firstKeyFrameIndex !== -1; video.firstKeyFramePTS = firstKeyFramePTS; } } } if (this.ISGenerated && this._initPTS && this._initDTS) { if (id3Track.samples.length) { id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS); } if (textTrack.samples.length) { text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS); } } return { audio, video, initSegment, independent, text, id3 }; } generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) { const audioSamples = audioTrack.samples; const videoSamples = videoTrack.samples; const typeSupported = this.typeSupported; const tracks = {}; const _initPTS = this._initPTS; let computePTSDTS = !_initPTS || accurateTimeOffset; let container = "audio/mp4"; let initPTS; let initDTS; let timescale; if (computePTSDTS) { initPTS = initDTS = Infinity; } if (audioTrack.config && audioSamples.length) { audioTrack.timescale = audioTrack.samplerate; switch (audioTrack.segmentCodec) { case "mp3": if (typeSupported.mpeg) { container = "audio/mpeg"; audioTrack.codec = ""; } else if (typeSupported.mp3) { audioTrack.codec = "mp3"; } break; case "ac3": audioTrack.codec = "ac-3"; break; } tracks.audio = { id: "audio", container, codec: audioTrack.codec, initSegment: audioTrack.segmentCodec === "mp3" && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]), metadata: { channelCount: audioTrack.channelCount } }; if (computePTSDTS) { timescale = audioTrack.inputTimeScale; if (!_initPTS || timescale !== _initPTS.timescale) { initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset); } else { computePTSDTS = false; } } } if (videoTrack.sps && videoTrack.pps && videoSamples.length) { videoTrack.timescale = videoTrack.inputTimeScale; tracks.video = { id: "main", container: "video/mp4", codec: videoTrack.codec, initSegment: MP4.initSegment([videoTrack]), metadata: { width: videoTrack.width, height: videoTrack.height } }; if (computePTSDTS) { timescale = videoTrack.inputTimeScale; if (!_initPTS || timescale !== _initPTS.timescale) { const startPTS = this.getVideoStartPts(videoSamples); const startOffset = Math.round(timescale * timeOffset); initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset); initPTS = Math.min(initPTS, startPTS - startOffset); } else { computePTSDTS = false; } } this.videoTrackConfig = { width: videoTrack.width, height: videoTrack.height, pixelRatio: videoTrack.pixelRatio }; } if (Object.keys(tracks).length) { this.ISGenerated = true; if (computePTSDTS) { this._initPTS = { baseTime: initPTS, timescale }; this._initDTS = { baseTime: initDTS, timescale }; } else { initPTS = timescale = void 0; } return { tracks, initPTS, timescale }; } } remuxVideo(track, timeOffset, contiguous, audioTrackLength) { const timeScale = track.inputTimeScale; const inputSamples = track.samples; const outputSamples = []; const nbSamples = inputSamples.length; const initPTS = this._initPTS; let nextAvcDts = this.nextAvcDts; let offset = 8; let mp4SampleDuration = this.videoSampleDuration; let firstDTS; let lastDTS; let minPTS = Number.POSITIVE_INFINITY; let maxPTS = Number.NEGATIVE_INFINITY; let sortSamples = false; if (!contiguous || nextAvcDts === null) { const pts = timeOffset * timeScale; const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15e3) { contiguous = true; } else { nextAvcDts = pts - cts; } } const initTime = initPTS.baseTime * timeScale / initPTS.timescale; for (let i3 = 0; i3 < nbSamples; i3++) { const sample = inputSamples[i3]; sample.pts = normalizePts(sample.pts - initTime, nextAvcDts); sample.dts = normalizePts(sample.dts - initTime, nextAvcDts); if (sample.dts < inputSamples[i3 > 0 ? i3 - 1 : i3].dts) { sortSamples = true; } } if (sortSamples) { inputSamples.sort(function(a2, b2) { const deltadts = a2.dts - b2.dts; const deltapts = a2.pts - b2.pts; return deltadts || deltapts; }); } firstDTS = inputSamples[0].dts; lastDTS = inputSamples[inputSamples.length - 1].dts; const inputDuration = lastDTS - firstDTS; const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30; if (contiguous) { const delta = firstDTS - nextAvcDts; const foundHole = delta > averageSampleDuration; const foundOverlap = delta < -1; if (foundHole || foundOverlap) { if (foundHole) { logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`); } else { logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`); } if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) { firstDTS = nextAvcDts; const firstPTS = inputSamples[0].pts - delta; if (foundHole) { inputSamples[0].dts = firstDTS; inputSamples[0].pts = firstPTS; } else { for (let i3 = 0; i3 < inputSamples.length; i3++) { if (inputSamples[i3].dts > firstPTS) { break; } inputSamples[i3].dts -= delta; inputSamples[i3].pts -= delta; } } logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`); } } } firstDTS = Math.max(0, firstDTS); let nbNalu = 0; let naluLen = 0; let dtsStep = firstDTS; for (let i3 = 0; i3 < nbSamples; i3++) { const sample = inputSamples[i3]; const units = sample.units; const nbUnits = units.length; let sampleLen = 0; for (let j3 = 0; j3 < nbUnits; j3++) { sampleLen += units[j3].data.length; } naluLen += sampleLen; nbNalu += nbUnits; sample.length = sampleLen; if (sample.dts < dtsStep) { sample.dts = dtsStep; dtsStep += averageSampleDuration / 4 | 0 || 1; } else { dtsStep = sample.dts; } minPTS = Math.min(sample.pts, minPTS); maxPTS = Math.max(sample.pts, maxPTS); } lastDTS = inputSamples[nbSamples - 1].dts; const mdatSize = naluLen + 4 * nbNalu + 8; let mdat; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, error: err, bytes: mdatSize, reason: `fail allocating video mdat ${mdatSize}` }); return; } const view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(MP4.types.mdat, 4); let stretchedLastFrame = false; let minDtsDelta = Number.POSITIVE_INFINITY; let minPtsDelta = Number.POSITIVE_INFINITY; let maxDtsDelta = Number.NEGATIVE_INFINITY; let maxPtsDelta = Number.NEGATIVE_INFINITY; for (let i3 = 0; i3 < nbSamples; i3++) { const VideoSample = inputSamples[i3]; const VideoSampleUnits = VideoSample.units; let mp4SampleLength = 0; for (let j3 = 0, nbUnits = VideoSampleUnits.length; j3 < nbUnits; j3++) { const unit = VideoSampleUnits[j3]; const unitData = unit.data; const unitDataLen = unit.data.byteLength; view.setUint32(offset, unitDataLen); offset += 4; mdat.set(unitData, offset); offset += unitDataLen; mp4SampleLength += 4 + unitDataLen; } let ptsDelta; if (i3 < nbSamples - 1) { mp4SampleDuration = inputSamples[i3 + 1].dts - VideoSample.dts; ptsDelta = inputSamples[i3 + 1].pts - VideoSample.pts; } else { const config = this.config; const lastFrameDuration = i3 > 0 ? VideoSample.dts - inputSamples[i3 - 1].dts : averageSampleDuration; ptsDelta = i3 > 0 ? VideoSample.pts - inputSamples[i3 - 1].pts : averageSampleDuration; if (config.stretchShortVideoTrack && this.nextAudioPts !== null) { const gapTolerance = Math.floor(config.maxBufferHole * timeScale); const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - VideoSample.pts; if (deltaToFrameEnd > gapTolerance) { mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; if (mp4SampleDuration < 0) { mp4SampleDuration = lastFrameDuration; } else { stretchedLastFrame = true; } logger.log(`[mp4-remuxer]: It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`); } else { mp4SampleDuration = lastFrameDuration; } } else { mp4SampleDuration = lastFrameDuration; } } const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts); minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration); maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration); minPtsDelta = Math.min(minPtsDelta, ptsDelta); maxPtsDelta = Math.max(maxPtsDelta, ptsDelta); outputSamples.push(new Mp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset)); } if (outputSamples.length) { if (chromeVersion) { if (chromeVersion < 70) { const flags = outputSamples[0].flags; flags.dependsOn = 2; flags.isNonSync = 0; } } else if (safariWebkitVersion) { if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) { logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration."); let dts = firstDTS; for (let i3 = 0, len = outputSamples.length; i3 < len; i3++) { const nextDts = dts + outputSamples[i3].duration; const pts = dts + outputSamples[i3].cts; if (i3 < len - 1) { const nextPts = nextDts + outputSamples[i3 + 1].cts; outputSamples[i3].duration = nextPts - pts; } else { outputSamples[i3].duration = i3 ? outputSamples[i3 - 1].duration : averageSampleDuration; } outputSamples[i3].cts = 0; dts = nextDts; } } } } mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration; this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration; this.videoSampleDuration = mp4SampleDuration; this.isVideoContiguous = true; const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends2({}, track, { samples: outputSamples })); const type = "video"; const data = { data1: moof, data2: mdat, startPTS: minPTS / timeScale, endPTS: (maxPTS + mp4SampleDuration) / timeScale, startDTS: firstDTS / timeScale, endDTS: nextAvcDts / timeScale, type, hasAudio: false, hasVideo: true, nb: outputSamples.length, dropped: track.dropped }; track.samples = []; track.dropped = 0; return data; } getSamplesPerFrame(track) { switch (track.segmentCodec) { case "mp3": return MPEG_AUDIO_SAMPLE_PER_FRAME; case "ac3": return AC3_SAMPLES_PER_FRAME; default: return AAC_SAMPLES_PER_FRAME; } } remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) { const inputTimeScale = track.inputTimeScale; const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale; const scaleFactor = inputTimeScale / mp4timeScale; const mp4SampleDuration = this.getSamplesPerFrame(track); const inputSampleDuration = mp4SampleDuration * scaleFactor; const initPTS = this._initPTS; const rawMPEG = track.segmentCodec === "mp3" && this.typeSupported.mpeg; const outputSamples = []; const alignedWithVideo = videoTimeOffset !== void 0; let inputSamples = track.samples; let offset = rawMPEG ? 0 : 8; let nextAudioPts = this.nextAudioPts || -1; const timeOffsetMpegTS = timeOffset * inputTimeScale; const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale; this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9e3 || Math.abs(normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); inputSamples.forEach(function(sample) { sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS); }); if (!contiguous || nextAudioPts < 0) { inputSamples = inputSamples.filter((sample) => sample.pts >= 0); if (!inputSamples.length) { return; } if (videoTimeOffset === 0) { nextAudioPts = 0; } else if (accurateTimeOffset && !alignedWithVideo) { nextAudioPts = Math.max(0, timeOffsetMpegTS); } else { nextAudioPts = inputSamples[0].pts; } } if (track.segmentCodec === "aac") { const maxAudioFramesDrift = this.config.maxAudioFramesDrift; for (let i3 = 0, nextPts = nextAudioPts; i3 < inputSamples.length; i3++) { const sample = inputSamples[i3]; const pts = sample.pts; const delta = pts - nextPts; const duration = Math.abs(1e3 * delta / inputTimeScale); if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) { if (i3 === 0) { logger.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3 * delta / inputTimeScale)} ms.`); this.nextAudioPts = nextAudioPts = nextPts = pts; } } else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) { let missing = Math.round(delta / inputSampleDuration); nextPts = pts - missing * inputSampleDuration; if (nextPts < 0) { missing--; nextPts += inputSampleDuration; } if (i3 === 0) { this.nextAudioPts = nextAudioPts = nextPts; } logger.warn(`[mp4-remuxer]: Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1e3 * delta / inputTimeScale)} ms gap.`); for (let j3 = 0; j3 < missing; j3++) { const newStamp = Math.max(nextPts, 0); let fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); if (!fillFrame) { logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."); fillFrame = sample.unit.subarray(); } inputSamples.splice(i3, 0, { unit: fillFrame, pts: newStamp }); nextPts += inputSampleDuration; i3++; } } sample.pts = nextPts; nextPts += inputSampleDuration; } } let firstPTS = null; let lastPTS = null; let mdat; let mdatSize = 0; let sampleLength = inputSamples.length; while (sampleLength--) { mdatSize += inputSamples[sampleLength].unit.byteLength; } for (let j3 = 0, _nbSamples = inputSamples.length; j3 < _nbSamples; j3++) { const audioSample = inputSamples[j3]; const unit = audioSample.unit; let pts = audioSample.pts; if (lastPTS !== null) { const prevSample = outputSamples[j3 - 1]; prevSample.duration = Math.round((pts - lastPTS) / scaleFactor); } else { if (contiguous && track.segmentCodec === "aac") { pts = nextAudioPts; } firstPTS = pts; if (mdatSize > 0) { mdatSize += offset; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, error: err, bytes: mdatSize, reason: `fail allocating audio mdat ${mdatSize}` }); return; } if (!rawMPEG) { const view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(MP4.types.mdat, 4); } } else { return; } } mdat.set(unit, offset); const unitLen = unit.byteLength; offset += unitLen; outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0)); lastPTS = pts; } const nbSamples = outputSamples.length; if (!nbSamples) { return; } const lastSample = outputSamples[outputSamples.length - 1]; this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends2({}, track, { samples: outputSamples })); track.samples = []; const start = firstPTS / inputTimeScale; const end = nextAudioPts / inputTimeScale; const type = "audio"; const audioData = { data1: moof, data2: mdat, startPTS: start, endPTS: end, startDTS: start, endDTS: end, type, hasAudio: true, hasVideo: false, nb: nbSamples }; this.isAudioContiguous = true; return audioData; } remuxEmptyAudio(track, timeOffset, contiguous, videoData) { const inputTimeScale = track.inputTimeScale; const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale; const scaleFactor = inputTimeScale / mp4timeScale; const nextAudioPts = this.nextAudioPts; const initDTS = this._initDTS; const init90kHz = initDTS.baseTime * 9e4 / initDTS.timescale; const startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + init90kHz; const endDTS = videoData.endDTS * inputTimeScale + init90kHz; const frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; const nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); const silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); logger.warn("[mp4-remuxer]: remux empty Audio"); if (!silentFrame) { logger.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec"); return; } const samples = []; for (let i3 = 0; i3 < nbSamples; i3++) { const stamp = startDTS + i3 * frameDuration; samples.push({ unit: silentFrame, pts: stamp, dts: stamp }); } track.samples = samples; return this.remuxAudio(track, timeOffset, contiguous, false); } }; function normalizePts(value, reference) { let offset; if (reference === null) { return value; } if (reference < value) { offset = -8589934592; } else { offset = 8589934592; } while (Math.abs(value - reference) > 4294967296) { value += offset; } return value; } function findKeyframeIndex(samples) { for (let i3 = 0; i3 < samples.length; i3++) { if (samples[i3].key) { return i3; } } return -1; } function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) { const length2 = track.samples.length; if (!length2) { return; } const inputTimeScale = track.inputTimeScale; for (let index2 = 0; index2 < length2; index2++) { const sample = track.samples[index2]; sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale; sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale; } const samples = track.samples; track.samples = []; return { samples }; } function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) { const length2 = track.samples.length; if (!length2) { return; } const inputTimeScale = track.inputTimeScale; for (let index2 = 0; index2 < length2; index2++) { const sample = track.samples[index2]; sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale; } track.samples.sort((a2, b2) => a2.pts - b2.pts); const samples = track.samples; track.samples = []; return { samples }; } var Mp4Sample = class { constructor(isKeyframe, duration, size, cts) { this.size = void 0; this.duration = void 0; this.cts = void 0; this.flags = void 0; this.duration = duration; this.size = size; this.cts = cts; this.flags = { isLeading: 0, isDependedOn: 0, hasRedundancy: 0, degradPrio: 0, dependsOn: isKeyframe ? 2 : 1, isNonSync: isKeyframe ? 0 : 1 }; } }; var PassThroughRemuxer = class { constructor() { this.emitInitSegment = false; this.audioCodec = void 0; this.videoCodec = void 0; this.initData = void 0; this.initPTS = null; this.initTracks = void 0; this.lastEndTime = null; } destroy() { } resetTimeStamp(defaultInitPTS) { this.initPTS = defaultInitPTS; this.lastEndTime = null; } resetNextTimestamp() { this.lastEndTime = null; } resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) { this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.generateInitSegment(patchEncyptionData(initSegment, decryptdata)); this.emitInitSegment = true; } generateInitSegment(initSegment) { let { audioCodec, videoCodec } = this; if (!(initSegment != null && initSegment.byteLength)) { this.initTracks = void 0; this.initData = void 0; return; } const initData = this.initData = parseInitSegment(initSegment); if (initData.audio) { audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO); } if (initData.video) { videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO); } const tracks = {}; if (initData.audio && initData.video) { tracks.audiovideo = { container: "video/mp4", codec: audioCodec + "," + videoCodec, initSegment, id: "main" }; } else if (initData.audio) { tracks.audio = { container: "audio/mp4", codec: audioCodec, initSegment, id: "audio" }; } else if (initData.video) { tracks.video = { container: "video/mp4", codec: videoCodec, initSegment, id: "main" }; } else { logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."); } this.initTracks = tracks; } remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) { var _initData, _initData2; let { initPTS, lastEndTime } = this; const result = { audio: void 0, video: void 0, text: textTrack, id3: id3Track, initSegment: void 0 }; if (!isFiniteNumber(lastEndTime)) { lastEndTime = this.lastEndTime = timeOffset || 0; } const data = videoTrack.samples; if (!(data != null && data.length)) { return result; } const initSegment = { initPTS: void 0, timescale: 1 }; let initData = this.initData; if (!((_initData = initData) != null && _initData.length)) { this.generateInitSegment(data); initData = this.initData; } if (!((_initData2 = initData) != null && _initData2.length)) { logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."); return result; } if (this.emitInitSegment) { initSegment.tracks = this.initTracks; this.emitInitSegment = false; } const duration = getDuration(data, initData); const startDTS = getStartDTS(initData, data); const decodeTime = startDTS === null ? timeOffset : startDTS; if (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale && accurateTimeOffset) { initSegment.initPTS = decodeTime - timeOffset; if (initPTS && initPTS.timescale === 1) { logger.warn(`Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`); } this.initPTS = initPTS = { baseTime: initSegment.initPTS, timescale: 1 }; } const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime; const endTime = startTime + duration; offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale); if (duration > 0) { this.lastEndTime = endTime; } else { logger.warn("Duration parsed from mp4 should be greater than zero"); this.resetNextTimestamp(); } const hasAudio = !!initData.audio; const hasVideo = !!initData.video; let type = ""; if (hasAudio) { type += "audio"; } if (hasVideo) { type += "video"; } const track = { data1: data, startPTS: startTime, startDTS: startTime, endPTS: endTime, endDTS: endTime, type, hasAudio, hasVideo, nb: 1, dropped: 0 }; result.audio = track.type === "audio" ? track : void 0; result.video = track.type !== "audio" ? track : void 0; result.initSegment = initSegment; result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS); if (textTrack.samples.length) { result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS); } return result; } }; function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) { if (initPTS === null) { return true; } const minDuration = Math.max(duration, 1); const startTime = startDTS - initPTS.baseTime / initPTS.timescale; return Math.abs(startTime - timeOffset) > minDuration; } function getParsedTrackCodec(track, type) { const parsedCodec = track == null ? void 0 : track.codec; if (parsedCodec && parsedCodec.length > 4) { return parsedCodec; } if (type === ElementaryStreamTypes.AUDIO) { if (parsedCodec === "ec-3" || parsedCodec === "ac-3" || parsedCodec === "alac") { return parsedCodec; } if (parsedCodec === "fLaC" || parsedCodec === "Opus") { const preferManagedMediaSource = false; return getCodecCompatibleName(parsedCodec, preferManagedMediaSource); } const result = "mp4a.40.5"; logger.info(`Parsed audio codec "${parsedCodec}" or audio object type not handled. Using "${result}"`); return result; } logger.warn(`Unhandled video codec "${parsedCodec}"`); if (parsedCodec === "hvc1" || parsedCodec === "hev1") { return "hvc1.1.6.L120.90"; } if (parsedCodec === "av01") { return "av01.0.04M.08"; } return "avc1.42e01e"; } var now; try { now = self.performance.now.bind(self.performance); } catch (err) { logger.debug("Unable to use Performance API on this environment"); now = optionalSelf == null ? void 0 : optionalSelf.Date.now; } var muxConfig = [{ demux: MP4Demuxer, remux: PassThroughRemuxer }, { demux: TSDemuxer, remux: MP4Remuxer }, { demux: AACDemuxer, remux: MP4Remuxer }, { demux: MP3Demuxer, remux: MP4Remuxer }]; { muxConfig.splice(2, 0, { demux: AC3Demuxer, remux: MP4Remuxer }); } var Transmuxer = class { constructor(observer2, typeSupported, config, vendor, id) { this.async = false; this.observer = void 0; this.typeSupported = void 0; this.config = void 0; this.vendor = void 0; this.id = void 0; this.demuxer = void 0; this.remuxer = void 0; this.decrypter = void 0; this.probe = void 0; this.decryptionPromise = null; this.transmuxConfig = void 0; this.currentTransmuxState = void 0; this.observer = observer2; this.typeSupported = typeSupported; this.config = config; this.vendor = vendor; this.id = id; } configure(transmuxConfig) { this.transmuxConfig = transmuxConfig; if (this.decrypter) { this.decrypter.reset(); } } push(data, decryptdata, chunkMeta, state) { const stats = chunkMeta.transmuxing; stats.executeStart = now(); let uintData = new Uint8Array(data); const { currentTransmuxState, transmuxConfig } = this; if (state) { this.currentTransmuxState = state; } const { contiguous, discontinuity, trackSwitch, accurateTimeOffset, timeOffset, initSegmentChange } = state || currentTransmuxState; const { audioCodec, videoCodec, defaultInitPts, duration, initSegmentData } = transmuxConfig; const keyData = getEncryptionType(uintData, decryptdata); if (keyData && keyData.method === "AES-128") { const decrypter = this.getDecrypter(); if (decrypter.isSync()) { let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer); const loadingParts = chunkMeta.part > -1; if (loadingParts) { decryptedData = decrypter.flush(); } if (!decryptedData) { stats.executeEnd = now(); return emptyResult(chunkMeta); } uintData = new Uint8Array(decryptedData); } else { this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then((decryptedData) => { const result2 = this.push(decryptedData, null, chunkMeta); this.decryptionPromise = null; return result2; }); return this.decryptionPromise; } } const resetMuxers = this.needsProbing(discontinuity, trackSwitch); if (resetMuxers) { const error = this.configureTransmuxer(uintData); if (error) { logger.warn(`[transmuxer] ${error.message}`); this.observer.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, error, reason: error.message }); stats.executeEnd = now(); return emptyResult(chunkMeta); } } if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) { this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata); } if (discontinuity || initSegmentChange || resetMuxers) { this.resetInitialTimestamp(defaultInitPts); } if (!contiguous) { this.resetContiguity(); } const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta); const currentState = this.currentTransmuxState; currentState.contiguous = true; currentState.discontinuity = false; currentState.trackSwitch = false; stats.executeEnd = now(); return result; } // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type) flush(chunkMeta) { const stats = chunkMeta.transmuxing; stats.executeStart = now(); const { decrypter, currentTransmuxState, decryptionPromise } = this; if (decryptionPromise) { return decryptionPromise.then(() => { return this.flush(chunkMeta); }); } const transmuxResults = []; const { timeOffset } = currentTransmuxState; if (decrypter) { const decryptedData = decrypter.flush(); if (decryptedData) { transmuxResults.push(this.push(decryptedData, null, chunkMeta)); } } const { demuxer, remuxer } = this; if (!demuxer || !remuxer) { stats.executeEnd = now(); return [emptyResult(chunkMeta)]; } const demuxResultOrPromise = demuxer.flush(timeOffset); if (isPromise(demuxResultOrPromise)) { return demuxResultOrPromise.then((demuxResult) => { this.flushRemux(transmuxResults, demuxResult, chunkMeta); return transmuxResults; }); } this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta); return transmuxResults; } flushRemux(transmuxResults, demuxResult, chunkMeta) { const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult; const { accurateTimeOffset, timeOffset } = this.currentTransmuxState; logger.log(`[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${chunkMeta.part > -1 ? " p: " + chunkMeta.part : ""} of level ${chunkMeta.level}`); const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id); transmuxResults.push({ remuxResult, chunkMeta }); chunkMeta.transmuxing.executeEnd = now(); } resetInitialTimestamp(defaultInitPts) { const { demuxer, remuxer } = this; if (!demuxer || !remuxer) { return; } demuxer.resetTimeStamp(defaultInitPts); remuxer.resetTimeStamp(defaultInitPts); } resetContiguity() { const { demuxer, remuxer } = this; if (!demuxer || !remuxer) { return; } demuxer.resetContiguity(); remuxer.resetNextTimestamp(); } resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) { const { demuxer, remuxer } = this; if (!demuxer || !remuxer) { return; } demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration); remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata); } destroy() { if (this.demuxer) { this.demuxer.destroy(); this.demuxer = void 0; } if (this.remuxer) { this.remuxer.destroy(); this.remuxer = void 0; } } transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) { let result; if (keyData && keyData.method === "SAMPLE-AES") { result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta); } else { result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta); } return result; } transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) { const { audioTrack, videoTrack, id3Track, textTrack } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive); const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id); return { remuxResult, chunkMeta }; } transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) { return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then((demuxResult) => { const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id); return { remuxResult, chunkMeta }; }); } configureTransmuxer(data) { const { config, observer: observer2, typeSupported, vendor } = this; let mux; for (let i3 = 0, len = muxConfig.length; i3 < len; i3++) { var _muxConfig$i$demux; if ((_muxConfig$i$demux = muxConfig[i3].demux) != null && _muxConfig$i$demux.probe(data)) { mux = muxConfig[i3]; break; } } if (!mux) { return new Error("Failed to find demuxer by probing fragment data"); } const demuxer = this.demuxer; const remuxer = this.remuxer; const Remuxer = mux.remux; const Demuxer = mux.demux; if (!remuxer || !(remuxer instanceof Remuxer)) { this.remuxer = new Remuxer(observer2, config, typeSupported, vendor); } if (!demuxer || !(demuxer instanceof Demuxer)) { this.demuxer = new Demuxer(observer2, config, typeSupported); this.probe = Demuxer.probe; } } needsProbing(discontinuity, trackSwitch) { return !this.demuxer || !this.remuxer || discontinuity || trackSwitch; } getDecrypter() { let decrypter = this.decrypter; if (!decrypter) { decrypter = this.decrypter = new Decrypter(this.config); } return decrypter; } }; function getEncryptionType(data, decryptData) { let encryptionType = null; if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) { encryptionType = decryptData; } return encryptionType; } var emptyResult = (chunkMeta) => ({ remuxResult: {}, chunkMeta }); function isPromise(p3) { return "then" in p3 && p3.then instanceof Function; } var TransmuxConfig = class { constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) { this.audioCodec = void 0; this.videoCodec = void 0; this.initSegmentData = void 0; this.duration = void 0; this.defaultInitPts = void 0; this.audioCodec = audioCodec; this.videoCodec = videoCodec; this.initSegmentData = initSegmentData; this.duration = duration; this.defaultInitPts = defaultInitPts || null; } }; var TransmuxState = class { constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) { this.discontinuity = void 0; this.contiguous = void 0; this.accurateTimeOffset = void 0; this.trackSwitch = void 0; this.timeOffset = void 0; this.initSegmentChange = void 0; this.discontinuity = discontinuity; this.contiguous = contiguous; this.accurateTimeOffset = accurateTimeOffset; this.trackSwitch = trackSwitch; this.timeOffset = timeOffset; this.initSegmentChange = initSegmentChange; } }; var eventemitter3 = { exports: {} }; (function(module) { var has = Object.prototype.hasOwnProperty, prefix3 = "~"; function Events2() { } if (Object.create) { Events2.prototype = /* @__PURE__ */ Object.create(null); if (!new Events2().__proto__) prefix3 = false; } function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } function addListener2(emitter, event, fn, context, once) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE(fn, context || emitter, once), evt = prefix3 ? prefix3 + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events2(); else delete emitter._events[evt]; } function EventEmitter2() { this._events = new Events2(); this._eventsCount = 0; } EventEmitter2.prototype.eventNames = function eventNames() { var names = [], events2, name; if (this._eventsCount === 0) return names; for (name in events2 = this._events) { if (has.call(events2, name)) names.push(prefix3 ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events2)); } return names; }; EventEmitter2.prototype.listeners = function listeners(event) { var evt = prefix3 ? prefix3 + event : event, handlers2 = this._events[evt]; if (!handlers2) return []; if (handlers2.fn) return [handlers2.fn]; for (var i3 = 0, l2 = handlers2.length, ee6 = new Array(l2); i3 < l2; i3++) { ee6[i3] = handlers2[i3].fn; } return ee6; }; EventEmitter2.prototype.listenerCount = function listenerCount(event) { var evt = prefix3 ? prefix3 + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix3 ? prefix3 + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i3; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i3 = 1, args = new Array(len - 1); i3 < len; i3++) { args[i3 - 1] = arguments[i3]; } listeners.fn.apply(listeners.context, args); } else { var length2 = listeners.length, j3; for (i3 = 0; i3 < length2; i3++) { if (listeners[i3].once) this.removeListener(event, listeners[i3].fn, void 0, true); switch (len) { case 1: listeners[i3].fn.call(listeners[i3].context); break; case 2: listeners[i3].fn.call(listeners[i3].context, a1); break; case 3: listeners[i3].fn.call(listeners[i3].context, a1, a2); break; case 4: listeners[i3].fn.call(listeners[i3].context, a1, a2, a3); break; default: if (!args) for (j3 = 1, args = new Array(len - 1); j3 < len; j3++) { args[j3 - 1] = arguments[j3]; } listeners[i3].fn.apply(listeners[i3].context, args); } } } return true; }; EventEmitter2.prototype.on = function on(event, fn, context) { return addListener2(this, event, fn, context, false); }; EventEmitter2.prototype.once = function once(event, fn, context) { return addListener2(this, event, fn, context, true); }; EventEmitter2.prototype.removeListener = function removeListener2(event, fn, context, once) { var evt = prefix3 ? prefix3 + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i3 = 0, events2 = [], length2 = listeners.length; i3 < length2; i3++) { if (listeners[i3].fn !== fn || once && !listeners[i3].once || context && listeners[i3].context !== context) { events2.push(listeners[i3]); } } if (events2.length) this._events[evt] = events2.length === 1 ? events2[0] : events2; else clearEvent(this, evt); } return this; }; EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix3 ? prefix3 + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events2(); this._eventsCount = 0; } return this; }; EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; EventEmitter2.prefixed = prefix3; EventEmitter2.EventEmitter = EventEmitter2; { module.exports = EventEmitter2; } })(eventemitter3); var eventemitter3Exports = eventemitter3.exports; var EventEmitter = getDefaultExportFromCjs(eventemitter3Exports); var TransmuxerInterface = class { constructor(hls, id, onTransmuxComplete, onFlush) { this.error = null; this.hls = void 0; this.id = void 0; this.observer = void 0; this.frag = null; this.part = null; this.useWorker = void 0; this.workerContext = null; this.onwmsg = void 0; this.transmuxer = null; this.onTransmuxComplete = void 0; this.onFlush = void 0; const config = hls.config; this.hls = hls; this.id = id; this.useWorker = !!config.enableWorker; this.onTransmuxComplete = onTransmuxComplete; this.onFlush = onFlush; const forwardMessage = (ev, data) => { data = data || {}; data.frag = this.frag; data.id = this.id; if (ev === Events.ERROR) { this.error = data.error; } this.hls.trigger(ev, data); }; this.observer = new EventEmitter(); this.observer.on(Events.FRAG_DECRYPTED, forwardMessage); this.observer.on(Events.ERROR, forwardMessage); const MediaSource = getMediaSource(config.preferManagedMediaSource) || { isTypeSupported: () => false }; const m2tsTypeSupported = { mpeg: MediaSource.isTypeSupported("audio/mpeg"), mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'), ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"') }; if (this.useWorker && typeof Worker !== "undefined") { const canCreateWorker = config.workerPath || hasUMDWorker(); if (canCreateWorker) { try { if (config.workerPath) { logger.log(`loading Web Worker ${config.workerPath} for "${id}"`); this.workerContext = loadWorker(config.workerPath); } else { logger.log(`injecting Web Worker for "${id}"`); this.workerContext = injectWorker(); } this.onwmsg = (event) => this.onWorkerMessage(event); const { worker } = this.workerContext; worker.addEventListener("message", this.onwmsg); worker.onerror = (event) => { const error = new Error(`${event.message} (${event.filename}:${event.lineno})`); config.enableWorker = false; logger.warn(`Error in "${id}" Web Worker, fallback to inline`); this.hls.trigger(Events.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: "demuxerWorker", error }); }; worker.postMessage({ cmd: "init", typeSupported: m2tsTypeSupported, vendor: "", id, config: JSON.stringify(config) }); } catch (err) { logger.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err); this.resetWorker(); this.error = null; this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id); } return; } } this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, "", id); } resetWorker() { if (this.workerContext) { const { worker, objectURL } = this.workerContext; if (objectURL) { self.URL.revokeObjectURL(objectURL); } worker.removeEventListener("message", this.onwmsg); worker.onerror = null; worker.terminate(); this.workerContext = null; } } destroy() { if (this.workerContext) { this.resetWorker(); this.onwmsg = void 0; } else { const transmuxer = this.transmuxer; if (transmuxer) { transmuxer.destroy(); this.transmuxer = null; } } const observer2 = this.observer; if (observer2) { observer2.removeAllListeners(); } this.frag = null; this.observer = null; this.hls = null; } push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) { var _frag$initSegment, _lastFrag$initSegment; chunkMeta.transmuxing.start = self.performance.now(); const { transmuxer } = this; const timeOffset = part ? part.start : frag.start; const decryptdata = frag.decryptdata; const lastFrag = this.frag; const discontinuity = !(lastFrag && frag.cc === lastFrag.cc); const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level); const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1; const partDiff = this.part ? chunkMeta.part - this.part.index : -1; const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount); const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0)); const now2 = self.performance.now(); if (trackSwitch || snDiff || frag.stats.parsing.start === 0) { frag.stats.parsing.start = now2; } if (part && (partDiff || !contiguous)) { part.stats.parsing.start = now2; } const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url)); const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange); if (!contiguous || discontinuity || initSegmentChange) { logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id} discontinuity: ${discontinuity} trackSwitch: ${trackSwitch} contiguous: ${contiguous} accurateTimeOffset: ${accurateTimeOffset} timeOffset: ${timeOffset} initSegmentChange: ${initSegmentChange}`); const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS); this.configureTransmuxer(config); } this.frag = frag; this.part = part; if (this.workerContext) { this.workerContext.worker.postMessage({ cmd: "demux", data, decryptdata, chunkMeta, state }, data instanceof ArrayBuffer ? [data] : []); } else if (transmuxer) { const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state); if (isPromise(transmuxResult)) { transmuxer.async = true; transmuxResult.then((data2) => { this.handleTransmuxComplete(data2); }).catch((error) => { this.transmuxerError(error, chunkMeta, "transmuxer-interface push error"); }); } else { transmuxer.async = false; this.handleTransmuxComplete(transmuxResult); } } } flush(chunkMeta) { chunkMeta.transmuxing.start = self.performance.now(); const { transmuxer } = this; if (this.workerContext) { this.workerContext.worker.postMessage({ cmd: "flush", chunkMeta }); } else if (transmuxer) { let transmuxResult = transmuxer.flush(chunkMeta); const asyncFlush = isPromise(transmuxResult); if (asyncFlush || transmuxer.async) { if (!isPromise(transmuxResult)) { transmuxResult = Promise.resolve(transmuxResult); } transmuxResult.then((data) => { this.handleFlushResult(data, chunkMeta); }).catch((error) => { this.transmuxerError(error, chunkMeta, "transmuxer-interface flush error"); }); } else { this.handleFlushResult(transmuxResult, chunkMeta); } } } transmuxerError(error, chunkMeta, reason) { if (!this.hls) { return; } this.error = error; this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, chunkMeta, frag: this.frag || void 0, fatal: false, error, err: error, reason }); } handleFlushResult(results, chunkMeta) { results.forEach((result) => { this.handleTransmuxComplete(result); }); this.onFlush(chunkMeta); } onWorkerMessage(event) { const data = event.data; if (!(data != null && data.event)) { logger.warn(`worker message received with no ${data ? "event name" : "data"}`); return; } const hls = this.hls; if (!this.hls) { return; } switch (data.event) { case "init": { var _this$workerContext; const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL; if (objectURL) { self.URL.revokeObjectURL(objectURL); } break; } case "transmuxComplete": { this.handleTransmuxComplete(data.data); break; } case "flush": { this.onFlush(data.data); break; } case "workerLog": if (logger[data.data.logType]) { logger[data.data.logType](data.data.message); } break; default: { data.data = data.data || {}; data.data.frag = this.frag; data.data.id = this.id; hls.trigger(data.event, data.data); break; } } } configureTransmuxer(config) { const { transmuxer } = this; if (this.workerContext) { this.workerContext.worker.postMessage({ cmd: "configure", config }); } else if (transmuxer) { transmuxer.configure(config); } } handleTransmuxComplete(result) { result.chunkMeta.transmuxing.end = self.performance.now(); this.onTransmuxComplete(result); } }; var TICK_INTERVAL$2 = 100; var AudioStreamController = class extends BaseStreamController { constructor(hls, fragmentTracker, keyLoader) { super(hls, fragmentTracker, keyLoader, "[audio-stream-controller]", PlaylistLevelType.AUDIO); this.videoBuffer = null; this.videoTrackCC = -1; this.waitingVideoCC = -1; this.bufferedTrack = null; this.switchingTrack = null; this.trackId = -1; this.waitingData = null; this.mainDetails = null; this.flushing = false; this.bufferFlushed = false; this.cachedTrackLoadedData = null; this._registerListeners(); } onHandlerDestroying() { this._unregisterListeners(); super.onHandlerDestroying(); this.mainDetails = null; this.bufferedTrack = null; this.switchingTrack = null; } _registerListeners() { const { hls } = this; hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this); hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.on(Events.ERROR, this.onError, this); hls.on(Events.BUFFER_RESET, this.onBufferReset, this); hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this); hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this); hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this); hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this); } _unregisterListeners() { const { hls } = this; hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this); hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.off(Events.ERROR, this.onError, this); hls.off(Events.BUFFER_RESET, this.onBufferReset, this); hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this); hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this); hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this); hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this); } // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value onInitPtsFound(event, { frag, id, initPTS, timescale }) { if (id === "main") { const cc = frag.cc; this.initPTS[frag.cc] = { baseTime: initPTS, timescale }; this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}`); this.videoTrackCC = cc; if (this.state === State.WAITING_INIT_PTS) { this.tick(); } } } startLoad(startPosition) { if (!this.levels) { this.startPosition = startPosition; this.state = State.STOPPED; return; } const lastCurrentTime = this.lastCurrentTime; this.stopLoad(); this.setInterval(TICK_INTERVAL$2); if (lastCurrentTime > 0 && startPosition === -1) { this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`); startPosition = lastCurrentTime; this.state = State.IDLE; } else { this.loadedmetadata = false; this.state = State.WAITING_TRACK; } this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; this.tick(); } doTick() { switch (this.state) { case State.IDLE: this.doTickIdle(); break; case State.WAITING_TRACK: { var _levels$trackId; const { levels, trackId } = this; const details = levels == null ? void 0 : (_levels$trackId = levels[trackId]) == null ? void 0 : _levels$trackId.details; if (details) { if (this.waitForCdnTuneIn(details)) { break; } this.state = State.WAITING_INIT_PTS; } break; } case State.FRAG_LOADING_WAITING_RETRY: { var _this$media; const now2 = performance.now(); const retryDate = this.retryDate; if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) { const { levels, trackId } = this; this.log("RetryDate reached, switch back to IDLE state"); this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null); this.state = State.IDLE; } break; } case State.WAITING_INIT_PTS: { const waitingData = this.waitingData; if (waitingData) { const { frag, part, cache, complete } = waitingData; if (this.initPTS[frag.cc] !== void 0) { this.waitingData = null; this.waitingVideoCC = -1; this.state = State.FRAG_LOADING; const payload = cache.flush(); const data = { frag, part, payload, networkDetails: null }; this._handleFragmentLoadProgress(data); if (complete) { super._handleFragmentLoadComplete(data); } } else if (this.videoTrackCC !== this.waitingVideoCC) { this.log(`Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${this.videoTrackCC}`); this.clearWaitingFragment(); } else { const pos = this.getLoadPosition(); const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole); const waitingFragmentAtPosition = fragmentWithinToleranceTest(bufferInfo.end, this.config.maxFragLookUpTolerance, frag); if (waitingFragmentAtPosition < 0) { this.log(`Waiting fragment cc (${frag.cc}) @ ${frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`); this.clearWaitingFragment(); } } } else { this.state = State.IDLE; } } } this.onTickEnd(); } clearWaitingFragment() { const waitingData = this.waitingData; if (waitingData) { this.fragmentTracker.removeFragment(waitingData.frag); this.waitingData = null; this.waitingVideoCC = -1; this.state = State.IDLE; } } resetLoadingState() { this.clearWaitingFragment(); super.resetLoadingState(); } onTickEnd() { const { media } = this; if (!(media != null && media.readyState)) { return; } this.lastCurrentTime = media.currentTime; } doTickIdle() { const { hls, levels, media, trackId } = this; const config = hls.config; if (!this.buffering || !media && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) { return; } const levelInfo = levels[trackId]; const trackDetails = levelInfo.details; if (!trackDetails || trackDetails.live && this.levelLastLoaded !== levelInfo || this.waitForCdnTuneIn(trackDetails)) { this.state = State.WAITING_TRACK; return; } const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media; if (this.bufferFlushed && bufferable) { this.bufferFlushed = false; this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO); } const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO); if (bufferInfo === null) { return; } if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) { hls.trigger(Events.BUFFER_EOS, { type: "audio" }); this.state = State.ENDED; return; } const mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, PlaylistLevelType.MAIN); const bufferLen = bufferInfo.len; const maxBufLen = this.getMaxBufferLength(mainBufferInfo == null ? void 0 : mainBufferInfo.len); const fragments = trackDetails.fragments; const start = fragments[0].start; const loadPosition = this.getLoadPosition(); const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end; if (this.switchingTrack && media) { const pos = loadPosition; if (trackDetails.PTSKnown && pos < start) { if (bufferInfo.end > start || bufferInfo.nextStart) { this.log("Alt audio track ahead of main track, seek to start of alt audio track"); media.currentTime = start + 0.05; } } } if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) { return; } let frag = this.getNextFragment(targetBufferTime, trackDetails); let atGap = false; if (frag && this.isLoopLoading(frag, targetBufferTime)) { atGap = !!frag.gap; frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen); } if (!frag) { this.bufferFlushed = true; return; } const atBufferSyncLimit = mainBufferInfo && frag.start > mainBufferInfo.end + trackDetails.targetduration; if (atBufferSyncLimit || // Or wait for main buffer after buffing some audio !(mainBufferInfo != null && mainBufferInfo.len) && bufferInfo.len) { const mainFrag = this.getAppendedFrag(frag.start, PlaylistLevelType.MAIN); if (mainFrag === null) { return; } atGap || (atGap = !!mainFrag.gap || !!atBufferSyncLimit && mainBufferInfo.len === 0); if (atBufferSyncLimit && !atGap || atGap && bufferInfo.nextStart && bufferInfo.nextStart < mainFrag.end) { return; } } this.loadFragment(frag, levelInfo, targetBufferTime); } getMaxBufferLength(mainBufferLength) { const maxConfigBuffer = super.getMaxBufferLength(); if (!mainBufferLength) { return maxConfigBuffer; } return Math.min(Math.max(maxConfigBuffer, mainBufferLength), this.config.maxMaxBufferLength); } onMediaDetaching() { this.videoBuffer = null; this.bufferFlushed = this.flushing = false; super.onMediaDetaching(); } onAudioTracksUpdated(event, { audioTracks }) { this.resetTransmuxer(); this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist)); } onAudioTrackSwitching(event, data) { const altAudio = !!data.url; this.trackId = data.id; const { fragCurrent } = this; if (fragCurrent) { fragCurrent.abortRequests(); this.removeUnbufferedFrags(fragCurrent.start); } this.resetLoadingState(); if (!altAudio) { this.resetTransmuxer(); } else { this.setInterval(TICK_INTERVAL$2); } if (altAudio) { this.switchingTrack = data; this.state = State.IDLE; this.flushAudioIfNeeded(data); } else { this.switchingTrack = null; this.bufferedTrack = data; this.state = State.STOPPED; } this.tick(); } onManifestLoading() { this.fragmentTracker.removeAllFragments(); this.startPosition = this.lastCurrentTime = 0; this.bufferFlushed = this.flushing = false; this.levels = this.mainDetails = this.waitingData = this.bufferedTrack = this.cachedTrackLoadedData = this.switchingTrack = null; this.startFragRequested = false; this.trackId = this.videoTrackCC = this.waitingVideoCC = -1; } onLevelLoaded(event, data) { this.mainDetails = data.details; if (this.cachedTrackLoadedData !== null) { this.hls.trigger(Events.AUDIO_TRACK_LOADED, this.cachedTrackLoadedData); this.cachedTrackLoadedData = null; } } onAudioTrackLoaded(event, data) { var _track$details; if (this.mainDetails == null) { this.cachedTrackLoadedData = data; return; } const { levels } = this; const { details: newDetails, id: trackId } = data; if (!levels) { this.warn(`Audio tracks were reset while loading level ${trackId}`); return; } this.log(`Audio track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`); const track = levels[trackId]; let sliding = 0; if (newDetails.live || (_track$details = track.details) != null && _track$details.live) { this.checkLiveUpdate(newDetails); const mainDetails = this.mainDetails; if (newDetails.deltaUpdateFailed || !mainDetails) { return; } if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) { alignMediaPlaylistByPDT(newDetails, mainDetails); sliding = newDetails.fragments[0].start; } else { var _this$levelLastLoaded; sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details); } } track.details = newDetails; this.levelLastLoaded = track; if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) { this.setStartPosition(this.mainDetails || newDetails, sliding); } if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) { this.state = State.IDLE; } this.tick(); } _handleFragmentLoadProgress(data) { var _frag$initSegment; const { frag, part, payload } = data; const { config, trackId, levels } = this; if (!levels) { this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`); return; } const track = levels[trackId]; if (!track) { this.warn("Audio track is undefined on fragment load progress"); return; } const details = track.details; if (!details) { this.warn("Audio track details undefined on fragment load progress"); this.removeUnbufferedFrags(frag.start); return; } const audioCodec = config.defaultAudioCodec || track.audioCodec || "mp4a.40.2"; let transmuxer = this.transmuxer; if (!transmuxer) { transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)); } const initPTS = this.initPTS[frag.cc]; const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data; if (initPTS !== void 0) { const accurateTimeOffset = false; const partIndex = part ? part.index : -1; const partial = partIndex !== -1; const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial); transmuxer.push(payload, initSegmentData, audioCodec, "", frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS); } else { this.log(`Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`); const { cache } = this.waitingData = this.waitingData || { frag, part, cache: new ChunkCache(), complete: false }; cache.push(new Uint8Array(payload)); this.waitingVideoCC = this.videoTrackCC; this.state = State.WAITING_INIT_PTS; } } _handleFragmentLoadComplete(fragLoadedData) { if (this.waitingData) { this.waitingData.complete = true; return; } super._handleFragmentLoadComplete(fragLoadedData); } onBufferReset() { this.mediaBuffer = this.videoBuffer = null; this.loadedmetadata = false; } onBufferCreated(event, data) { const audioTrack = data.tracks.audio; if (audioTrack) { this.mediaBuffer = audioTrack.buffer || null; } if (data.tracks.video) { this.videoBuffer = data.tracks.video.buffer || null; } } onFragBuffered(event, data) { const { frag, part } = data; if (frag.type !== PlaylistLevelType.AUDIO) { if (!this.loadedmetadata && frag.type === PlaylistLevelType.MAIN) { const bufferable = this.videoBuffer || this.media; if (bufferable) { const bufferedTimeRanges = BufferHelper.getBuffered(bufferable); if (bufferedTimeRanges.length) { this.loadedmetadata = true; } } } return; } if (this.fragContextChanged(frag)) { this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : "false"}`); return; } if (frag.sn !== "initSegment") { this.fragPrevious = frag; const track = this.switchingTrack; if (track) { this.bufferedTrack = track; this.switchingTrack = null; this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread23({}, track)); } } this.fragBufferedComplete(frag, part); } onError(event, data) { var _data$context; if (data.fatal) { this.state = State.ERROR; return; } switch (data.details) { case ErrorDetails.FRAG_GAP: case ErrorDetails.FRAG_PARSING_ERROR: case ErrorDetails.FRAG_DECRYPT_ERROR: case ErrorDetails.FRAG_LOAD_ERROR: case ErrorDetails.FRAG_LOAD_TIMEOUT: case ErrorDetails.KEY_LOAD_ERROR: case ErrorDetails.KEY_LOAD_TIMEOUT: this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data); break; case ErrorDetails.AUDIO_TRACK_LOAD_ERROR: case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT: case ErrorDetails.LEVEL_PARSING_ERROR: if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) { this.state = State.IDLE; } break; case ErrorDetails.BUFFER_APPEND_ERROR: case ErrorDetails.BUFFER_FULL_ERROR: if (!data.parent || data.parent !== "audio") { return; } if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) { this.resetLoadingState(); return; } if (this.reduceLengthAndFlushBuffer(data)) { this.bufferedTrack = null; super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio"); } break; case ErrorDetails.INTERNAL_EXCEPTION: this.recoverWorkerError(data); break; } } onBufferFlushing(event, { type }) { if (type !== ElementaryStreamTypes.VIDEO) { this.flushing = true; } } onBufferFlushed(event, { type }) { if (type !== ElementaryStreamTypes.VIDEO) { this.flushing = false; this.bufferFlushed = true; if (this.state === State.ENDED) { this.state = State.IDLE; } const mediaBuffer = this.mediaBuffer || this.media; if (mediaBuffer) { this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO); this.tick(); } } } _handleTransmuxComplete(transmuxResult) { var _id3$samples; const id = "audio"; const { hls } = this; const { remuxResult, chunkMeta } = transmuxResult; const context = this.getCurrentContext(chunkMeta); if (!context) { this.resetWhenMissingContext(chunkMeta); return; } const { frag, part, level } = context; const { details } = level; const { audio, text, id3, initSegment } = remuxResult; if (this.fragContextChanged(frag) || !details) { this.fragmentTracker.removeFragment(frag); return; } this.state = State.PARSING; if (this.switchingTrack && audio) { this.completeAudioSwitch(this.switchingTrack); } if (initSegment != null && initSegment.tracks) { const mapFragment = frag.initSegment || frag; this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta); hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, { frag: mapFragment, id, tracks: initSegment.tracks }); } if (audio) { const { startPTS, endPTS, startDTS, endDTS } = audio; if (part) { part.elementaryStreams[ElementaryStreamTypes.AUDIO] = { startPTS, endPTS, startDTS, endDTS }; } frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS); this.bufferFragmentData(audio, frag, part, chunkMeta); } if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) { const emittedID3 = _extends2({ id, frag, details }, id3); hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3); } if (text) { const emittedText = _extends2({ id, frag, details }, text); hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText); } } _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) { if (this.state !== State.PARSING) { return; } if (tracks.video) { delete tracks.video; } const track = tracks.audio; if (!track) { return; } track.id = "audio"; const variantAudioCodecs = currentLevel.audioCodec; this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`); if (variantAudioCodecs && variantAudioCodecs.split(",").length === 1) { track.levelCodec = variantAudioCodecs; } this.hls.trigger(Events.BUFFER_CODECS, tracks); const initSegment = track.initSegment; if (initSegment != null && initSegment.byteLength) { const segment = { type: "audio", frag, part: null, chunkMeta, parent: frag.type, data: initSegment }; this.hls.trigger(Events.BUFFER_APPENDING, segment); } this.tickImmediate(); } loadFragment(frag, track, targetBufferTime) { const fragState = this.fragmentTracker.getState(frag); this.fragCurrent = frag; if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) { var _track$details2; if (frag.sn === "initSegment") { this._loadInitSegment(frag, track); } else if ((_track$details2 = track.details) != null && _track$details2.live && !this.initPTS[frag.cc]) { this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`); this.state = State.WAITING_INIT_PTS; const mainDetails = this.mainDetails; if (mainDetails && mainDetails.fragments[0].start !== track.details.fragments[0].start) { alignMediaPlaylistByPDT(track.details, mainDetails); } } else { this.startFragRequested = true; super.loadFragment(frag, track, targetBufferTime); } } else { this.clearTrackerIfNeeded(frag); } } flushAudioIfNeeded(switchingTrack) { if (this.media && this.bufferedTrack) { const { name, lang, assocLang, characteristics, audioCodec, channels } = this.bufferedTrack; if (!matchesOption({ name, lang, assocLang, characteristics, audioCodec, channels }, switchingTrack, audioMatchPredicate)) { this.log("Switching audio track : flushing all audio"); super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio"); this.bufferedTrack = null; } } } completeAudioSwitch(switchingTrack) { const { hls } = this; this.flushAudioIfNeeded(switchingTrack); this.bufferedTrack = switchingTrack; this.switchingTrack = null; hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread23({}, switchingTrack)); } }; function subtitleOptionsIdentical(trackList1, trackList2) { if (trackList1.length !== trackList2.length) { return false; } for (let i3 = 0; i3 < trackList1.length; i3++) { if (!mediaAttributesIdentical(trackList1[i3].attrs, trackList2[i3].attrs)) { return false; } } return true; } function mediaAttributesIdentical(attrs1, attrs2, customAttributes) { const stableRenditionId = attrs1["STABLE-RENDITION-ID"]; if (stableRenditionId && !customAttributes) { return stableRenditionId === attrs2["STABLE-RENDITION-ID"]; } return !(customAttributes || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((subtitleAttribute) => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]); } function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) { return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || "").toLowerCase()); } var AudioTrackController = class extends BasePlaylistController { constructor(hls) { super(hls, "[audio-track-controller]"); this.tracks = []; this.groupIds = null; this.tracksInGroup = []; this.trackId = -1; this.currentTrack = null; this.selectDefaultTrack = true; this.registerListeners(); } registerListeners() { const { hls } = this; hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this); hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.on(Events.ERROR, this.onError, this); } unregisterListeners() { const { hls } = this; hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this); hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this); hls.off(Events.ERROR, this.onError, this); } destroy() { this.unregisterListeners(); this.tracks.length = 0; this.tracksInGroup.length = 0; this.currentTrack = null; super.destroy(); } onManifestLoading() { this.tracks = []; this.tracksInGroup = []; this.groupIds = null; this.currentTrack = null; this.trackId = -1; this.selectDefaultTrack = true; } onManifestParsed(event, data) { this.tracks = data.audioTracks || []; } onAudioTrackLoaded(event, data) { const { id, groupId, details } = data; const trackInActiveGroup = this.tracksInGroup[id]; if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) { this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`); return; } const curDetails = trackInActiveGroup.details; trackInActiveGroup.details = data.details; this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`); if (id === this.trackId) { this.playlistLoaded(id, data, curDetails); } } onLevelLoading(event, data) { this.switchLevel(data.level); } onLevelSwitching(event, data) { this.switchLevel(data.level); } switchLevel(levelIndex) { const levelInfo = this.hls.levels[levelIndex]; if (!levelInfo) { return; } const audioGroups = levelInfo.audioGroups || null; const currentGroups = this.groupIds; let currentTrack = this.currentTrack; if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) { this.groupIds = audioGroups; this.trackId = -1; this.currentTrack = null; const audioTracks = this.tracks.filter((track) => !audioGroups || audioGroups.indexOf(track.groupId) !== -1); if (audioTracks.length) { if (this.selectDefaultTrack && !audioTracks.some((track) => track.default)) { this.selectDefaultTrack = false; } audioTracks.forEach((track, i3) => { track.id = i3; }); } else if (!currentTrack && !this.tracksInGroup.length) { return; } this.tracksInGroup = audioTracks; const audioPreference = this.hls.config.audioPreference; if (!currentTrack && audioPreference) { const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate); if (groupIndex > -1) { currentTrack = audioTracks[groupIndex]; } else { const allIndex = findMatchingOption(audioPreference, this.tracks); currentTrack = this.tracks[allIndex]; } } let trackId = this.findTrackId(currentTrack); if (trackId === -1 && currentTrack) { trackId = this.findTrackId(null); } const audioTracksUpdated = { audioTracks }; this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(",")}`); this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated); const selectedTrackId = this.trackId; if (trackId !== -1 && selectedTrackId === -1) { this.setAudioTrack(trackId); } else if (audioTracks.length && selectedTrackId === -1) { var _this$groupIds; const error = new Error(`No audio track selected for current audio group-ID(s): ${(_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(",")} track count: ${audioTracks.length}`); this.warn(error.message); this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: true, error }); } } else if (this.shouldReloadPlaylist(currentTrack)) { this.setAudioTrack(this.trackId); } } onError(event, data) { if (data.fatal || !data.context) { return; } if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) { this.requestScheduled = -1; this.checkRetry(data); } } get allAudioTracks() { return this.tracks; } get audioTracks() { return this.tracksInGroup; } get audioTrack() { return this.trackId; } set audioTrack(newId) { this.selectDefaultTrack = false; this.setAudioTrack(newId); } setAudioOption(audioOption) { const hls = this.hls; hls.config.audioPreference = audioOption; if (audioOption) { const allAudioTracks = this.allAudioTracks; this.selectDefaultTrack = false; if (allAudioTracks.length) { const currentTrack = this.currentTrack; if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) { return currentTrack; } const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate); if (groupIndex > -1) { const track = this.tracksInGroup[groupIndex]; this.setAudioTrack(groupIndex); return track; } else if (currentTrack) { let searchIndex = hls.loadLevel; if (searchIndex === -1) { searchIndex = hls.firstAutoLevel; } const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate); if (switchIndex === -1) { return null; } hls.nextLoadLevel = switchIndex; } if (audioOption.channels || audioOption.audioCodec) { const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks); if (withoutCodecAndChannelsMatch > -1) { return allAudioTracks[withoutCodecAndChannelsMatch]; } } } } return null; } setAudioTrack(newId) { const tracks = this.tracksInGroup; if (newId < 0 || newId >= tracks.length) { this.warn(`Invalid audio track id: ${newId}`); return; } this.clearTimer(); this.selectDefaultTrack = false; const lastTrack = this.currentTrack; const track = tracks[newId]; const trackLoaded = track.details && !track.details.live; if (newId === this.trackId && track === lastTrack && trackLoaded) { return; } this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`); this.trackId = newId; this.currentTrack = track; this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread23({}, track)); if (trackLoaded) { return; } const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details); this.loadPlaylist(hlsUrlParameters); } findTrackId(currentTrack) { const audioTracks = this.tracksInGroup; for (let i3 = 0; i3 < audioTracks.length; i3++) { const track = audioTracks[i3]; if (this.selectDefaultTrack && !track.default) { continue; } if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) { return i3; } } if (currentTrack) { const { name, lang, assocLang, characteristics, audioCodec, channels } = currentTrack; for (let i3 = 0; i3 < audioTracks.length; i3++) { const track = audioTracks[i3]; if (matchesOption({ name, lang, assocLang, characteristics, audioCodec, channels }, track, audioMatchPredicate)) { return i3; } } for (let i3 = 0; i3 < audioTracks.length; i3++) { const track = audioTracks[i3]; if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) { return i3; } } for (let i3 = 0; i3 < audioTracks.length; i3++) { const track = audioTracks[i3]; if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) { return i3; } } } return -1; } loadPlaylist(hlsUrlParameters) { const audioTrack = this.currentTrack; if (this.shouldLoadPlaylist(audioTrack) && audioTrack) { super.loadPlaylist(); const id = audioTrack.id; const groupId = audioTrack.groupId; let url = audioTrack.url; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`); } } this.log(`loading audio-track playlist ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}`); this.clearTimer(); this.hls.trigger(Events.AUDIO_TRACK_LOADING, { url, id, groupId, deliveryDirectives: hlsUrlParameters || null }); } } }; var TICK_INTERVAL$1 = 500; var SubtitleStreamController = class extends BaseStreamController { constructor(hls, fragmentTracker, keyLoader) { super(hls, fragmentTracker, keyLoader, "[subtitle-stream-controller]", PlaylistLevelType.SUBTITLE); this.currentTrackId = -1; this.tracksBuffered = []; this.mainDetails = null; this._registerListeners(); } onHandlerDestroying() { this._unregisterListeners(); super.onHandlerDestroying(); this.mainDetails = null; } _registerListeners() { const { hls } = this; hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.on(Events.ERROR, this.onError, this); hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this); hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this); hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this); } _unregisterListeners() { const { hls } = this; hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.off(Events.ERROR, this.onError, this); hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this); hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this); hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this); } startLoad(startPosition) { this.stopLoad(); this.state = State.IDLE; this.setInterval(TICK_INTERVAL$1); this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; this.tick(); } onManifestLoading() { this.mainDetails = null; this.fragmentTracker.removeAllFragments(); } onMediaDetaching() { this.tracksBuffered = []; super.onMediaDetaching(); } onLevelLoaded(event, data) { this.mainDetails = data.details; } onSubtitleFragProcessed(event, data) { const { frag, success } = data; this.fragPrevious = frag; this.state = State.IDLE; if (!success) { return; } const buffered = this.tracksBuffered[this.currentTrackId]; if (!buffered) { return; } let timeRange; const fragStart = frag.start; for (let i3 = 0; i3 < buffered.length; i3++) { if (fragStart >= buffered[i3].start && fragStart <= buffered[i3].end) { timeRange = buffered[i3]; break; } } const fragEnd = frag.start + frag.duration; if (timeRange) { timeRange.end = fragEnd; } else { timeRange = { start: fragStart, end: fragEnd }; buffered.push(timeRange); } this.fragmentTracker.fragBuffered(frag); this.fragBufferedComplete(frag, null); } onBufferFlushing(event, data) { const { startOffset, endOffset } = data; if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) { const endOffsetSubtitles = endOffset - 1; if (endOffsetSubtitles <= 0) { return; } data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles); this.tracksBuffered.forEach((buffered) => { for (let i3 = 0; i3 < buffered.length; ) { if (buffered[i3].end <= endOffsetSubtitles) { buffered.shift(); continue; } else if (buffered[i3].start < endOffsetSubtitles) { buffered[i3].start = endOffsetSubtitles; } else { break; } i3++; } }); this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE); } } onFragBuffered(event, data) { if (!this.loadedmetadata && data.frag.type === PlaylistLevelType.MAIN) { var _this$media; if ((_this$media = this.media) != null && _this$media.buffered.length) { this.loadedmetadata = true; } } } // If something goes wrong, proceed to next frag, if we were processing one. onError(event, data) { const frag = data.frag; if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) { if (data.details === ErrorDetails.FRAG_GAP) { this.fragmentTracker.fragBuffered(frag, true); } if (this.fragCurrent) { this.fragCurrent.abortRequests(); } if (this.state !== State.STOPPED) { this.state = State.IDLE; } } } // Got all new subtitle levels. onSubtitleTracksUpdated(event, { subtitleTracks }) { if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) { this.levels = subtitleTracks.map((mediaPlaylist) => new Level(mediaPlaylist)); return; } this.tracksBuffered = []; this.levels = subtitleTracks.map((mediaPlaylist) => { const level = new Level(mediaPlaylist); this.tracksBuffered[level.id] = []; return level; }); this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE); this.fragPrevious = null; this.mediaBuffer = null; } onSubtitleTrackSwitch(event, data) { var _this$levels; this.currentTrackId = data.id; if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) { this.clearInterval(); return; } const currentTrack = this.levels[this.currentTrackId]; if (currentTrack != null && currentTrack.details) { this.mediaBuffer = this.mediaBufferTimeRanges; } else { this.mediaBuffer = null; } if (currentTrack) { this.setInterval(TICK_INTERVAL$1); } } // Got a new set of subtitle fragments. onSubtitleTrackLoaded(event, data) { var _track$details; const { currentTrackId, levels } = this; const { details: newDetails, id: trackId } = data; if (!levels) { this.warn(`Subtitle tracks were reset while loading level ${trackId}`); return; } const track = levels[trackId]; if (trackId >= levels.length || !track) { return; } this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""},duration:${newDetails.totalduration}`); this.mediaBuffer = this.mediaBufferTimeRanges; let sliding = 0; if (newDetails.live || (_track$details = track.details) != null && _track$details.live) { const mainDetails = this.mainDetails; if (newDetails.deltaUpdateFailed || !mainDetails) { return; } const mainSlidingStartFragment = mainDetails.fragments[0]; if (!track.details) { if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) { alignMediaPlaylistByPDT(newDetails, mainDetails); sliding = newDetails.fragments[0].start; } else if (mainSlidingStartFragment) { sliding = mainSlidingStartFragment.start; addSliding(newDetails, sliding); } } else { var _this$levelLastLoaded; sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details); if (sliding === 0 && mainSlidingStartFragment) { sliding = mainSlidingStartFragment.start; addSliding(newDetails, sliding); } } } track.details = newDetails; this.levelLastLoaded = track; if (trackId !== currentTrackId) { return; } if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) { this.setStartPosition(this.mainDetails || newDetails, sliding); } this.tick(); if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) { const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0); if (!foundFrag) { this.warn("Subtitle playlist not aligned with playback"); track.details = void 0; } } } _handleFragmentLoadComplete(fragLoadedData) { const { frag, payload } = fragLoadedData; const decryptData = frag.decryptdata; const hls = this.hls; if (this.fragContextChanged(frag)) { return; } if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === "AES-128") { const startTime = performance.now(); this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch((err) => { hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_DECRYPT_ERROR, fatal: false, error: err, reason: err.message, frag }); throw err; }).then((decryptedData) => { const endTime = performance.now(); hls.trigger(Events.FRAG_DECRYPTED, { frag, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); }).catch((err) => { this.warn(`${err.name}: ${err.message}`); this.state = State.IDLE; }); } } doTick() { if (!this.media) { this.state = State.IDLE; return; } if (this.state === State.IDLE) { const { currentTrackId, levels } = this; const track = levels == null ? void 0 : levels[currentTrackId]; if (!track || !levels.length || !track.details) { return; } const { config } = this; const currentTime = this.getLoadPosition(); const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole); const { end: targetBufferTime, len: bufferLen } = bufferedInfo; const mainBufferInfo = this.getFwdBufferInfo(this.media, PlaylistLevelType.MAIN); const trackDetails = track.details; const maxBufLen = this.getMaxBufferLength(mainBufferInfo == null ? void 0 : mainBufferInfo.len) + trackDetails.levelTargetDuration; if (bufferLen > maxBufLen) { return; } const fragments = trackDetails.fragments; const fragLen = fragments.length; const end = trackDetails.edge; let foundFrag = null; const fragPrevious = this.fragPrevious; if (targetBufferTime < end) { const tolerance = config.maxFragLookUpTolerance; const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance; foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance); if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) { foundFrag = fragments[0]; } } else { foundFrag = fragments[fragLen - 1]; } if (!foundFrag) { return; } foundFrag = this.mapToInitFragWhenRequired(foundFrag); if (foundFrag.sn !== "initSegment") { const curSNIdx = foundFrag.sn - trackDetails.startSN; const prevFrag = fragments[curSNIdx - 1]; if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) { foundFrag = prevFrag; } } if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) { this.loadFragment(foundFrag, track, targetBufferTime); } } } getMaxBufferLength(mainBufferLength) { const maxConfigBuffer = super.getMaxBufferLength(); if (!mainBufferLength) { return maxConfigBuffer; } return Math.max(maxConfigBuffer, mainBufferLength); } loadFragment(frag, level, targetBufferTime) { this.fragCurrent = frag; if (frag.sn === "initSegment") { this._loadInitSegment(frag, level); } else { this.startFragRequested = true; super.loadFragment(frag, level, targetBufferTime); } } get mediaBufferTimeRanges() { return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []); } }; var BufferableInstance = class { constructor(timeranges) { this.buffered = void 0; const getRange = (name, index2, length2) => { index2 = index2 >>> 0; if (index2 > length2 - 1) { throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index2}) is greater than the maximum bound (${length2})`); } return timeranges[index2][name]; }; this.buffered = { get length() { return timeranges.length; }, end(index2) { return getRange("end", index2, timeranges.length); }, start(index2) { return getRange("start", index2, timeranges.length); } }; } }; var SubtitleTrackController = class extends BasePlaylistController { constructor(hls) { super(hls, "[subtitle-track-controller]"); this.media = null; this.tracks = []; this.groupIds = null; this.tracksInGroup = []; this.trackId = -1; this.currentTrack = null; this.selectDefaultTrack = true; this.queuedDefaultTrack = -1; this.asyncPollTrackChange = () => this.pollTrackChange(0); this.useTextTrackPolling = false; this.subtitlePollingInterval = -1; this._subtitleDisplay = true; this.onTextTracksChanged = () => { if (!this.useTextTrackPolling) { self.clearInterval(this.subtitlePollingInterval); } if (!this.media || !this.hls.config.renderTextTracksNatively) { return; } let textTrack = null; const tracks = filterSubtitleTracks(this.media.textTracks); for (let i3 = 0; i3 < tracks.length; i3++) { if (tracks[i3].mode === "hidden") { textTrack = tracks[i3]; } else if (tracks[i3].mode === "showing") { textTrack = tracks[i3]; break; } } const trackId = this.findTrackForTextTrack(textTrack); if (this.subtitleTrack !== trackId) { this.setSubtitleTrack(trackId); } }; this.registerListeners(); } destroy() { this.unregisterListeners(); this.tracks.length = 0; this.tracksInGroup.length = 0; this.currentTrack = null; this.onTextTracksChanged = this.asyncPollTrackChange = null; super.destroy(); } get subtitleDisplay() { return this._subtitleDisplay; } set subtitleDisplay(value) { this._subtitleDisplay = value; if (this.trackId > -1) { this.toggleTrackModes(); } } registerListeners() { const { hls } = this; hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this); hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.on(Events.ERROR, this.onError, this); } unregisterListeners() { const { hls } = this; hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this); hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this); hls.off(Events.ERROR, this.onError, this); } // Listen for subtitle track change, then extract the current track ID. onMediaAttached(event, data) { this.media = data.media; if (!this.media) { return; } if (this.queuedDefaultTrack > -1) { this.subtitleTrack = this.queuedDefaultTrack; this.queuedDefaultTrack = -1; } this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks); if (this.useTextTrackPolling) { this.pollTrackChange(500); } else { this.media.textTracks.addEventListener("change", this.asyncPollTrackChange); } } pollTrackChange(timeout) { self.clearInterval(this.subtitlePollingInterval); this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout); } onMediaDetaching() { if (!this.media) { return; } self.clearInterval(this.subtitlePollingInterval); if (!this.useTextTrackPolling) { this.media.textTracks.removeEventListener("change", this.asyncPollTrackChange); } if (this.trackId > -1) { this.queuedDefaultTrack = this.trackId; } const textTracks = filterSubtitleTracks(this.media.textTracks); textTracks.forEach((track) => { clearCurrentCues(track); }); this.subtitleTrack = -1; this.media = null; } onManifestLoading() { this.tracks = []; this.groupIds = null; this.tracksInGroup = []; this.trackId = -1; this.currentTrack = null; this.selectDefaultTrack = true; } // Fired whenever a new manifest is loaded. onManifestParsed(event, data) { this.tracks = data.subtitleTracks; } onSubtitleTrackLoaded(event, data) { const { id, groupId, details } = data; const trackInActiveGroup = this.tracksInGroup[id]; if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) { this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`); return; } const curDetails = trackInActiveGroup.details; trackInActiveGroup.details = data.details; this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`); if (id === this.trackId) { this.playlistLoaded(id, data, curDetails); } } onLevelLoading(event, data) { this.switchLevel(data.level); } onLevelSwitching(event, data) { this.switchLevel(data.level); } switchLevel(levelIndex) { const levelInfo = this.hls.levels[levelIndex]; if (!levelInfo) { return; } const subtitleGroups = levelInfo.subtitleGroups || null; const currentGroups = this.groupIds; let currentTrack = this.currentTrack; if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some((groupId) => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) { this.groupIds = subtitleGroups; this.trackId = -1; this.currentTrack = null; const subtitleTracks = this.tracks.filter((track) => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1); if (subtitleTracks.length) { if (this.selectDefaultTrack && !subtitleTracks.some((track) => track.default)) { this.selectDefaultTrack = false; } subtitleTracks.forEach((track, i3) => { track.id = i3; }); } else if (!currentTrack && !this.tracksInGroup.length) { return; } this.tracksInGroup = subtitleTracks; const subtitlePreference = this.hls.config.subtitlePreference; if (!currentTrack && subtitlePreference) { this.selectDefaultTrack = false; const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks); if (groupIndex > -1) { currentTrack = subtitleTracks[groupIndex]; } else { const allIndex = findMatchingOption(subtitlePreference, this.tracks); currentTrack = this.tracks[allIndex]; } } let trackId = this.findTrackId(currentTrack); if (trackId === -1 && currentTrack) { trackId = this.findTrackId(null); } const subtitleTracksUpdated = { subtitleTracks }; this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(",")}" group-id`); this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated); if (trackId !== -1 && this.trackId === -1) { this.setSubtitleTrack(trackId); } } else if (this.shouldReloadPlaylist(currentTrack)) { this.setSubtitleTrack(this.trackId); } } findTrackId(currentTrack) { const tracks = this.tracksInGroup; const selectDefault = this.selectDefaultTrack; for (let i3 = 0; i3 < tracks.length; i3++) { const track = tracks[i3]; if (selectDefault && !track.default || !selectDefault && !currentTrack) { continue; } if (!currentTrack || matchesOption(track, currentTrack)) { return i3; } } if (currentTrack) { for (let i3 = 0; i3 < tracks.length; i3++) { const track = tracks[i3]; if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"])) { return i3; } } for (let i3 = 0; i3 < tracks.length; i3++) { const track = tracks[i3]; if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ["LANGUAGE"])) { return i3; } } } return -1; } findTrackForTextTrack(textTrack) { if (textTrack) { const tracks = this.tracksInGroup; for (let i3 = 0; i3 < tracks.length; i3++) { const track = tracks[i3]; if (subtitleTrackMatchesTextTrack(track, textTrack)) { return i3; } } } return -1; } onError(event, data) { if (data.fatal || !data.context) { return; } if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) { this.checkRetry(data); } } get allSubtitleTracks() { return this.tracks; } /** get alternate subtitle tracks list from playlist **/ get subtitleTracks() { return this.tracksInGroup; } /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/ get subtitleTrack() { return this.trackId; } set subtitleTrack(newId) { this.selectDefaultTrack = false; this.setSubtitleTrack(newId); } setSubtitleOption(subtitleOption) { this.hls.config.subtitlePreference = subtitleOption; if (subtitleOption) { const allSubtitleTracks = this.allSubtitleTracks; this.selectDefaultTrack = false; if (allSubtitleTracks.length) { const currentTrack = this.currentTrack; if (currentTrack && matchesOption(subtitleOption, currentTrack)) { return currentTrack; } const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup); if (groupIndex > -1) { const track = this.tracksInGroup[groupIndex]; this.setSubtitleTrack(groupIndex); return track; } else if (currentTrack) { return null; } else { const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks); if (allIndex > -1) { return allSubtitleTracks[allIndex]; } } } } return null; } loadPlaylist(hlsUrlParameters) { super.loadPlaylist(); const currentTrack = this.currentTrack; if (this.shouldLoadPlaylist(currentTrack) && currentTrack) { const id = currentTrack.id; const groupId = currentTrack.groupId; let url = currentTrack.url; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`); } } this.log(`Loading subtitle playlist for id ${id}`); this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, { url, id, groupId, deliveryDirectives: hlsUrlParameters || null }); } } /** * Disables the old subtitleTrack and sets current mode on the next subtitleTrack. * This operates on the DOM textTracks. * A value of -1 will disable all subtitle tracks. */ toggleTrackModes() { const { media } = this; if (!media) { return; } const textTracks = filterSubtitleTracks(media.textTracks); const currentTrack = this.currentTrack; let nextTrack; if (currentTrack) { nextTrack = textTracks.filter((textTrack) => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0]; if (!nextTrack) { this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`); } } [].slice.call(textTracks).forEach((track) => { if (track.mode !== "disabled" && track !== nextTrack) { track.mode = "disabled"; } }); if (nextTrack) { const mode = this.subtitleDisplay ? "showing" : "hidden"; if (nextTrack.mode !== mode) { nextTrack.mode = mode; } } } /** * This method is responsible for validating the subtitle index and periodically reloading if live. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track. */ setSubtitleTrack(newId) { const tracks = this.tracksInGroup; if (!this.media) { this.queuedDefaultTrack = newId; return; } if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) { this.warn(`Invalid subtitle track id: ${newId}`); return; } this.clearTimer(); this.selectDefaultTrack = false; const lastTrack = this.currentTrack; const track = tracks[newId] || null; this.trackId = newId; this.currentTrack = track; this.toggleTrackModes(); if (!track) { this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, { id: newId }); return; } const trackLoaded = !!track.details && !track.details.live; if (newId === this.trackId && track === lastTrack && trackLoaded) { return; } this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : "")); const { id, groupId = "", name, type, url } = track; this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, { id, groupId, name, type, url }); const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details); this.loadPlaylist(hlsUrlParameters); } }; var BufferOperationQueue = class { constructor(sourceBufferReference) { this.buffers = void 0; this.queues = { video: [], audio: [], audiovideo: [] }; this.buffers = sourceBufferReference; } append(operation, type, pending) { const queue = this.queues[type]; queue.push(operation); if (queue.length === 1 && !pending) { this.executeNext(type); } } insertAbort(operation, type) { const queue = this.queues[type]; queue.unshift(operation); this.executeNext(type); } appendBlocker(type) { let execute; const promise = new Promise((resolve) => { execute = resolve; }); const operation = { execute, onStart: () => { }, onComplete: () => { }, onError: () => { } }; this.append(operation, type); return promise; } executeNext(type) { const queue = this.queues[type]; if (queue.length) { const operation = queue[0]; try { operation.execute(); } catch (error) { logger.warn(`[buffer-operation-queue]: Exception executing "${type}" SourceBuffer operation: ${error}`); operation.onError(error); const sb = this.buffers[type]; if (!(sb != null && sb.updating)) { this.shiftAndExecuteNext(type); } } } } shiftAndExecuteNext(type) { this.queues[type].shift(); this.executeNext(type); } current(type) { return this.queues[type][0]; } }; var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/; var BufferController = class { constructor(hls) { this.details = null; this._objectUrl = null; this.operationQueue = void 0; this.listeners = void 0; this.hls = void 0; this.bufferCodecEventsExpected = 0; this._bufferCodecEventsTotal = 0; this.media = null; this.mediaSource = null; this.lastMpegAudioChunk = null; this.appendSource = void 0; this.appendErrors = { audio: 0, video: 0, audiovideo: 0 }; this.tracks = {}; this.pendingTracks = {}; this.sourceBuffer = void 0; this.log = void 0; this.warn = void 0; this.error = void 0; this._onEndStreaming = (event) => { if (!this.hls) { return; } this.hls.pauseBuffering(); }; this._onStartStreaming = (event) => { if (!this.hls) { return; } this.hls.resumeBuffering(); }; this._onMediaSourceOpen = () => { const { media, mediaSource } = this; this.log("Media source opened"); if (media) { media.removeEventListener("emptied", this._onMediaEmptied); this.updateMediaElementDuration(); this.hls.trigger(Events.MEDIA_ATTACHED, { media, mediaSource }); } if (mediaSource) { mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen); } this.checkPendingTracks(); }; this._onMediaSourceClose = () => { this.log("Media source closed"); }; this._onMediaSourceEnded = () => { this.log("Media source ended"); }; this._onMediaEmptied = () => { const { mediaSrc, _objectUrl } = this; if (mediaSrc !== _objectUrl) { logger.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`); } }; this.hls = hls; const logPrefix = "[buffer-controller]"; this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource)); this.log = logger.log.bind(logger, logPrefix); this.warn = logger.warn.bind(logger, logPrefix); this.error = logger.error.bind(logger, logPrefix); this._initSourceBuffer(); this.registerListeners(); } hasSourceTypes() { return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0; } destroy() { this.unregisterListeners(); this.details = null; this.lastMpegAudioChunk = null; this.hls = null; } registerListeners() { const { hls } = this; hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.on(Events.BUFFER_RESET, this.onBufferReset, this); hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this); hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this); hls.on(Events.BUFFER_EOS, this.onBufferEos, this); hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this); hls.on(Events.FRAG_PARSED, this.onFragParsed, this); hls.on(Events.FRAG_CHANGED, this.onFragChanged, this); } unregisterListeners() { const { hls } = this; hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.off(Events.BUFFER_RESET, this.onBufferReset, this); hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this); hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this); hls.off(Events.BUFFER_EOS, this.onBufferEos, this); hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this); hls.off(Events.FRAG_PARSED, this.onFragParsed, this); hls.off(Events.FRAG_CHANGED, this.onFragChanged, this); } _initSourceBuffer() { this.sourceBuffer = {}; this.operationQueue = new BufferOperationQueue(this.sourceBuffer); this.listeners = { audio: [], video: [], audiovideo: [] }; this.appendErrors = { audio: 0, video: 0, audiovideo: 0 }; this.lastMpegAudioChunk = null; } onManifestLoading() { this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0; this.details = null; } onManifestParsed(event, data) { let codecEvents = 2; if (data.audio && !data.video || !data.altAudio || false) { codecEvents = 1; } this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents; this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`); } onMediaAttaching(event, data) { const media = this.media = data.media; const MediaSource = getMediaSource(this.appendSource); if (media && MediaSource) { var _ms$constructor; const ms = this.mediaSource = new MediaSource(); this.log(`created media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`); ms.addEventListener("sourceopen", this._onMediaSourceOpen); ms.addEventListener("sourceended", this._onMediaSourceEnded); ms.addEventListener("sourceclose", this._onMediaSourceClose); if (this.appendSource) { ms.addEventListener("startstreaming", this._onStartStreaming); ms.addEventListener("endstreaming", this._onEndStreaming); } const objectUrl = this._objectUrl = self.URL.createObjectURL(ms); if (this.appendSource) { try { media.removeAttribute("src"); const MMS = self.ManagedMediaSource; media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS; removeSourceChildren(media); addSource(media, objectUrl); media.load(); } catch (error) { media.src = objectUrl; } } else { media.src = objectUrl; } media.addEventListener("emptied", this._onMediaEmptied); } } onMediaDetaching() { const { media, mediaSource, _objectUrl } = this; if (mediaSource) { this.log("media source detaching"); if (mediaSource.readyState === "open") { try { mediaSource.endOfStream(); } catch (err) { this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`); } } this.onBufferReset(); mediaSource.removeEventListener("sourceopen", this._onMediaSourceOpen); mediaSource.removeEventListener("sourceended", this._onMediaSourceEnded); mediaSource.removeEventListener("sourceclose", this._onMediaSourceClose); if (this.appendSource) { mediaSource.removeEventListener("startstreaming", this._onStartStreaming); mediaSource.removeEventListener("endstreaming", this._onEndStreaming); } if (media) { media.removeEventListener("emptied", this._onMediaEmptied); if (_objectUrl) { self.URL.revokeObjectURL(_objectUrl); } if (this.mediaSrc === _objectUrl) { media.removeAttribute("src"); if (this.appendSource) { removeSourceChildren(media); } media.load(); } else { this.warn("media|source.src was changed by a third party - skip cleanup"); } } this.mediaSource = null; this.media = null; this._objectUrl = null; this.bufferCodecEventsExpected = this._bufferCodecEventsTotal; this.pendingTracks = {}; this.tracks = {}; } this.hls.trigger(Events.MEDIA_DETACHED, void 0); } onBufferReset() { this.getSourceBufferTypes().forEach((type) => { this.resetBuffer(type); }); this._initSourceBuffer(); this.hls.resumeBuffering(); } resetBuffer(type) { const sb = this.sourceBuffer[type]; try { if (sb) { var _this$mediaSource; this.removeBufferListeners(type); this.sourceBuffer[type] = void 0; if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) { this.mediaSource.removeSourceBuffer(sb); } } } catch (err) { this.warn(`onBufferReset ${type}`, err); } } onBufferCodecs(event, data) { const sourceBufferCount = this.getSourceBufferTypes().length; const trackNames = Object.keys(data); trackNames.forEach((trackName) => { if (sourceBufferCount) { const track = this.tracks[trackName]; if (track && typeof track.buffer.changeType === "function") { var _trackCodec; const { id, codec, levelCodec, container, metadata } = data[trackName]; const currentCodecFull = pickMostCompleteCodecName(track.codec, track.levelCodec); const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1"); let trackCodec = pickMostCompleteCodecName(codec, levelCodec); const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, "$1"); if (trackCodec && currentCodec !== nextCodec) { if (trackName.slice(0, 5) === "audio") { trackCodec = getCodecCompatibleName(trackCodec, this.appendSource); } const mimeType = `${container};codecs=${trackCodec}`; this.appendChangeType(trackName, mimeType); this.log(`switching codec ${currentCodecFull} to ${trackCodec}`); this.tracks[trackName] = { buffer: track.buffer, codec, container, levelCodec, metadata, id }; } } } else { this.pendingTracks[trackName] = data[trackName]; } }); if (sourceBufferCount) { return; } const bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0); if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) { this.log(`${bufferCodecEventsExpected} bufferCodec event(s) expected ${trackNames.join(",")}`); this.bufferCodecEventsExpected = bufferCodecEventsExpected; } if (this.mediaSource && this.mediaSource.readyState === "open") { this.checkPendingTracks(); } } appendChangeType(type, mimeType) { const { operationQueue } = this; const operation = { execute: () => { const sb = this.sourceBuffer[type]; if (sb) { this.log(`changing ${type} sourceBuffer type to ${mimeType}`); sb.changeType(mimeType); } operationQueue.shiftAndExecuteNext(type); }, onStart: () => { }, onComplete: () => { }, onError: (error) => { this.warn(`Failed to change ${type} SourceBuffer type`, error); } }; operationQueue.append(operation, type, !!this.pendingTracks[type]); } onBufferAppending(event, eventData) { const { hls, operationQueue, tracks } = this; const { data, type, frag, part, chunkMeta } = eventData; const chunkStats = chunkMeta.buffering[type]; const bufferAppendingStart = self.performance.now(); chunkStats.start = bufferAppendingStart; const fragBuffering = frag.stats.buffering; const partBuffering = part ? part.stats.buffering : null; if (fragBuffering.start === 0) { fragBuffering.start = bufferAppendingStart; } if (partBuffering && partBuffering.start === 0) { partBuffering.start = bufferAppendingStart; } const audioTrack = tracks.audio; let checkTimestampOffset = false; if (type === "audio" && (audioTrack == null ? void 0 : audioTrack.container) === "audio/mpeg") { checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn; this.lastMpegAudioChunk = chunkMeta; } const fragStart = frag.start; const operation = { execute: () => { chunkStats.executeStart = self.performance.now(); if (checkTimestampOffset) { const sb = this.sourceBuffer[type]; if (sb) { const delta = fragStart - sb.timestampOffset; if (Math.abs(delta) >= 0.1) { this.log(`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`); sb.timestampOffset = fragStart; } } } this.appendExecutor(data, type); }, onStart: () => { }, onComplete: () => { const end = self.performance.now(); chunkStats.executeEnd = chunkStats.end = end; if (fragBuffering.first === 0) { fragBuffering.first = end; } if (partBuffering && partBuffering.first === 0) { partBuffering.first = end; } const { sourceBuffer } = this; const timeRanges = {}; for (const type2 in sourceBuffer) { timeRanges[type2] = BufferHelper.getBuffered(sourceBuffer[type2]); } this.appendErrors[type] = 0; if (type === "audio" || type === "video") { this.appendErrors.audiovideo = 0; } else { this.appendErrors.audio = 0; this.appendErrors.video = 0; } this.hls.trigger(Events.BUFFER_APPENDED, { type, frag, part, chunkMeta, parent: frag.type, timeRanges }); }, onError: (error) => { const event2 = { type: ErrorTypes.MEDIA_ERROR, parent: frag.type, details: ErrorDetails.BUFFER_APPEND_ERROR, sourceBufferName: type, frag, part, chunkMeta, error, err: error, fatal: false }; if (error.code === DOMException.QUOTA_EXCEEDED_ERR) { event2.details = ErrorDetails.BUFFER_FULL_ERROR; } else { const appendErrorCount = ++this.appendErrors[type]; event2.details = ErrorDetails.BUFFER_APPEND_ERROR; this.warn(`Failed ${appendErrorCount}/${hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer`); if (appendErrorCount >= hls.config.appendErrorMaxRetry) { event2.fatal = true; } } hls.trigger(Events.ERROR, event2); } }; operationQueue.append(operation, type, !!this.pendingTracks[type]); } onBufferFlushing(event, data) { const { operationQueue } = this; const flushOperation = (type) => ({ execute: this.removeExecutor.bind(this, type, data.startOffset, data.endOffset), onStart: () => { }, onComplete: () => { this.hls.trigger(Events.BUFFER_FLUSHED, { type }); }, onError: (error) => { this.warn(`Failed to remove from ${type} SourceBuffer`, error); } }); if (data.type) { operationQueue.append(flushOperation(data.type), data.type); } else { this.getSourceBufferTypes().forEach((type) => { operationQueue.append(flushOperation(type), type); }); } } onFragParsed(event, data) { const { frag, part } = data; const buffersAppendedTo = []; const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams; if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) { buffersAppendedTo.push("audiovideo"); } else { if (elementaryStreams[ElementaryStreamTypes.AUDIO]) { buffersAppendedTo.push("audio"); } if (elementaryStreams[ElementaryStreamTypes.VIDEO]) { buffersAppendedTo.push("video"); } } const onUnblocked = () => { const now2 = self.performance.now(); frag.stats.buffering.end = now2; if (part) { part.stats.buffering.end = now2; } const stats = part ? part.stats : frag.stats; this.hls.trigger(Events.FRAG_BUFFERED, { frag, part, stats, id: frag.type }); }; if (buffersAppendedTo.length === 0) { this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`); } this.blockBuffers(onUnblocked, buffersAppendedTo); } onFragChanged(event, data) { this.trimBuffers(); } // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos() // an undefined data.type will mark all buffers as EOS. onBufferEos(event, data) { const ended = this.getSourceBufferTypes().reduce((acc, type) => { const sb = this.sourceBuffer[type]; if (sb && (!data.type || data.type === type)) { sb.ending = true; if (!sb.ended) { sb.ended = true; this.log(`${type} sourceBuffer now EOS`); } } return acc && !!(!sb || sb.ended); }, true); if (ended) { this.log(`Queueing mediaSource.endOfStream()`); this.blockBuffers(() => { this.getSourceBufferTypes().forEach((type) => { const sb = this.sourceBuffer[type]; if (sb) { sb.ending = false; } }); const { mediaSource } = this; if (!mediaSource || mediaSource.readyState !== "open") { if (mediaSource) { this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`); } return; } this.log(`Calling mediaSource.endOfStream()`); mediaSource.endOfStream(); }); } } onLevelUpdated(event, { details }) { if (!details.fragments.length) { return; } this.details = details; if (this.getSourceBufferTypes().length) { this.blockBuffers(this.updateMediaElementDuration.bind(this)); } else { this.updateMediaElementDuration(); } } trimBuffers() { const { hls, details, media } = this; if (!media || details === null) { return; } const sourceBufferTypes = this.getSourceBufferTypes(); if (!sourceBufferTypes.length) { return; } const config = hls.config; const currentTime = media.currentTime; const targetDuration = details.levelTargetDuration; const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength; if (isFiniteNumber(backBufferLength) && backBufferLength > 0) { const maxBackBufferLength = Math.max(backBufferLength, targetDuration); const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength; this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition); } if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) { const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold); const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration); const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength; this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition); } } flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) { const { details, sourceBuffer } = this; const sourceBufferTypes = this.getSourceBufferTypes(); sourceBufferTypes.forEach((type) => { const sb = sourceBuffer[type]; if (sb) { const buffered = BufferHelper.getBuffered(sb); if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) { this.hls.trigger(Events.BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition }); if (details != null && details.live) { this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition }); } else if (sb.ended && buffered.end(buffered.length - 1) - currentTime < targetDuration * 2) { this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`); return; } this.hls.trigger(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: targetBackBufferPosition, type }); } } }); } flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) { const { sourceBuffer } = this; const sourceBufferTypes = this.getSourceBufferTypes(); sourceBufferTypes.forEach((type) => { const sb = sourceBuffer[type]; if (sb) { const buffered = BufferHelper.getBuffered(sb); const numBufferedRanges = buffered.length; if (numBufferedRanges < 2) { return; } const bufferStart = buffered.start(numBufferedRanges - 1); const bufferEnd = buffered.end(numBufferedRanges - 1); if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) { return; } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) { this.log(`Cannot flush ${type} front buffer while SourceBuffer is in ended state`); return; } this.hls.trigger(Events.BUFFER_FLUSHING, { startOffset: bufferStart, endOffset: Infinity, type }); } }); } /** * Update Media Source duration to current level duration or override to Infinity if configuration parameter * 'liveDurationInfinity` is set to `true` * More details: https://github.com/video-dev/hls.js/issues/355 */ updateMediaElementDuration() { if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== "open") { return; } const { details, hls, media, mediaSource } = this; const levelDuration = details.fragments[0].start + details.totalduration; const mediaDuration = media.duration; const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0; if (details.live && hls.config.liveDurationInfinity) { mediaSource.duration = Infinity; this.updateSeekableRange(details); } else if (levelDuration > msDuration && levelDuration > mediaDuration || !isFiniteNumber(mediaDuration)) { this.log(`Updating Media Source duration to ${levelDuration.toFixed(3)}`); mediaSource.duration = levelDuration; } } updateSeekableRange(levelDetails) { const mediaSource = this.mediaSource; const fragments = levelDetails.fragments; const len = fragments.length; if (len && levelDetails.live && mediaSource != null && mediaSource.setLiveSeekableRange) { const start = Math.max(0, fragments[0].start); const end = Math.max(start, start + levelDetails.totalduration); this.log(`Media Source duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`); mediaSource.setLiveSeekableRange(start, end); } } checkPendingTracks() { const { bufferCodecEventsExpected, operationQueue, pendingTracks } = this; const pendingTracksCount = Object.keys(pendingTracks).length; if (pendingTracksCount && (!bufferCodecEventsExpected || pendingTracksCount === 2 || "audiovideo" in pendingTracks)) { this.createSourceBuffers(pendingTracks); this.pendingTracks = {}; const buffers = this.getSourceBufferTypes(); if (buffers.length) { this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks }); buffers.forEach((type) => { operationQueue.executeNext(type); }); } else { const error = new Error("could not create source buffer for media codec(s)"); this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR, fatal: true, error, reason: error.message }); } } } createSourceBuffers(tracks) { const { sourceBuffer, mediaSource } = this; if (!mediaSource) { throw Error("createSourceBuffers called when mediaSource was null"); } for (const trackName in tracks) { if (!sourceBuffer[trackName]) { var _track$levelCodec; const track = tracks[trackName]; if (!track) { throw Error(`source buffer exists for track ${trackName}, however track does not`); } let codec = ((_track$levelCodec = track.levelCodec) == null ? void 0 : _track$levelCodec.indexOf(",")) === -1 ? track.levelCodec : track.codec; if (codec) { if (trackName.slice(0, 5) === "audio") { codec = getCodecCompatibleName(codec, this.appendSource); } } const mimeType = `${track.container};codecs=${codec}`; this.log(`creating sourceBuffer(${mimeType})`); try { const sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType); const sbName = trackName; this.addBufferListener(sbName, "updatestart", this._onSBUpdateStart); this.addBufferListener(sbName, "updateend", this._onSBUpdateEnd); this.addBufferListener(sbName, "error", this._onSBUpdateError); if (this.appendSource) { this.addBufferListener(sbName, "bufferedchange", (type, event) => { const removedRanges = event.removedRanges; if (removedRanges != null && removedRanges.length) { this.hls.trigger(Events.BUFFER_FLUSHED, { type: trackName }); } }); } this.tracks[trackName] = { buffer: sb, codec, container: track.container, levelCodec: track.levelCodec, metadata: track.metadata, id: track.id }; } catch (err) { this.error(`error while trying to add sourceBuffer: ${err.message}`); this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, error: err, sourceBufferName: trackName, mimeType }); } } } } get mediaSrc() { var _this$media, _this$media$querySele; const media = ((_this$media = this.media) == null ? void 0 : (_this$media$querySele = _this$media.querySelector) == null ? void 0 : _this$media$querySele.call(_this$media, "source")) || this.media; return media == null ? void 0 : media.src; } _onSBUpdateStart(type) { const { operationQueue } = this; const operation = operationQueue.current(type); operation.onStart(); } _onSBUpdateEnd(type) { var _this$mediaSource2; if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === "closed") { this.resetBuffer(type); return; } const { operationQueue } = this; const operation = operationQueue.current(type); operation.onComplete(); operationQueue.shiftAndExecuteNext(type); } _onSBUpdateError(type, event) { var _this$mediaSource3; const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState}`); this.error(`${error}`, event); this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, sourceBufferName: type, error, fatal: false }); const operation = this.operationQueue.current(type); if (operation) { operation.onError(error); } } // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually removeExecutor(type, startOffset, endOffset) { const { media, mediaSource, operationQueue, sourceBuffer } = this; const sb = sourceBuffer[type]; if (!media || !mediaSource || !sb) { this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`); operationQueue.shiftAndExecuteNext(type); return; } const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity; const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity; const removeStart = Math.max(0, startOffset); const removeEnd = Math.min(endOffset, mediaDuration, msDuration); if (removeEnd > removeStart && (!sb.ending || sb.ended)) { sb.ended = false; this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`); sb.remove(removeStart, removeEnd); } else { operationQueue.shiftAndExecuteNext(type); } } // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually appendExecutor(data, type) { const sb = this.sourceBuffer[type]; if (!sb) { if (!this.pendingTracks[type]) { throw new Error(`Attempting to append to the ${type} SourceBuffer, but it does not exist`); } return; } sb.ended = false; sb.appendBuffer(data); } // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue // upon completion, since we already do it here blockBuffers(onUnblocked, buffers = this.getSourceBufferTypes()) { if (!buffers.length) { this.log("Blocking operation requested, but no SourceBuffers exist"); Promise.resolve().then(onUnblocked); return; } const { operationQueue } = this; const blockingOperations = buffers.map((type) => operationQueue.appendBlocker(type)); Promise.all(blockingOperations).then(() => { onUnblocked(); buffers.forEach((type) => { const sb = this.sourceBuffer[type]; if (!(sb != null && sb.updating)) { operationQueue.shiftAndExecuteNext(type); } }); }); } getSourceBufferTypes() { return Object.keys(this.sourceBuffer); } addBufferListener(type, event, fn) { const buffer = this.sourceBuffer[type]; if (!buffer) { return; } const listener = fn.bind(this, type); this.listeners[type].push({ event, listener }); buffer.addEventListener(event, listener); } removeBufferListeners(type) { const buffer = this.sourceBuffer[type]; if (!buffer) { return; } this.listeners[type].forEach((l2) => { buffer.removeEventListener(l2.event, l2.listener); }); } }; function removeSourceChildren(node2) { const sourceChildren = node2.querySelectorAll("source"); [].slice.call(sourceChildren).forEach((source) => { node2.removeChild(source); }); } function addSource(media, url) { const source = self.document.createElement("source"); source.type = "video/mp4"; source.src = url; media.appendChild(source); } var specialCea608CharsCodes = { 42: 225, // lowercase a, acute accent 92: 233, // lowercase e, acute accent 94: 237, // lowercase i, acute accent 95: 243, // lowercase o, acute accent 96: 250, // lowercase u, acute accent 123: 231, // lowercase c with cedilla 124: 247, // division symbol 125: 209, // uppercase N tilde 126: 241, // lowercase n tilde 127: 9608, // Full block // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES 128: 174, // Registered symbol (R) 129: 176, // degree sign 130: 189, // 1/2 symbol 131: 191, // Inverted (open) question mark 132: 8482, // Trademark symbol (TM) 133: 162, // Cents symbol 134: 163, // Pounds sterling 135: 9834, // Music 8'th note 136: 224, // lowercase a, grave accent 137: 32, // transparent space (regular) 138: 232, // lowercase e, grave accent 139: 226, // lowercase a, circumflex accent 140: 234, // lowercase e, circumflex accent 141: 238, // lowercase i, circumflex accent 142: 244, // lowercase o, circumflex accent 143: 251, // lowercase u, circumflex accent // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F 144: 193, // capital letter A with acute 145: 201, // capital letter E with acute 146: 211, // capital letter O with acute 147: 218, // capital letter U with acute 148: 220, // capital letter U with diaresis 149: 252, // lowercase letter U with diaeresis 150: 8216, // opening single quote 151: 161, // inverted exclamation mark 152: 42, // asterisk 153: 8217, // closing single quote 154: 9473, // box drawings heavy horizontal 155: 169, // copyright sign 156: 8480, // Service mark 157: 8226, // (round) bullet 158: 8220, // Left double quotation mark 159: 8221, // Right double quotation mark 160: 192, // uppercase A, grave accent 161: 194, // uppercase A, circumflex 162: 199, // uppercase C with cedilla 163: 200, // uppercase E, grave accent 164: 202, // uppercase E, circumflex 165: 203, // capital letter E with diaresis 166: 235, // lowercase letter e with diaresis 167: 206, // uppercase I, circumflex 168: 207, // uppercase I, with diaresis 169: 239, // lowercase i, with diaresis 170: 212, // uppercase O, circumflex 171: 217, // uppercase U, grave accent 172: 249, // lowercase u, grave accent 173: 219, // uppercase U, circumflex 174: 171, // left-pointing double angle quotation mark 175: 187, // right-pointing double angle quotation mark // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F 176: 195, // Uppercase A, tilde 177: 227, // Lowercase a, tilde 178: 205, // Uppercase I, acute accent 179: 204, // Uppercase I, grave accent 180: 236, // Lowercase i, grave accent 181: 210, // Uppercase O, grave accent 182: 242, // Lowercase o, grave accent 183: 213, // Uppercase O, tilde 184: 245, // Lowercase o, tilde 185: 123, // Open curly brace 186: 125, // Closing curly brace 187: 92, // Backslash 188: 94, // Caret 189: 95, // Underscore 190: 124, // Pipe (vertical line) 191: 8764, // Tilde operator 192: 196, // Uppercase A, umlaut 193: 228, // Lowercase A, umlaut 194: 214, // Uppercase O, umlaut 195: 246, // Lowercase o, umlaut 196: 223, // Esszett (sharp S) 197: 165, // Yen symbol 198: 164, // Generic currency sign 199: 9475, // Box drawings heavy vertical 200: 197, // Uppercase A, ring 201: 229, // Lowercase A, ring 202: 216, // Uppercase O, stroke 203: 248, // Lowercase o, strok 204: 9487, // Box drawings heavy down and right 205: 9491, // Box drawings heavy down and left 206: 9495, // Box drawings heavy up and right 207: 9499 // Box drawings heavy up and left }; var getCharForByte = (byte) => String.fromCharCode(specialCea608CharsCodes[byte] || byte); var NR_ROWS = 15; var NR_COLS = 100; var rowsLowCh1 = { 17: 1, 18: 3, 21: 5, 22: 7, 23: 9, 16: 11, 19: 12, 20: 14 }; var rowsHighCh1 = { 17: 2, 18: 4, 21: 6, 22: 8, 23: 10, 19: 13, 20: 15 }; var rowsLowCh2 = { 25: 1, 26: 3, 29: 5, 30: 7, 31: 9, 24: 11, 27: 12, 28: 14 }; var rowsHighCh2 = { 25: 2, 26: 4, 29: 6, 30: 8, 31: 10, 27: 13, 28: 15 }; var backgroundColors = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"]; var CaptionsLogger = class { constructor() { this.time = null; this.verboseLevel = 0; } log(severity, msg) { if (this.verboseLevel >= severity) { const m2 = typeof msg === "function" ? msg() : msg; logger.log(`${this.time} [${severity}] ${m2}`); } } }; var numArrayToHexArray = function numArrayToHexArray2(numArray) { const hexArray = []; for (let j3 = 0; j3 < numArray.length; j3++) { hexArray.push(numArray[j3].toString(16)); } return hexArray; }; var PenState = class { constructor() { this.foreground = "white"; this.underline = false; this.italics = false; this.background = "black"; this.flash = false; } reset() { this.foreground = "white"; this.underline = false; this.italics = false; this.background = "black"; this.flash = false; } setStyles(styles) { const attribs = ["foreground", "underline", "italics", "background", "flash"]; for (let i3 = 0; i3 < attribs.length; i3++) { const style = attribs[i3]; if (styles.hasOwnProperty(style)) { this[style] = styles[style]; } } } isDefault() { return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash; } equals(other) { return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash; } copy(newPenState) { this.foreground = newPenState.foreground; this.underline = newPenState.underline; this.italics = newPenState.italics; this.background = newPenState.background; this.flash = newPenState.flash; } toString() { return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash; } }; var StyledUnicodeChar = class { constructor() { this.uchar = " "; this.penState = new PenState(); } reset() { this.uchar = " "; this.penState.reset(); } setChar(uchar, newPenState) { this.uchar = uchar; this.penState.copy(newPenState); } setPenState(newPenState) { this.penState.copy(newPenState); } equals(other) { return this.uchar === other.uchar && this.penState.equals(other.penState); } copy(newChar) { this.uchar = newChar.uchar; this.penState.copy(newChar.penState); } isEmpty() { return this.uchar === " " && this.penState.isDefault(); } }; var Row = class { constructor(logger2) { this.chars = []; this.pos = 0; this.currPenState = new PenState(); this.cueStartTime = null; this.logger = void 0; for (let i3 = 0; i3 < NR_COLS; i3++) { this.chars.push(new StyledUnicodeChar()); } this.logger = logger2; } equals(other) { for (let i3 = 0; i3 < NR_COLS; i3++) { if (!this.chars[i3].equals(other.chars[i3])) { return false; } } return true; } copy(other) { for (let i3 = 0; i3 < NR_COLS; i3++) { this.chars[i3].copy(other.chars[i3]); } } isEmpty() { let empty = true; for (let i3 = 0; i3 < NR_COLS; i3++) { if (!this.chars[i3].isEmpty()) { empty = false; break; } } return empty; } /** * Set the cursor to a valid column. */ setCursor(absPos) { if (this.pos !== absPos) { this.pos = absPos; } if (this.pos < 0) { this.logger.log(3, "Negative cursor position " + this.pos); this.pos = 0; } else if (this.pos > NR_COLS) { this.logger.log(3, "Too large cursor position " + this.pos); this.pos = NR_COLS; } } /** * Move the cursor relative to current position. */ moveCursor(relPos) { const newPos = this.pos + relPos; if (relPos > 1) { for (let i3 = this.pos + 1; i3 < newPos + 1; i3++) { this.chars[i3].setPenState(this.currPenState); } } this.setCursor(newPos); } /** * Backspace, move one step back and clear character. */ backSpace() { this.moveCursor(-1); this.chars[this.pos].setChar(" ", this.currPenState); } insertChar(byte) { if (byte >= 144) { this.backSpace(); } const char2 = getCharForByte(byte); if (this.pos >= NR_COLS) { this.logger.log(0, () => "Cannot insert " + byte.toString(16) + " (" + char2 + ") at position " + this.pos + ". Skipping it!"); return; } this.chars[this.pos].setChar(char2, this.currPenState); this.moveCursor(1); } clearFromPos(startPos) { let i3; for (i3 = startPos; i3 < NR_COLS; i3++) { this.chars[i3].reset(); } } clear() { this.clearFromPos(0); this.pos = 0; this.currPenState.reset(); } clearToEndOfRow() { this.clearFromPos(this.pos); } getTextString() { const chars = []; let empty = true; for (let i3 = 0; i3 < NR_COLS; i3++) { const char2 = this.chars[i3].uchar; if (char2 !== " ") { empty = false; } chars.push(char2); } if (empty) { return ""; } else { return chars.join(""); } } setPenStyles(styles) { this.currPenState.setStyles(styles); const currChar = this.chars[this.pos]; currChar.setPenState(this.currPenState); } }; var CaptionScreen = class { constructor(logger2) { this.rows = []; this.currRow = NR_ROWS - 1; this.nrRollUpRows = null; this.lastOutputScreen = null; this.logger = void 0; for (let i3 = 0; i3 < NR_ROWS; i3++) { this.rows.push(new Row(logger2)); } this.logger = logger2; } reset() { for (let i3 = 0; i3 < NR_ROWS; i3++) { this.rows[i3].clear(); } this.currRow = NR_ROWS - 1; } equals(other) { let equal = true; for (let i3 = 0; i3 < NR_ROWS; i3++) { if (!this.rows[i3].equals(other.rows[i3])) { equal = false; break; } } return equal; } copy(other) { for (let i3 = 0; i3 < NR_ROWS; i3++) { this.rows[i3].copy(other.rows[i3]); } } isEmpty() { let empty = true; for (let i3 = 0; i3 < NR_ROWS; i3++) { if (!this.rows[i3].isEmpty()) { empty = false; break; } } return empty; } backSpace() { const row = this.rows[this.currRow]; row.backSpace(); } clearToEndOfRow() { const row = this.rows[this.currRow]; row.clearToEndOfRow(); } /** * Insert a character (without styling) in the current row. */ insertChar(char2) { const row = this.rows[this.currRow]; row.insertChar(char2); } setPen(styles) { const row = this.rows[this.currRow]; row.setPenStyles(styles); } moveCursor(relPos) { const row = this.rows[this.currRow]; row.moveCursor(relPos); } setCursor(absPos) { this.logger.log(2, "setCursor: " + absPos); const row = this.rows[this.currRow]; row.setCursor(absPos); } setPAC(pacData) { this.logger.log(2, () => "pacData = " + JSON.stringify(pacData)); let newRow = pacData.row - 1; if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) { newRow = this.nrRollUpRows - 1; } if (this.nrRollUpRows && this.currRow !== newRow) { for (let i3 = 0; i3 < NR_ROWS; i3++) { this.rows[i3].clear(); } const topRowIndex = this.currRow + 1 - this.nrRollUpRows; const lastOutputScreen = this.lastOutputScreen; if (lastOutputScreen) { const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime; const time = this.logger.time; if (prevLineTime !== null && time !== null && prevLineTime < time) { for (let i3 = 0; i3 < this.nrRollUpRows; i3++) { this.rows[newRow - this.nrRollUpRows + i3 + 1].copy(lastOutputScreen.rows[topRowIndex + i3]); } } } } this.currRow = newRow; const row = this.rows[this.currRow]; if (pacData.indent !== null) { const indent = pacData.indent; const prevPos = Math.max(indent - 1, 0); row.setCursor(pacData.indent); pacData.color = row.chars[prevPos].penState.foreground; } const styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: "black", flash: false }; this.setPen(styles); } /** * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility). */ setBkgData(bkgData) { this.logger.log(2, () => "bkgData = " + JSON.stringify(bkgData)); this.backSpace(); this.setPen(bkgData); this.insertChar(32); } setRollUpRows(nrRows) { this.nrRollUpRows = nrRows; } rollUp() { if (this.nrRollUpRows === null) { this.logger.log(3, "roll_up but nrRollUpRows not set yet"); return; } this.logger.log(1, () => this.getDisplayText()); const topRowIndex = this.currRow + 1 - this.nrRollUpRows; const topRow = this.rows.splice(topRowIndex, 1)[0]; topRow.clear(); this.rows.splice(this.currRow, 0, topRow); this.logger.log(2, "Rolling up"); } /** * Get all non-empty rows with as unicode text. */ getDisplayText(asOneRow) { asOneRow = asOneRow || false; const displayText = []; let text = ""; let rowNr = -1; for (let i3 = 0; i3 < NR_ROWS; i3++) { const rowText = this.rows[i3].getTextString(); if (rowText) { rowNr = i3 + 1; if (asOneRow) { displayText.push("Row " + rowNr + ": '" + rowText + "'"); } else { displayText.push(rowText.trim()); } } } if (displayText.length > 0) { if (asOneRow) { text = "[" + displayText.join(" | ") + "]"; } else { text = displayText.join("\n"); } } return text; } getTextAndFormat() { return this.rows; } }; var Cea608Channel = class { constructor(channelNumber, outputFilter, logger2) { this.chNr = void 0; this.outputFilter = void 0; this.mode = void 0; this.verbose = void 0; this.displayedMemory = void 0; this.nonDisplayedMemory = void 0; this.lastOutputScreen = void 0; this.currRollUpRow = void 0; this.writeScreen = void 0; this.cueStartTime = void 0; this.logger = void 0; this.chNr = channelNumber; this.outputFilter = outputFilter; this.mode = null; this.verbose = 0; this.displayedMemory = new CaptionScreen(logger2); this.nonDisplayedMemory = new CaptionScreen(logger2); this.lastOutputScreen = new CaptionScreen(logger2); this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; this.writeScreen = this.displayedMemory; this.mode = null; this.cueStartTime = null; this.logger = logger2; } reset() { this.mode = null; this.displayedMemory.reset(); this.nonDisplayedMemory.reset(); this.lastOutputScreen.reset(); this.outputFilter.reset(); this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; this.writeScreen = this.displayedMemory; this.mode = null; this.cueStartTime = null; } getHandler() { return this.outputFilter; } setHandler(newHandler) { this.outputFilter = newHandler; } setPAC(pacData) { this.writeScreen.setPAC(pacData); } setBkgData(bkgData) { this.writeScreen.setBkgData(bkgData); } setMode(newMode) { if (newMode === this.mode) { return; } this.mode = newMode; this.logger.log(2, () => "MODE=" + newMode); if (this.mode === "MODE_POP-ON") { this.writeScreen = this.nonDisplayedMemory; } else { this.writeScreen = this.displayedMemory; this.writeScreen.reset(); } if (this.mode !== "MODE_ROLL-UP") { this.displayedMemory.nrRollUpRows = null; this.nonDisplayedMemory.nrRollUpRows = null; } this.mode = newMode; } insertChars(chars) { for (let i3 = 0; i3 < chars.length; i3++) { this.writeScreen.insertChar(chars[i3]); } const screen = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP"; this.logger.log(2, () => screen + ": " + this.writeScreen.getDisplayText(true)); if (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") { this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(true)); this.outputDataUpdate(); } } ccRCL() { this.logger.log(2, "RCL - Resume Caption Loading"); this.setMode("MODE_POP-ON"); } ccBS() { this.logger.log(2, "BS - BackSpace"); if (this.mode === "MODE_TEXT") { return; } this.writeScreen.backSpace(); if (this.writeScreen === this.displayedMemory) { this.outputDataUpdate(); } } ccAOF() { } ccAON() { } ccDER() { this.logger.log(2, "DER- Delete to End of Row"); this.writeScreen.clearToEndOfRow(); this.outputDataUpdate(); } ccRU(nrRows) { this.logger.log(2, "RU(" + nrRows + ") - Roll Up"); this.writeScreen = this.displayedMemory; this.setMode("MODE_ROLL-UP"); this.writeScreen.setRollUpRows(nrRows); } ccFON() { this.logger.log(2, "FON - Flash On"); this.writeScreen.setPen({ flash: true }); } ccRDC() { this.logger.log(2, "RDC - Resume Direct Captioning"); this.setMode("MODE_PAINT-ON"); } ccTR() { this.logger.log(2, "TR"); this.setMode("MODE_TEXT"); } ccRTD() { this.logger.log(2, "RTD"); this.setMode("MODE_TEXT"); } ccEDM() { this.logger.log(2, "EDM - Erase Displayed Memory"); this.displayedMemory.reset(); this.outputDataUpdate(true); } ccCR() { this.logger.log(2, "CR - Carriage Return"); this.writeScreen.rollUp(); this.outputDataUpdate(true); } ccENM() { this.logger.log(2, "ENM - Erase Non-displayed Memory"); this.nonDisplayedMemory.reset(); } ccEOC() { this.logger.log(2, "EOC - End Of Caption"); if (this.mode === "MODE_POP-ON") { const tmp = this.displayedMemory; this.displayedMemory = this.nonDisplayedMemory; this.nonDisplayedMemory = tmp; this.writeScreen = this.nonDisplayedMemory; this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText()); } this.outputDataUpdate(true); } ccTO(nrCols) { this.logger.log(2, "TO(" + nrCols + ") - Tab Offset"); this.writeScreen.moveCursor(nrCols); } ccMIDROW(secondByte) { const styles = { flash: false }; styles.underline = secondByte % 2 === 1; styles.italics = secondByte >= 46; if (!styles.italics) { const colorIndex = Math.floor(secondByte / 2) - 16; const colors2 = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"]; styles.foreground = colors2[colorIndex]; } else { styles.foreground = "white"; } this.logger.log(2, "MIDROW: " + JSON.stringify(styles)); this.writeScreen.setPen(styles); } outputDataUpdate(dispatch = false) { const time = this.logger.time; if (time === null) { return; } if (this.outputFilter) { if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { this.cueStartTime = time; } else { if (!this.displayedMemory.equals(this.lastOutputScreen)) { this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen); if (dispatch && this.outputFilter.dispatchCue) { this.outputFilter.dispatchCue(); } this.cueStartTime = this.displayedMemory.isEmpty() ? null : time; } } this.lastOutputScreen.copy(this.displayedMemory); } } cueSplitAtTime(t2) { if (this.outputFilter) { if (!this.displayedMemory.isEmpty()) { if (this.outputFilter.newCue) { this.outputFilter.newCue(this.cueStartTime, t2, this.displayedMemory); } this.cueStartTime = t2; } } } }; var Cea608Parser = class { constructor(field, out1, out2) { this.channels = void 0; this.currentChannel = 0; this.cmdHistory = createCmdHistory(); this.logger = void 0; const logger2 = this.logger = new CaptionsLogger(); this.channels = [null, new Cea608Channel(field, out1, logger2), new Cea608Channel(field + 1, out2, logger2)]; } getHandler(channel) { return this.channels[channel].getHandler(); } setHandler(channel, newHandler) { this.channels[channel].setHandler(newHandler); } /** * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs. */ addData(time, byteList) { this.logger.time = time; for (let i3 = 0; i3 < byteList.length; i3 += 2) { const a2 = byteList[i3] & 127; const b2 = byteList[i3 + 1] & 127; let cmdFound = false; let charsFound = null; if (a2 === 0 && b2 === 0) { continue; } else { this.logger.log(3, () => "[" + numArrayToHexArray([byteList[i3], byteList[i3 + 1]]) + "] -> (" + numArrayToHexArray([a2, b2]) + ")"); } const cmdHistory = this.cmdHistory; const isControlCode = a2 >= 16 && a2 <= 31; if (isControlCode) { if (hasCmdRepeated(a2, b2, cmdHistory)) { setLastCmd(null, null, cmdHistory); this.logger.log(3, () => "Repeated command (" + numArrayToHexArray([a2, b2]) + ") is dropped"); continue; } setLastCmd(a2, b2, this.cmdHistory); cmdFound = this.parseCmd(a2, b2); if (!cmdFound) { cmdFound = this.parseMidrow(a2, b2); } if (!cmdFound) { cmdFound = this.parsePAC(a2, b2); } if (!cmdFound) { cmdFound = this.parseBackgroundAttributes(a2, b2); } } else { setLastCmd(null, null, cmdHistory); } if (!cmdFound) { charsFound = this.parseChars(a2, b2); if (charsFound) { const currChNr = this.currentChannel; if (currChNr && currChNr > 0) { const channel = this.channels[currChNr]; channel.insertChars(charsFound); } else { this.logger.log(2, "No channel found yet. TEXT-MODE?"); } } } if (!cmdFound && !charsFound) { this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a2, b2]) + " orig: " + numArrayToHexArray([byteList[i3], byteList[i3 + 1]])); } } } /** * Parse Command. * @returns True if a command was found */ parseCmd(a2, b2) { const cond1 = (a2 === 20 || a2 === 28 || a2 === 21 || a2 === 29) && b2 >= 32 && b2 <= 47; const cond2 = (a2 === 23 || a2 === 31) && b2 >= 33 && b2 <= 35; if (!(cond1 || cond2)) { return false; } const chNr = a2 === 20 || a2 === 21 || a2 === 23 ? 1 : 2; const channel = this.channels[chNr]; if (a2 === 20 || a2 === 21 || a2 === 28 || a2 === 29) { if (b2 === 32) { channel.ccRCL(); } else if (b2 === 33) { channel.ccBS(); } else if (b2 === 34) { channel.ccAOF(); } else if (b2 === 35) { channel.ccAON(); } else if (b2 === 36) { channel.ccDER(); } else if (b2 === 37) { channel.ccRU(2); } else if (b2 === 38) { channel.ccRU(3); } else if (b2 === 39) { channel.ccRU(4); } else if (b2 === 40) { channel.ccFON(); } else if (b2 === 41) { channel.ccRDC(); } else if (b2 === 42) { channel.ccTR(); } else if (b2 === 43) { channel.ccRTD(); } else if (b2 === 44) { channel.ccEDM(); } else if (b2 === 45) { channel.ccCR(); } else if (b2 === 46) { channel.ccENM(); } else if (b2 === 47) { channel.ccEOC(); } } else { channel.ccTO(b2 - 32); } this.currentChannel = chNr; return true; } /** * Parse midrow styling command */ parseMidrow(a2, b2) { let chNr = 0; if ((a2 === 17 || a2 === 25) && b2 >= 32 && b2 <= 47) { if (a2 === 17) { chNr = 1; } else { chNr = 2; } if (chNr !== this.currentChannel) { this.logger.log(0, "Mismatch channel in midrow parsing"); return false; } const channel = this.channels[chNr]; if (!channel) { return false; } channel.ccMIDROW(b2); this.logger.log(3, () => "MIDROW (" + numArrayToHexArray([a2, b2]) + ")"); return true; } return false; } /** * Parse Preable Access Codes (Table 53). * @returns {Boolean} Tells if PAC found */ parsePAC(a2, b2) { let row; const case1 = (a2 >= 17 && a2 <= 23 || a2 >= 25 && a2 <= 31) && b2 >= 64 && b2 <= 127; const case2 = (a2 === 16 || a2 === 24) && b2 >= 64 && b2 <= 95; if (!(case1 || case2)) { return false; } const chNr = a2 <= 23 ? 1 : 2; if (b2 >= 64 && b2 <= 95) { row = chNr === 1 ? rowsLowCh1[a2] : rowsLowCh2[a2]; } else { row = chNr === 1 ? rowsHighCh1[a2] : rowsHighCh2[a2]; } const channel = this.channels[chNr]; if (!channel) { return false; } channel.setPAC(this.interpretPAC(row, b2)); this.currentChannel = chNr; return true; } /** * Interpret the second byte of the pac, and return the information. * @returns pacData with style parameters */ interpretPAC(row, byte) { let pacIndex; const pacData = { color: null, italics: false, indent: null, underline: false, row }; if (byte > 95) { pacIndex = byte - 96; } else { pacIndex = byte - 64; } pacData.underline = (pacIndex & 1) === 1; if (pacIndex <= 13) { pacData.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(pacIndex / 2)]; } else if (pacIndex <= 15) { pacData.italics = true; pacData.color = "white"; } else { pacData.indent = Math.floor((pacIndex - 16) / 2) * 4; } return pacData; } /** * Parse characters. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise. */ parseChars(a2, b2) { let channelNr; let charCodes = null; let charCode1 = null; if (a2 >= 25) { channelNr = 2; charCode1 = a2 - 8; } else { channelNr = 1; charCode1 = a2; } if (charCode1 >= 17 && charCode1 <= 19) { let oneCode; if (charCode1 === 17) { oneCode = b2 + 80; } else if (charCode1 === 18) { oneCode = b2 + 112; } else { oneCode = b2 + 144; } this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr); charCodes = [oneCode]; } else if (a2 >= 32 && a2 <= 127) { charCodes = b2 === 0 ? [a2] : [a2, b2]; } if (charCodes) { this.logger.log(3, () => "Char codes = " + numArrayToHexArray(charCodes).join(",")); } return charCodes; } /** * Parse extended background attributes as well as new foreground color black. * @returns True if background attributes are found */ parseBackgroundAttributes(a2, b2) { const case1 = (a2 === 16 || a2 === 24) && b2 >= 32 && b2 <= 47; const case2 = (a2 === 23 || a2 === 31) && b2 >= 45 && b2 <= 47; if (!(case1 || case2)) { return false; } let index2; const bkgData = {}; if (a2 === 16 || a2 === 24) { index2 = Math.floor((b2 - 32) / 2); bkgData.background = backgroundColors[index2]; if (b2 % 2 === 1) { bkgData.background = bkgData.background + "_semi"; } } else if (b2 === 45) { bkgData.background = "transparent"; } else { bkgData.foreground = "black"; if (b2 === 47) { bkgData.underline = true; } } const chNr = a2 <= 23 ? 1 : 2; const channel = this.channels[chNr]; channel.setBkgData(bkgData); return true; } /** * Reset state of parser and its channels. */ reset() { for (let i3 = 0; i3 < Object.keys(this.channels).length; i3++) { const channel = this.channels[i3]; if (channel) { channel.reset(); } } setLastCmd(null, null, this.cmdHistory); } /** * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty. */ cueSplitAtTime(t2) { for (let i3 = 0; i3 < this.channels.length; i3++) { const channel = this.channels[i3]; if (channel) { channel.cueSplitAtTime(t2); } } } }; function setLastCmd(a2, b2, cmdHistory) { cmdHistory.a = a2; cmdHistory.b = b2; } function hasCmdRepeated(a2, b2, cmdHistory) { return cmdHistory.a === a2 && cmdHistory.b === b2; } function createCmdHistory() { return { a: null, b: null }; } var OutputFilter = class { constructor(timelineController, trackName) { this.timelineController = void 0; this.cueRanges = []; this.trackName = void 0; this.startTime = null; this.endTime = null; this.screen = null; this.timelineController = timelineController; this.trackName = trackName; } dispatchCue() { if (this.startTime === null) { return; } this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges); this.startTime = null; } newCue(startTime, endTime, screen) { if (this.startTime === null || this.startTime > startTime) { this.startTime = startTime; } this.endTime = endTime; this.screen = screen; this.timelineController.createCaptionsTrack(this.trackName); } reset() { this.cueRanges = []; this.startTime = null; } }; var VTTCue2 = function() { if (optionalSelf != null && optionalSelf.VTTCue) { return self.VTTCue; } const AllowedDirections = ["", "lr", "rl"]; const AllowedAlignments = ["start", "middle", "end", "left", "right"]; function isAllowedValue(allowed, value) { if (typeof value !== "string") { return false; } if (!Array.isArray(allowed)) { return false; } const lcValue = value.toLowerCase(); if (~allowed.indexOf(lcValue)) { return lcValue; } return false; } function findDirectionSetting(value) { return isAllowedValue(AllowedDirections, value); } function findAlignSetting(value) { return isAllowedValue(AllowedAlignments, value); } function extend(obj, ...rest) { let i3 = 1; for (; i3 < arguments.length; i3++) { const cobj = arguments[i3]; for (const p3 in cobj) { obj[p3] = cobj[p3]; } } return obj; } function VTTCue3(startTime, endTime, text) { const cue = this; const baseObj = { enumerable: true }; cue.hasBeenReset = false; let _id2 = ""; let _pauseOnExit = false; let _startTime2 = startTime; let _endTime = endTime; let _text = text; let _region = null; let _vertical = ""; let _snapToLines = true; let _line = "auto"; let _lineAlign = "start"; let _position = 50; let _positionAlign = "middle"; let _size = 50; let _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id2; }, set: function(value) { _id2 = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime2; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime2 = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { const setting = findDirectionSetting(value); if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== "auto") { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { const setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { const setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { const setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); cue.displayState = void 0; } VTTCue3.prototype.getCueAsHTML = function() { const WebVTT = self.WebVTT; return WebVTT.convertCueToDOMTree(self, this.text); }; return VTTCue3; }(); var StringDecoder = class { // eslint-disable-next-line @typescript-eslint/no-unused-vars decode(data, options2) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; function parseTimeStamp(input) { function computeSeconds(h3, m3, s, f) { return (h3 | 0) * 3600 + (m3 | 0) * 60 + (s | 0) + parseFloat(f || 0); } const m2 = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/); if (!m2) { return null; } if (parseFloat(m2[2]) > 59) { return computeSeconds(m2[2], m2[3], 0, m2[4]); } return computeSeconds(m2[1], m2[2], m2[3], m2[4]); } var Settings = class { constructor() { this.values = /* @__PURE__ */ Object.create(null); } // Only accept the first assignment to any key. set(k3, v2) { if (!this.get(k3) && v2 !== "") { this.values[k3] = v2; } } // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get(k3, dflt, defaultKey) { if (defaultKey) { return this.has(k3) ? this.values[k3] : dflt[defaultKey]; } return this.has(k3) ? this.values[k3] : dflt; } // Check whether we have a value for a key. has(k3) { return k3 in this.values; } // Accept a setting if its one of the given alternatives. alt(k3, v2, a2) { for (let n2 = 0; n2 < a2.length; ++n2) { if (v2 === a2[n2]) { this.set(k3, v2); break; } } } // Accept a setting if its a valid (signed) integer. integer(k3, v2) { if (/^-?\d+$/.test(v2)) { this.set(k3, parseInt(v2, 10)); } } // Accept a setting if its a valid percentage. percent(k3, v2) { if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v2)) { const percent = parseFloat(v2); if (percent >= 0 && percent <= 100) { this.set(k3, percent); return true; } } return false; } }; function parseOptions(input, callback, keyValueDelim, groupDelim) { const groups = groupDelim ? input.split(groupDelim) : [input]; for (const i3 in groups) { if (typeof groups[i3] !== "string") { continue; } const kv = groups[i3].split(keyValueDelim); if (kv.length !== 2) { continue; } const k3 = kv[0]; const v2 = kv[1]; callback(k3, v2); } } var defaults = new VTTCue2(0, 0, ""); var center = defaults.align === "middle" ? "middle" : "center"; function parseCue(input, cue, regionList) { const oInput = input; function consumeTimeStamp() { const ts = parseTimeStamp(input); if (ts === null) { throw new Error("Malformed timestamp: " + oInput); } input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } function consumeCueSettings(input2, cue2) { const settings = new Settings(); parseOptions(input2, function(k3, v2) { let vals; switch (k3) { case "region": for (let i3 = regionList.length - 1; i3 >= 0; i3--) { if (regionList[i3].id === v2) { settings.set(k3, regionList[i3].region); break; } } break; case "vertical": settings.alt(k3, v2, ["rl", "lr"]); break; case "line": vals = v2.split(","); settings.integer(k3, vals[0]); if (settings.percent(k3, vals[0])) { settings.set("snapToLines", false); } settings.alt(k3, vals[0], ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", center, "end"]); } break; case "position": vals = v2.split(","); settings.percent(k3, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", center, "end", "line-left", "line-right", "auto"]); } break; case "size": settings.percent(k3, v2); break; case "align": settings.alt(k3, v2, ["start", center, "end", "left", "right"]); break; } }, /:/, /\s/); cue2.region = settings.get("region", null); cue2.vertical = settings.get("vertical", ""); let line2 = settings.get("line", "auto"); if (line2 === "auto" && defaults.line === -1) { line2 = -1; } cue2.line = line2; cue2.lineAlign = settings.get("lineAlign", "start"); cue2.snapToLines = settings.get("snapToLines", true); cue2.size = settings.get("size", 100); cue2.align = settings.get("align", center); let position2 = settings.get("position", "auto"); if (position2 === "auto" && defaults.position === 50) { position2 = cue2.align === "start" || cue2.align === "left" ? 0 : cue2.align === "end" || cue2.align === "right" ? 100 : 50; } cue2.position = position2; } function skipWhitespace() { input = input.replace(/^\s+/, ""); } skipWhitespace(); cue.startTime = consumeTimeStamp(); skipWhitespace(); if (input.slice(0, 3) !== "-->") { throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.slice(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); skipWhitespace(); consumeCueSettings(input, cue); } function fixLineBreaks(input) { return input.replace(/<br(?: \/)?>/gi, "\n"); } var VTTParser = class { constructor() { this.state = "INITIAL"; this.buffer = ""; this.decoder = new StringDecoder(); this.regionList = []; this.cue = null; this.oncue = void 0; this.onparsingerror = void 0; this.onflush = void 0; } parse(data) { const _this = this; if (data) { _this.buffer += _this.decoder.decode(data, { stream: true }); } function collectNextLine() { let buffer = _this.buffer; let pos = 0; buffer = fixLineBreaks(buffer); while (pos < buffer.length && buffer[pos] !== "\r" && buffer[pos] !== "\n") { ++pos; } const line2 = buffer.slice(0, pos); if (buffer[pos] === "\r") { ++pos; } if (buffer[pos] === "\n") { ++pos; } _this.buffer = buffer.slice(pos); return line2; } function parseHeader2(input) { parseOptions(input, function(k3, v2) { }, /:/); } try { let line2 = ""; if (_this.state === "INITIAL") { if (!/\r\n|\n/.test(_this.buffer)) { return this; } line2 = collectNextLine(); const m2 = line2.match(/^()?WEBVTT([ \t].*)?$/); if (!(m2 != null && m2[0])) { throw new Error("Malformed WebVTT signature."); } _this.state = "HEADER"; } let alreadyCollectedLine = false; while (_this.buffer) { if (!/\r\n|\n/.test(_this.buffer)) { return this; } if (!alreadyCollectedLine) { line2 = collectNextLine(); } else { alreadyCollectedLine = false; } switch (_this.state) { case "HEADER": if (/:/.test(line2)) { parseHeader2(line2); } else if (!line2) { _this.state = "ID"; } continue; case "NOTE": if (!line2) { _this.state = "ID"; } continue; case "ID": if (/^NOTE($|[ \t])/.test(line2)) { _this.state = "NOTE"; break; } if (!line2) { continue; } _this.cue = new VTTCue2(0, 0, ""); _this.state = "CUE"; if (line2.indexOf("-->") === -1) { _this.cue.id = line2; continue; } case "CUE": if (!_this.cue) { _this.state = "BADCUE"; continue; } try { parseCue(line2, _this.cue, _this.regionList); } catch (e) { _this.cue = null; _this.state = "BADCUE"; continue; } _this.state = "CUETEXT"; continue; case "CUETEXT": { const hasSubstring = line2.indexOf("-->") !== -1; if (!line2 || hasSubstring && (alreadyCollectedLine = true)) { if (_this.oncue && _this.cue) { _this.oncue(_this.cue); } _this.cue = null; _this.state = "ID"; continue; } if (_this.cue === null) { continue; } if (_this.cue.text) { _this.cue.text += "\n"; } _this.cue.text += line2; } continue; case "BADCUE": if (!line2) { _this.state = "ID"; } } } } catch (e) { if (_this.state === "CUETEXT" && _this.cue && _this.oncue) { _this.oncue(_this.cue); } _this.cue = null; _this.state = _this.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; } flush() { const _this = this; try { if (_this.cue || _this.state === "HEADER") { _this.buffer += "\n\n"; _this.parse(); } if (_this.state === "INITIAL" || _this.state === "BADWEBVTT") { throw new Error("Malformed WebVTT signature."); } } catch (e) { if (_this.onparsingerror) { _this.onparsingerror(e); } } if (_this.onflush) { _this.onflush(); } return this; } }; var LINEBREAKS = /\r\n|\n\r|\n|\r/g; var startsWith = function startsWith2(inputString, searchString, position2 = 0) { return inputString.slice(position2, position2 + searchString.length) === searchString; }; var cueString2millis = function cueString2millis2(timeString) { let ts = parseInt(timeString.slice(-3)); const secs = parseInt(timeString.slice(-6, -4)); const mins = parseInt(timeString.slice(-9, -7)); const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(":"))) : 0; if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) { throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`); } ts += 1e3 * secs; ts += 60 * 1e3 * mins; ts += 60 * 60 * 1e3 * hours; return ts; }; var hash2 = function hash3(text) { let _hash = 5381; let i3 = text.length; while (i3) { _hash = _hash * 33 ^ text.charCodeAt(--i3); } return (_hash >>> 0).toString(); }; function generateCueId(startTime, endTime, text) { return hash2(startTime.toString()) + hash2(endTime.toString()) + hash2(text); } var calculateOffset = function calculateOffset2(vttCCs, cc, presentationTime) { let currCC = vttCCs[cc]; let prevCC = vttCCs[currCC.prevCC]; if (!prevCC || !prevCC.new && currCC.new) { vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start; currCC.new = false; return; } while ((_prevCC = prevCC) != null && _prevCC.new) { var _prevCC; vttCCs.ccOffset += currCC.start - prevCC.start; currCC.new = false; currCC = prevCC; prevCC = vttCCs[currCC.prevCC]; } vttCCs.presentationOffset = presentationTime; }; function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) { const parser = new VTTParser(); const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, "\n").split("\n"); const cues = []; const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0; let cueTime = "00:00.000"; let timestampMapMPEGTS = 0; let timestampMapLOCAL = 0; let parsingError; let inHeader = true; parser.oncue = function(cue) { const currCC = vttCCs[cc]; let cueOffset = vttCCs.ccOffset; const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 9e4; if (currCC != null && currCC.new) { if (timestampMapLOCAL !== void 0) { cueOffset = vttCCs.ccOffset = currCC.start; } else { calculateOffset(vttCCs, cc, webVttMpegTsMapOffset); } } if (webVttMpegTsMapOffset) { if (!initPTS) { parsingError = new Error("Missing initPTS for VTT MPEGTS"); return; } cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset; } const duration = cue.endTime - cue.startTime; const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 9e4, timeOffset * 9e4) / 9e4; cue.startTime = Math.max(startTime, 0); cue.endTime = Math.max(startTime + duration, 0); const text = cue.text.trim(); cue.text = decodeURIComponent(encodeURIComponent(text)); if (!cue.id) { cue.id = generateCueId(cue.startTime, cue.endTime, text); } if (cue.endTime > 0) { cues.push(cue); } }; parser.onparsingerror = function(error) { parsingError = error; }; parser.onflush = function() { if (parsingError) { errorCallBack(parsingError); return; } callBack(cues); }; vttLines.forEach((line2) => { if (inHeader) { if (startsWith(line2, "X-TIMESTAMP-MAP=")) { inHeader = false; line2.slice(16).split(",").forEach((timestamp) => { if (startsWith(timestamp, "LOCAL:")) { cueTime = timestamp.slice(6); } else if (startsWith(timestamp, "MPEGTS:")) { timestampMapMPEGTS = parseInt(timestamp.slice(7)); } }); try { timestampMapLOCAL = cueString2millis(cueTime) / 1e3; } catch (error) { parsingError = error; } return; } else if (line2 === "") { inHeader = false; } } parser.parse(line2 + "\n"); }); parser.flush(); } var IMSC1_CODEC = "stpp.ttml.im1t"; var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/; var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/; var textAlignToLineAlign = { left: "start", center: "center", right: "end", start: "start", end: "end" }; function parseIMSC1(payload, initPTS, callBack, errorCallBack) { const results = findBox(new Uint8Array(payload), ["mdat"]); if (results.length === 0) { errorCallBack(new Error("Could not parse IMSC1 mdat")); return; } const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat)); const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale); try { ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime))); } catch (error) { errorCallBack(error); } } function parseTTML(ttml, syncTime) { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(ttml, "text/xml"); const tt3 = xmlDoc.getElementsByTagName("tt")[0]; if (!tt3) { throw new Error("Invalid ttml"); } const defaultRateInfo = { frameRate: 30, subFrameRate: 1, frameRateMultiplier: 0, tickRate: 0 }; const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => { result[key] = tt3.getAttribute(`ttp:${key}`) || defaultRateInfo[key]; return result; }, {}); const trim2 = tt3.getAttribute("xml:space") !== "preserve"; const styleElements = collectionToDictionary(getElementCollection(tt3, "styling", "style")); const regionElements = collectionToDictionary(getElementCollection(tt3, "layout", "region")); const cueElements = getElementCollection(tt3, "body", "[begin]"); return [].map.call(cueElements, (cueElement) => { const cueText = getTextContent(cueElement, trim2); if (!cueText || !cueElement.hasAttribute("begin")) { return null; } const startTime = parseTtmlTime(cueElement.getAttribute("begin"), rateInfo); const duration = parseTtmlTime(cueElement.getAttribute("dur"), rateInfo); let endTime = parseTtmlTime(cueElement.getAttribute("end"), rateInfo); if (startTime === null) { throw timestampParsingError(cueElement); } if (endTime === null) { if (duration === null) { throw timestampParsingError(cueElement); } endTime = startTime + duration; } const cue = new VTTCue2(startTime - syncTime, endTime - syncTime, cueText); cue.id = generateCueId(cue.startTime, cue.endTime, cue.text); const region = regionElements[cueElement.getAttribute("region")]; const style = styleElements[cueElement.getAttribute("style")]; const styles = getTtmlStyles(region, style, styleElements); const { textAlign } = styles; if (textAlign) { const lineAlign = textAlignToLineAlign[textAlign]; if (lineAlign) { cue.lineAlign = lineAlign; } cue.align = textAlign; } _extends2(cue, styles); return cue; }).filter((cue) => cue !== null); } function getElementCollection(fromElement, parentName, childName) { const parent = fromElement.getElementsByTagName(parentName)[0]; if (parent) { return [].slice.call(parent.querySelectorAll(childName)); } return []; } function collectionToDictionary(elementsWithId) { return elementsWithId.reduce((dict, element) => { const id = element.getAttribute("xml:id"); if (id) { dict[id] = element; } return dict; }, {}); } function getTextContent(element, trim2) { return [].slice.call(element.childNodes).reduce((str, node2, i3) => { var _node$childNodes; if (node2.nodeName === "br" && i3) { return str + "\n"; } if ((_node$childNodes = node2.childNodes) != null && _node$childNodes.length) { return getTextContent(node2, trim2); } else if (trim2) { return str + node2.textContent.trim().replace(/\s+/g, " "); } return str + node2.textContent; }, ""); } function getTtmlStyles(region, style, styleElements) { const ttsNs = "http://www.w3.org/ns/ttml#styling"; let regionStyle = null; const styleAttributes = [ "displayAlign", "textAlign", "color", "backgroundColor", "fontSize", "fontFamily" // 'fontWeight', // 'lineHeight', // 'wrapOption', // 'fontStyle', // 'direction', // 'writingMode' ]; const regionStyleName = region != null && region.hasAttribute("style") ? region.getAttribute("style") : null; if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) { regionStyle = styleElements[regionStyleName]; } return styleAttributes.reduce((styles, name) => { const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name); if (value) { styles[name] = value; } return styles; }, {}); } function getAttributeNS(element, ns, name) { if (!element) { return null; } return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null; } function timestampParsingError(node2) { return new Error(`Could not parse ttml timestamp ${node2}`); } function parseTtmlTime(timeAttributeValue, rateInfo) { if (!timeAttributeValue) { return null; } let seconds = parseTimeStamp(timeAttributeValue); if (seconds === null) { if (HMSF_REGEX.test(timeAttributeValue)) { seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo); } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) { seconds = parseTimeUnits(timeAttributeValue, rateInfo); } } return seconds; } function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) { const m2 = HMSF_REGEX.exec(timeAttributeValue); const frames = (m2[4] | 0) + (m2[5] | 0) / rateInfo.subFrameRate; return (m2[1] | 0) * 3600 + (m2[2] | 0) * 60 + (m2[3] | 0) + frames / rateInfo.frameRate; } function parseTimeUnits(timeAttributeValue, rateInfo) { const m2 = TIME_UNIT_REGEX.exec(timeAttributeValue); const value = Number(m2[1]); const unit = m2[2]; switch (unit) { case "h": return value * 3600; case "m": return value * 60; case "ms": return value * 1e3; case "f": return value / rateInfo.frameRate; case "t": return value / rateInfo.tickRate; } return value; } var TimelineController = class { constructor(hls) { this.hls = void 0; this.media = null; this.config = void 0; this.enabled = true; this.Cues = void 0; this.textTracks = []; this.tracks = []; this.initPTS = []; this.unparsedVttFrags = []; this.captionsTracks = {}; this.nonNativeCaptionsTracks = {}; this.cea608Parser1 = void 0; this.cea608Parser2 = void 0; this.lastCc = -1; this.lastSn = -1; this.lastPartIndex = -1; this.prevCC = -1; this.vttCCs = newVTTCCs(); this.captionsProperties = void 0; this.hls = hls; this.config = hls.config; this.Cues = hls.config.cueHandler; this.captionsProperties = { textTrack1: { label: this.config.captionsTextTrack1Label, languageCode: this.config.captionsTextTrack1LanguageCode }, textTrack2: { label: this.config.captionsTextTrack2Label, languageCode: this.config.captionsTextTrack2LanguageCode }, textTrack3: { label: this.config.captionsTextTrack3Label, languageCode: this.config.captionsTextTrack3LanguageCode }, textTrack4: { label: this.config.captionsTextTrack4Label, languageCode: this.config.captionsTextTrack4LanguageCode } }; hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this); hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.on(Events.FRAG_LOADING, this.onFragLoading, this); hls.on(Events.FRAG_LOADED, this.onFragLoaded, this); hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this); hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this); hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this); hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this); hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); } destroy() { const { hls } = this; hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this); hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this); hls.off(Events.FRAG_LOADING, this.onFragLoading, this); hls.off(Events.FRAG_LOADED, this.onFragLoaded, this); hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this); hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this); hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this); hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this); hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this); this.hls = this.config = null; this.cea608Parser1 = this.cea608Parser2 = void 0; } initCea608Parsers() { if (this.config.enableCEA708Captions && (!this.cea608Parser1 || !this.cea608Parser2)) { const channel1 = new OutputFilter(this, "textTrack1"); const channel2 = new OutputFilter(this, "textTrack2"); const channel3 = new OutputFilter(this, "textTrack3"); const channel4 = new OutputFilter(this, "textTrack4"); this.cea608Parser1 = new Cea608Parser(1, channel1, channel2); this.cea608Parser2 = new Cea608Parser(3, channel3, channel4); } } addCues(trackName, startTime, endTime, screen, cueRanges) { let merged = false; for (let i3 = cueRanges.length; i3--; ) { const cueRange = cueRanges[i3]; const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime); if (overlap >= 0) { cueRange[0] = Math.min(cueRange[0], startTime); cueRange[1] = Math.max(cueRange[1], endTime); merged = true; if (overlap / (endTime - startTime) > 0.5) { return; } } } if (!merged) { cueRanges.push([startTime, endTime]); } if (this.config.renderTextTracksNatively) { const track = this.captionsTracks[trackName]; this.Cues.newCue(track, startTime, endTime, screen); } else { const cues = this.Cues.newCue(null, startTime, endTime, screen); this.hls.trigger(Events.CUES_PARSED, { type: "captions", cues, track: trackName }); } } // Triggered when an initial PTS is found; used for synchronisation of WebVTT. onInitPtsFound(event, { frag, id, initPTS, timescale }) { const { unparsedVttFrags } = this; if (id === "main") { this.initPTS[frag.cc] = { baseTime: initPTS, timescale }; } if (unparsedVttFrags.length) { this.unparsedVttFrags = []; unparsedVttFrags.forEach((frag2) => { this.onFragLoaded(Events.FRAG_LOADED, frag2); }); } } getExistingTrack(label, language) { const { media } = this; if (media) { for (let i3 = 0; i3 < media.textTracks.length; i3++) { const textTrack = media.textTracks[i3]; if (canReuseVttTextTrack(textTrack, { name: label, lang: language, attrs: {} })) { return textTrack; } } } return null; } createCaptionsTrack(trackName) { if (this.config.renderTextTracksNatively) { this.createNativeTrack(trackName); } else { this.createNonNativeTrack(trackName); } } createNativeTrack(trackName) { if (this.captionsTracks[trackName]) { return; } const { captionsProperties, captionsTracks, media } = this; const { label, languageCode } = captionsProperties[trackName]; const existingTrack = this.getExistingTrack(label, languageCode); if (!existingTrack) { const textTrack = this.createTextTrack("captions", label, languageCode); if (textTrack) { textTrack[trackName] = true; captionsTracks[trackName] = textTrack; } } else { captionsTracks[trackName] = existingTrack; clearCurrentCues(captionsTracks[trackName]); sendAddTrackEvent(captionsTracks[trackName], media); } } createNonNativeTrack(trackName) { if (this.nonNativeCaptionsTracks[trackName]) { return; } const trackProperties = this.captionsProperties[trackName]; if (!trackProperties) { return; } const label = trackProperties.label; const track = { _id: trackName, label, kind: "captions", default: trackProperties.media ? !!trackProperties.media.default : false, closedCaptions: trackProperties.media }; this.nonNativeCaptionsTracks[trackName] = track; this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] }); } createTextTrack(kind, label, lang) { const media = this.media; if (!media) { return; } return media.addTextTrack(kind, label, lang); } onMediaAttaching(event, data) { this.media = data.media; this._cleanTracks(); } onMediaDetaching() { const { captionsTracks } = this; Object.keys(captionsTracks).forEach((trackName) => { clearCurrentCues(captionsTracks[trackName]); delete captionsTracks[trackName]; }); this.nonNativeCaptionsTracks = {}; } onManifestLoading() { this.lastCc = -1; this.lastSn = -1; this.lastPartIndex = -1; this.prevCC = -1; this.vttCCs = newVTTCCs(); this._cleanTracks(); this.tracks = []; this.captionsTracks = {}; this.nonNativeCaptionsTracks = {}; this.textTracks = []; this.unparsedVttFrags = []; this.initPTS = []; if (this.cea608Parser1 && this.cea608Parser2) { this.cea608Parser1.reset(); this.cea608Parser2.reset(); } } _cleanTracks() { const { media } = this; if (!media) { return; } const textTracks = media.textTracks; if (textTracks) { for (let i3 = 0; i3 < textTracks.length; i3++) { clearCurrentCues(textTracks[i3]); } } } onSubtitleTracksUpdated(event, data) { const tracks = data.subtitleTracks || []; const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC); if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) { const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks); if (listIsIdentical) { this.tracks = tracks; return; } this.textTracks = []; this.tracks = tracks; if (this.config.renderTextTracksNatively) { const media = this.media; const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null; this.tracks.forEach((track, index2) => { let textTrack; if (inUseTracks) { let inUseTrack = null; for (let i3 = 0; i3 < inUseTracks.length; i3++) { if (inUseTracks[i3] && canReuseVttTextTrack(inUseTracks[i3], track)) { inUseTrack = inUseTracks[i3]; inUseTracks[i3] = null; break; } } if (inUseTrack) { textTrack = inUseTrack; } } if (textTrack) { clearCurrentCues(textTrack); } else { const textTrackKind = captionsOrSubtitlesFromCharacteristics(track); textTrack = this.createTextTrack(textTrackKind, track.name, track.lang); if (textTrack) { textTrack.mode = "disabled"; } } if (textTrack) { this.textTracks.push(textTrack); } }); if (inUseTracks != null && inUseTracks.length) { const unusedTextTracks = inUseTracks.filter((t2) => t2 !== null).map((t2) => t2.label); if (unusedTextTracks.length) { logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`); } } } else if (this.tracks.length) { const tracksList = this.tracks.map((track) => { return { label: track.name, kind: track.type.toLowerCase(), default: track.default, subtitleTrack: track }; }); this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: tracksList }); } } } onManifestLoaded(event, data) { if (this.config.enableCEA708Captions && data.captions) { data.captions.forEach((captionsTrack) => { const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId); if (!instreamIdMatch) { return; } const trackName = `textTrack${instreamIdMatch[1]}`; const trackProperties = this.captionsProperties[trackName]; if (!trackProperties) { return; } trackProperties.label = captionsTrack.name; if (captionsTrack.lang) { trackProperties.languageCode = captionsTrack.lang; } trackProperties.media = captionsTrack; }); } } closedCaptionsForLevel(frag) { const level = this.hls.levels[frag.level]; return level == null ? void 0 : level.attrs["CLOSED-CAPTIONS"]; } onFragLoading(event, data) { if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) { var _data$part$index, _data$part; const { cea608Parser1, cea608Parser2, lastSn } = this; const { cc, sn } = data.frag; const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1; if (cea608Parser1 && cea608Parser2) { if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) { cea608Parser1.reset(); cea608Parser2.reset(); } } this.lastCc = cc; this.lastSn = sn; this.lastPartIndex = partIndex; } } onFragLoaded(event, data) { const { frag, payload } = data; if (frag.type === PlaylistLevelType.SUBTITLE) { if (payload.byteLength) { const decryptData = frag.decryptdata; const decrypted = "stats" in data; if (decryptData == null || !decryptData.encrypted || decrypted) { const trackPlaylistMedia = this.tracks[frag.level]; const vttCCs = this.vttCCs; if (!vttCCs[frag.cc]) { vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true }; this.prevCC = frag.cc; } if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) { this._parseIMSC1(frag, payload); } else { this._parseVTTs(data); } } } else { this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, { success: false, frag, error: new Error("Empty subtitle payload") }); } } } _parseIMSC1(frag, payload) { const hls = this.hls; parseIMSC1(payload, this.initPTS[frag.cc], (cues) => { this._appendCues(cues, frag.level); hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, { success: true, frag }); }, (error) => { logger.log(`Failed to parse IMSC1: ${error}`); hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, { success: false, frag, error }); }); } _parseVTTs(data) { var _frag$initSegment; const { frag, payload } = data; const { initPTS, unparsedVttFrags } = this; const maxAvCC = initPTS.length - 1; if (!initPTS[frag.cc] && maxAvCC === -1) { unparsedVttFrags.push(data); return; } const hls = this.hls; const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)) : payload; parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, (cues) => { this._appendCues(cues, frag.level); hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, { success: true, frag }); }, (error) => { const missingInitPTS = error.message === "Missing initPTS for VTT MPEGTS"; if (missingInitPTS) { unparsedVttFrags.push(data); } else { this._fallbackToIMSC1(frag, payload); } logger.log(`Failed to parse VTT cue: ${error}`); if (missingInitPTS && maxAvCC > frag.cc) { return; } hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, { success: false, frag, error }); }); } _fallbackToIMSC1(frag, payload) { const trackPlaylistMedia = this.tracks[frag.level]; if (!trackPlaylistMedia.textCodec) { parseIMSC1(payload, this.initPTS[frag.cc], () => { trackPlaylistMedia.textCodec = IMSC1_CODEC; this._parseIMSC1(frag, payload); }, () => { trackPlaylistMedia.textCodec = "wvtt"; }); } } _appendCues(cues, fragLevel) { const hls = this.hls; if (this.config.renderTextTracksNatively) { const textTrack = this.textTracks[fragLevel]; if (!textTrack || textTrack.mode === "disabled") { return; } cues.forEach((cue) => addCueToTrack(textTrack, cue)); } else { const currentTrack = this.tracks[fragLevel]; if (!currentTrack) { return; } const track = currentTrack.default ? "default" : "subtitles" + fragLevel; hls.trigger(Events.CUES_PARSED, { type: "subtitles", cues, track }); } } onFragDecrypted(event, data) { const { frag } = data; if (frag.type === PlaylistLevelType.SUBTITLE) { this.onFragLoaded(Events.FRAG_LOADED, data); } } onSubtitleTracksCleared() { this.tracks = []; this.captionsTracks = {}; } onFragParsingUserdata(event, data) { this.initCea608Parsers(); const { cea608Parser1, cea608Parser2 } = this; if (!this.enabled || !cea608Parser1 || !cea608Parser2) { return; } const { frag, samples } = data; if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === "NONE") { return; } for (let i3 = 0; i3 < samples.length; i3++) { const ccBytes = samples[i3].bytes; if (ccBytes) { const ccdatas = this.extractCea608Data(ccBytes); cea608Parser1.addData(samples[i3].pts, ccdatas[0]); cea608Parser2.addData(samples[i3].pts, ccdatas[1]); } } } onBufferFlushing(event, { startOffset, endOffset, endOffsetSubtitles, type }) { const { media } = this; if (!media || media.currentTime < endOffset) { return; } if (!type || type === "video") { const { captionsTracks } = this; Object.keys(captionsTracks).forEach((trackName) => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset)); } if (this.config.renderTextTracksNatively) { if (startOffset === 0 && endOffsetSubtitles !== void 0) { const { textTracks } = this; Object.keys(textTracks).forEach((trackName) => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles)); } } } extractCea608Data(byteArray) { const actualCCBytes = [[], []]; const count = byteArray[0] & 31; let position2 = 2; for (let j3 = 0; j3 < count; j3++) { const tmpByte = byteArray[position2++]; const ccbyte1 = 127 & byteArray[position2++]; const ccbyte2 = 127 & byteArray[position2++]; if (ccbyte1 === 0 && ccbyte2 === 0) { continue; } const ccValid = (4 & tmpByte) !== 0; if (ccValid) { const ccType = 3 & tmpByte; if (0 === ccType || 1 === ccType) { actualCCBytes[ccType].push(ccbyte1); actualCCBytes[ccType].push(ccbyte2); } } } return actualCCBytes; } }; function captionsOrSubtitlesFromCharacteristics(track) { if (track.characteristics) { if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) { return "captions"; } } return "subtitles"; } function canReuseVttTextTrack(inUseTrack, manifestTrack) { return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack); } function intersection(x1, x2, y1, y22) { return Math.min(x2, y22) - Math.max(x1, y1); } function newVTTCCs() { return { ccOffset: 0, presentationOffset: 0, 0: { start: 0, prevCC: -1, new: true } }; } var CapLevelController = class _CapLevelController { constructor(hls) { this.hls = void 0; this.autoLevelCapping = void 0; this.firstLevel = void 0; this.media = void 0; this.restrictedLevels = void 0; this.timer = void 0; this.clientRect = void 0; this.streamController = void 0; this.hls = hls; this.autoLevelCapping = Number.POSITIVE_INFINITY; this.firstLevel = -1; this.media = null; this.restrictedLevels = []; this.timer = void 0; this.clientRect = null; this.registerListeners(); } setStreamController(streamController) { this.streamController = streamController; } destroy() { if (this.hls) { this.unregisterListener(); } if (this.timer) { this.stopCapping(); } this.media = null; this.clientRect = null; this.hls = this.streamController = null; } registerListeners() { const { hls } = this; hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this); hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); } unregisterListener() { const { hls } = this; hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this); hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); } onFpsDropLevelCapping(event, data) { const level = this.hls.levels[data.droppedLevel]; if (this.isLevelAllowed(level)) { this.restrictedLevels.push({ bitrate: level.bitrate, height: level.height, width: level.width }); } } onMediaAttaching(event, data) { this.media = data.media instanceof HTMLVideoElement ? data.media : null; this.clientRect = null; if (this.timer && this.hls.levels.length) { this.detectPlayerSize(); } } onManifestParsed(event, data) { const hls = this.hls; this.restrictedLevels = []; this.firstLevel = data.firstLevel; if (hls.config.capLevelToPlayerSize && data.video) { this.startCapping(); } } onLevelsUpdated(event, data) { if (this.timer && isFiniteNumber(this.autoLevelCapping)) { this.detectPlayerSize(); } } // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted // to the first level onBufferCodecs(event, data) { const hls = this.hls; if (hls.config.capLevelToPlayerSize && data.video) { this.startCapping(); } } onMediaDetaching() { this.stopCapping(); } detectPlayerSize() { if (this.media) { if (this.mediaHeight <= 0 || this.mediaWidth <= 0) { this.clientRect = null; return; } const levels = this.hls.levels; if (levels.length) { const hls = this.hls; const maxLevel = this.getMaxLevel(levels.length - 1); if (maxLevel !== this.autoLevelCapping) { logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`); } hls.autoLevelCapping = maxLevel; if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) { this.streamController.nextLevelSwitch(); } this.autoLevelCapping = hls.autoLevelCapping; } } } /* * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled) */ getMaxLevel(capLevelIndex) { const levels = this.hls.levels; if (!levels.length) { return -1; } const validLevels = levels.filter((level, index2) => this.isLevelAllowed(level) && index2 <= capLevelIndex); this.clientRect = null; return _CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight); } startCapping() { if (this.timer) { return; } this.autoLevelCapping = Number.POSITIVE_INFINITY; self.clearInterval(this.timer); this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3); this.detectPlayerSize(); } stopCapping() { this.restrictedLevels = []; this.firstLevel = -1; this.autoLevelCapping = Number.POSITIVE_INFINITY; if (this.timer) { self.clearInterval(this.timer); this.timer = void 0; } } getDimensions() { if (this.clientRect) { return this.clientRect; } const media = this.media; const boundsRect = { width: 0, height: 0 }; if (media) { const clientRect = media.getBoundingClientRect(); boundsRect.width = clientRect.width; boundsRect.height = clientRect.height; if (!boundsRect.width && !boundsRect.height) { boundsRect.width = clientRect.right - clientRect.left || media.width || 0; boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0; } } this.clientRect = boundsRect; return boundsRect; } get mediaWidth() { return this.getDimensions().width * this.contentScaleFactor; } get mediaHeight() { return this.getDimensions().height * this.contentScaleFactor; } get contentScaleFactor() { let pixelRatio = 1; if (!this.hls.config.ignoreDevicePixelRatio) { try { pixelRatio = self.devicePixelRatio; } catch (e) { } } return pixelRatio; } isLevelAllowed(level) { const restrictedLevels = this.restrictedLevels; return !restrictedLevels.some((restrictedLevel) => { return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height; }); } static getMaxLevelByMediaSize(levels, width, height) { if (!(levels != null && levels.length)) { return -1; } const atGreatestBandwidth = (curLevel, nextLevel) => { if (!nextLevel) { return true; } return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height; }; let maxLevelIndex = levels.length - 1; const squareSize = Math.max(width, height); for (let i3 = 0; i3 < levels.length; i3 += 1) { const level = levels[i3]; if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i3 + 1])) { maxLevelIndex = i3; break; } } return maxLevelIndex; } }; var FPSController = class { constructor(hls) { this.hls = void 0; this.isVideoPlaybackQualityAvailable = false; this.timer = void 0; this.media = null; this.lastTime = void 0; this.lastDroppedFrames = 0; this.lastDecodedFrames = 0; this.streamController = void 0; this.hls = hls; this.registerListeners(); } setStreamController(streamController) { this.streamController = streamController; } registerListeners() { this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); } unregisterListeners() { this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this); } destroy() { if (this.timer) { clearInterval(this.timer); } this.unregisterListeners(); this.isVideoPlaybackQualityAvailable = false; this.media = null; } onMediaAttaching(event, data) { const config = this.hls.config; if (config.capLevelOnFPSDrop) { const media = data.media instanceof self.HTMLVideoElement ? data.media : null; this.media = media; if (media && typeof media.getVideoPlaybackQuality === "function") { this.isVideoPlaybackQualityAvailable = true; } self.clearInterval(this.timer); this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod); } } checkFPS(video, decodedFrames, droppedFrames) { const currentTime = performance.now(); if (decodedFrames) { if (this.lastTime) { const currentPeriod = currentTime - this.lastTime; const currentDropped = droppedFrames - this.lastDroppedFrames; const currentDecoded = decodedFrames - this.lastDecodedFrames; const droppedFPS = 1e3 * currentDropped / currentPeriod; const hls = this.hls; hls.trigger(Events.FPS_DROP, { currentDropped, currentDecoded, totalDroppedFrames: droppedFrames }); if (droppedFPS > 0) { if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) { let currentLevel = hls.currentLevel; logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + currentLevel); if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) { currentLevel = currentLevel - 1; hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel }); hls.autoLevelCapping = currentLevel; this.streamController.nextLevelSwitch(); } } } } this.lastTime = currentTime; this.lastDroppedFrames = droppedFrames; this.lastDecodedFrames = decodedFrames; } } checkFPSInterval() { const video = this.media; if (video) { if (this.isVideoPlaybackQualityAvailable) { const videoPlaybackQuality = video.getVideoPlaybackQuality(); this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames); } else { this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount); } } } }; var LOGGER_PREFIX = "[eme]"; var EMEController = class _EMEController { constructor(hls) { this.hls = void 0; this.config = void 0; this.media = null; this.keyFormatPromise = null; this.keySystemAccessPromises = {}; this._requestLicenseFailureCount = 0; this.mediaKeySessions = []; this.keyIdToKeySessionPromise = {}; this.setMediaKeysQueue = _EMEController.CDMCleanupPromise ? [_EMEController.CDMCleanupPromise] : []; this.debug = logger.debug.bind(logger, LOGGER_PREFIX); this.log = logger.log.bind(logger, LOGGER_PREFIX); this.warn = logger.warn.bind(logger, LOGGER_PREFIX); this.error = logger.error.bind(logger, LOGGER_PREFIX); this.onMediaEncrypted = (event) => { const { initDataType, initData } = event; const logMessage = `"${event.type}" event: init data type: "${initDataType}"`; this.debug(logMessage); if (initData === null) { return; } if (!this.keyFormatPromise) { let keySystems = Object.keys(this.keySystemAccessPromises); if (!keySystems.length) { keySystems = getKeySystemsForConfig(this.config); } const keyFormats = keySystems.map(keySystemDomainToKeySystemFormat).filter((k3) => !!k3); this.keyFormatPromise = this.getKeyFormatPromise(keyFormats); } this.keyFormatPromise.then((keySystemFormat) => { const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat); let keyId; let keySystemDomain; if (initDataType === "sinf") { if (keySystem !== KeySystems.FAIRPLAY) { this.warn(`Ignoring unexpected "${event.type}" event with init data type: "${initDataType}" for selected key-system ${keySystem}`); return; } const json = bin2str(new Uint8Array(initData)); try { const sinf = base64Decode(JSON.parse(json).sinf); const tenc = parseSinf(sinf); if (!tenc) { throw new Error(`'schm' box missing or not cbcs/cenc with schi > tenc`); } keyId = tenc.subarray(8, 24); keySystemDomain = KeySystems.FAIRPLAY; } catch (error) { this.warn(`${logMessage} Failed to parse sinf: ${error}`); return; } } else { if (keySystem !== KeySystems.WIDEVINE && keySystem !== KeySystems.PLAYREADY) { this.warn(`Ignoring unexpected "${event.type}" event with init data type: "${initDataType}" for selected key-system ${keySystem}`); return; } const psshResults = parseMultiPssh(initData); const psshInfos = psshResults.filter((pssh) => !!pssh.systemId && keySystemIdToKeySystemDomain(pssh.systemId) === keySystem); if (psshInfos.length > 1) { this.warn(`${logMessage} Using first of ${psshInfos.length} pssh found for selected key-system ${keySystem}`); } const psshInfo = psshInfos[0]; if (!psshInfo) { if (psshResults.length === 0 || psshResults.some((pssh) => !pssh.systemId)) { this.warn(`${logMessage} contains incomplete or invalid pssh data`); } else { this.log(`ignoring ${logMessage} for ${psshResults.map((pssh) => keySystemIdToKeySystemDomain(pssh.systemId)).join(",")} pssh data in favor of playlist keys`); } return; } keySystemDomain = keySystemIdToKeySystemDomain(psshInfo.systemId); if (psshInfo.version === 0 && psshInfo.data) { if (keySystemDomain === KeySystems.WIDEVINE) { const offset = psshInfo.data.length - 22; keyId = psshInfo.data.subarray(offset, offset + 16); } else if (keySystemDomain === KeySystems.PLAYREADY) { keyId = parsePlayReadyWRM(psshInfo.data); } } } if (!keySystemDomain || !keyId) { this.log(`Unable to handle ${logMessage} with key-system ${keySystem}`); return; } const keyIdHex = Hex.hexDump(keyId); const { keyIdToKeySessionPromise, mediaKeySessions } = this; let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex]; for (let i3 = 0; i3 < mediaKeySessions.length; i3++) { const keyContext = mediaKeySessions[i3]; const decryptdata = keyContext.decryptdata; if (!decryptdata.keyId) { continue; } const oldKeyIdHex = Hex.hexDump(decryptdata.keyId); if (keyIdHex === oldKeyIdHex || decryptdata.uri.replace(/-/g, "").indexOf(keyIdHex) !== -1) { keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex]; if (decryptdata.pssh) { break; } delete keyIdToKeySessionPromise[oldKeyIdHex]; decryptdata.pssh = new Uint8Array(initData); decryptdata.keyId = keyId; keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = keySessionContextPromise.then(() => { return this.generateRequestWithPreferredKeySession(keyContext, initDataType, initData, "encrypted-event-key-match"); }); keySessionContextPromise.catch((error) => this.handleError(error)); break; } } if (!keySessionContextPromise) { if (keySystemDomain !== keySystem) { this.log(`Ignoring "${logMessage}" with ${keySystemDomain} init data for selected key-system ${keySystem}`); return; } keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = this.getKeySystemSelectionPromise([keySystemDomain]).then(({ keySystem: keySystem2, mediaKeys }) => { var _keySystemToKeySystem; this.throwIfDestroyed(); const decryptdata = new LevelKey("ISO-23001-7", keyIdHex, (_keySystemToKeySystem = keySystemDomainToKeySystemFormat(keySystem2)) != null ? _keySystemToKeySystem : ""); decryptdata.pssh = new Uint8Array(initData); decryptdata.keyId = keyId; return this.attemptSetMediaKeys(keySystem2, mediaKeys).then(() => { this.throwIfDestroyed(); const keySessionContext = this.createMediaKeySessionContext({ decryptdata, keySystem: keySystem2, mediaKeys }); return this.generateRequestWithPreferredKeySession(keySessionContext, initDataType, initData, "encrypted-event-no-match"); }); }); keySessionContextPromise.catch((error) => this.handleError(error)); } }); }; this.onWaitingForKey = (event) => { this.log(`"${event.type}" event`); }; this.hls = hls; this.config = hls.config; this.registerListeners(); } destroy() { this.unregisterListeners(); this.onMediaDetached(); const config = this.config; config.requestMediaKeySystemAccessFunc = null; config.licenseXhrSetup = config.licenseResponseCallback = void 0; config.drmSystems = config.drmSystemOptions = {}; this.hls = this.config = this.keyIdToKeySessionPromise = null; this.onMediaEncrypted = this.onWaitingForKey = null; } registerListeners() { this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this); this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this); } unregisterListeners() { this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this); this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this); } getLicenseServerUrl(keySystem) { const { drmSystems, widevineLicenseUrl } = this.config; const keySystemConfiguration = drmSystems[keySystem]; if (keySystemConfiguration) { return keySystemConfiguration.licenseUrl; } if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) { return widevineLicenseUrl; } } getLicenseServerUrlOrThrow(keySystem) { const url = this.getLicenseServerUrl(keySystem); if (url === void 0) { throw new Error(`no license server URL configured for key-system "${keySystem}"`); } return url; } getServerCertificateUrl(keySystem) { const { drmSystems } = this.config; const keySystemConfiguration = drmSystems[keySystem]; if (keySystemConfiguration) { return keySystemConfiguration.serverCertificateUrl; } else { this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`); } } attemptKeySystemAccess(keySystemsToAttempt) { const levels = this.hls.levels; const uniqueCodec = (value, i3, a2) => !!value && a2.indexOf(value) === i3; const audioCodecs = levels.map((level) => level.audioCodec).filter(uniqueCodec); const videoCodecs = levels.map((level) => level.videoCodec).filter(uniqueCodec); if (audioCodecs.length + videoCodecs.length === 0) { videoCodecs.push("avc1.42e01e"); } return new Promise((resolve, reject) => { const attempt = (keySystems) => { const keySystem = keySystems.shift(); this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then((mediaKeys) => resolve({ keySystem, mediaKeys })).catch((error) => { if (keySystems.length) { attempt(keySystems); } else if (error instanceof EMEKeyError) { reject(error); } else { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_NO_ACCESS, error, fatal: true }, error.message)); } }); }; attempt(keySystemsToAttempt); }); } requestMediaKeySystemAccess(keySystem, supportedConfigurations) { const { requestMediaKeySystemAccessFunc } = this.config; if (!(typeof requestMediaKeySystemAccessFunc === "function")) { let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`; if (requestMediaKeySystemAccess === null && self.location.protocol === "http:") { errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`; } return Promise.reject(new Error(errMessage)); } return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations); } getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) { const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions); const keySystemAccessPromises = this.keySystemAccessPromises[keySystem]; let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess; if (!keySystemAccess) { this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${JSON.stringify(mediaKeySystemConfigs)}`); keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs); const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = { keySystemAccess }; keySystemAccess.catch((error) => { this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`); }); return keySystemAccess.then((mediaKeySystemAccess) => { this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`); const certificateRequest = this.fetchServerCertificate(keySystem); this.log(`Create media-keys for "${keySystem}"`); _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then((mediaKeys) => { this.log(`Media-keys created for "${keySystem}"`); return certificateRequest.then((certificate) => { if (certificate) { return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate); } return mediaKeys; }); }); _keySystemAccessPromises.mediaKeys.catch((error) => { this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`); }); return _keySystemAccessPromises.mediaKeys; }); } return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys); } createMediaKeySessionContext({ decryptdata, keySystem, mediaKeys }) { this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`); const mediaKeysSession = mediaKeys.createSession(); const mediaKeySessionContext = { decryptdata, keySystem, mediaKeys, mediaKeysSession, keyStatus: "status-pending" }; this.mediaKeySessions.push(mediaKeySessionContext); return mediaKeySessionContext; } renewKeySession(mediaKeySessionContext) { const decryptdata = mediaKeySessionContext.decryptdata; if (decryptdata.pssh) { const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext); const keyId = this.getKeyIdString(decryptdata); const scheme = "cenc"; this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh, "expired"); } else { this.warn(`Could not renew expired session. Missing pssh initData.`); } this.removeSession(mediaKeySessionContext); } getKeyIdString(decryptdata) { if (!decryptdata) { throw new Error("Could not read keyId of undefined decryptdata"); } if (decryptdata.keyId === null) { throw new Error("keyId is null"); } return Hex.hexDump(decryptdata.keyId); } updateKeySession(mediaKeySessionContext, data) { var _mediaKeySessionConte; const keySession = mediaKeySessionContext.mediaKeysSession; this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])} } (data length: ${data ? data.byteLength : data})`); return keySession.update(data); } selectKeySystemFormat(frag) { const keyFormats = Object.keys(frag.levelkeys || {}); if (!this.keyFormatPromise) { this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(", ")}`); this.keyFormatPromise = this.getKeyFormatPromise(keyFormats); } return this.keyFormatPromise; } getKeyFormatPromise(keyFormats) { return new Promise((resolve, reject) => { const keySystemsInConfig = getKeySystemsForConfig(this.config); const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter((value) => !!value && keySystemsInConfig.indexOf(value) !== -1); return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({ keySystem }) => { const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem); if (keySystemFormat) { resolve(keySystemFormat); } else { reject(new Error(`Unable to find format for key-system "${keySystem}"`)); } }).catch(reject); }); } loadKey(data) { const decryptdata = data.keyInfo.decryptdata; const keyId = this.getKeyIdString(decryptdata); const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`; this.log(`Starting session for key ${keyDetails}`); let keySessionContextPromise = this.keyIdToKeySessionPromise[keyId]; if (!keySessionContextPromise) { keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = this.getKeySystemForKeyPromise(decryptdata).then(({ keySystem, mediaKeys }) => { this.throwIfDestroyed(); this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`); return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => { this.throwIfDestroyed(); const keySessionContext = this.createMediaKeySessionContext({ keySystem, mediaKeys, decryptdata }); const scheme = "cenc"; return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh, "playlist-key"); }); }); keySessionContextPromise.catch((error) => this.handleError(error)); } return keySessionContextPromise; } throwIfDestroyed(message = "Invalid state") { if (!this.hls) { throw new Error("invalid state"); } } handleError(error) { if (!this.hls) { return; } this.error(error.message); if (error instanceof EMEKeyError) { this.hls.trigger(Events.ERROR, error.data); } else { this.hls.trigger(Events.ERROR, { type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_NO_KEYS, error, fatal: true }); } } getKeySystemForKeyPromise(decryptdata) { const keyId = this.getKeyIdString(decryptdata); const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId]; if (!mediaKeySessionContext) { const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat); const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config); return this.attemptKeySystemAccess(keySystemsToAttempt); } return mediaKeySessionContext; } getKeySystemSelectionPromise(keySystemsToAttempt) { if (!keySystemsToAttempt.length) { keySystemsToAttempt = getKeySystemsForConfig(this.config); } if (keySystemsToAttempt.length === 0) { throw new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE, fatal: true }, `Missing key-system license configuration options ${JSON.stringify({ drmSystems: this.config.drmSystems })}`); } return this.attemptKeySystemAccess(keySystemsToAttempt); } attemptSetMediaKeys(keySystem, mediaKeys) { const queue = this.setMediaKeysQueue.slice(); this.log(`Setting media-keys for "${keySystem}"`); const setMediaKeysPromise = Promise.all(queue).then(() => { if (!this.media) { throw new Error("Attempted to set mediaKeys without media element attached"); } return this.media.setMediaKeys(mediaKeys); }); this.setMediaKeysQueue.push(setMediaKeysPromise); return setMediaKeysPromise.then(() => { this.log(`Media-keys set for "${keySystem}"`); queue.push(setMediaKeysPromise); this.setMediaKeysQueue = this.setMediaKeysQueue.filter((p3) => queue.indexOf(p3) === -1); }); } generateRequestWithPreferredKeySession(context, initDataType, initData, reason) { var _this$config$drmSyste, _this$config$drmSyste2; const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest; if (generateRequestFilter) { try { const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context); if (!mappedInitData) { throw new Error("Invalid response from configured generateRequest filter"); } initDataType = mappedInitData.initDataType; initData = context.decryptdata.pssh = mappedInitData.initData ? new Uint8Array(mappedInitData.initData) : null; } catch (error) { var _this$hls; this.warn(error.message); if ((_this$hls = this.hls) != null && _this$hls.config.debug) { throw error; } } } if (initData === null) { this.log(`Skipping key-session request for "${reason}" (no initData)`); return Promise.resolve(context); } const keyId = this.getKeyIdString(context.decryptdata); this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`); const licenseStatus = new EventEmitter(); const onmessage = context._onmessage = (event) => { const keySession = context.mediaKeysSession; if (!keySession) { licenseStatus.emit("error", new Error("invalid state")); return; } const { messageType, message } = event; this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`); if (messageType === "license-request" || messageType === "license-renewal") { this.renewLicense(context, message).catch((error) => { this.handleError(error); licenseStatus.emit("error", error); }); } else if (messageType === "license-release") { if (context.keySystem === KeySystems.FAIRPLAY) { this.updateKeySession(context, strToUtf8array("acknowledged")); this.removeSession(context); } } else { this.warn(`unhandled media key message type "${messageType}"`); } }; const onkeystatuseschange = context._onkeystatuseschange = (event) => { const keySession = context.mediaKeysSession; if (!keySession) { licenseStatus.emit("error", new Error("invalid state")); return; } this.onKeyStatusChange(context); const keyStatus = context.keyStatus; licenseStatus.emit("keyStatus", keyStatus); if (keyStatus === "expired") { this.warn(`${context.keySystem} expired for key ${keyId}`); this.renewKeySession(context); } }; context.mediaKeysSession.addEventListener("message", onmessage); context.mediaKeysSession.addEventListener("keystatuseschange", onkeystatuseschange); const keyUsablePromise = new Promise((resolve, reject) => { licenseStatus.on("error", reject); licenseStatus.on("keyStatus", (keyStatus) => { if (keyStatus.startsWith("usable")) { resolve(); } else if (keyStatus === "output-restricted") { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED, fatal: false }, "HDCP level output restricted")); } else if (keyStatus === "internal-error") { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR, fatal: true }, `key status changed to "${keyStatus}"`)); } else if (keyStatus === "expired") { reject(new Error("key expired while generating request")); } else { this.warn(`unhandled key status change "${keyStatus}"`); } }); }); return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => { var _context$mediaKeysSes; this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`); }).catch((error) => { throw new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_NO_SESSION, error, fatal: false }, `Error generating key-session request: ${error}`); }).then(() => keyUsablePromise).catch((error) => { licenseStatus.removeAllListeners(); this.removeSession(context); throw error; }).then(() => { licenseStatus.removeAllListeners(); return context; }); } onKeyStatusChange(mediaKeySessionContext) { mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status2, keyId) => { this.log(`key status change "${status2}" for keyStatuses keyId: ${Hex.hexDump("buffer" in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId))} session keyId: ${Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || []))} uri: ${mediaKeySessionContext.decryptdata.uri}`); mediaKeySessionContext.keyStatus = status2; }); } fetchServerCertificate(keySystem) { const config = this.config; const Loader2 = config.loader; const certLoader = new Loader2(config); const url = this.getServerCertificateUrl(keySystem); if (!url) { return Promise.resolve(); } this.log(`Fetching server certificate for "${keySystem}"`); return new Promise((resolve, reject) => { const loaderContext = { responseType: "arraybuffer", url }; const loadPolicy = config.certLoadPolicy.default; const loaderConfig = { loadPolicy, timeout: loadPolicy.maxLoadTimeMs, maxRetry: 0, retryDelay: 0, maxRetryDelay: 0 }; const loaderCallbacks = { onSuccess: (response, stats, context, networkDetails) => { resolve(response.data); }, onError: (response, contex, networkDetails, stats) => { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED, fatal: true, networkDetails, response: _objectSpread23({ url: loaderContext.url, data: void 0 }, response) }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`)); }, onTimeout: (stats, context, networkDetails) => { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED, fatal: true, networkDetails, response: { url: loaderContext.url, data: void 0 } }, `"${keySystem}" certificate request timed out (${url})`)); }, onAbort: (stats, context, networkDetails) => { reject(new Error("aborted")); } }; certLoader.load(loaderContext, loaderConfig, loaderCallbacks); }); } setMediaKeysServerCertificate(mediaKeys, keySystem, cert) { return new Promise((resolve, reject) => { mediaKeys.setServerCertificate(cert).then((success) => { this.log(`setServerCertificate ${success ? "success" : "not supported by CDM"} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`); resolve(mediaKeys); }).catch((error) => { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED, error, fatal: true }, error.message)); }); }); } renewLicense(context, keyMessage) { return this.requestLicense(context, new Uint8Array(keyMessage)).then((data) => { return this.updateKeySession(context, new Uint8Array(data)).catch((error) => { throw new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED, error, fatal: true }, error.message); }); }); } unpackPlayReadyKeyMessage(xhr, licenseChallenge) { const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer)); if (!xmlString.includes("PlayReadyKeyMessage")) { xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); return licenseChallenge; } const keyMessageXml = new DOMParser().parseFromString(xmlString, "application/xml"); const headers = keyMessageXml.querySelectorAll("HttpHeader"); if (headers.length > 0) { let header; for (let i3 = 0, len = headers.length; i3 < len; i3++) { var _header$querySelector, _header$querySelector2; header = headers[i3]; const name = (_header$querySelector = header.querySelector("name")) == null ? void 0 : _header$querySelector.textContent; const value = (_header$querySelector2 = header.querySelector("value")) == null ? void 0 : _header$querySelector2.textContent; if (name && value) { xhr.setRequestHeader(name, value); } } } const challengeElement = keyMessageXml.querySelector("Challenge"); const challengeText = challengeElement == null ? void 0 : challengeElement.textContent; if (!challengeText) { throw new Error(`Cannot find <Challenge> in key message`); } return strToUtf8array(atob(challengeText)); } setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) { const licenseXhrSetup = this.config.licenseXhrSetup; if (!licenseXhrSetup) { xhr.open("POST", url, true); return Promise.resolve({ xhr, licenseChallenge }); } return Promise.resolve().then(() => { if (!keysListItem.decryptdata) { throw new Error("Key removed"); } return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge); }).catch((error) => { if (!keysListItem.decryptdata) { throw error; } xhr.open("POST", url, true); return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge); }).then((licenseXhrSetupResult) => { if (!xhr.readyState) { xhr.open("POST", url, true); } const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge; return { xhr, licenseChallenge: finalLicenseChallenge }; }); } requestLicense(keySessionContext, licenseChallenge) { const keyLoadPolicy = this.config.keyLoadPolicy.default; return new Promise((resolve, reject) => { const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem); this.log(`Sending license request to URL: ${url}`); const xhr = new XMLHttpRequest(); xhr.responseType = "arraybuffer"; xhr.onreadystatechange = () => { if (!this.hls || !keySessionContext.mediaKeysSession) { return reject(new Error("invalid state")); } if (xhr.readyState === 4) { if (xhr.status === 200) { this._requestLicenseFailureCount = 0; let data = xhr.response; this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`); const licenseResponseCallback = this.config.licenseResponseCallback; if (licenseResponseCallback) { try { data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext); } catch (error) { this.error(error); } } resolve(data); } else { const retryConfig = keyLoadPolicy.errorRetry; const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0; this._requestLicenseFailureCount++; if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) { reject(new EMEKeyError({ type: ErrorTypes.KEY_SYSTEM_ERROR, details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED, fatal: true, networkDetails: xhr, response: { url, data: void 0, code: xhr.status, text: xhr.statusText } }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`)); } else { const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1; this.warn(`Retrying license request, ${attemptsLeft} attempts left`); this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject); } } } }; if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) { keySessionContext.licenseXhr.abort(); } keySessionContext.licenseXhr = xhr; this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({ xhr: xhr2, licenseChallenge: licenseChallenge2 }) => { if (keySessionContext.keySystem == KeySystems.PLAYREADY) { licenseChallenge2 = this.unpackPlayReadyKeyMessage(xhr2, licenseChallenge2); } xhr2.send(licenseChallenge2); }); }); } onMediaAttached(event, data) { if (!this.config.emeEnabled) { return; } const media = data.media; this.media = media; media.removeEventListener("encrypted", this.onMediaEncrypted); media.removeEventListener("waitingforkey", this.onWaitingForKey); media.addEventListener("encrypted", this.onMediaEncrypted); media.addEventListener("waitingforkey", this.onWaitingForKey); } onMediaDetached() { const media = this.media; const mediaKeysList = this.mediaKeySessions; if (media) { media.removeEventListener("encrypted", this.onMediaEncrypted); media.removeEventListener("waitingforkey", this.onWaitingForKey); this.media = null; } this._requestLicenseFailureCount = 0; this.setMediaKeysQueue = []; this.mediaKeySessions = []; this.keyIdToKeySessionPromise = {}; LevelKey.clearKeyUriToKeyIdMap(); const keySessionCount = mediaKeysList.length; _EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map((mediaKeySessionContext) => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : media.setMediaKeys(null).catch((error) => { this.log(`Could not clear media keys: ${error}`); }))).then(() => { if (keySessionCount) { this.log("finished closing key sessions and clearing media keys"); mediaKeysList.length = 0; } }).catch((error) => { this.log(`Could not close sessions and clear media keys: ${error}`); }); } onManifestLoading() { this.keyFormatPromise = null; } onManifestLoaded(event, { sessionKeys }) { if (!sessionKeys || !this.config.emeEnabled) { return; } if (!this.keyFormatPromise) { const keyFormats = sessionKeys.reduce((formats, sessionKey) => { if (formats.indexOf(sessionKey.keyFormat) === -1) { formats.push(sessionKey.keyFormat); } return formats; }, []); this.log(`Selecting key-system from session-keys ${keyFormats.join(", ")}`); this.keyFormatPromise = this.getKeyFormatPromise(keyFormats); } } removeSession(mediaKeySessionContext) { const { mediaKeysSession, licenseXhr } = mediaKeySessionContext; if (mediaKeysSession) { this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`); if (mediaKeySessionContext._onmessage) { mediaKeysSession.removeEventListener("message", mediaKeySessionContext._onmessage); mediaKeySessionContext._onmessage = void 0; } if (mediaKeySessionContext._onkeystatuseschange) { mediaKeysSession.removeEventListener("keystatuseschange", mediaKeySessionContext._onkeystatuseschange); mediaKeySessionContext._onkeystatuseschange = void 0; } if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) { licenseXhr.abort(); } mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = void 0; const index2 = this.mediaKeySessions.indexOf(mediaKeySessionContext); if (index2 > -1) { this.mediaKeySessions.splice(index2, 1); } return mediaKeysSession.remove().catch((error) => { this.log(`Could not remove session: ${error}`); }).then(() => { return mediaKeysSession.close(); }).catch((error) => { this.log(`Could not close session: ${error}`); }); } } }; EMEController.CDMCleanupPromise = void 0; var EMEKeyError = class extends Error { constructor(data, message) { super(message); this.data = void 0; data.error || (data.error = new Error(message)); this.data = data; data.err = data.error; } }; var CmObjectType; (function(CmObjectType2) { CmObjectType2["MANIFEST"] = "m"; CmObjectType2["AUDIO"] = "a"; CmObjectType2["VIDEO"] = "v"; CmObjectType2["MUXED"] = "av"; CmObjectType2["INIT"] = "i"; CmObjectType2["CAPTION"] = "c"; CmObjectType2["TIMED_TEXT"] = "tt"; CmObjectType2["KEY"] = "k"; CmObjectType2["OTHER"] = "o"; })(CmObjectType || (CmObjectType = {})); var CmStreamingFormat; (function(CmStreamingFormat2) { CmStreamingFormat2["DASH"] = "d"; CmStreamingFormat2["HLS"] = "h"; CmStreamingFormat2["SMOOTH"] = "s"; CmStreamingFormat2["OTHER"] = "o"; })(CmStreamingFormat || (CmStreamingFormat = {})); var CmcdHeaderField; (function(CmcdHeaderField2) { CmcdHeaderField2["OBJECT"] = "CMCD-Object"; CmcdHeaderField2["REQUEST"] = "CMCD-Request"; CmcdHeaderField2["SESSION"] = "CMCD-Session"; CmcdHeaderField2["STATUS"] = "CMCD-Status"; })(CmcdHeaderField || (CmcdHeaderField = {})); var CmcdHeaderMap = { [CmcdHeaderField.OBJECT]: ["br", "d", "ot", "tb"], [CmcdHeaderField.REQUEST]: ["bl", "dl", "mtp", "nor", "nrr", "su"], [CmcdHeaderField.SESSION]: ["cid", "pr", "sf", "sid", "st", "v"], [CmcdHeaderField.STATUS]: ["bs", "rtp"] }; var SfItem = class _SfItem { constructor(value, params) { this.value = void 0; this.params = void 0; if (Array.isArray(value)) { value = value.map((v2) => v2 instanceof _SfItem ? v2 : new _SfItem(v2)); } this.value = value; this.params = params; } }; var SfToken = class { constructor(description) { this.description = void 0; this.description = description; } }; var DICT = "Dict"; function format(value) { if (Array.isArray(value)) { return JSON.stringify(value); } if (value instanceof Map) { return "Map{}"; } if (value instanceof Set) { return "Set{}"; } if (typeof value === "object") { return JSON.stringify(value); } return String(value); } function throwError(action, src, type, cause) { return new Error(`failed to ${action} "${format(src)}" as ${type}`, { cause }); } var BARE_ITEM = "Bare Item"; var BOOLEAN = "Boolean"; var BYTES = "Byte Sequence"; var DECIMAL = "Decimal"; var INTEGER = "Integer"; function isInvalidInt(value) { return value < -999999999999999 || 999999999999999 < value; } var STRING_REGEX = /[\x00-\x1f\x7f]+/; var TOKEN = "Token"; var KEY = "Key"; function serializeError(src, type, cause) { return throwError("serialize", src, type, cause); } function serializeBoolean(value) { if (typeof value !== "boolean") { throw serializeError(value, BOOLEAN); } return value ? "?1" : "?0"; } function base64encode(binary) { return btoa(String.fromCharCode(...binary)); } function serializeByteSequence(value) { if (ArrayBuffer.isView(value) === false) { throw serializeError(value, BYTES); } return `:${base64encode(value)}:`; } function serializeInteger(value) { if (isInvalidInt(value)) { throw serializeError(value, INTEGER); } return value.toString(); } function serializeDate(value) { return `@${serializeInteger(value.getTime() / 1e3)}`; } function roundToEven(value, precision) { if (value < 0) { return -roundToEven(-value, precision); } const decimalShift = Math.pow(10, precision); const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON; if (isEquidistant) { const flooredValue = Math.floor(value * decimalShift); return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift; } else { return Math.round(value * decimalShift) / decimalShift; } } function serializeDecimal(value) { const roundedValue = roundToEven(value, 3); if (Math.floor(Math.abs(roundedValue)).toString().length > 12) { throw serializeError(value, DECIMAL); } const stringValue = roundedValue.toString(); return stringValue.includes(".") ? stringValue : `${stringValue}.0`; } var STRING = "String"; function serializeString(value) { if (STRING_REGEX.test(value)) { throw serializeError(value, STRING); } return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`; } function symbolToStr(symbol) { return symbol.description || symbol.toString().slice(7, -1); } function serializeToken(token2) { const value = symbolToStr(token2); if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) { throw serializeError(value, TOKEN); } return value; } function serializeBareItem(value) { switch (typeof value) { case "number": if (!isFiniteNumber(value)) { throw serializeError(value, BARE_ITEM); } if (Number.isInteger(value)) { return serializeInteger(value); } return serializeDecimal(value); case "string": return serializeString(value); case "symbol": return serializeToken(value); case "boolean": return serializeBoolean(value); case "object": if (value instanceof Date) { return serializeDate(value); } if (value instanceof Uint8Array) { return serializeByteSequence(value); } if (value instanceof SfToken) { return serializeToken(value); } default: throw serializeError(value, BARE_ITEM); } } function serializeKey(value) { if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) { throw serializeError(value, KEY); } return value; } function serializeParams(params) { if (params == null) { return ""; } return Object.entries(params).map(([key, value]) => { if (value === true) { return `;${serializeKey(key)}`; } return `;${serializeKey(key)}=${serializeBareItem(value)}`; }).join(""); } function serializeItem(value) { if (value instanceof SfItem) { return `${serializeBareItem(value.value)}${serializeParams(value.params)}`; } else { return serializeBareItem(value); } } function serializeInnerList(value) { return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`; } function serializeDict(dict, options2 = { whitespace: true }) { if (typeof dict !== "object") { throw serializeError(dict, DICT); } const entries = dict instanceof Map ? dict.entries() : Object.entries(dict); const optionalWhiteSpace = options2 != null && options2.whitespace ? " " : ""; return Array.from(entries).map(([key, item]) => { if (item instanceof SfItem === false) { item = new SfItem(item); } let output2 = serializeKey(key); if (item.value === true) { output2 += serializeParams(item.params); } else { output2 += "="; if (Array.isArray(item.value)) { output2 += serializeInnerList(item); } else { output2 += serializeItem(item); } } return output2; }).join(`,${optionalWhiteSpace}`); } function encodeSfDict(value, options2) { return serializeDict(value, options2); } var isTokenField = (key) => key === "ot" || key === "sf" || key === "st"; var isValid = (value) => { if (typeof value === "number") { return isFiniteNumber(value); } return value != null && value !== "" && value !== false; }; function urlToRelativePath(url, base) { const to = new URL(url); const from2 = new URL(base); if (to.origin !== from2.origin) { return url; } const toPath = to.pathname.split("/").slice(1); const fromPath = from2.pathname.split("/").slice(1, -1); while (toPath[0] === fromPath[0]) { toPath.shift(); fromPath.shift(); } while (fromPath.length) { fromPath.shift(); toPath.unshift(".."); } return toPath.join("/"); } function uuid() { try { return crypto.randomUUID(); } catch (error) { try { const url = URL.createObjectURL(new Blob()); const uuid2 = url.toString(); URL.revokeObjectURL(url); return uuid2.slice(uuid2.lastIndexOf("/") + 1); } catch (error2) { let dt5 = (/* @__PURE__ */ new Date()).getTime(); const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c3) => { const r9 = (dt5 + Math.random() * 16) % 16 | 0; dt5 = Math.floor(dt5 / 16); return (c3 == "x" ? r9 : r9 & 3 | 8).toString(16); }); return uuid2; } } } var toRounded = (value) => Math.round(value); var toUrlSafe = (value, options2) => { if (options2 != null && options2.baseUrl) { value = urlToRelativePath(value, options2.baseUrl); } return encodeURIComponent(value); }; var toHundred = (value) => toRounded(value / 100) * 100; var CmcdFormatters = { /** * Bitrate (kbps) rounded integer */ br: toRounded, /** * Duration (milliseconds) rounded integer */ d: toRounded, /** * Buffer Length (milliseconds) rounded nearest 100ms */ bl: toHundred, /** * Deadline (milliseconds) rounded nearest 100ms */ dl: toHundred, /** * Measured Throughput (kbps) rounded nearest 100kbps */ mtp: toHundred, /** * Next Object Request URL encoded */ nor: toUrlSafe, /** * Requested maximum throughput (kbps) rounded nearest 100kbps */ rtp: toHundred, /** * Top Bitrate (kbps) rounded integer */ tb: toRounded }; function processCmcd(obj, options2) { const results = {}; if (obj == null || typeof obj !== "object") { return results; } const keys = Object.keys(obj).sort(); const formatters = _extends2({}, CmcdFormatters, options2 == null ? void 0 : options2.formatters); const filter = options2 == null ? void 0 : options2.filter; keys.forEach((key) => { if (filter != null && filter(key)) { return; } let value = obj[key]; const formatter = formatters[key]; if (formatter) { value = formatter(value, options2); } if (key === "v" && value === 1) { return; } if (key == "pr" && value === 1) { return; } if (!isValid(value)) { return; } if (isTokenField(key) && typeof value === "string") { value = new SfToken(value); } results[key] = value; }); return results; } function encodeCmcd(cmcd, options2 = {}) { if (!cmcd) { return ""; } return encodeSfDict(processCmcd(cmcd, options2), _extends2({ whitespace: false }, options2)); } function toCmcdHeaders(cmcd, options2 = {}) { if (!cmcd) { return {}; } const entries = Object.entries(cmcd); const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options2 == null ? void 0 : options2.customHeaderMap) || {})); const shards = entries.reduce((acc, entry) => { var _headerMap$find, _acc$field; const [key, value] = entry; const field = ((_headerMap$find = headerMap.find((entry2) => entry2[1].includes(key))) == null ? void 0 : _headerMap$find[0]) || CmcdHeaderField.REQUEST; (_acc$field = acc[field]) != null ? _acc$field : acc[field] = {}; acc[field][key] = value; return acc; }, {}); return Object.entries(shards).reduce((acc, [field, value]) => { acc[field] = encodeCmcd(value, options2); return acc; }, {}); } function appendCmcdHeaders(headers, cmcd, options2) { return _extends2(headers, toCmcdHeaders(cmcd, options2)); } var CMCD_PARAM = "CMCD"; function toCmcdQuery(cmcd, options2 = {}) { if (!cmcd) { return ""; } const params = encodeCmcd(cmcd, options2); return `${CMCD_PARAM}=${encodeURIComponent(params)}`; } var REGEX = /CMCD=[^&#]+/; function appendCmcdQuery(url, cmcd, options2) { const query = toCmcdQuery(cmcd, options2); if (!query) { return url; } if (REGEX.test(url)) { return url.replace(REGEX, query); } const separator = url.includes("?") ? "&" : "?"; return `${url}${separator}${query}`; } var CMCDController = class { // eslint-disable-line no-restricted-globals constructor(hls) { this.hls = void 0; this.config = void 0; this.media = void 0; this.sid = void 0; this.cid = void 0; this.useHeaders = false; this.includeKeys = void 0; this.initialized = false; this.starved = false; this.buffering = true; this.audioBuffer = void 0; this.videoBuffer = void 0; this.onWaiting = () => { if (this.initialized) { this.starved = true; } this.buffering = true; }; this.onPlaying = () => { if (!this.initialized) { this.initialized = true; } this.buffering = false; }; this.applyPlaylistData = (context) => { try { this.apply(context, { ot: CmObjectType.MANIFEST, su: !this.initialized }); } catch (error) { logger.warn("Could not generate manifest CMCD data.", error); } }; this.applyFragmentData = (context) => { try { const fragment = context.frag; const level = this.hls.levels[fragment.level]; const ot4 = this.getObjectType(fragment); const data = { d: fragment.duration * 1e3, ot: ot4 }; if (ot4 === CmObjectType.VIDEO || ot4 === CmObjectType.AUDIO || ot4 == CmObjectType.MUXED) { data.br = level.bitrate / 1e3; data.tb = this.getTopBandwidth(ot4) / 1e3; data.bl = this.getBufferLength(ot4); } this.apply(context, data); } catch (error) { logger.warn("Could not generate segment CMCD data.", error); } }; this.hls = hls; const config = this.config = hls.config; const { cmcd } = config; if (cmcd != null) { config.pLoader = this.createPlaylistLoader(); config.fLoader = this.createFragmentLoader(); this.sid = cmcd.sessionId || uuid(); this.cid = cmcd.contentId; this.useHeaders = cmcd.useHeaders === true; this.includeKeys = cmcd.includeKeys; this.registerListeners(); } } registerListeners() { const hls = this.hls; hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this); hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this); } unregisterListeners() { const hls = this.hls; hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this); hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this); } destroy() { this.unregisterListeners(); this.onMediaDetached(); this.hls = this.config = this.audioBuffer = this.videoBuffer = null; this.onWaiting = this.onPlaying = null; } onMediaAttached(event, data) { this.media = data.media; this.media.addEventListener("waiting", this.onWaiting); this.media.addEventListener("playing", this.onPlaying); } onMediaDetached() { if (!this.media) { return; } this.media.removeEventListener("waiting", this.onWaiting); this.media.removeEventListener("playing", this.onPlaying); this.media = null; } onBufferCreated(event, data) { var _data$tracks$audio, _data$tracks$video; this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer; this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer; } /** * Create baseline CMCD data */ createData() { var _this$media; return { v: 1, sf: CmStreamingFormat.HLS, sid: this.sid, cid: this.cid, pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate, mtp: this.hls.bandwidthEstimate / 1e3 }; } /** * Apply CMCD data to a request. */ apply(context, data = {}) { _extends2(data, this.createData()); const isVideo = data.ot === CmObjectType.INIT || data.ot === CmObjectType.VIDEO || data.ot === CmObjectType.MUXED; if (this.starved && isVideo) { data.bs = true; data.su = true; this.starved = false; } if (data.su == null) { data.su = this.buffering; } const { includeKeys } = this; if (includeKeys) { data = Object.keys(data).reduce((acc, key) => { includeKeys.includes(key) && (acc[key] = data[key]); return acc; }, {}); } if (this.useHeaders) { if (!context.headers) { context.headers = {}; } appendCmcdHeaders(context.headers, data); } else { context.url = appendCmcdQuery(context.url, data); } } /** * The CMCD object type. */ getObjectType(fragment) { const { type } = fragment; if (type === "subtitle") { return CmObjectType.TIMED_TEXT; } if (fragment.sn === "initSegment") { return CmObjectType.INIT; } if (type === "audio") { return CmObjectType.AUDIO; } if (type === "main") { if (!this.hls.audioTracks.length) { return CmObjectType.MUXED; } return CmObjectType.VIDEO; } return void 0; } /** * Get the highest bitrate. */ getTopBandwidth(type) { let bitrate = 0; let levels; const hls = this.hls; if (type === CmObjectType.AUDIO) { levels = hls.audioTracks; } else { const max = hls.maxAutoLevel; const len = max > -1 ? max + 1 : hls.levels.length; levels = hls.levels.slice(0, len); } for (const level of levels) { if (level.bitrate > bitrate) { bitrate = level.bitrate; } } return bitrate > 0 ? bitrate : NaN; } /** * Get the buffer length for a media type in milliseconds */ getBufferLength(type) { const media = this.hls.media; const buffer = type === CmObjectType.AUDIO ? this.audioBuffer : this.videoBuffer; if (!buffer || !media) { return NaN; } const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole); return info.len * 1e3; } /** * Create a playlist loader */ createPlaylistLoader() { const { pLoader } = this.config; const apply = this.applyPlaylistData; const Ctor = pLoader || this.config.loader; return class CmcdPlaylistLoader { constructor(config) { this.loader = void 0; this.loader = new Ctor(config); } get stats() { return this.loader.stats; } get context() { return this.loader.context; } destroy() { this.loader.destroy(); } abort() { this.loader.abort(); } load(context, config, callbacks) { apply(context); this.loader.load(context, config, callbacks); } }; } /** * Create a playlist loader */ createFragmentLoader() { const { fLoader } = this.config; const apply = this.applyFragmentData; const Ctor = fLoader || this.config.loader; return class CmcdFragmentLoader { constructor(config) { this.loader = void 0; this.loader = new Ctor(config); } get stats() { return this.loader.stats; } get context() { return this.loader.context; } destroy() { this.loader.destroy(); } abort() { this.loader.abort(); } load(context, config, callbacks) { apply(context); this.loader.load(context, config, callbacks); } }; } }; var PATHWAY_PENALTY_DURATION_MS = 3e5; var ContentSteeringController = class { constructor(hls) { this.hls = void 0; this.log = void 0; this.loader = null; this.uri = null; this.pathwayId = "."; this.pathwayPriority = null; this.timeToLoad = 300; this.reloadTimer = -1; this.updated = 0; this.started = false; this.enabled = true; this.levels = null; this.audioTracks = null; this.subtitleTracks = null; this.penalizedPathways = {}; this.hls = hls; this.log = logger.log.bind(logger, `[content-steering]:`); this.registerListeners(); } registerListeners() { const hls = this.hls; hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this); hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.on(Events.ERROR, this.onError, this); } unregisterListeners() { const hls = this.hls; if (!hls) { return; } hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this); hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.off(Events.ERROR, this.onError, this); } startLoad() { this.started = true; this.clearTimeout(); if (this.enabled && this.uri) { if (this.updated) { const ttl = this.timeToLoad * 1e3 - (performance.now() - this.updated); if (ttl > 0) { this.scheduleRefresh(this.uri, ttl); return; } } this.loadSteeringManifest(this.uri); } } stopLoad() { this.started = false; if (this.loader) { this.loader.destroy(); this.loader = null; } this.clearTimeout(); } clearTimeout() { if (this.reloadTimer !== -1) { self.clearTimeout(this.reloadTimer); this.reloadTimer = -1; } } destroy() { this.unregisterListeners(); this.stopLoad(); this.hls = null; this.levels = this.audioTracks = this.subtitleTracks = null; } removeLevel(levelToRemove) { const levels = this.levels; if (levels) { this.levels = levels.filter((level) => level !== levelToRemove); } } onManifestLoading() { this.stopLoad(); this.enabled = true; this.timeToLoad = 300; this.updated = 0; this.uri = null; this.pathwayId = "."; this.levels = this.audioTracks = this.subtitleTracks = null; } onManifestLoaded(event, data) { const { contentSteering } = data; if (contentSteering === null) { return; } this.pathwayId = contentSteering.pathwayId; this.uri = contentSteering.uri; if (this.started) { this.startLoad(); } } onManifestParsed(event, data) { this.audioTracks = data.audioTracks; this.subtitleTracks = data.subtitleTracks; } onError(event, data) { const { errorAction } = data; if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) { const levels = this.levels; let pathwayPriority = this.pathwayPriority; let errorPathway = this.pathwayId; if (data.context) { const { groupId, pathwayId, type } = data.context; if (groupId && levels) { errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway); } else if (pathwayId) { errorPathway = pathwayId; } } if (!(errorPathway in this.penalizedPathways)) { this.penalizedPathways[errorPathway] = performance.now(); } if (!pathwayPriority && levels) { pathwayPriority = levels.reduce((pathways, level) => { if (pathways.indexOf(level.pathwayId) === -1) { pathways.push(level.pathwayId); } return pathways; }, []); } if (pathwayPriority && pathwayPriority.length > 1) { this.updatePathwayPriority(pathwayPriority); errorAction.resolved = this.pathwayId !== errorPathway; } if (!errorAction.resolved) { logger.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${JSON.stringify(pathwayPriority)} penalized: ${JSON.stringify(this.penalizedPathways)}`); } } } filterParsedLevels(levels) { this.levels = levels; let pathwayLevels = this.getLevelsForPathway(this.pathwayId); if (pathwayLevels.length === 0) { const pathwayId = levels[0].pathwayId; this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`); pathwayLevels = this.getLevelsForPathway(pathwayId); this.pathwayId = pathwayId; } if (pathwayLevels.length !== levels.length) { this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`); } return pathwayLevels; } getLevelsForPathway(pathwayId) { if (this.levels === null) { return []; } return this.levels.filter((level) => pathwayId === level.pathwayId); } updatePathwayPriority(pathwayPriority) { this.pathwayPriority = pathwayPriority; let levels; const penalizedPathways = this.penalizedPathways; const now2 = performance.now(); Object.keys(penalizedPathways).forEach((pathwayId) => { if (now2 - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) { delete penalizedPathways[pathwayId]; } }); for (let i3 = 0; i3 < pathwayPriority.length; i3++) { const pathwayId = pathwayPriority[i3]; if (pathwayId in penalizedPathways) { continue; } if (pathwayId === this.pathwayId) { return; } const selectedIndex = this.hls.nextLoadLevel; const selectedLevel = this.hls.levels[selectedIndex]; levels = this.getLevelsForPathway(pathwayId); if (levels.length > 0) { this.log(`Setting Pathway to "${pathwayId}"`); this.pathwayId = pathwayId; reassignFragmentLevelIndexes(levels); this.hls.trigger(Events.LEVELS_UPDATED, { levels }); const levelAfterChange = this.hls.levels[selectedIndex]; if (selectedLevel && levelAfterChange && this.levels) { if (levelAfterChange.attrs["STABLE-VARIANT-ID"] !== selectedLevel.attrs["STABLE-VARIANT-ID"] && levelAfterChange.bitrate !== selectedLevel.bitrate) { this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`); } this.hls.nextLoadLevel = selectedIndex; } break; } } } getPathwayForGroupId(groupId, type, defaultPathway) { const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []); for (let i3 = 0; i3 < levels.length; i3++) { if (type === PlaylistContextType.AUDIO_TRACK && levels[i3].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i3].hasSubtitleGroup(groupId)) { return levels[i3].pathwayId; } } return defaultPathway; } clonePathways(pathwayClones) { const levels = this.levels; if (!levels) { return; } const audioGroupCloneMap = {}; const subtitleGroupCloneMap = {}; pathwayClones.forEach((pathwayClone) => { const { ID: cloneId, "BASE-ID": baseId, "URI-REPLACEMENT": uriReplacement } = pathwayClone; if (levels.some((level) => level.pathwayId === cloneId)) { return; } const clonedVariants = this.getLevelsForPathway(baseId).map((baseLevel) => { const attributes = new AttrList(baseLevel.attrs); attributes["PATHWAY-ID"] = cloneId; const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`; const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`; if (clonedAudioGroupId) { audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId; attributes.AUDIO = clonedAudioGroupId; } if (clonedSubtitleGroupId) { subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId; attributes.SUBTITLES = clonedSubtitleGroupId; } const url = performUriReplacement(baseLevel.uri, attributes["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", uriReplacement); const clonedLevel = new Level({ attrs: attributes, audioCodec: baseLevel.audioCodec, bitrate: baseLevel.bitrate, height: baseLevel.height, name: baseLevel.name, url, videoCodec: baseLevel.videoCodec, width: baseLevel.width }); if (baseLevel.audioGroups) { for (let i3 = 1; i3 < baseLevel.audioGroups.length; i3++) { clonedLevel.addGroupId("audio", `${baseLevel.audioGroups[i3]}_clone_${cloneId}`); } } if (baseLevel.subtitleGroups) { for (let i3 = 1; i3 < baseLevel.subtitleGroups.length; i3++) { clonedLevel.addGroupId("text", `${baseLevel.subtitleGroups[i3]}_clone_${cloneId}`); } } return clonedLevel; }); levels.push(...clonedVariants); cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId); cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId); }); } loadSteeringManifest(uri) { const config = this.hls.config; const Loader2 = config.loader; if (this.loader) { this.loader.destroy(); } this.loader = new Loader2(config); let url; try { url = new self.URL(uri); } catch (error) { this.enabled = false; this.log(`Failed to parse Steering Manifest URI: ${uri}`); return; } if (url.protocol !== "data:") { const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0; url.searchParams.set("_HLS_pathway", this.pathwayId); url.searchParams.set("_HLS_throughput", "" + throughput); } const context = { responseType: "json", url: url.href }; const loadPolicy = config.steeringManifestLoadPolicy.default; const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {}; const loaderConfig = { loadPolicy, timeout: loadPolicy.maxLoadTimeMs, maxRetry: legacyRetryCompatibility.maxNumRetry || 0, retryDelay: legacyRetryCompatibility.retryDelayMs || 0, maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0 }; const callbacks = { onSuccess: (response, stats, context2, networkDetails) => { this.log(`Loaded steering manifest: "${url}"`); const steeringData = response.data; if (steeringData.VERSION !== 1) { this.log(`Steering VERSION ${steeringData.VERSION} not supported!`); return; } this.updated = performance.now(); this.timeToLoad = steeringData.TTL; const { "RELOAD-URI": reloadUri, "PATHWAY-CLONES": pathwayClones, "PATHWAY-PRIORITY": pathwayPriority } = steeringData; if (reloadUri) { try { this.uri = new self.URL(reloadUri, url).href; } catch (error) { this.enabled = false; this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`); return; } } this.scheduleRefresh(this.uri || context2.url); if (pathwayClones) { this.clonePathways(pathwayClones); } const loadedSteeringData = { steeringManifest: steeringData, url: url.toString() }; this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData); if (pathwayPriority) { this.updatePathwayPriority(pathwayPriority); } }, onError: (error, context2, networkDetails, stats) => { this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context2.url})`); this.stopLoad(); if (error.code === 410) { this.enabled = false; this.log(`Steering manifest ${context2.url} no longer available`); return; } let ttl = this.timeToLoad * 1e3; if (error.code === 429) { const loader = this.loader; if (typeof (loader == null ? void 0 : loader.getResponseHeader) === "function") { const retryAfter = loader.getResponseHeader("Retry-After"); if (retryAfter) { ttl = parseFloat(retryAfter) * 1e3; } } this.log(`Steering manifest ${context2.url} rate limited`); return; } this.scheduleRefresh(this.uri || context2.url, ttl); }, onTimeout: (stats, context2, networkDetails) => { this.log(`Timeout loading steering manifest (${context2.url})`); this.scheduleRefresh(this.uri || context2.url); } }; this.log(`Requesting steering manifest: ${url}`); this.loader.load(context, loaderConfig, callbacks); } scheduleRefresh(uri, ttlMs = this.timeToLoad * 1e3) { this.clearTimeout(); this.reloadTimer = self.setTimeout(() => { var _this$hls; const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media; if (media && !media.ended) { this.loadSteeringManifest(uri); return; } this.scheduleRefresh(uri, this.timeToLoad * 1e3); }, ttlMs); } }; function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) { if (!tracks) { return; } Object.keys(groupCloneMap).forEach((audioGroupId) => { const clonedTracks = tracks.filter((track) => track.groupId === audioGroupId).map((track) => { const clonedTrack = _extends2({}, track); clonedTrack.details = void 0; clonedTrack.attrs = new AttrList(clonedTrack.attrs); clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", uriReplacement); clonedTrack.groupId = clonedTrack.attrs["GROUP-ID"] = groupCloneMap[audioGroupId]; clonedTrack.attrs["PATHWAY-ID"] = cloneId; return clonedTrack; }); tracks.push(...clonedTracks); }); } function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) { const { HOST: host, PARAMS: params, [perOptionKey]: perOptionUris } = uriReplacement; let perVariantUri; if (stableId) { perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId]; if (perVariantUri) { uri = perVariantUri; } } const url = new self.URL(uri); if (host && !perVariantUri) { url.host = host; } if (params) { Object.keys(params).sort().forEach((key) => { if (key) { url.searchParams.set(key, params[key]); } }); } return url.href; } var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im; var XhrLoader = class { constructor(config) { this.xhrSetup = void 0; this.requestTimeout = void 0; this.retryTimeout = void 0; this.retryDelay = void 0; this.config = null; this.callbacks = null; this.context = null; this.loader = null; this.stats = void 0; this.xhrSetup = config ? config.xhrSetup || null : null; this.stats = new LoadStats(); this.retryDelay = 0; } destroy() { this.callbacks = null; this.abortInternal(); this.loader = null; this.config = null; this.context = null; this.xhrSetup = null; } abortInternal() { const loader = this.loader; self.clearTimeout(this.requestTimeout); self.clearTimeout(this.retryTimeout); if (loader) { loader.onreadystatechange = null; loader.onprogress = null; if (loader.readyState !== 4) { this.stats.aborted = true; loader.abort(); } } } abort() { var _this$callbacks; this.abortInternal(); if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) { this.callbacks.onAbort(this.stats, this.context, this.loader); } } load(context, config, callbacks) { if (this.stats.loading.start) { throw new Error("Loader can only be used once."); } this.stats.loading.start = self.performance.now(); this.context = context; this.config = config; this.callbacks = callbacks; this.loadInternal(); } loadInternal() { const { config, context } = this; if (!config || !context) { return; } const xhr = this.loader = new self.XMLHttpRequest(); const stats = this.stats; stats.loading.first = 0; stats.loaded = 0; stats.aborted = false; const xhrSetup = this.xhrSetup; if (xhrSetup) { Promise.resolve().then(() => { if (this.loader !== xhr || this.stats.aborted) return; return xhrSetup(xhr, context.url); }).catch((error) => { if (this.loader !== xhr || this.stats.aborted) return; xhr.open("GET", context.url, true); return xhrSetup(xhr, context.url); }).then(() => { if (this.loader !== xhr || this.stats.aborted) return; this.openAndSendXhr(xhr, context, config); }).catch((error) => { this.callbacks.onError({ code: xhr.status, text: error.message }, context, xhr, stats); return; }); } else { this.openAndSendXhr(xhr, context, config); } } openAndSendXhr(xhr, context, config) { if (!xhr.readyState) { xhr.open("GET", context.url, true); } const headers = context.headers; const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy; if (headers) { for (const header in headers) { xhr.setRequestHeader(header, headers[header]); } } if (context.rangeEnd) { xhr.setRequestHeader("Range", "bytes=" + context.rangeStart + "-" + (context.rangeEnd - 1)); } xhr.onreadystatechange = this.readystatechange.bind(this); xhr.onprogress = this.loadprogress.bind(this); xhr.responseType = context.responseType; self.clearTimeout(this.requestTimeout); config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs; this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout); xhr.send(); } readystatechange() { const { context, loader: xhr, stats } = this; if (!context || !xhr) { return; } const readyState = xhr.readyState; const config = this.config; if (stats.aborted) { return; } if (readyState >= 2) { if (stats.loading.first === 0) { stats.loading.first = Math.max(self.performance.now(), stats.loading.start); if (config.timeout !== config.loadPolicy.maxLoadTimeMs) { self.clearTimeout(this.requestTimeout); config.timeout = config.loadPolicy.maxLoadTimeMs; this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start)); } } if (readyState === 4) { self.clearTimeout(this.requestTimeout); xhr.onreadystatechange = null; xhr.onprogress = null; const status2 = xhr.status; const useResponseText = xhr.responseType === "text" ? xhr.responseText : null; if (status2 >= 200 && status2 < 300) { const data = useResponseText != null ? useResponseText : xhr.response; if (data != null) { stats.loading.end = Math.max(self.performance.now(), stats.loading.first); const len = xhr.responseType === "arraybuffer" ? data.byteLength : data.length; stats.loaded = stats.total = len; stats.bwEstimate = stats.total * 8e3 / (stats.loading.end - stats.loading.first); if (!this.callbacks) { return; } const onProgress = this.callbacks.onProgress; if (onProgress) { onProgress(stats, context, data, xhr); } if (!this.callbacks) { return; } const _response = { url: xhr.responseURL, data, code: status2 }; this.callbacks.onSuccess(_response, stats, context, xhr); return; } } const retryConfig = config.loadPolicy.errorRetry; const retryCount = stats.retry; const response = { url: context.url, data: void 0, code: status2 }; if (shouldRetry(retryConfig, retryCount, false, response)) { this.retry(retryConfig); } else { logger.error(`${status2} while loading ${context.url}`); this.callbacks.onError({ code: status2, text: xhr.statusText }, context, xhr, stats); } } } } loadtimeout() { if (!this.config) return; const retryConfig = this.config.loadPolicy.timeoutRetry; const retryCount = this.stats.retry; if (shouldRetry(retryConfig, retryCount, true)) { this.retry(retryConfig); } else { var _this$context; logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`); const callbacks = this.callbacks; if (callbacks) { this.abortInternal(); callbacks.onTimeout(this.stats, this.context, this.loader); } } } retry(retryConfig) { const { context, stats } = this; this.retryDelay = getRetryDelay(retryConfig, stats.retry); stats.retry++; logger.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`); this.abortInternal(); this.loader = null; self.clearTimeout(this.retryTimeout); this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); } loadprogress(event) { const stats = this.stats; stats.loaded = event.loaded; if (event.lengthComputable) { stats.total = event.total; } } getCacheAge() { let result = null; if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) { const ageHeader = this.loader.getResponseHeader("age"); result = ageHeader ? parseFloat(ageHeader) : null; } return result; } getResponseHeader(name) { if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders())) { return this.loader.getResponseHeader(name); } return null; } }; function fetchSupported() { if ( // @ts-ignore self.fetch && self.AbortController && self.ReadableStream && self.Request ) { try { new self.ReadableStream({}); return true; } catch (e) { } } return false; } var BYTERANGE = /(\d+)-(\d+)\/(\d+)/; var FetchLoader = class { constructor(config) { this.fetchSetup = void 0; this.requestTimeout = void 0; this.request = null; this.response = null; this.controller = void 0; this.context = null; this.config = null; this.callbacks = null; this.stats = void 0; this.loader = null; this.fetchSetup = config.fetchSetup || getRequest; this.controller = new self.AbortController(); this.stats = new LoadStats(); } destroy() { this.loader = this.callbacks = this.context = this.config = this.request = null; this.abortInternal(); this.response = null; this.fetchSetup = this.controller = this.stats = null; } abortInternal() { if (this.controller && !this.stats.loading.end) { this.stats.aborted = true; this.controller.abort(); } } abort() { var _this$callbacks; this.abortInternal(); if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) { this.callbacks.onAbort(this.stats, this.context, this.response); } } load(context, config, callbacks) { const stats = this.stats; if (stats.loading.start) { throw new Error("Loader can only be used once."); } stats.loading.start = self.performance.now(); const initParams = getRequestParameters(context, this.controller.signal); const onProgress = callbacks.onProgress; const isArrayBuffer = context.responseType === "arraybuffer"; const LENGTH = isArrayBuffer ? "byteLength" : "length"; const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy; this.context = context; this.config = config; this.callbacks = callbacks; this.request = this.fetchSetup(context, initParams); self.clearTimeout(this.requestTimeout); config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs; this.requestTimeout = self.setTimeout(() => { this.abortInternal(); callbacks.onTimeout(stats, context, this.response); }, config.timeout); self.fetch(this.request).then((response) => { this.response = this.loader = response; const first = Math.max(self.performance.now(), stats.loading.start); self.clearTimeout(this.requestTimeout); config.timeout = maxLoadTimeMs; this.requestTimeout = self.setTimeout(() => { this.abortInternal(); callbacks.onTimeout(stats, context, this.response); }, maxLoadTimeMs - (first - stats.loading.start)); if (!response.ok) { const { status: status2, statusText } = response; throw new FetchError(statusText || "fetch, bad network response", status2, response); } stats.loading.first = first; stats.total = getContentLength(response.headers) || stats.total; if (onProgress && isFiniteNumber(config.highWaterMark)) { return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress); } if (isArrayBuffer) { return response.arrayBuffer(); } if (context.responseType === "json") { return response.json(); } return response.text(); }).then((responseData) => { const response = this.response; if (!response) { throw new Error("loader destroyed"); } self.clearTimeout(this.requestTimeout); stats.loading.end = Math.max(self.performance.now(), stats.loading.first); const total = responseData[LENGTH]; if (total) { stats.loaded = stats.total = total; } const loaderResponse = { url: response.url, data: responseData, code: response.status }; if (onProgress && !isFiniteNumber(config.highWaterMark)) { onProgress(stats, context, responseData, response); } callbacks.onSuccess(loaderResponse, stats, context, response); }).catch((error) => { self.clearTimeout(this.requestTimeout); if (stats.aborted) { return; } const code = !error ? 0 : error.code || 0; const text = !error ? null : error.message; callbacks.onError({ code, text }, context, error ? error.details : null, stats); }); } getCacheAge() { let result = null; if (this.response) { const ageHeader = this.response.headers.get("age"); result = ageHeader ? parseFloat(ageHeader) : null; } return result; } getResponseHeader(name) { return this.response ? this.response.headers.get(name) : null; } loadProgressively(response, stats, context, highWaterMark = 0, onProgress) { const chunkCache = new ChunkCache(); const reader = response.body.getReader(); const pump = () => { return reader.read().then((data) => { if (data.done) { if (chunkCache.dataLength) { onProgress(stats, context, chunkCache.flush(), response); } return Promise.resolve(new ArrayBuffer(0)); } const chunk = data.value; const len = chunk.length; stats.loaded += len; if (len < highWaterMark || chunkCache.dataLength) { chunkCache.push(chunk); if (chunkCache.dataLength >= highWaterMark) { onProgress(stats, context, chunkCache.flush(), response); } } else { onProgress(stats, context, chunk, response); } return pump(); }).catch(() => { return Promise.reject(); }); }; return pump(); } }; function getRequestParameters(context, signal) { const initParams = { method: "GET", mode: "cors", credentials: "same-origin", signal, headers: new self.Headers(_extends2({}, context.headers)) }; if (context.rangeEnd) { initParams.headers.set("Range", "bytes=" + context.rangeStart + "-" + String(context.rangeEnd - 1)); } return initParams; } function getByteRangeLength(byteRangeHeader) { const result = BYTERANGE.exec(byteRangeHeader); if (result) { return parseInt(result[2]) - parseInt(result[1]) + 1; } } function getContentLength(headers) { const contentRange = headers.get("Content-Range"); if (contentRange) { const byteRangeLength = getByteRangeLength(contentRange); if (isFiniteNumber(byteRangeLength)) { return byteRangeLength; } } const contentLength = headers.get("Content-Length"); if (contentLength) { return parseInt(contentLength); } } function getRequest(context, initParams) { return new self.Request(context.url, initParams); } var FetchError = class extends Error { constructor(message, code, details) { super(message); this.code = void 0; this.details = void 0; this.code = code; this.details = details; } }; var WHITESPACE_CHAR = /\s/; var Cues = { newCue(track, startTime, endTime, captionScreen) { const result = []; let row; let cue; let indenting; let indent; let text; const Cue = self.VTTCue || self.TextTrackCue; for (let r9 = 0; r9 < captionScreen.rows.length; r9++) { row = captionScreen.rows[r9]; indenting = true; indent = 0; text = ""; if (!row.isEmpty()) { var _track$cues; for (let c3 = 0; c3 < row.chars.length; c3++) { if (WHITESPACE_CHAR.test(row.chars[c3].uchar) && indenting) { indent++; } else { text += row.chars[c3].uchar; indenting = false; } } row.cueStartTime = startTime; if (startTime === endTime) { endTime += 1e-4; } if (indent >= 16) { indent--; } else { indent++; } const cueText = fixLineBreaks(text.trim()); const id = generateCueId(startTime, endTime, cueText); if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) { cue = new Cue(startTime, endTime, cueText); cue.id = id; cue.line = r9 + 1; cue.align = "left"; cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10); result.push(cue); } } } if (track && result.length) { result.sort((cueA, cueB) => { if (cueA.line === "auto" || cueB.line === "auto") { return 0; } if (cueA.line > 8 && cueB.line > 8) { return cueB.line - cueA.line; } return cueA.line - cueB.line; }); result.forEach((cue2) => addCueToTrack(track, cue2)); } return result; } }; var defaultLoadPolicy = { maxTimeToFirstByteMs: 8e3, maxLoadTimeMs: 2e4, timeoutRetry: null, errorRetry: null }; var hlsDefaultConfig = _objectSpread23(_objectSpread23({ autoStartLoad: true, // used by stream-controller startPosition: -1, // used by stream-controller defaultAudioCodec: void 0, // used by stream-controller debug: false, // used by logger capLevelOnFPSDrop: false, // used by fps-controller capLevelToPlayerSize: false, // used by cap-level-controller ignoreDevicePixelRatio: false, // used by cap-level-controller preferManagedMediaSource: true, initialLiveManifestSize: 1, // used by stream-controller maxBufferLength: 30, // used by stream-controller backBufferLength: Infinity, // used by buffer-controller frontBufferFlushThreshold: Infinity, maxBufferSize: 60 * 1e3 * 1e3, // used by stream-controller maxBufferHole: 0.1, // used by stream-controller highBufferWatchdogPeriod: 2, // used by stream-controller nudgeOffset: 0.1, // used by stream-controller nudgeMaxRetry: 3, // used by stream-controller maxFragLookUpTolerance: 0.25, // used by stream-controller liveSyncDurationCount: 3, // used by latency-controller liveMaxLatencyDurationCount: Infinity, // used by latency-controller liveSyncDuration: void 0, // used by latency-controller liveMaxLatencyDuration: void 0, // used by latency-controller maxLiveSyncPlaybackRate: 1, // used by latency-controller liveDurationInfinity: false, // used by buffer-controller /** * @deprecated use backBufferLength */ liveBackBufferLength: null, // used by buffer-controller maxMaxBufferLength: 600, // used by stream-controller enableWorker: true, // used by transmuxer workerPath: null, // used by transmuxer enableSoftwareAES: true, // used by decrypter startLevel: void 0, // used by level-controller startFragPrefetch: false, // used by stream-controller fpsDroppedMonitoringPeriod: 5e3, // used by fps-controller fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller appendErrorMaxRetry: 3, // used by buffer-controller loader: XhrLoader, // loader: FetchLoader, fLoader: void 0, // used by fragment-loader pLoader: void 0, // used by playlist-loader xhrSetup: void 0, // used by xhr-loader licenseXhrSetup: void 0, // used by eme-controller licenseResponseCallback: void 0, // used by eme-controller abrController: AbrController, bufferController: BufferController, capLevelController: CapLevelController, errorController: ErrorController, fpsController: FPSController, stretchShortVideoTrack: false, // used by mp4-remuxer maxAudioFramesDrift: 1, // used by mp4-remuxer forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer abrEwmaFastLive: 3, // used by abr-controller abrEwmaSlowLive: 9, // used by abr-controller abrEwmaFastVoD: 3, // used by abr-controller abrEwmaSlowVoD: 9, // used by abr-controller abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller abrEwmaDefaultEstimateMax: 5e6, // 5 mbps abrBandWidthFactor: 0.95, // used by abr-controller abrBandWidthUpFactor: 0.7, // used by abr-controller abrMaxWithRealBitrate: false, // used by abr-controller maxStarvationDelay: 4, // used by abr-controller maxLoadingDelay: 4, // used by abr-controller minAutoBitrate: 0, // used by hls emeEnabled: false, // used by eme-controller widevineLicenseUrl: void 0, // used by eme-controller drmSystems: {}, // used by eme-controller drmSystemOptions: {}, // used by eme-controller requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, // used by eme-controller testBandwidth: true, progressive: false, lowLatencyMode: true, cmcd: void 0, enableDateRangeMetadataCues: true, enableEmsgMetadataCues: true, enableID3MetadataCues: true, useMediaCapabilities: true, certLoadPolicy: { default: defaultLoadPolicy }, keyLoadPolicy: { default: { maxTimeToFirstByteMs: 8e3, maxLoadTimeMs: 2e4, timeoutRetry: { maxNumRetry: 1, retryDelayMs: 1e3, maxRetryDelayMs: 2e4, backoff: "linear" }, errorRetry: { maxNumRetry: 8, retryDelayMs: 1e3, maxRetryDelayMs: 2e4, backoff: "linear" } } }, manifestLoadPolicy: { default: { maxTimeToFirstByteMs: Infinity, maxLoadTimeMs: 2e4, timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0 }, errorRetry: { maxNumRetry: 1, retryDelayMs: 1e3, maxRetryDelayMs: 8e3 } } }, playlistLoadPolicy: { default: { maxTimeToFirstByteMs: 1e4, maxLoadTimeMs: 2e4, timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0 }, errorRetry: { maxNumRetry: 2, retryDelayMs: 1e3, maxRetryDelayMs: 8e3 } } }, fragLoadPolicy: { default: { maxTimeToFirstByteMs: 1e4, maxLoadTimeMs: 12e4, timeoutRetry: { maxNumRetry: 4, retryDelayMs: 0, maxRetryDelayMs: 0 }, errorRetry: { maxNumRetry: 6, retryDelayMs: 1e3, maxRetryDelayMs: 8e3 } } }, steeringManifestLoadPolicy: { default: { maxTimeToFirstByteMs: 1e4, maxLoadTimeMs: 2e4, timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0 }, errorRetry: { maxNumRetry: 1, retryDelayMs: 1e3, maxRetryDelayMs: 8e3 } } }, // These default settings are deprecated in favor of the above policies // and are maintained for backwards compatibility manifestLoadingTimeOut: 1e4, manifestLoadingMaxRetry: 1, manifestLoadingRetryDelay: 1e3, manifestLoadingMaxRetryTimeout: 64e3, levelLoadingTimeOut: 1e4, levelLoadingMaxRetry: 4, levelLoadingRetryDelay: 1e3, levelLoadingMaxRetryTimeout: 64e3, fragLoadingTimeOut: 2e4, fragLoadingMaxRetry: 6, fragLoadingRetryDelay: 1e3, fragLoadingMaxRetryTimeout: 64e3 }, timelineConfig()), {}, { subtitleStreamController: SubtitleStreamController, subtitleTrackController: SubtitleTrackController, timelineController: TimelineController, audioStreamController: AudioStreamController, audioTrackController: AudioTrackController, emeController: EMEController, cmcdController: CMCDController, contentSteeringController: ContentSteeringController }); function timelineConfig() { return { cueHandler: Cues, // used by timeline-controller enableWebVTT: true, // used by timeline-controller enableIMSC1: true, // used by timeline-controller enableCEA708Captions: true, // used by timeline-controller captionsTextTrack1Label: "English", // used by timeline-controller captionsTextTrack1LanguageCode: "en", // used by timeline-controller captionsTextTrack2Label: "Spanish", // used by timeline-controller captionsTextTrack2LanguageCode: "es", // used by timeline-controller captionsTextTrack3Label: "Unknown CC", // used by timeline-controller captionsTextTrack3LanguageCode: "", // used by timeline-controller captionsTextTrack4Label: "Unknown CC", // used by timeline-controller captionsTextTrack4LanguageCode: "", // used by timeline-controller renderTextTracksNatively: true }; } function mergeConfig(defaultConfig, userConfig) { if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) { throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration"); } if (userConfig.liveMaxLatencyDurationCount !== void 0 && (userConfig.liveSyncDurationCount === void 0 || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"'); } if (userConfig.liveMaxLatencyDuration !== void 0 && (userConfig.liveSyncDuration === void 0 || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) { throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"'); } const defaultsCopy = deepCpy(defaultConfig); const deprecatedSettingTypes = ["manifest", "level", "frag"]; const deprecatedSettings = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"]; deprecatedSettingTypes.forEach((type) => { const policyName = `${type === "level" ? "playlist" : type}LoadPolicy`; const policyNotSet = userConfig[policyName] === void 0; const report = []; deprecatedSettings.forEach((setting) => { const deprecatedSetting = `${type}Loading${setting}`; const value = userConfig[deprecatedSetting]; if (value !== void 0 && policyNotSet) { report.push(deprecatedSetting); const settings = defaultsCopy[policyName].default; userConfig[policyName] = { default: settings }; switch (setting) { case "TimeOut": settings.maxLoadTimeMs = value; settings.maxTimeToFirstByteMs = value; break; case "MaxRetry": settings.errorRetry.maxNumRetry = value; settings.timeoutRetry.maxNumRetry = value; break; case "RetryDelay": settings.errorRetry.retryDelayMs = value; settings.timeoutRetry.retryDelayMs = value; break; case "MaxRetryTimeout": settings.errorRetry.maxRetryDelayMs = value; settings.timeoutRetry.maxRetryDelayMs = value; break; } } }); if (report.length) { logger.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${JSON.stringify(userConfig[policyName])}`); } }); return _objectSpread23(_objectSpread23({}, defaultsCopy), userConfig); } function deepCpy(obj) { if (obj && typeof obj === "object") { if (Array.isArray(obj)) { return obj.map(deepCpy); } return Object.keys(obj).reduce((result, key) => { result[key] = deepCpy(obj[key]); return result; }, {}); } return obj; } function enableStreamingMode(config) { const currentLoader = config.loader; if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) { logger.log("[config]: Custom loader detected, cannot enable progressive streaming"); config.progressive = false; } else { const canStreamProgressively = fetchSupported(); if (canStreamProgressively) { config.loader = FetchLoader; config.progressive = true; config.enableSoftwareAES = true; logger.log("[config]: Progressive streaming enabled, using FetchLoader"); } } } var chromeOrFirefox; var LevelController = class extends BasePlaylistController { constructor(hls, contentSteeringController) { super(hls, "[level-controller]"); this._levels = []; this._firstLevel = -1; this._maxAutoLevel = -1; this._startLevel = void 0; this.currentLevel = null; this.currentLevelIndex = -1; this.manualLevelIndex = -1; this.steering = void 0; this.onParsedComplete = void 0; this.steering = contentSteeringController; this._registerListeners(); } _registerListeners() { const { hls } = this; hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this); hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this); hls.on(Events.ERROR, this.onError, this); } _unregisterListeners() { const { hls } = this; hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this); hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this); hls.off(Events.ERROR, this.onError, this); } destroy() { this._unregisterListeners(); this.steering = null; this.resetLevels(); super.destroy(); } stopLoad() { const levels = this._levels; levels.forEach((level) => { level.loadError = 0; level.fragmentError = 0; }); super.stopLoad(); } resetLevels() { this._startLevel = void 0; this.manualLevelIndex = -1; this.currentLevelIndex = -1; this.currentLevel = null; this._levels = []; this._maxAutoLevel = -1; } onManifestLoading(event, data) { this.resetLevels(); } onManifestLoaded(event, data) { const preferManagedMediaSource = this.hls.config.preferManagedMediaSource; const levels = []; const redundantSet = {}; const generatePathwaySet = {}; let resolutionFound = false; let videoCodecFound = false; let audioCodecFound = false; data.levels.forEach((levelParsed) => { var _audioCodec, _videoCodec; const attributes = levelParsed.attrs; let { audioCodec, videoCodec } = levelParsed; if (((_audioCodec = audioCodec) == null ? void 0 : _audioCodec.indexOf("mp4a.40.34")) !== -1) { chromeOrFirefox || (chromeOrFirefox = /chrome|firefox/i.test(navigator.userAgent)); if (chromeOrFirefox) { levelParsed.audioCodec = audioCodec = void 0; } } if (audioCodec) { levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource); } if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf("avc1")) === 0) { videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec); } const { width, height, unknownCodecs } = levelParsed; resolutionFound || (resolutionFound = !!(width && height)); videoCodecFound || (videoCodecFound = !!videoCodec); audioCodecFound || (audioCodecFound = !!audioCodec); if (unknownCodecs != null && unknownCodecs.length || audioCodec && !areCodecsMediaSourceSupported(audioCodec, "audio", preferManagedMediaSource) || videoCodec && !areCodecsMediaSourceSupported(videoCodec, "video", preferManagedMediaSource)) { return; } const { CODECS, "FRAME-RATE": FRAMERATE, "HDCP-LEVEL": HDCP, "PATHWAY-ID": PATHWAY, RESOLUTION, "VIDEO-RANGE": VIDEO_RANGE } = attributes; const contentSteeringPrefix = `${PATHWAY || "."}-`; const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`; if (!redundantSet[levelKey]) { const level = new Level(levelParsed); redundantSet[levelKey] = level; generatePathwaySet[levelKey] = 1; levels.push(level); } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs["PATHWAY-ID"]) { const pathwayCount = generatePathwaySet[levelKey] += 1; levelParsed.attrs["PATHWAY-ID"] = new Array(pathwayCount + 1).join("."); const level = new Level(levelParsed); redundantSet[levelKey] = level; levels.push(level); } else { redundantSet[levelKey].addGroupId("audio", attributes.AUDIO); redundantSet[levelKey].addGroupId("text", attributes.SUBTITLES); } }); this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound); } filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) { let audioTracks = []; let subtitleTracks = []; let levels = filteredLevels; if ((resolutionFound || videoCodecFound) && audioCodecFound) { levels = levels.filter(({ videoCodec, videoRange, width, height }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange)); } if (levels.length === 0) { Promise.resolve().then(() => { if (this.hls) { if (data.levels.length) { this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(data.levels[0].attrs)}`); } const error = new Error("no level with compatible codecs found in manifest"); this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: data.url, error, reason: error.message }); } }); return; } if (data.audioTracks) { const { preferManagedMediaSource } = this.hls.config; audioTracks = data.audioTracks.filter((track) => !track.audioCodec || areCodecsMediaSourceSupported(track.audioCodec, "audio", preferManagedMediaSource)); assignTrackIdsByGroup(audioTracks); } if (data.subtitles) { subtitleTracks = data.subtitles; assignTrackIdsByGroup(subtitleTracks); } const unsortedLevels = levels.slice(0); levels.sort((a2, b2) => { if (a2.attrs["HDCP-LEVEL"] !== b2.attrs["HDCP-LEVEL"]) { return (a2.attrs["HDCP-LEVEL"] || "") > (b2.attrs["HDCP-LEVEL"] || "") ? 1 : -1; } if (resolutionFound && a2.height !== b2.height) { return a2.height - b2.height; } if (a2.frameRate !== b2.frameRate) { return a2.frameRate - b2.frameRate; } if (a2.videoRange !== b2.videoRange) { return VideoRangeValues.indexOf(a2.videoRange) - VideoRangeValues.indexOf(b2.videoRange); } if (a2.videoCodec !== b2.videoCodec) { const valueA = videoCodecPreferenceValue(a2.videoCodec); const valueB = videoCodecPreferenceValue(b2.videoCodec); if (valueA !== valueB) { return valueB - valueA; } } if (a2.uri === b2.uri && a2.codecSet !== b2.codecSet) { const valueA = codecsSetSelectionPreferenceValue(a2.codecSet); const valueB = codecsSetSelectionPreferenceValue(b2.codecSet); if (valueA !== valueB) { return valueB - valueA; } } if (a2.averageBitrate !== b2.averageBitrate) { return a2.averageBitrate - b2.averageBitrate; } return 0; }); let firstLevelInPlaylist = unsortedLevels[0]; if (this.steering) { levels = this.steering.filterParsedLevels(levels); if (levels.length !== unsortedLevels.length) { for (let i3 = 0; i3 < unsortedLevels.length; i3++) { if (unsortedLevels[i3].pathwayId === levels[0].pathwayId) { firstLevelInPlaylist = unsortedLevels[i3]; break; } } } } this._levels = levels; for (let i3 = 0; i3 < levels.length; i3++) { if (levels[i3] === firstLevelInPlaylist) { var _this$hls$userConfig; this._firstLevel = i3; const firstLevelBitrate = firstLevelInPlaylist.bitrate; const bandwidthEstimate = this.hls.bandwidthEstimate; this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`); if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === void 0) { const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax); if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate) { this.hls.bandwidthEstimate = startingBwEstimate; } } break; } } const audioOnly = audioCodecFound && !videoCodecFound; const edata = { levels, audioTracks, subtitleTracks, sessionData: data.sessionData, sessionKeys: data.sessionKeys, firstLevel: this._firstLevel, stats: data.stats, audio: audioCodecFound, video: videoCodecFound, altAudio: !audioOnly && audioTracks.some((t2) => !!t2.url) }; this.hls.trigger(Events.MANIFEST_PARSED, edata); if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) { this.hls.startLoad(this.hls.config.startPosition); } } get levels() { if (this._levels.length === 0) { return null; } return this._levels; } get level() { return this.currentLevelIndex; } set level(newLevel) { const levels = this._levels; if (levels.length === 0) { return; } if (newLevel < 0 || newLevel >= levels.length) { const error = new Error("invalid level idx"); const fatal = newLevel < 0; this.hls.trigger(Events.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal, error, reason: error.message }); if (fatal) { return; } newLevel = Math.min(newLevel, levels.length - 1); } const lastLevelIndex = this.currentLevelIndex; const lastLevel = this.currentLevel; const lastPathwayId = lastLevel ? lastLevel.attrs["PATHWAY-ID"] : void 0; const level = levels[newLevel]; const pathwayId = level.attrs["PATHWAY-ID"]; this.currentLevelIndex = newLevel; this.currentLevel = level; if (lastLevelIndex === newLevel && level.details && lastLevel && lastPathwayId === pathwayId) { return; } this.log(`Switching to level ${newLevel} (${level.height ? level.height + "p " : ""}${level.videoRange ? level.videoRange + " " : ""}${level.codecSet ? level.codecSet + " " : ""}@${level.bitrate})${pathwayId ? " with Pathway " + pathwayId : ""} from level ${lastLevelIndex}${lastPathwayId ? " with Pathway " + lastPathwayId : ""}`); const levelSwitchingData = { level: newLevel, attrs: level.attrs, details: level.details, bitrate: level.bitrate, averageBitrate: level.averageBitrate, maxBitrate: level.maxBitrate, realBitrate: level.realBitrate, width: level.width, height: level.height, codecSet: level.codecSet, audioCodec: level.audioCodec, videoCodec: level.videoCodec, audioGroups: level.audioGroups, subtitleGroups: level.subtitleGroups, loaded: level.loaded, loadError: level.loadError, fragmentError: level.fragmentError, name: level.name, id: level.id, uri: level.uri, url: level.url, urlId: 0, audioGroupIds: level.audioGroupIds, textGroupIds: level.textGroupIds }; this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData); const levelDetails = level.details; if (!levelDetails || levelDetails.live) { const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails); this.loadPlaylist(hlsUrlParameters); } } get manualLevel() { return this.manualLevelIndex; } set manualLevel(newLevel) { this.manualLevelIndex = newLevel; if (this._startLevel === void 0) { this._startLevel = newLevel; } if (newLevel !== -1) { this.level = newLevel; } } get firstLevel() { return this._firstLevel; } set firstLevel(newLevel) { this._firstLevel = newLevel; } get startLevel() { if (this._startLevel === void 0) { const configStartLevel = this.hls.config.startLevel; if (configStartLevel !== void 0) { return configStartLevel; } return this.hls.firstAutoLevel; } return this._startLevel; } set startLevel(newLevel) { this._startLevel = newLevel; } onError(event, data) { if (data.fatal || !data.context) { return; } if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) { this.checkRetry(data); } } // reset errors on the successful load of a fragment onFragBuffered(event, { frag }) { if (frag !== void 0 && frag.type === PlaylistLevelType.MAIN) { const el = frag.elementaryStreams; if (!Object.keys(el).some((type) => !!el[type])) { return; } const level = this._levels[frag.level]; if (level != null && level.loadError) { this.log(`Resetting level error count of ${level.loadError} on frag buffered`); level.loadError = 0; } } } onLevelLoaded(event, data) { var _data$deliveryDirecti2; const { level, details } = data; const curLevel = this._levels[level]; if (!curLevel) { var _data$deliveryDirecti; this.warn(`Invalid level index ${level}`); if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) { details.deltaUpdateFailed = true; } return; } if (level === this.currentLevelIndex) { if (curLevel.fragmentError === 0) { curLevel.loadError = 0; } this.playlistLoaded(level, data, curLevel.details); } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) { details.deltaUpdateFailed = true; } } loadPlaylist(hlsUrlParameters) { super.loadPlaylist(); const currentLevelIndex = this.currentLevelIndex; const currentLevel = this.currentLevel; if (currentLevel && this.shouldLoadPlaylist(currentLevel)) { let url = currentLevel.uri; if (hlsUrlParameters) { try { url = hlsUrlParameters.addDirectives(url); } catch (error) { this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`); } } const pathwayId = currentLevel.attrs["PATHWAY-ID"]; this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== void 0 ? " at sn " + hlsUrlParameters.msn + " part " + hlsUrlParameters.part : ""} with${pathwayId ? " Pathway " + pathwayId : ""} ${url}`); this.clearTimer(); this.hls.trigger(Events.LEVEL_LOADING, { url, level: currentLevelIndex, pathwayId: currentLevel.attrs["PATHWAY-ID"], id: 0, // Deprecated Level urlId deliveryDirectives: hlsUrlParameters || null }); } } get nextLoadLevel() { if (this.manualLevelIndex !== -1) { return this.manualLevelIndex; } else { return this.hls.nextAutoLevel; } } set nextLoadLevel(nextLevel) { this.level = nextLevel; if (this.manualLevelIndex === -1) { this.hls.nextAutoLevel = nextLevel; } } removeLevel(levelIndex) { var _this$currentLevel; const levels = this._levels.filter((level, index2) => { if (index2 !== levelIndex) { return true; } if (this.steering) { this.steering.removeLevel(level); } if (level === this.currentLevel) { this.currentLevel = null; this.currentLevelIndex = -1; if (level.details) { level.details.fragments.forEach((f) => f.level = -1); } } return false; }); reassignFragmentLevelIndexes(levels); this._levels = levels; if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) { this.currentLevelIndex = this.currentLevel.details.fragments[0].level; } this.hls.trigger(Events.LEVELS_UPDATED, { levels }); } onLevelsUpdated(event, { levels }) { this._levels = levels; } checkMaxAutoUpdated() { const { autoLevelCapping, maxAutoLevel, maxHdcpLevel } = this.hls; if (this._maxAutoLevel !== maxAutoLevel) { this._maxAutoLevel = maxAutoLevel; this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, { autoLevelCapping, levels: this.levels, maxAutoLevel, minAutoLevel: this.hls.minAutoLevel, maxHdcpLevel }); } } }; function assignTrackIdsByGroup(tracks) { const groups = {}; tracks.forEach((track) => { const groupId = track.groupId || ""; track.id = groups[groupId] = groups[groupId] || 0; groups[groupId]++; }); } var KeyLoader = class { constructor(config) { this.config = void 0; this.keyUriToKeyInfo = {}; this.emeController = null; this.config = config; } abort(type) { for (const uri in this.keyUriToKeyInfo) { const loader = this.keyUriToKeyInfo[uri].loader; if (loader) { var _loader$context; if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) { return; } loader.abort(); } } } detach() { for (const uri in this.keyUriToKeyInfo) { const keyInfo = this.keyUriToKeyInfo[uri]; if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) { delete this.keyUriToKeyInfo[uri]; } } } destroy() { this.detach(); for (const uri in this.keyUriToKeyInfo) { const loader = this.keyUriToKeyInfo[uri].loader; if (loader) { loader.destroy(); } } this.keyUriToKeyInfo = {}; } createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) { return new LoadError({ type: ErrorTypes.NETWORK_ERROR, details, fatal: false, frag, response, error, networkDetails }); } loadClear(loadingFrag, encryptedFragments) { if (this.emeController && this.config.emeEnabled) { const { sn, cc } = loadingFrag; for (let i3 = 0; i3 < encryptedFragments.length; i3++) { const frag = encryptedFragments[i3]; if (cc <= frag.cc && (sn === "initSegment" || frag.sn === "initSegment" || sn < frag.sn)) { this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => { frag.setKeyFormat(keySystemFormat); }); break; } } } } load(frag) { if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) { return this.emeController.selectKeySystemFormat(frag).then((keySystemFormat) => { return this.loadInternal(frag, keySystemFormat); }); } return this.loadInternal(frag); } loadInternal(frag, keySystemFormat) { var _keyInfo, _keyInfo2; if (keySystemFormat) { frag.setKeyFormat(keySystemFormat); } const decryptdata = frag.decryptdata; if (!decryptdata) { const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : "Missing decryption data on fragment in onKeyLoading"); return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error)); } const uri = decryptdata.uri; if (!uri) { return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`))); } let keyInfo = this.keyUriToKeyInfo[uri]; if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) { decryptdata.key = keyInfo.decryptdata.key; return Promise.resolve({ frag, keyInfo }); } if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) { var _keyInfo$mediaKeySess; switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) { case void 0: case "status-pending": case "usable": case "usable-in-future": return keyInfo.keyLoadPromise.then((keyLoadedData) => { decryptdata.key = keyLoadedData.keyInfo.decryptdata.key; return { frag, keyInfo }; }); } } keyInfo = this.keyUriToKeyInfo[uri] = { decryptdata, keyLoadPromise: null, loader: null, mediaKeySessionContext: null }; switch (decryptdata.method) { case "ISO-23001-7": case "SAMPLE-AES": case "SAMPLE-AES-CENC": case "SAMPLE-AES-CTR": if (decryptdata.keyFormat === "identity") { return this.loadKeyHTTP(keyInfo, frag); } return this.loadKeyEME(keyInfo, frag); case "AES-128": return this.loadKeyHTTP(keyInfo, frag); default: return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`))); } } loadKeyEME(keyInfo, frag) { const keyLoadedData = { frag, keyInfo }; if (this.emeController && this.config.emeEnabled) { const keySessionContextPromise = this.emeController.loadKey(keyLoadedData); if (keySessionContextPromise) { return (keyInfo.keyLoadPromise = keySessionContextPromise.then((keySessionContext) => { keyInfo.mediaKeySessionContext = keySessionContext; return keyLoadedData; })).catch((error) => { keyInfo.keyLoadPromise = null; throw error; }); } } return Promise.resolve(keyLoadedData); } loadKeyHTTP(keyInfo, frag) { const config = this.config; const Loader2 = config.loader; const keyLoader = new Loader2(config); frag.keyLoader = keyInfo.loader = keyLoader; return keyInfo.keyLoadPromise = new Promise((resolve, reject) => { const loaderContext = { keyInfo, frag, responseType: "arraybuffer", url: keyInfo.decryptdata.uri }; const loadPolicy = config.keyLoadPolicy.default; const loaderConfig = { loadPolicy, timeout: loadPolicy.maxLoadTimeMs, maxRetry: 0, retryDelay: 0, maxRetryDelay: 0 }; const loaderCallbacks = { onSuccess: (response, stats, context, networkDetails) => { const { frag: frag2, keyInfo: keyInfo2, url: uri } = context; if (!frag2.decryptdata || keyInfo2 !== this.keyUriToKeyInfo[uri]) { return reject(this.createKeyLoadError(frag2, ErrorDetails.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), networkDetails)); } keyInfo2.decryptdata.key = frag2.decryptdata.key = new Uint8Array(response.data); frag2.keyLoader = null; keyInfo2.loader = null; resolve({ frag: frag2, keyInfo: keyInfo2 }); }, onError: (response, context, networkDetails, stats) => { this.resetLoader(context); reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread23({ url: loaderContext.url, data: void 0 }, response))); }, onTimeout: (stats, context, networkDetails) => { this.resetLoader(context); reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), networkDetails)); }, onAbort: (stats, context, networkDetails) => { this.resetLoader(context); reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error("key loading aborted"), networkDetails)); } }; keyLoader.load(loaderContext, loaderConfig, loaderCallbacks); }); } resetLoader(context) { const { frag, keyInfo, url: uri } = context; const loader = keyInfo.loader; if (frag.keyLoader === loader) { frag.keyLoader = null; keyInfo.loader = null; } delete this.keyUriToKeyInfo[uri]; if (loader) { loader.destroy(); } } }; function getSourceBuffer() { return self.SourceBuffer || self.WebKitSourceBuffer; } function isMSESupported() { const mediaSource = getMediaSource(); if (!mediaSource) { return false; } const sourceBuffer = getSourceBuffer(); return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === "function" && typeof sourceBuffer.prototype.remove === "function"; } function isSupported() { if (!isMSESupported()) { return false; } const mediaSource = getMediaSource(); return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === "function" && (["avc1.42E01E,mp4a.40.2", "av01.0.01M.08", "vp09.00.50.08"].some((codecsForVideoContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, "video"))) || ["mp4a.40.2", "fLaC"].some((codecForAudioContainer) => mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, "audio")))); } function changeTypeSupported() { var _sourceBuffer$prototy; const sourceBuffer = getSourceBuffer(); return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === "function"; } var STALL_MINIMUM_DURATION_MS = 250; var MAX_START_GAP_JUMP = 2; var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1; var SKIP_BUFFER_RANGE_START = 0.05; var GapController = class { constructor(config, media, fragmentTracker, hls) { this.config = void 0; this.media = null; this.fragmentTracker = void 0; this.hls = void 0; this.nudgeRetry = 0; this.stallReported = false; this.stalled = null; this.moved = false; this.seeking = false; this.config = config; this.media = media; this.fragmentTracker = fragmentTracker; this.hls = hls; } destroy() { this.media = null; this.hls = this.fragmentTracker = null; } /** * Checks if the playhead is stuck within a gap, and if so, attempts to free it. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range). * * @param lastCurrentTime - Previously read playhead position */ poll(lastCurrentTime, activeFrag) { const { config, media, stalled } = this; if (media === null) { return; } const { currentTime, seeking } = media; const seeked = this.seeking && !seeking; const beginSeek = !this.seeking && seeking; this.seeking = seeking; if (currentTime !== lastCurrentTime) { this.moved = true; if (!seeking) { this.nudgeRetry = 0; } if (stalled !== null) { if (this.stallReported) { const _stalledDuration = self.performance.now() - stalled; logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(_stalledDuration)}ms`); this.stallReported = false; } this.stalled = null; } return; } if (beginSeek || seeked) { this.stalled = null; return; } if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length) { this.nudgeRetry = 0; return; } const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0); const nextStart = bufferInfo.nextStart || 0; if (seeking) { const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; const noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime); if (hasEnoughBuffer || noBufferGap) { return; } this.moved = false; } if (!this.moved && this.stalled !== null) { var _level$details; const isBuffered = bufferInfo.len > 0; if (!isBuffered && !nextStart) { return; } const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; const level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null; const isLive = level == null ? void 0 : (_level$details = level.details) == null ? void 0 : _level$details.live; const maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP; const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime); if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) { if (!media.paused) { this._trySkipBufferHole(partialOrGap); } return; } } const tnow = self.performance.now(); if (stalled === null) { this.stalled = tnow; return; } const stalledDuration = tnow - stalled; if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) { this._reportStall(bufferInfo); if (!this.media) { return; } } const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole); this._tryFixBufferStall(bufferedWithHoles, stalledDuration); } /** * Detects and attempts to fix known buffer stalling issues. * @param bufferInfo - The properties of the current buffer. * @param stalledDurationMs - The amount of time Hls.js has been stalling for. * @private */ _tryFixBufferStall(bufferInfo, stalledDurationMs) { const { config, fragmentTracker, media } = this; if (media === null) { return; } const currentTime = media.currentTime; const partial = fragmentTracker.getPartialFragment(currentTime); if (partial) { const targetTime = this._trySkipBufferHole(partial); if (targetTime || !this.media) { return; } } if ((bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && stalledDurationMs > config.highBufferWatchdogPeriod * 1e3) { logger.warn("Trying to nudge playhead over buffer-hole"); this.stalled = null; this._tryNudgeBuffer(); } } /** * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period. * @param bufferLen - The playhead distance from the end of the current buffer segment. * @private */ _reportStall(bufferInfo) { const { hls, media, stallReported } = this; if (!stallReported && media) { this.stallReported = true; const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${JSON.stringify(bufferInfo)})`); logger.warn(error.message); hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, error, buffer: bufferInfo.len }); } } /** * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments * @param partial - The partial fragment found at the current time (where playback is stalling). * @private */ _trySkipBufferHole(partial) { const { config, hls, media } = this; if (media === null) { return 0; } const currentTime = media.currentTime; const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0); const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart; if (startTime) { const bufferStarved = bufferInfo.len <= config.maxBufferHole; const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3; const gapLength = startTime - currentTime; if (gapLength > 0 && (bufferStarved || waiting)) { if (gapLength > config.maxBufferHole) { const { fragmentTracker } = this; let startGap = false; if (currentTime === 0) { const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN); if (startFrag && startTime < startFrag.end) { startGap = true; } } if (!startGap) { const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN); if (startProvisioned) { let moreToLoad = false; let pos = startProvisioned.end; while (pos < startTime) { const provisioned = fragmentTracker.getPartialFragment(pos); if (provisioned) { pos += provisioned.duration; } else { moreToLoad = true; break; } } if (moreToLoad) { return 0; } } } } const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS); logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`); this.moved = true; this.stalled = null; media.currentTime = targetTime; if (partial && !partial.gap) { const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`); hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, error, reason: error.message, frag: partial }); } return targetTime; } } return 0; } /** * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount. * @private */ _tryNudgeBuffer() { const { config, hls, media, nudgeRetry } = this; if (media === null) { return; } const currentTime = media.currentTime; this.nudgeRetry++; if (nudgeRetry < config.nudgeMaxRetry) { const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset; const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`); logger.warn(error.message); media.currentTime = targetTime; hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_NUDGE_ON_STALL, error, fatal: false }); } else { const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`); logger.error(error.message); hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, error, fatal: true }); } } }; var TICK_INTERVAL = 100; var StreamController = class extends BaseStreamController { constructor(hls, fragmentTracker, keyLoader) { super(hls, fragmentTracker, keyLoader, "[stream-controller]", PlaylistLevelType.MAIN); this.audioCodecSwap = false; this.gapController = null; this.level = -1; this._forceStartLoad = false; this.altAudio = false; this.audioOnly = false; this.fragPlaying = null; this.onvplaying = null; this.onvseeked = null; this.fragLastKbps = 0; this.couldBacktrack = false; this.backtrackFragment = null; this.audioCodecSwitch = false; this.videoBuffer = null; this._registerListeners(); } _registerListeners() { const { hls } = this; hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this); hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this); hls.on(Events.ERROR, this.onError, this); hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this); hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this); hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this); } _unregisterListeners() { const { hls } = this; hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this); hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this); hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this); hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this); hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this); hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this); hls.off(Events.ERROR, this.onError, this); hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this); hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this); hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this); hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this); hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this); hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this); } onHandlerDestroying() { this._unregisterListeners(); super.onHandlerDestroying(); } startLoad(startPosition) { if (this.levels) { const { lastCurrentTime, hls } = this; this.stopLoad(); this.setInterval(TICK_INTERVAL); this.level = -1; if (!this.startFragRequested) { let startLevel = hls.startLevel; if (startLevel === -1) { if (hls.config.testBandwidth && this.levels.length > 1) { startLevel = 0; this.bitrateTest = true; } else { startLevel = hls.firstAutoLevel; } } hls.nextLoadLevel = startLevel; this.level = hls.loadLevel; this.loadedmetadata = false; } if (lastCurrentTime > 0 && startPosition === -1) { this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`); startPosition = lastCurrentTime; } this.state = State.IDLE; this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; this.tick(); } else { this._forceStartLoad = true; this.state = State.STOPPED; } } stopLoad() { this._forceStartLoad = false; super.stopLoad(); } doTick() { switch (this.state) { case State.WAITING_LEVEL: { const { levels, level } = this; const currentLevel = levels == null ? void 0 : levels[level]; const details = currentLevel == null ? void 0 : currentLevel.details; if (details && (!details.live || this.levelLastLoaded === currentLevel)) { if (this.waitForCdnTuneIn(details)) { break; } this.state = State.IDLE; break; } else if (this.hls.nextLoadLevel !== this.level) { this.state = State.IDLE; break; } break; } case State.FRAG_LOADING_WAITING_RETRY: { var _this$media; const now2 = self.performance.now(); const retryDate = this.retryDate; if (!retryDate || now2 >= retryDate || (_this$media = this.media) != null && _this$media.seeking) { const { levels, level } = this; const currentLevel = levels == null ? void 0 : levels[level]; this.resetStartWhenNotLoaded(currentLevel || null); this.state = State.IDLE; } } break; } if (this.state === State.IDLE) { this.doTickIdle(); } this.onTickEnd(); } onTickEnd() { super.onTickEnd(); this.checkBuffer(); this.checkFragmentChanged(); } doTickIdle() { const { hls, levelLastLoaded, levels, media } = this; if (levelLastLoaded === null || !media && (this.startFragRequested || !hls.config.startFragPrefetch)) { return; } if (this.altAudio && this.audioOnly) { return; } const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel; if (!(levels != null && levels[level])) { return; } const levelInfo = levels[level]; const bufferInfo = this.getMainFwdBufferInfo(); if (bufferInfo === null) { return; } const lastDetails = this.getLevelDetails(); if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) { const data = {}; if (this.altAudio) { data.type = "video"; } this.hls.trigger(Events.BUFFER_EOS, data); this.state = State.ENDED; return; } if (!this.buffering) { return; } if (hls.loadLevel !== level && hls.manualLevel === -1) { this.log(`Adapting to level ${level} from level ${this.level}`); } this.level = hls.nextLoadLevel = level; const levelDetails = levelInfo.details; if (!levelDetails || this.state === State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== levelInfo) { this.level = level; this.state = State.WAITING_LEVEL; return; } const bufferLen = bufferInfo.len; const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); if (bufferLen >= maxBufLen) { return; } if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) { this.backtrackFragment = null; } const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end; let frag = this.getNextFragment(targetBufferTime, levelDetails); if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== "initSegment" && this.fragmentTracker.getState(frag) !== FragmentState.OK) { var _this$backtrackFragme; const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn; const fragIdx = backtrackSn - levelDetails.startSN; const backtrackFrag = levelDetails.fragments[fragIdx - 1]; if (backtrackFrag && frag.cc === backtrackFrag.cc) { frag = backtrackFrag; this.fragmentTracker.removeFragment(backtrackFrag); } } else if (this.backtrackFragment && bufferInfo.len) { this.backtrackFragment = null; } if (frag && this.isLoopLoading(frag, targetBufferTime)) { const gapStart = frag.gap; if (!gapStart) { const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO; const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media; if (mediaBuffer) { this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN); } } frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen); } if (!frag) { return; } if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) { frag = frag.initSegment; } this.loadFragment(frag, levelInfo, targetBufferTime); } loadFragment(frag, level, targetBufferTime) { const fragState = this.fragmentTracker.getState(frag); this.fragCurrent = frag; if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) { if (frag.sn === "initSegment") { this._loadInitSegment(frag, level); } else if (this.bitrateTest) { this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`); this._loadBitrateTestFrag(frag, level); } else { this.startFragRequested = true; super.loadFragment(frag, level, targetBufferTime); } } else { this.clearTrackerIfNeeded(frag); } } getBufferedFrag(position2) { return this.fragmentTracker.getBufferedFrag(position2, PlaylistLevelType.MAIN); } followingBufferedFrag(frag) { if (frag) { return this.getBufferedFrag(frag.end + 0.5); } return null; } /* on immediate level switch : - pause playback if playing - cancel any pending load request - and trigger a buffer flush */ immediateLevelSwitch() { this.abortCurrentFrag(); this.flushMainBuffer(0, Number.POSITIVE_INFINITY); } /** * try to switch ASAP without breaking video playback: * in order to ensure smooth but quick level switching, * we need to find the next flushable buffer range * we should take into account new segment fetch time */ nextLevelSwitch() { const { levels, media } = this; if (media != null && media.readyState) { let fetchdelay; const fragPlayingCurrent = this.getAppendedFrag(media.currentTime); if (fragPlayingCurrent && fragPlayingCurrent.start > 1) { this.flushMainBuffer(0, fragPlayingCurrent.start - 1); } const levelDetails = this.getLevelDetails(); if (levelDetails != null && levelDetails.live) { const bufferInfo = this.getMainFwdBufferInfo(); if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) { return; } } if (!media.paused && levels) { const nextLevelId = this.hls.nextLoadLevel; const nextLevel = levels[nextLevelId]; const fragLastKbps = this.fragLastKbps; if (fragLastKbps && this.fragCurrent) { fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1e3 * fragLastKbps) + 1; } else { fetchdelay = 0; } } else { fetchdelay = 0; } const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay); if (bufferedFrag) { const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag); if (nextBufferedFrag) { this.abortCurrentFrag(); const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start; const fragDuration = nextBufferedFrag.duration; const startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * (this.couldBacktrack ? 0.5 : 0.125)), fragDuration * (this.couldBacktrack ? 0.75 : 0.25))); this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY); } } } } abortCurrentFrag() { const fragCurrent = this.fragCurrent; this.fragCurrent = null; this.backtrackFragment = null; if (fragCurrent) { fragCurrent.abortRequests(); this.fragmentTracker.removeFragment(fragCurrent); } switch (this.state) { case State.KEY_LOADING: case State.FRAG_LOADING: case State.FRAG_LOADING_WAITING_RETRY: case State.PARSING: case State.PARSED: this.state = State.IDLE; break; } this.nextLoadPosition = this.getLoadPosition(); } flushMainBuffer(startOffset, endOffset) { super.flushMainBuffer(startOffset, endOffset, this.altAudio ? "video" : null); } onMediaAttached(event, data) { super.onMediaAttached(event, data); const media = data.media; this.onvplaying = this.onMediaPlaying.bind(this); this.onvseeked = this.onMediaSeeked.bind(this); media.addEventListener("playing", this.onvplaying); media.addEventListener("seeked", this.onvseeked); this.gapController = new GapController(this.config, media, this.fragmentTracker, this.hls); } onMediaDetaching() { const { media } = this; if (media && this.onvplaying && this.onvseeked) { media.removeEventListener("playing", this.onvplaying); media.removeEventListener("seeked", this.onvseeked); this.onvplaying = this.onvseeked = null; this.videoBuffer = null; } this.fragPlaying = null; if (this.gapController) { this.gapController.destroy(); this.gapController = null; } super.onMediaDetaching(); } onMediaPlaying() { this.tick(); } onMediaSeeked() { const media = this.media; const currentTime = media ? media.currentTime : null; if (isFiniteNumber(currentTime)) { this.log(`Media seeked to ${currentTime.toFixed(3)}`); } const bufferInfo = this.getMainFwdBufferInfo(); if (bufferInfo === null || bufferInfo.len === 0) { this.warn(`Main forward buffer length on "seeked" event ${bufferInfo ? bufferInfo.len : "empty"})`); return; } this.tick(); } onManifestLoading() { this.log("Trigger BUFFER_RESET"); this.hls.trigger(Events.BUFFER_RESET, void 0); this.fragmentTracker.removeAllFragments(); this.couldBacktrack = false; this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0; this.levels = this.fragPlaying = this.backtrackFragment = this.levelLastLoaded = null; this.altAudio = this.audioOnly = this.startFragRequested = false; } onManifestParsed(event, data) { let aac = false; let heaac = false; data.levels.forEach((level) => { const codec = level.audioCodec; if (codec) { aac = aac || codec.indexOf("mp4a.40.2") !== -1; heaac = heaac || codec.indexOf("mp4a.40.5") !== -1; } }); this.audioCodecSwitch = aac && heaac && !changeTypeSupported(); if (this.audioCodecSwitch) { this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"); } this.levels = data.levels; this.startFragRequested = false; } onLevelLoading(event, data) { const { levels } = this; if (!levels || this.state !== State.IDLE) { return; } const level = levels[data.level]; if (!level.details || level.details.live && this.levelLastLoaded !== level || this.waitForCdnTuneIn(level.details)) { this.state = State.WAITING_LEVEL; } } onLevelLoaded(event, data) { var _curLevel$details; const { levels } = this; const newLevelId = data.level; const newDetails = data.details; const duration = newDetails.totalduration; if (!levels) { this.warn(`Levels were reset while loading level ${newLevelId}`); return; } this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ""}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`); const curLevel = levels[newLevelId]; const fragCurrent = this.fragCurrent; if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) { if (fragCurrent.level !== data.level && fragCurrent.loader) { this.abortCurrentFrag(); } } let sliding = 0; if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) { var _this$levelLastLoaded; this.checkLiveUpdate(newDetails); if (newDetails.deltaUpdateFailed) { return; } sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details); } curLevel.details = newDetails; this.levelLastLoaded = curLevel; this.hls.trigger(Events.LEVEL_UPDATED, { details: newDetails, level: newLevelId }); if (this.state === State.WAITING_LEVEL) { if (this.waitForCdnTuneIn(newDetails)) { return; } this.state = State.IDLE; } if (!this.startFragRequested) { this.setStartPosition(newDetails, sliding); } else if (newDetails.live) { this.synchronizeToLiveEdge(newDetails); } this.tick(); } _handleFragmentLoadProgress(data) { var _frag$initSegment; const { frag, part, payload } = data; const { levels } = this; if (!levels) { this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`); return; } const currentLevel = levels[frag.level]; const details = currentLevel.details; if (!details) { this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`); this.fragmentTracker.removeFragment(frag); return; } const videoCodec = currentLevel.videoCodec; const accurateTimeOffset = details.PTSKnown || !details.live; const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data; const audioCodec = this._getAudioCodec(currentLevel); const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)); const partIndex = part ? part.index : -1; const partial = partIndex !== -1; const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial); const initPTS = this.initPTS[frag.cc]; transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS); } onAudioTrackSwitching(event, data) { const fromAltAudio = this.altAudio; const altAudio = !!data.url; if (!altAudio) { if (this.mediaBuffer !== this.media) { this.log("Switching on main audio, use media.buffered to schedule main fragment loading"); this.mediaBuffer = this.media; const fragCurrent = this.fragCurrent; if (fragCurrent) { this.log("Switching to main audio track, cancel main fragment load"); fragCurrent.abortRequests(); this.fragmentTracker.removeFragment(fragCurrent); } this.resetTransmuxer(); this.resetLoadingState(); } else if (this.audioOnly) { this.resetTransmuxer(); } const hls = this.hls; if (fromAltAudio) { hls.trigger(Events.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: null }); this.fragmentTracker.removeAllFragments(); } hls.trigger(Events.AUDIO_TRACK_SWITCHED, data); } } onAudioTrackSwitched(event, data) { const trackId = data.id; const altAudio = !!this.hls.audioTracks[trackId].url; if (altAudio) { const videoBuffer = this.videoBuffer; if (videoBuffer && this.mediaBuffer !== videoBuffer) { this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"); this.mediaBuffer = videoBuffer; } } this.altAudio = altAudio; this.tick(); } onBufferCreated(event, data) { const tracks = data.tracks; let mediaTrack; let name; let alternate = false; for (const type in tracks) { const track = tracks[type]; if (track.id === "main") { name = type; mediaTrack = track; if (type === "video") { const videoTrack = tracks[type]; if (videoTrack) { this.videoBuffer = videoTrack.buffer; } } } else { alternate = true; } } if (alternate && mediaTrack) { this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`); this.mediaBuffer = mediaTrack.buffer; } else { this.mediaBuffer = this.media; } } onFragBuffered(event, data) { const { frag, part } = data; if (frag && frag.type !== PlaylistLevelType.MAIN) { return; } if (this.fragContextChanged(frag)) { this.warn(`Fragment ${frag.sn}${part ? " p: " + part.index : ""} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`); if (this.state === State.PARSED) { this.state = State.IDLE; } return; } const stats = part ? part.stats : frag.stats; this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first)); if (frag.sn !== "initSegment") { this.fragPrevious = frag; } this.fragBufferedComplete(frag, part); } onError(event, data) { var _data$context; if (data.fatal) { this.state = State.ERROR; return; } switch (data.details) { case ErrorDetails.FRAG_GAP: case ErrorDetails.FRAG_PARSING_ERROR: case ErrorDetails.FRAG_DECRYPT_ERROR: case ErrorDetails.FRAG_LOAD_ERROR: case ErrorDetails.FRAG_LOAD_TIMEOUT: case ErrorDetails.KEY_LOAD_ERROR: case ErrorDetails.KEY_LOAD_TIMEOUT: this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data); break; case ErrorDetails.LEVEL_LOAD_ERROR: case ErrorDetails.LEVEL_LOAD_TIMEOUT: case ErrorDetails.LEVEL_PARSING_ERROR: if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) { this.state = State.IDLE; } break; case ErrorDetails.BUFFER_APPEND_ERROR: case ErrorDetails.BUFFER_FULL_ERROR: if (!data.parent || data.parent !== "main") { return; } if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) { this.resetLoadingState(); return; } if (this.reduceLengthAndFlushBuffer(data)) { this.flushMainBuffer(0, Number.POSITIVE_INFINITY); } break; case ErrorDetails.INTERNAL_EXCEPTION: this.recoverWorkerError(data); break; } } // Checks the health of the buffer and attempts to resolve playback stalls. checkBuffer() { const { media, gapController } = this; if (!media || !gapController || !media.readyState) { return; } if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) { const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null; gapController.poll(this.lastCurrentTime, activeFrag); } this.lastCurrentTime = media.currentTime; } onFragLoadEmergencyAborted() { this.state = State.IDLE; if (!this.loadedmetadata) { this.startFragRequested = false; this.nextLoadPosition = this.startPosition; } this.tickImmediate(); } onBufferFlushed(event, { type }) { if (type !== ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) { const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media; this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN); this.tick(); } } onLevelsUpdated(event, data) { if (this.level > -1 && this.fragCurrent) { this.level = this.fragCurrent.level; } this.levels = data.levels; } swapAudioCodec() { this.audioCodecSwap = !this.audioCodecSwap; } /** * Seeks to the set startPosition if not equal to the mediaElement's current time. */ seekToStartPos() { const { media } = this; if (!media) { return; } const currentTime = media.currentTime; let startPosition = this.startPosition; if (startPosition >= 0 && currentTime < startPosition) { if (media.seeking) { this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`); return; } const buffered = BufferHelper.getBuffered(media); const bufferStart = buffered.length ? buffered.start(0) : 0; const delta = bufferStart - startPosition; if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) { this.log(`adjusting start position by ${delta} to match buffer start`); startPosition += delta; this.startPosition = startPosition; } this.log(`seek to target start position ${startPosition} from current time ${currentTime}`); media.currentTime = startPosition; } } _getAudioCodec(currentLevel) { let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec; if (this.audioCodecSwap && audioCodec) { this.log("Swapping audio codec"); if (audioCodec.indexOf("mp4a.40.5") !== -1) { audioCodec = "mp4a.40.2"; } else { audioCodec = "mp4a.40.5"; } } return audioCodec; } _loadBitrateTestFrag(frag, level) { frag.bitrateTest = true; this._doFragLoad(frag, level).then((data) => { const { hls } = this; if (!data || this.fragContextChanged(frag)) { return; } level.fragmentError = 0; this.state = State.IDLE; this.startFragRequested = false; this.bitrateTest = false; const stats = frag.stats; stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now(); hls.trigger(Events.FRAG_LOADED, data); frag.bitrateTest = false; }); } _handleTransmuxComplete(transmuxResult) { var _id3$samples; const id = "main"; const { hls } = this; const { remuxResult, chunkMeta } = transmuxResult; const context = this.getCurrentContext(chunkMeta); if (!context) { this.resetWhenMissingContext(chunkMeta); return; } const { frag, part, level } = context; const { video, text, id3, initSegment } = remuxResult; const { details } = level; const audio = this.altAudio ? void 0 : remuxResult.audio; if (this.fragContextChanged(frag)) { this.fragmentTracker.removeFragment(frag); return; } this.state = State.PARSING; if (initSegment) { if (initSegment != null && initSegment.tracks) { const mapFragment = frag.initSegment || frag; this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta); hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, { frag: mapFragment, id, tracks: initSegment.tracks }); } const initPTS = initSegment.initPTS; const timescale = initSegment.timescale; if (isFiniteNumber(initPTS)) { this.initPTS[frag.cc] = { baseTime: initPTS, timescale }; hls.trigger(Events.INIT_PTS_FOUND, { frag, id, initPTS, timescale }); } } if (video && details && frag.sn !== "initSegment") { const prevFrag = details.fragments[frag.sn - 1 - details.startSN]; const isFirstFragment = frag.sn === details.startSN; const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc; if (remuxResult.independent !== false) { const { startPTS, endPTS, startDTS, endDTS } = video; if (part) { part.elementaryStreams[video.type] = { startPTS, endPTS, startDTS, endDTS }; } else { if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) { this.couldBacktrack = true; } if (video.dropped && video.independent) { const bufferInfo = this.getMainFwdBufferInfo(); const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole; const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS; if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) { this.backtrack(frag); return; } else if (isFirstInDiscontinuity) { frag.gap = true; } frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true); } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) { frag.gap = true; } } frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS); if (this.backtrackFragment) { this.backtrackFragment = frag; } this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity); } else if (isFirstFragment || isFirstInDiscontinuity) { frag.gap = true; } else { this.backtrack(frag); return; } } if (audio) { const { startPTS, endPTS, startDTS, endDTS } = audio; if (part) { part.elementaryStreams[ElementaryStreamTypes.AUDIO] = { startPTS, endPTS, startDTS, endDTS }; } frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS); this.bufferFragmentData(audio, frag, part, chunkMeta); } if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) { const emittedID3 = { id, frag, details, samples: id3.samples }; hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3); } if (details && text) { const emittedText = { id, frag, details, samples: text.samples }; hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText); } } _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) { if (this.state !== State.PARSING) { return; } this.audioOnly = !!tracks.audio && !tracks.video; if (this.altAudio && !this.audioOnly) { delete tracks.audio; } const { audio, video, audiovideo } = tracks; if (audio) { let audioCodec = currentLevel.audioCodec; const ua3 = navigator.userAgent.toLowerCase(); if (this.audioCodecSwitch) { if (audioCodec) { if (audioCodec.indexOf("mp4a.40.5") !== -1) { audioCodec = "mp4a.40.2"; } else { audioCodec = "mp4a.40.5"; } } const audioMetadata = audio.metadata; if (audioMetadata && "channelCount" in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua3.indexOf("firefox") === -1) { audioCodec = "mp4a.40.5"; } } if (audioCodec && audioCodec.indexOf("mp4a.40.5") !== -1 && ua3.indexOf("android") !== -1 && audio.container !== "audio/mpeg") { audioCodec = "mp4a.40.2"; this.log(`Android: force audio codec to ${audioCodec}`); } if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) { this.log(`Swapping manifest audio codec "${currentLevel.audioCodec}" for "${audioCodec}"`); } audio.levelCodec = audioCodec; audio.id = "main"; this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ""}/${currentLevel.audioCodec || ""}/${audio.codec}]`); } if (video) { video.levelCodec = currentLevel.videoCodec; video.id = "main"; this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ""}/${video.codec}]`); } if (audiovideo) { this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`); } this.hls.trigger(Events.BUFFER_CODECS, tracks); Object.keys(tracks).forEach((trackName) => { const track = tracks[trackName]; const initSegment = track.initSegment; if (initSegment != null && initSegment.byteLength) { this.hls.trigger(Events.BUFFER_APPENDING, { type: trackName, data: initSegment, frag, part: null, chunkMeta, parent: frag.type }); } }); this.tickImmediate(); } getMainFwdBufferInfo() { return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, PlaylistLevelType.MAIN); } backtrack(frag) { this.couldBacktrack = true; this.backtrackFragment = frag; this.resetTransmuxer(); this.flushBufferGap(frag); this.fragmentTracker.removeFragment(frag); this.fragPrevious = null; this.nextLoadPosition = frag.start; this.state = State.IDLE; } checkFragmentChanged() { const video = this.media; let fragPlayingCurrent = null; if (video && video.readyState > 1 && video.seeking === false) { const currentTime = video.currentTime; if (BufferHelper.isBuffered(video, currentTime)) { fragPlayingCurrent = this.getAppendedFrag(currentTime); } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) { fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1); } if (fragPlayingCurrent) { this.backtrackFragment = null; const fragPlaying = this.fragPlaying; const fragCurrentLevel = fragPlayingCurrent.level; if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) { this.fragPlaying = fragPlayingCurrent; this.hls.trigger(Events.FRAG_CHANGED, { frag: fragPlayingCurrent }); if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) { this.hls.trigger(Events.LEVEL_SWITCHED, { level: fragCurrentLevel }); } } } } } get nextLevel() { const frag = this.nextBufferedFrag; if (frag) { return frag.level; } return -1; } get currentFrag() { const media = this.media; if (media) { return this.fragPlaying || this.getAppendedFrag(media.currentTime); } return null; } get currentProgramDateTime() { const media = this.media; if (media) { const currentTime = media.currentTime; const frag = this.currentFrag; if (frag && isFiniteNumber(currentTime) && isFiniteNumber(frag.programDateTime)) { const epocMs = frag.programDateTime + (currentTime - frag.start) * 1e3; return new Date(epocMs); } } return null; } get currentLevel() { const frag = this.currentFrag; if (frag) { return frag.level; } return -1; } get nextBufferedFrag() { const frag = this.currentFrag; if (frag) { return this.followingBufferedFrag(frag); } return null; } get forceStartLoad() { return this._forceStartLoad; } }; var Hls = class _Hls { /** * Get the video-dev/hls.js package version. */ static get version() { return "1.5.20"; } /** * Check if the required MediaSource Extensions are available. */ static isMSESupported() { return isMSESupported(); } /** * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs. */ static isSupported() { return isSupported(); } /** * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource). */ static getMediaSource() { return getMediaSource(); } static get Events() { return Events; } static get ErrorTypes() { return ErrorTypes; } static get ErrorDetails() { return ErrorDetails; } /** * Get the default configuration applied to new instances. */ static get DefaultConfig() { if (!_Hls.defaultConfig) { return hlsDefaultConfig; } return _Hls.defaultConfig; } /** * Replace the default configuration applied to new instances. */ static set DefaultConfig(defaultConfig) { _Hls.defaultConfig = defaultConfig; } /** * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`. * @param userConfig - Configuration options applied over `Hls.DefaultConfig` */ constructor(userConfig = {}) { this.config = void 0; this.userConfig = void 0; this.coreComponents = void 0; this.networkControllers = void 0; this.started = false; this._emitter = new EventEmitter(); this._autoLevelCapping = -1; this._maxHdcpLevel = null; this.abrController = void 0; this.bufferController = void 0; this.capLevelController = void 0; this.latencyController = void 0; this.levelController = void 0; this.streamController = void 0; this.audioTrackController = void 0; this.subtitleTrackController = void 0; this.emeController = void 0; this.cmcdController = void 0; this._media = null; this.url = null; this.triggeringException = void 0; enableLogs(userConfig.debug || false, "Hls instance"); const config = this.config = mergeConfig(_Hls.DefaultConfig, userConfig); this.userConfig = userConfig; if (config.progressive) { enableStreamingMode(config); } const { abrController: ConfigAbrController, bufferController: ConfigBufferController, capLevelController: ConfigCapLevelController, errorController: ConfigErrorController, fpsController: ConfigFpsController } = config; const errorController = new ConfigErrorController(this); const abrController = this.abrController = new ConfigAbrController(this); const bufferController = this.bufferController = new ConfigBufferController(this); const capLevelController = this.capLevelController = new ConfigCapLevelController(this); const fpsController = new ConfigFpsController(this); const playListLoader = new PlaylistLoader(this); const id3TrackController = new ID3TrackController(this); const ConfigContentSteeringController = config.contentSteeringController; const contentSteering = ConfigContentSteeringController ? new ConfigContentSteeringController(this) : null; const levelController = this.levelController = new LevelController(this, contentSteering); const fragmentTracker = new FragmentTracker(this); const keyLoader = new KeyLoader(this.config); const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader); capLevelController.setStreamController(streamController); fpsController.setStreamController(streamController); const networkControllers = [playListLoader, levelController, streamController]; if (contentSteering) { networkControllers.splice(1, 0, contentSteering); } this.networkControllers = networkControllers; const coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; this.audioTrackController = this.createController(config.audioTrackController, networkControllers); const AudioStreamControllerClass = config.audioStreamController; if (AudioStreamControllerClass) { networkControllers.push(new AudioStreamControllerClass(this, fragmentTracker, keyLoader)); } this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers); const SubtitleStreamControllerClass = config.subtitleStreamController; if (SubtitleStreamControllerClass) { networkControllers.push(new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader)); } this.createController(config.timelineController, coreComponents); keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents); this.cmcdController = this.createController(config.cmcdController, coreComponents); this.latencyController = this.createController(LatencyController, coreComponents); this.coreComponents = coreComponents; networkControllers.push(errorController); const onErrorOut = errorController.onErrorOut; if (typeof onErrorOut === "function") { this.on(Events.ERROR, onErrorOut, errorController); } } createController(ControllerClass, components2) { if (ControllerClass) { const controllerInstance = new ControllerClass(this); if (components2) { components2.push(controllerInstance); } return controllerInstance; } return null; } // Delegate the EventEmitter through the public API of Hls.js on(event, listener, context = this) { this._emitter.on(event, listener, context); } once(event, listener, context = this) { this._emitter.once(event, listener, context); } removeAllListeners(event) { this._emitter.removeAllListeners(event); } off(event, listener, context = this, once) { this._emitter.off(event, listener, context, once); } listeners(event) { return this._emitter.listeners(event); } emit(event, name, eventObject) { return this._emitter.emit(event, name, eventObject); } trigger(event, eventObject) { if (this.config.debug) { return this.emit(event, event, eventObject); } else { try { return this.emit(event, event, eventObject); } catch (error) { logger.error("An internal error happened while handling event " + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error); if (!this.triggeringException) { this.triggeringException = true; const fatal = event === Events.ERROR; this.trigger(Events.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal, event, error }); this.triggeringException = false; } } } return false; } listenerCount(event) { return this._emitter.listenerCount(event); } /** * Dispose of the instance */ destroy() { logger.log("destroy"); this.trigger(Events.DESTROYING, void 0); this.detachMedia(); this.removeAllListeners(); this._autoLevelCapping = -1; this.url = null; this.networkControllers.forEach((component) => component.destroy()); this.networkControllers.length = 0; this.coreComponents.forEach((component) => component.destroy()); this.coreComponents.length = 0; const config = this.config; config.xhrSetup = config.fetchSetup = void 0; this.userConfig = null; } /** * Attaches Hls.js to a media element */ attachMedia(media) { logger.log("attachMedia"); this._media = media; this.trigger(Events.MEDIA_ATTACHING, { media }); } /** * Detach Hls.js from the media */ detachMedia() { logger.log("detachMedia"); this.trigger(Events.MEDIA_DETACHING, void 0); this._media = null; } /** * Set the source URL. Can be relative or absolute. */ loadSource(url) { this.stopLoad(); const media = this.media; const loadedSource = this.url; const loadingSource = this.url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, { alwaysNormalize: true }); this._autoLevelCapping = -1; this._maxHdcpLevel = null; logger.log(`loadSource:${loadingSource}`); if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) { this.detachMedia(); this.attachMedia(media); } this.trigger(Events.MANIFEST_LOADING, { url }); } /** * Start loading data from the stream source. * Depending on default config, client starts loading automatically when a source is set. * * @param startPosition - Set the start position to stream from. * Defaults to -1 (None: starts from earliest point) */ startLoad(startPosition = -1) { logger.log(`startLoad(${startPosition})`); this.started = true; this.resumeBuffering(); for (let i3 = 0; i3 < this.networkControllers.length; i3++) { this.networkControllers[i3].startLoad(startPosition); if (!this.started || !this.networkControllers) { break; } } } /** * Stop loading of any stream data. */ stopLoad() { logger.log("stopLoad"); this.started = false; for (let i3 = 0; i3 < this.networkControllers.length; i3++) { this.networkControllers[i3].stopLoad(); if (this.started || !this.networkControllers) { break; } } } /** * Resumes stream controller segment loading after `pauseBuffering` has been called. */ resumeBuffering() { logger.log(`resume buffering`); this.networkControllers.forEach((controller) => { if (controller.resumeBuffering) { controller.resumeBuffering(); } }); } /** * Prevents stream controller from loading new segments until `resumeBuffering` is called. * This allows for media buffering to be paused without interupting playlist loading. */ pauseBuffering() { logger.log(`pause buffering`); this.networkControllers.forEach((controller) => { if (controller.pauseBuffering) { controller.pauseBuffering(); } }); } /** * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1) */ swapAudioCodec() { logger.log("swapAudioCodec"); this.streamController.swapAudioCodec(); } /** * When the media-element fails, this allows to detach and then re-attach it * as one call (convenience method). * * Automatic recovery of media-errors by this process is configurable. */ recoverMediaError() { logger.log("recoverMediaError"); const media = this._media; this.detachMedia(); if (media) { this.attachMedia(media); } } removeLevel(levelIndex) { this.levelController.removeLevel(levelIndex); } /** * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH */ get levels() { const levels = this.levelController.levels; return levels ? levels : []; } /** * Index of quality level (variant) currently played */ get currentLevel() { return this.streamController.currentLevel; } /** * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection. */ set currentLevel(newLevel) { logger.log(`set currentLevel:${newLevel}`); this.levelController.manualLevel = newLevel; this.streamController.immediateLevelSwitch(); } /** * Index of next quality level loaded as scheduled by stream controller. */ get nextLevel() { return this.streamController.nextLevel; } /** * Set quality level index for next loaded data. * This will switch the video quality asap, without interrupting playback. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region). * @param newLevel - Pass -1 for automatic level selection */ set nextLevel(newLevel) { logger.log(`set nextLevel:${newLevel}`); this.levelController.manualLevel = newLevel; this.streamController.nextLevelSwitch(); } /** * Return the quality level of the currently or last (of none is loaded currently) segment */ get loadLevel() { return this.levelController.level; } /** * Set quality level index for next loaded data in a conservative way. * This will switch the quality without flushing, but interrupt current loading. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer. * @param newLevel - Pass -1 for automatic level selection */ set loadLevel(newLevel) { logger.log(`set loadLevel:${newLevel}`); this.levelController.manualLevel = newLevel; } /** * get next quality level loaded */ get nextLoadLevel() { return this.levelController.nextLoadLevel; } /** * Set quality level of next loaded segment in a fully "non-destructive" way. * Same as `loadLevel` but will wait for next switch (until current loading is done). */ set nextLoadLevel(level) { this.levelController.nextLoadLevel = level; } /** * Return "first level": like a default level, if not set, * falls back to index of first level referenced in manifest */ get firstLevel() { return Math.max(this.levelController.firstLevel, this.minAutoLevel); } /** * Sets "first-level", see getter. */ set firstLevel(newLevel) { logger.log(`set firstLevel:${newLevel}`); this.levelController.firstLevel = newLevel; } /** * Return the desired start level for the first fragment that will be loaded. * The default value of -1 indicates automatic start level selection. * Setting hls.nextAutoLevel without setting a startLevel will result in * the nextAutoLevel value being used for one fragment load. */ get startLevel() { const startLevel = this.levelController.startLevel; if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) { return this.abrController.forcedAutoLevel; } return startLevel; } /** * set start level (level of first fragment that will be played back) * if not overrided by user, first level appearing in manifest will be used as start level * if -1 : automatic start level selection, playback will start from level matching download bandwidth * (determined from download of first segment) */ set startLevel(newLevel) { logger.log(`set startLevel:${newLevel}`); if (newLevel !== -1) { newLevel = Math.max(newLevel, this.minAutoLevel); } this.levelController.startLevel = newLevel; } /** * Whether level capping is enabled. * Default value is set via `config.capLevelToPlayerSize`. */ get capLevelToPlayerSize() { return this.config.capLevelToPlayerSize; } /** * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called. */ set capLevelToPlayerSize(shouldStartCapping) { const newCapLevelToPlayerSize = !!shouldStartCapping; if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) { if (newCapLevelToPlayerSize) { this.capLevelController.startCapping(); } else { this.capLevelController.stopCapping(); this.autoLevelCapping = -1; this.streamController.nextLevelSwitch(); } this.config.capLevelToPlayerSize = newCapLevelToPlayerSize; } } /** * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) */ get autoLevelCapping() { return this._autoLevelCapping; } /** * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned. */ get bandwidthEstimate() { const { bwEstimator } = this.abrController; if (!bwEstimator) { return NaN; } return bwEstimator.getEstimate(); } set bandwidthEstimate(abrEwmaDefaultEstimate) { this.abrController.resetEstimator(abrEwmaDefaultEstimate); } /** * get time to first byte estimate * @type {number} */ get ttfbEstimate() { const { bwEstimator } = this.abrController; if (!bwEstimator) { return NaN; } return bwEstimator.getEstimateTTFB(); } /** * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) */ set autoLevelCapping(newLevel) { if (this._autoLevelCapping !== newLevel) { logger.log(`set autoLevelCapping:${newLevel}`); this._autoLevelCapping = newLevel; this.levelController.checkMaxAutoUpdated(); } } get maxHdcpLevel() { return this._maxHdcpLevel; } set maxHdcpLevel(value) { if (isHdcpLevel(value) && this._maxHdcpLevel !== value) { this._maxHdcpLevel = value; this.levelController.checkMaxAutoUpdated(); } } /** * True when automatic level selection enabled */ get autoLevelEnabled() { return this.levelController.manualLevel === -1; } /** * Level set manually (if any) */ get manualLevel() { return this.levelController.manualLevel; } /** * min level selectable in auto mode according to config.minAutoBitrate */ get minAutoLevel() { const { levels, config: { minAutoBitrate } } = this; if (!levels) return 0; const len = levels.length; for (let i3 = 0; i3 < len; i3++) { if (levels[i3].maxBitrate >= minAutoBitrate) { return i3; } } return 0; } /** * max level selectable in auto mode according to autoLevelCapping */ get maxAutoLevel() { const { levels, autoLevelCapping, maxHdcpLevel } = this; let maxAutoLevel; if (autoLevelCapping === -1 && levels != null && levels.length) { maxAutoLevel = levels.length - 1; } else { maxAutoLevel = autoLevelCapping; } if (maxHdcpLevel) { for (let i3 = maxAutoLevel; i3--; ) { const hdcpLevel = levels[i3].attrs["HDCP-LEVEL"]; if (hdcpLevel && hdcpLevel <= maxHdcpLevel) { return i3; } } } return maxAutoLevel; } get firstAutoLevel() { return this.abrController.firstAutoLevel; } /** * next automatically selected quality level */ get nextAutoLevel() { return this.abrController.nextAutoLevel; } /** * this setter is used to force next auto level. * this is useful to force a switch down in auto mode: * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example) * forced value is valid for one fragment. upon successful frag loading at forced level, * this value will be resetted to -1 by ABR controller. */ set nextAutoLevel(nextLevel) { this.abrController.nextAutoLevel = nextLevel; } /** * get the datetime value relative to media.currentTime for the active level Program Date Time if present */ get playingDate() { return this.streamController.currentProgramDateTime; } get mainForwardBufferInfo() { return this.streamController.getMainFwdBufferInfo(); } /** * Find and select the best matching audio track, making a level switch when a Group change is necessary. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found. */ setAudioOption(audioOption) { var _this$audioTrackContr; return (_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption); } /** * Find and select the best matching subtitle track, making a level switch when a Group change is necessary. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found. */ setSubtitleOption(subtitleOption) { var _this$subtitleTrackCo; (_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption); return null; } /** * Get the complete list of audio tracks across all media groups */ get allAudioTracks() { const audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.allAudioTracks : []; } /** * Get the list of selectable audio tracks */ get audioTracks() { const audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.audioTracks : []; } /** * index of the selected audio track (index in audio track lists) */ get audioTrack() { const audioTrackController = this.audioTrackController; return audioTrackController ? audioTrackController.audioTrack : -1; } /** * selects an audio track, based on its index in audio track lists */ set audioTrack(audioTrackId) { const audioTrackController = this.audioTrackController; if (audioTrackController) { audioTrackController.audioTrack = audioTrackId; } } /** * get the complete list of subtitle tracks across all media groups */ get allSubtitleTracks() { const subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : []; } /** * get alternate subtitle tracks list from playlist */ get subtitleTracks() { const subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; } /** * index of the selected subtitle track (index in subtitle track lists) */ get subtitleTrack() { const subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1; } get media() { return this._media; } /** * select an subtitle track, based on its index in subtitle track lists */ set subtitleTrack(subtitleTrackId) { const subtitleTrackController = this.subtitleTrackController; if (subtitleTrackController) { subtitleTrackController.subtitleTrack = subtitleTrackId; } } /** * Whether subtitle display is enabled or not */ get subtitleDisplay() { const subtitleTrackController = this.subtitleTrackController; return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; } /** * Enable/disable subtitle display rendering */ set subtitleDisplay(value) { const subtitleTrackController = this.subtitleTrackController; if (subtitleTrackController) { subtitleTrackController.subtitleDisplay = value; } } /** * get mode for Low-Latency HLS loading */ get lowLatencyMode() { return this.config.lowLatencyMode; } /** * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK. */ set lowLatencyMode(mode) { this.config.lowLatencyMode = mode; } /** * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```) * @returns null prior to loading live Playlist */ get liveSyncPosition() { return this.latencyController.liveSyncPosition; } /** * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced) * @returns 0 before first playlist is loaded */ get latency() { return this.latencyController.latency; } /** * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition``` * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration``` * @returns 0 before first playlist is loaded */ get maxLatency() { return this.latencyController.maxLatency; } /** * target distance from the edge as calculated by the latency controller */ get targetLatency() { return this.latencyController.targetLatency; } /** * the rate at which the edge of the current live playlist is advancing or 1 if there is none */ get drift() { return this.latencyController.drift; } /** * set to true when startLoad is called before MANIFEST_PARSED event */ get forceStartLoad() { return this.streamController.forceStartLoad; } }; Hls.defaultConfig = void 0; // node_modules/@mux/playback-core/dist/index.mjs var R = Hls; var C2 = { VIDEO: "video", THUMBNAIL: "thumbnail", STORYBOARD: "storyboard", DRM: "drm" }; var M = { NOT_AN_ERROR: 0, NETWORK_OFFLINE: 2000002, NETWORK_UNKNOWN_ERROR: 2e6, NETWORK_NO_STATUS: 2000001, NETWORK_INVALID_URL: 24e5, NETWORK_NOT_FOUND: 2404e3, NETWORK_NOT_READY: 2412e3, NETWORK_GENERIC_SERVER_FAIL: 25e5, NETWORK_TOKEN_MISSING: 2403201, NETWORK_TOKEN_MALFORMED: 2412202, NETWORK_TOKEN_EXPIRED: 2403210, NETWORK_TOKEN_AUD_MISSING: 2403221, NETWORK_TOKEN_AUD_MISMATCH: 2403222, NETWORK_TOKEN_SUB_MISMATCH: 2403232, ENCRYPTED_ERROR: 5e6, ENCRYPTED_UNSUPPORTED_KEY_SYSTEM: 5000001, ENCRYPTED_GENERATE_REQUEST_FAILED: 5000002, ENCRYPTED_UPDATE_LICENSE_FAILED: 5000003, ENCRYPTED_UPDATE_SERVER_CERT_FAILED: 5000004, ENCRYPTED_CDM_ERROR: 5000005, ENCRYPTED_OUTPUT_RESTRICTED: 5000006, ENCRYPTED_MISSING_TOKEN: 5000002 }; var H2 = (e) => e === C2.VIDEO ? "playback" : e; var k = class k2 extends Error { constructor(t2, r9 = k2.MEDIA_ERR_CUSTOM, n2, o2) { var a2; super(t2), this.name = "MediaError", this.code = r9, this.context = o2, this.fatal = n2 != null ? n2 : r9 >= k2.MEDIA_ERR_NETWORK && r9 <= k2.MEDIA_ERR_ENCRYPTED, this.message || (this.message = (a2 = k2.defaultMessages[this.code]) != null ? a2 : ""); } }; k.MEDIA_ERR_ABORTED = 1, k.MEDIA_ERR_NETWORK = 2, k.MEDIA_ERR_DECODE = 3, k.MEDIA_ERR_SRC_NOT_SUPPORTED = 4, k.MEDIA_ERR_ENCRYPTED = 5, k.MEDIA_ERR_CUSTOM = 100, k.defaultMessages = { 1: "You aborted the media playback", 2: "A network error caused the media download to fail.", 3: "A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.", 4: "An unsupported error occurred. The server or network failed, or your browser does not support this format.", 5: "The media is encrypted and there are no keys to decrypt it." }; var T = k; var je = (e) => e == null; var S = (e, t2) => je(t2) ? false : e in t2; var V2 = { ANY: "any", MUTED: "muted" }; var D2 = { ON_DEMAND: "on-demand", LIVE: "live", UNKNOWN: "unknown" }; var q2 = { MSE: "mse", NATIVE: "native" }; var w2 = { HEADER: "header", QUERY: "query", NONE: "none" }; var Ut2 = Object.values(w2); var N = { M3U8: "application/vnd.apple.mpegurl", MP4: "video/mp4" }; var F2 = { HLS: N.M3U8 }; var Ht2 = Object.keys(F2); var Vt2 = [...Object.values(N), "hls", "HLS"]; var ze2 = "en"; var K = { code: ze2 }; var x = (e, t2, r9, n2, o2 = e) => { o2.addEventListener(t2, r9, n2), e.addEventListener("teardown", () => { o2.removeEventListener(t2, r9); }, { once: true }); }; function de2(e, t2, r9) { t2 && r9 > t2 && (r9 = t2); for (let n2 = 0; n2 < e.length; n2++) if (e.start(n2) <= r9 && e.end(n2) >= r9) return true; return false; } var Y2 = (e) => { let t2 = e.indexOf("?"); if (t2 < 0) return [e]; let r9 = e.slice(0, t2), n2 = e.slice(t2); return [r9, n2]; }; var O2 = (e) => { let t2 = e.type; if (t2) { let n2 = t2.toUpperCase(); return S(n2, F2) ? F2[n2] : t2; } let { src: r9 } = e; return r9 ? Xe2(r9) : ""; }; var z = (e) => e === "VOD" ? D2.ON_DEMAND : D2.LIVE; var X2 = (e) => e === "EVENT" ? Number.POSITIVE_INFINITY : e === "VOD" ? Number.NaN : 0; var Xe2 = (e) => { let t2 = ""; try { t2 = new URL(e).pathname; } catch { console.error("invalid url"); } let r9 = t2.lastIndexOf("."); if (r9 < 0) return ""; let o2 = t2.slice(r9 + 1).toUpperCase(); return S(o2, N) ? N[o2] : ""; }; var Q2 = (e) => { let t2 = (e != null ? e : "").split(".")[1]; if (t2) try { let r9 = t2.replace(/-/g, "+").replace(/_/g, "/"), n2 = decodeURIComponent(atob(r9).split("").map(function(o2) { return "%" + ("00" + o2.charCodeAt(0).toString(16)).slice(-2); }).join("")); return JSON.parse(n2); } catch { return; } }; var le2 = ({ exp: e }, t2 = Date.now()) => !e || e * 1e3 < t2; var pe2 = ({ sub: e }, t2) => e !== t2; var fe2 = ({ aud: e }, t2) => !e; var Te = ({ aud: e }, t2) => e !== t2; var ye2 = "en"; function E(e, t2 = true) { var o2, a2; let r9 = t2 && (a2 = (o2 = K) == null ? void 0 : o2[e]) != null ? a2 : e, n2 = t2 ? K.code : ye2; return new j(r9, n2); } var j = class { constructor(t2, r9 = ((n2) => (n2 = K) != null ? n2 : ye2)()) { this.message = t2, this.locale = r9; } format(t2) { return this.message.replace(/\{(\w+)\}/g, (r9, n2) => { var o2; return (o2 = t2[n2]) != null ? o2 : ""; }); } toString() { return this.message; } }; var Qe2 = Object.values(V2); var me = (e) => typeof e == "boolean" || typeof e == "string" && Qe2.includes(e); var Ee = (e, t2, r9) => { let { autoplay: n2 } = e, o2 = false, a2 = false, s = me(n2) ? n2 : !!n2, u3 = () => { o2 || x(t2, "playing", () => { o2 = true; }, { once: true }); }; if (u3(), x(t2, "loadstart", () => { o2 = false, u3(), Z(t2, s); }, { once: true }), x(t2, "loadstart", () => { r9 || (e.streamType && e.streamType !== D2.UNKNOWN ? a2 = e.streamType === D2.LIVE : a2 = !Number.isFinite(t2.duration)), Z(t2, s); }, { once: true }), r9 && r9.once(R.Events.LEVEL_LOADED, (c3, i3) => { var d2; e.streamType && e.streamType !== D2.UNKNOWN ? a2 = e.streamType === D2.LIVE : a2 = (d2 = i3.details.live) != null ? d2 : false; }), !s) { let c3 = () => { !a2 || Number.isFinite(e.startTime) || (r9 != null && r9.liveSyncPosition ? t2.currentTime = r9.liveSyncPosition : Number.isFinite(t2.seekable.end(0)) && (t2.currentTime = t2.seekable.end(0))); }; r9 && x(t2, "play", () => { t2.preload === "metadata" ? r9.once(R.Events.LEVEL_UPDATED, c3) : c3(); }, { once: true }); } return (c3) => { o2 || (s = me(c3) ? c3 : !!c3, Z(t2, s)); }; }; var Z = (e, t2) => { if (!t2) return; let r9 = e.muted, n2 = () => e.muted = r9; switch (t2) { case V2.ANY: e.play().catch(() => { e.muted = true, e.play().catch(n2); }); break; case V2.MUTED: e.muted = true, e.play().catch(n2); break; default: e.play().catch(() => { }); break; } }; var ge2 = ({ preload: e, src: t2 }, r9, n2) => { let o2 = (d2) => { d2 != null && ["", "none", "metadata", "auto"].includes(d2) ? r9.setAttribute("preload", d2) : r9.removeAttribute("preload"); }; if (!n2) return o2(e), o2; let a2 = false, s = false, u3 = n2.config.maxBufferLength, l2 = n2.config.maxBufferSize, c3 = (d2) => { o2(d2); let p3 = d2 != null ? d2 : r9.preload; s || p3 === "none" || (p3 === "metadata" ? (n2.config.maxBufferLength = 1, n2.config.maxBufferSize = 1) : (n2.config.maxBufferLength = u3, n2.config.maxBufferSize = l2), i3()); }, i3 = () => { !a2 && t2 && (a2 = true, n2.loadSource(t2)); }; return x(r9, "play", () => { s = true, n2.config.maxBufferLength = u3, n2.config.maxBufferSize = l2, i3(); }, { once: true }), c3(e), c3; }; function Me2(e, t2) { var l2; if (!("videoTracks" in e)) return; let r9 = /* @__PURE__ */ new WeakMap(); t2.on(R.Events.MANIFEST_PARSED, function(c3, i3) { u3(); let d2 = e.addVideoTrack("main"); d2.selected = true; for (let [p3, f] of i3.levels.entries()) { let y4 = d2.addRendition(f.url[0], f.width, f.height, f.videoCodec, f.bitrate); r9.set(f, `${p3}`), y4.id = `${p3}`; } }), t2.on(R.Events.AUDIO_TRACKS_UPDATED, function(c3, i3) { s(); for (let d2 of i3.audioTracks) { let p3 = d2.default ? "main" : "alternative", f = e.addAudioTrack(p3, d2.name, d2.lang); f.id = `${d2.id}`, d2.default && (f.enabled = true); } }), e.audioTracks.addEventListener("change", () => { var d2; let c3 = +((d2 = [...e.audioTracks].find((p3) => p3.enabled)) == null ? void 0 : d2.id), i3 = t2.audioTracks.map((p3) => p3.id); c3 != t2.audioTrack && i3.includes(c3) && (t2.audioTrack = c3); }), t2.on(R.Events.LEVELS_UPDATED, function(c3, i3) { var f; let d2 = e.videoTracks[(f = e.videoTracks.selectedIndex) != null ? f : 0]; if (!d2) return; let p3 = i3.levels.map((y4) => r9.get(y4)); for (let y4 of e.videoRenditions) y4.id && !p3.includes(y4.id) && d2.removeRendition(y4); }); let n2 = (c3) => { let i3 = c3.target.selectedIndex; i3 != t2.nextLevel && o2(i3); }, o2 = (c3) => { let i3 = e.currentTime, d2 = false, p3 = (f, y4) => { d2 || (d2 = !Number.isFinite(y4.endOffset)); }; t2.on(R.Events.BUFFER_FLUSHING, p3), t2.nextLevel = c3, t2.off(R.Events.BUFFER_FLUSHING, p3), d2 || t2.trigger(R.Events.BUFFER_FLUSHING, { startOffset: i3 + 10, endOffset: 1 / 0, type: "video" }); }; (l2 = e.videoRenditions) == null || l2.addEventListener("change", n2); let a2 = () => { for (let c3 of e.videoTracks) e.removeVideoTrack(c3); }, s = () => { for (let c3 of e.audioTracks) e.removeAudioTrack(c3); }, u3 = () => { a2(), s(); }; t2.once(R.Events.DESTROYING, u3); } var ee2 = (e) => "time" in e ? e.time : e.startTime; function Re(e, t2) { t2.on(R.Events.NON_NATIVE_TEXT_TRACKS_FOUND, (o2, { tracks: a2 }) => { a2.forEach((s) => { var i3, d2; let u3 = (i3 = s.subtitleTrack) != null ? i3 : s.closedCaptions, l2 = t2.subtitleTracks.findIndex(({ lang: p3, name: f, type: y4 }) => p3 == (u3 == null ? void 0 : u3.lang) && f === s.label && y4.toLowerCase() === s.kind), c3 = ((d2 = s._id) != null ? d2 : s.default) ? "default" : `${s.kind}${l2}`; te2(e, s.kind, s.label, u3 == null ? void 0 : u3.lang, c3, s.default); }); }); let r9 = () => { if (!t2.subtitleTracks.length) return; let o2 = Array.from(e.textTracks).find((u3) => u3.id && u3.mode === "showing" && ["subtitles", "captions"].includes(u3.kind)); if (!o2) return; let a2 = t2.subtitleTracks[t2.subtitleTrack], s = a2 ? a2.default ? "default" : `${t2.subtitleTracks[t2.subtitleTrack].type.toLowerCase()}${t2.subtitleTrack}` : void 0; if (t2.subtitleTrack < 0 || (o2 == null ? void 0 : o2.id) !== s) { let u3 = t2.subtitleTracks.findIndex(({ lang: l2, name: c3, type: i3, default: d2 }) => o2.id === "default" && d2 || l2 == o2.language && c3 === o2.label && i3.toLowerCase() === o2.kind); t2.subtitleTrack = u3; } (o2 == null ? void 0 : o2.id) === s && o2.cues && Array.from(o2.cues).forEach((u3) => { o2.addCue(u3); }); }; e.textTracks.addEventListener("change", r9), t2.on(R.Events.CUES_PARSED, (o2, { track: a2, cues: s }) => { let u3 = e.textTracks.getTrackById(a2); if (!u3) return; let l2 = u3.mode === "disabled"; l2 && (u3.mode = "hidden"), s.forEach((c3) => { var i3; (i3 = u3.cues) != null && i3.getCueById(c3.id) || u3.addCue(c3); }), l2 && (u3.mode = "disabled"); }), t2.once(R.Events.DESTROYING, () => { e.textTracks.removeEventListener("change", r9), e.querySelectorAll("track[data-removeondestroy]").forEach((a2) => { a2.remove(); }); }); let n2 = () => { Array.from(e.textTracks).forEach((o2) => { var a2, s; if (!["subtitles", "caption"].includes(o2.kind) && (o2.label === "thumbnails" || o2.kind === "chapters")) { if (!((a2 = o2.cues) != null && a2.length)) { let u3 = "track"; o2.kind && (u3 += `[kind="${o2.kind}"]`), o2.label && (u3 += `[label="${o2.label}"]`); let l2 = e.querySelector(u3), c3 = (s = l2 == null ? void 0 : l2.getAttribute("src")) != null ? s : ""; l2 == null || l2.removeAttribute("src"), setTimeout(() => { l2 == null || l2.setAttribute("src", c3); }, 0); } o2.mode !== "hidden" && (o2.mode = "hidden"); } }); }; t2.once(R.Events.MANIFEST_LOADED, n2), t2.once(R.Events.MEDIA_ATTACHED, n2); } function te2(e, t2, r9, n2, o2, a2) { let s = document.createElement("track"); return s.kind = t2, s.label = r9, n2 && (s.srclang = n2), o2 && (s.id = o2), a2 && (s.default = true), s.track.mode = ["subtitles", "captions"].includes(t2) ? "disabled" : "hidden", s.setAttribute("data-removeondestroy", ""), e.append(s), s.track; } function Ze2(e, t2) { let r9 = Array.prototype.find.call(e.querySelectorAll("track"), (n2) => n2.track === t2); r9 == null || r9.remove(); } function A2(e, t2, r9) { var n2; return (n2 = Array.from(e.querySelectorAll("track")).find((o2) => o2.track.label === t2 && o2.track.kind === r9)) == null ? void 0 : n2.track; } async function Ce2(e, t2, r9, n2) { let o2 = A2(e, r9, n2); return o2 || (o2 = te2(e, n2, r9), o2.mode = "hidden", await new Promise((a2) => setTimeout(() => a2(void 0), 0))), o2.mode !== "hidden" && (o2.mode = "hidden"), [...t2].sort((a2, s) => ee2(s) - ee2(a2)).forEach((a2) => { var l2, c3; let s = a2.value, u3 = ee2(a2); if ("endTime" in a2 && a2.endTime != null) o2 == null || o2.addCue(new VTTCue(u3, a2.endTime, n2 === "chapters" ? s : JSON.stringify(s != null ? s : null))); else { let i3 = Array.prototype.findIndex.call(o2 == null ? void 0 : o2.cues, (y4) => y4.startTime >= u3), d2 = (l2 = o2 == null ? void 0 : o2.cues) == null ? void 0 : l2[i3], p3 = d2 ? d2.startTime : Number.isFinite(e.duration) ? e.duration : Number.MAX_SAFE_INTEGER, f = (c3 = o2 == null ? void 0 : o2.cues) == null ? void 0 : c3[i3 - 1]; f && (f.endTime = u3), o2 == null || o2.addCue(new VTTCue(u3, p3, n2 === "chapters" ? s : JSON.stringify(s != null ? s : null))); } }), e.textTracks.dispatchEvent(new Event("change", { bubbles: true, composed: true })), o2; } var re2 = "cuepoints"; var be2 = Object.freeze({ label: re2 }); async function xe(e, t2, r9 = be2) { return Ce2(e, t2, r9.label, "metadata"); } var W2 = (e) => ({ time: e.startTime, value: JSON.parse(e.text) }); function et(e, t2 = { label: re2 }) { let r9 = A2(e, t2.label, "metadata"); return r9 != null && r9.cues ? Array.from(r9.cues, (n2) => W2(n2)) : []; } function ve2(e, t2 = { label: re2 }) { var a2, s; let r9 = A2(e, t2.label, "metadata"); if (!((a2 = r9 == null ? void 0 : r9.activeCues) != null && a2.length)) return; if (r9.activeCues.length === 1) return W2(r9.activeCues[0]); let { currentTime: n2 } = e, o2 = Array.prototype.find.call((s = r9.activeCues) != null ? s : [], ({ startTime: u3, endTime: l2 }) => u3 <= n2 && l2 > n2); return W2(o2 || r9.activeCues[0]); } async function Pe2(e, t2 = be2) { return new Promise((r9) => { x(e, "loadstart", async () => { let n2 = await xe(e, [], t2); x(e, "cuechange", () => { let o2 = ve2(e); if (o2) { let a2 = new CustomEvent("cuepointchange", { composed: true, bubbles: true, detail: o2 }); e.dispatchEvent(a2); } }, {}, n2), r9(n2); }); }); } var ne2 = "chapters"; var De2 = Object.freeze({ label: ne2 }); var $2 = (e) => ({ startTime: e.startTime, endTime: e.endTime, value: e.text }); async function _e2(e, t2, r9 = De2) { return Ce2(e, t2, r9.label, "chapters"); } function tt(e, t2 = { label: ne2 }) { var n2; let r9 = A2(e, t2.label, "chapters"); return (n2 = r9 == null ? void 0 : r9.cues) != null && n2.length ? Array.from(r9.cues, (o2) => $2(o2)) : []; } function ke2(e, t2 = { label: ne2 }) { var a2, s; let r9 = A2(e, t2.label, "chapters"); if (!((a2 = r9 == null ? void 0 : r9.activeCues) != null && a2.length)) return; if (r9.activeCues.length === 1) return $2(r9.activeCues[0]); let { currentTime: n2 } = e, o2 = Array.prototype.find.call((s = r9.activeCues) != null ? s : [], ({ startTime: u3, endTime: l2 }) => u3 <= n2 && l2 > n2); return $2(o2 || r9.activeCues[0]); } async function he2(e, t2 = De2) { return new Promise((r9) => { x(e, "loadstart", async () => { let n2 = await _e2(e, [], t2); x(e, "cuechange", () => { let o2 = ke2(e); if (o2) { let a2 = new CustomEvent("chapterchange", { composed: true, bubbles: true, detail: o2 }); e.dispatchEvent(a2); } }, {}, n2), r9(n2); }); }); } function rt2(e, t2) { if (t2) { let r9 = t2.playingDate; if (r9 != null) return new Date(r9.getTime() - e.currentTime * 1e3); } return typeof e.getStartDate == "function" ? e.getStartDate() : /* @__PURE__ */ new Date(NaN); } function nt3(e, t2) { if (t2 && t2.playingDate) return t2.playingDate; if (typeof e.getStartDate == "function") { let r9 = e.getStartDate(); return new Date(r9.getTime() + e.currentTime * 1e3); } return /* @__PURE__ */ new Date(NaN); } var oe = { VIDEO: "v", THUMBNAIL: "t", STORYBOARD: "s", DRM: "d" }; var ot2 = (e) => { if (e === C2.VIDEO) return oe.VIDEO; if (e === C2.DRM) return oe.DRM; }; var at = (e, t2) => { var o2, a2; let r9 = H2(e), n2 = `${r9}Token`; return (o2 = t2.tokens) != null && o2[r9] ? (a2 = t2.tokens) == null ? void 0 : a2[r9] : S(n2, t2) ? t2[n2] : void 0; }; var U2 = (e, t2, r9, n2 = false, o2 = !((a2) => (a2 = globalThis.navigator) == null ? void 0 : a2.onLine)()) => { var v2, P2; if (o2) { let g2 = E("Your device appears to be offline", n2), b2 = void 0, m2 = T.MEDIA_ERR_NETWORK, h3 = new T(g2, m2, true, b2); return h3.errorCategory = t2, h3.muxCode = M.NETWORK_OFFLINE, h3.data = e, h3; } let s = "status" in e ? e.status : e.code, u3 = Date.now(), l2 = T.MEDIA_ERR_NETWORK; if (s === 200) return; let c3 = H2(t2), i3 = at(t2, r9), d2 = ot2(t2), [p3] = Y2((v2 = r9.playbackId) != null ? v2 : ""); if (!s || !p3) return; let f = Q2(i3); if (i3 && !f) { let g2 = E("The {tokenNamePrefix}-token provided is invalid or malformed.", n2).format({ tokenNamePrefix: c3 }), b2 = E("Compact JWT string: {token}", n2).format({ token: i3 }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_TOKEN_MALFORMED, m2.data = e, m2; } if (s >= 500) { let g2 = new T("", l2, true); return g2.errorCategory = t2, g2.muxCode = M.NETWORK_UNKNOWN_ERROR, g2; } if (s === 403) if (f) { if (le2(f, u3)) { let g2 = { timeStyle: "medium", dateStyle: "medium" }, b2 = E("The video’s secured {tokenNamePrefix}-token has expired.", n2).format({ tokenNamePrefix: c3 }), m2 = E("Expired at: {expiredDate}. Current time: {currentDate}.", n2).format({ expiredDate: new Intl.DateTimeFormat("en", g2).format((P2 = f.exp) != null ? P2 : 0 * 1e3), currentDate: new Intl.DateTimeFormat("en", g2).format(u3) }), h3 = new T(b2, l2, true, m2); return h3.errorCategory = t2, h3.muxCode = M.NETWORK_TOKEN_EXPIRED, h3.data = e, h3; } if (pe2(f, p3)) { let g2 = E("The video’s playback ID does not match the one encoded in the {tokenNamePrefix}-token.", n2).format({ tokenNamePrefix: c3 }), b2 = E("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}", n2).format({ tokenNamePrefix: c3, playbackId: p3, tokenPlaybackId: f.sub }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_TOKEN_SUB_MISMATCH, m2.data = e, m2; } if (fe2(f, d2)) { let g2 = E("The {tokenNamePrefix}-token is formatted with incorrect information.", n2).format({ tokenNamePrefix: c3 }), b2 = E("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.", n2).format({ tokenNamePrefix: c3, expectedAud: d2 }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_TOKEN_AUD_MISSING, m2.data = e, m2; } if (Te(f, d2)) { let g2 = E("The {tokenNamePrefix}-token is formatted with incorrect information.", n2).format({ tokenNamePrefix: c3 }), b2 = E("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.", n2).format({ tokenNamePrefix: c3, expectedAud: d2, aud: f.aud }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_TOKEN_AUD_MISMATCH, m2.data = e, m2; } } else { let g2 = E("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.", n2).format({ tokenNamePrefix: c3, category: t2 }), b2 = E("Specified playback ID: {playbackId}", n2).format({ playbackId: p3 }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_TOKEN_MISSING, m2.data = e, m2; } if (s === 412) { let g2 = E("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.", n2), b2 = E("Specified playback ID: {playbackId}", n2).format({ playbackId: p3 }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_NOT_READY, m2.data = e, m2; } if (s === 404) { let g2 = E("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.", n2), b2 = E("Specified playback ID: {playbackId}", n2).format({ playbackId: p3 }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_NOT_FOUND, m2.data = e, m2; } if (s === 400) { let g2 = E("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."), b2 = E("Specified playback ID: {playbackId}", n2).format({ playbackId: p3 }), m2 = new T(g2, l2, true, b2); return m2.errorCategory = t2, m2.muxCode = M.NETWORK_INVALID_URL, m2.data = e, m2; } let y4 = new T("", l2, true); return y4.errorCategory = t2, y4.muxCode = M.NETWORK_UNKNOWN_ERROR, y4.data = e, y4; }; var B2 = { FAIRPLAY: "fairplay", PLAYREADY: "playready", WIDEVINE: "widevine" }; var st2 = (e) => { if (e.includes("fps")) return B2.FAIRPLAY; if (e.includes("playready")) return B2.PLAYREADY; if (e.includes("widevine")) return B2.WIDEVINE; }; var it = async (e) => fetch(e).then((t2) => t2.status !== 200 ? Promise.reject(t2) : t2.text()).then((t2) => { let r9 = t2.split(` `).find((n2, o2, a2) => o2 && a2[o2 - 1].startsWith("#EXT-X-STREAM-INF")); return fetch(r9).then((n2) => n2.status !== 200 ? Promise.reject(n2) : n2.text()).then((n2) => n2.split(` `)); }); var ct2 = (e) => { var s, u3, l2; let r9 = (u3 = ((s = e.find((c3) => c3.startsWith("#EXT-X-PLAYLIST-TYPE"))) != null ? s : "").split(":")[1]) == null ? void 0 : u3.trim(), n2 = z(r9), o2 = X2(r9), a2; if (n2 === D2.LIVE) { let c3 = e.find((d2) => d2.startsWith("#EXT-X-PART-INF")); if (!!c3) a2 = +c3.split(":")[1].split("=")[1] * 2; else { let d2 = e.find((y4) => y4.startsWith("#EXT-X-TARGETDURATION")), p3 = (l2 = d2 == null ? void 0 : d2.split(":")) == null ? void 0 : l2[1]; a2 = +(p3 != null ? p3 : 6) * 3; } } return { streamType: n2, targetLiveWindow: o2, liveEdgeStartOffset: a2 }; }; var ut2 = async (e, t2) => { if (t2 === N.MP4) return { streamType: D2.ON_DEMAND, targetLiveWindow: Number.NaN, liveEdgeStartOffset: void 0 }; if (t2 === N.M3U8) { let r9 = await it(e); return ct2(r9); } return console.error(`Media type ${t2} is an unrecognized or unsupported type for src ${e}.`), { streamType: void 0, targetLiveWindow: void 0, liveEdgeStartOffset: void 0 }; }; var dt3 = async (e, t2, r9 = O2({ src: e })) => { var s, u3, l2; let { streamType: n2, targetLiveWindow: o2, liveEdgeStartOffset: a2 } = await ut2(e, r9); ((s = _.get(t2)) != null ? s : {}).liveEdgeStartOffset = a2, ((u3 = _.get(t2)) != null ? u3 : {}).targetLiveWindow = o2, t2.dispatchEvent(new CustomEvent("targetlivewindowchange", { composed: true, bubbles: true })), ((l2 = _.get(t2)) != null ? l2 : {}).streamType = n2, t2.dispatchEvent(new CustomEvent("streamtypechange", { composed: true, bubbles: true })); }; var lt2 = (e) => { var s; let t2 = e.type, r9 = z(t2), n2 = X2(t2), o2, a2 = !!((s = e.partList) != null && s.length); return r9 === D2.LIVE && (o2 = a2 ? e.partTarget * 2 : e.targetduration * 3), { streamType: r9, targetLiveWindow: n2, liveEdgeStartOffset: o2, lowLatency: a2 }; }; var pt2 = (e, t2, r9) => { var u3, l2, c3, i3, d2, p3, f, y4; let { streamType: n2, targetLiveWindow: o2, liveEdgeStartOffset: a2, lowLatency: s } = lt2(e); if (n2 === D2.LIVE) { s ? (r9.config.backBufferLength = (u3 = r9.userConfig.backBufferLength) != null ? u3 : 4, r9.config.maxFragLookUpTolerance = (l2 = r9.userConfig.maxFragLookUpTolerance) != null ? l2 : 1e-3, r9.config.abrBandWidthUpFactor = (c3 = r9.userConfig.abrBandWidthUpFactor) != null ? c3 : r9.config.abrBandWidthFactor) : r9.config.backBufferLength = (i3 = r9.userConfig.backBufferLength) != null ? i3 : 8; let v2 = Object.freeze({ get length() { return t2.seekable.length; }, start(P2) { return t2.seekable.start(P2); }, end(P2) { var g2; return P2 > this.length || P2 < 0 || Number.isFinite(t2.duration) ? t2.seekable.end(P2) : (g2 = r9.liveSyncPosition) != null ? g2 : t2.seekable.end(P2); } }); ((d2 = _.get(t2)) != null ? d2 : {}).seekable = v2; } ((p3 = _.get(t2)) != null ? p3 : {}).liveEdgeStartOffset = a2, ((f = _.get(t2)) != null ? f : {}).targetLiveWindow = o2, t2.dispatchEvent(new CustomEvent("targetlivewindowchange", { composed: true, bubbles: true })), ((y4 = _.get(t2)) != null ? y4 : {}).streamType = n2, t2.dispatchEvent(new CustomEvent("streamtypechange", { composed: true, bubbles: true })); }; var Ie2; var Ae2; var ft2 = (Ae2 = (Ie2 = globalThis == null ? void 0 : globalThis.navigator) == null ? void 0 : Ie2.userAgent) != null ? Ae2 : ""; var Se2; var we; var Oe2; var Tt2 = (Oe2 = (we = (Se2 = globalThis == null ? void 0 : globalThis.navigator) == null ? void 0 : Se2.userAgentData) == null ? void 0 : we.platform) != null ? Oe2 : ""; var yt = ft2.toLowerCase().includes("android") || ["x11", "android"].some((e) => Tt2.toLowerCase().includes(e)); var _ = /* @__PURE__ */ new WeakMap(); var I = "mux.com"; var Ue2; var He2; var Ve = (He2 = (Ue2 = R).isSupported) == null ? void 0 : He2.call(Ue2); var mt2 = yt; var Nr = () => Ed.utils.now(); var Et2 = Ed.utils.generateUUID; var Lr2 = ({ playbackId: e, customDomain: t2 = I, maxResolution: r9, minResolution: n2, renditionOrder: o2, programStartTime: a2, programEndTime: s, assetStartTime: u3, assetEndTime: l2, playbackToken: c3, tokens: { playback: i3 = c3 } = {}, extraSourceParams: d2 = {} } = {}) => { if (!e) return; let [p3, f = ""] = Y2(e), y4 = new URL(`https://stream.${t2}/${p3}.m3u8${f}`); return i3 || y4.searchParams.has("token") ? (y4.searchParams.forEach((v2, P2) => { P2 != "token" && y4.searchParams.delete(P2); }), i3 && y4.searchParams.set("token", i3)) : (r9 && y4.searchParams.set("max_resolution", r9), n2 && (y4.searchParams.set("min_resolution", n2), r9 && +r9.slice(0, -1) < +n2.slice(0, -1) && console.error("minResolution must be <= maxResolution", "minResolution", n2, "maxResolution", r9)), o2 && y4.searchParams.set("rendition_order", o2), a2 && y4.searchParams.set("program_start_time", `${a2}`), s && y4.searchParams.set("program_end_time", `${s}`), u3 && y4.searchParams.set("asset_start_time", `${u3}`), l2 && y4.searchParams.set("asset_end_time", `${l2}`), Object.entries(d2).forEach(([v2, P2]) => { P2 != null && y4.searchParams.set(v2, P2); })), y4.toString(); }; var G = (e) => { if (!e) return; let [t2] = e.split("?"); return t2 || void 0; }; var gt2 = (e) => { if (!e || !e.startsWith("https://stream.")) return; let [t2] = new URL(e).pathname.slice(1).split(".m3u8"); return t2 || void 0; }; var Mt2 = (e) => { var t2, r9, n2; return (t2 = e == null ? void 0 : e.metadata) != null && t2.video_id ? e.metadata.video_id : Be(e) && (n2 = (r9 = G(e.playbackId)) != null ? r9 : gt2(e.src)) != null ? n2 : e.src; }; var Rt2 = (e) => { var t2; return (t2 = _.get(e)) == null ? void 0 : t2.error; }; var Le2 = (e) => { var t2, r9; return (r9 = (t2 = _.get(e)) == null ? void 0 : t2.streamType) != null ? r9 : D2.UNKNOWN; }; var Ir = (e) => { var t2, r9; return (r9 = (t2 = _.get(e)) == null ? void 0 : t2.targetLiveWindow) != null ? r9 : Number.NaN; }; var Fe2 = (e) => { var t2, r9; return (r9 = (t2 = _.get(e)) == null ? void 0 : t2.seekable) != null ? r9 : e.seekable; }; var Ar2 = (e) => { var n2; let t2 = (n2 = _.get(e)) == null ? void 0 : n2.liveEdgeStartOffset; if (typeof t2 != "number") return Number.NaN; let r9 = Fe2(e); return r9.length ? r9.end(r9.length - 1) - t2 : Number.NaN; }; var ie2 = 0.034; var Ct2 = (e, t2, r9 = ie2) => Math.abs(e - t2) <= r9; var Ke2 = (e, t2, r9 = ie2) => e > t2 || Ct2(e, t2, r9); var bt2 = (e, t2 = ie2) => e.paused && Ke2(e.currentTime, e.duration, t2); var Ye2 = (e, t2) => { var c3, i3, d2; if (!t2 || !e.buffered.length) return; if (e.readyState > 2) return false; let r9 = t2.currentLevel >= 0 ? (i3 = (c3 = t2.levels) == null ? void 0 : c3[t2.currentLevel]) == null ? void 0 : i3.details : (d2 = t2.levels.find((p3) => !!p3.details)) == null ? void 0 : d2.details; if (!r9 || r9.live) return; let { fragments: n2 } = r9; if (!(n2 != null && n2.length)) return; if (e.currentTime < e.duration - (r9.targetduration + 0.5)) return false; let o2 = n2[n2.length - 1]; if (e.currentTime <= o2.start) return false; let a2 = o2.start + o2.duration / 2, s = e.buffered.start(e.buffered.length - 1), u3 = e.buffered.end(e.buffered.length - 1); return a2 > s && a2 < u3; }; var xt2 = (e, t2) => e.ended || e.loop ? e.ended : t2 && Ye2(e, t2) ? true : bt2(e); var Sr = (e, t2, r9) => { vt2(t2, r9); let { metadata: n2 = {} } = e, { view_session_id: o2 = Et2() } = n2, a2 = Mt2(e); n2.view_session_id = o2, n2.video_id = a2, e.metadata = n2; let s = (i3) => { var d2; (d2 = t2.mux) == null || d2.emit("hb", { view_drm_type: i3 }); }; e.drmTypeCb = s, _.set(t2, {}); let u3 = Pt2(e, t2), l2 = ge2(e, t2, u3); Lt2(e, t2, u3), It2(e, t2, u3), Pe2(t2), he2(t2); let c3 = Ee(e, t2, u3); return { engine: u3, setAutoplay: c3, setPreload: l2 }; }; var vt2 = (e, t2) => { let r9 = t2 == null ? void 0 : t2.engine; r9 && (r9.detachMedia(), r9.destroy()), e != null && e.mux && !e.mux.deleted && (e.mux.destroy(), delete e.mux), e && (e.removeAttribute("src"), e.load(), e.removeEventListener("error", Ge2), e.removeEventListener("error", ae), e.removeEventListener("durationchange", Je2), _.delete(e), e.dispatchEvent(new Event("teardown"))); }; function We(e, t2) { var c3; let r9 = O2(e); if (!(r9 === N.M3U8)) return true; let o2 = !r9 || ((c3 = t2.canPlayType(r9)) != null ? c3 : true), { preferPlayback: a2 } = e, s = a2 === q2.MSE, u3 = a2 === q2.NATIVE; return o2 && (u3 || !(Ve && (s || mt2))); } var Pt2 = (e, t2) => { let { debug: r9, streamType: n2, startTime: o2 = -1, metadata: a2, preferCmcd: s, _hlsConfig: u3 = {} } = e, c3 = O2(e) === N.M3U8, i3 = We(e, t2); if (c3 && !i3 && Ve) { let d2 = { backBufferLength: 30, renderTextTracksNatively: false, liveDurationInfinity: true, capLevelToPlayerSize: true, capLevelOnFPSDrop: true }, p3 = Dt2(n2), f = _t2(e), y4 = s !== w2.NONE ? { useHeaders: s === w2.HEADER, sessionId: a2 == null ? void 0 : a2.view_session_id, contentId: a2 == null ? void 0 : a2.video_id } : void 0; return new R({ debug: r9, startPosition: o2, cmcd: y4, xhrSetup: (P2, g2) => { var h3, ce5; if (s && s !== w2.QUERY) return; let b2 = new URL(g2); if (!b2.searchParams.has("CMCD")) return; let m2 = ((ce5 = (h3 = b2.searchParams.get("CMCD")) == null ? void 0 : h3.split(",")) != null ? ce5 : []).filter((ue5) => ue5.startsWith("sid") || ue5.startsWith("cid")).join(","); b2.searchParams.set("CMCD", m2), P2.open("GET", b2); }, ...d2, ...p3, ...f, ...u3 }); } }; var Dt2 = (e) => e === D2.LIVE ? { backBufferLength: 8 } : {}; var _t2 = (e) => { let { tokens: { drm: t2 } = {}, playbackId: r9, drmTypeCb: n2 } = e, o2 = G(r9); return !t2 || !o2 ? {} : { emeEnabled: true, drmSystems: { "com.apple.fps": { licenseUrl: J2(e, "fairplay"), serverCertificateUrl: $e2(e, "fairplay") }, "com.widevine.alpha": { licenseUrl: J2(e, "widevine") }, "com.microsoft.playready": { licenseUrl: J2(e, "playready") } }, requestMediaKeySystemAccessFunc: (a2, s) => (a2 === "com.widevine.alpha" && (s = [...s.map((u3) => { var c3; let l2 = (c3 = u3.videoCapabilities) == null ? void 0 : c3.map((i3) => ({ ...i3, robustness: "HW_SECURE_ALL" })); return { ...u3, videoCapabilities: l2 }; }), ...s]), navigator.requestMediaKeySystemAccess(a2, s).then((u3) => { let l2 = st2(a2); return n2 == null || n2(l2), u3; })) }; }; var kt2 = async (e) => { let t2 = await fetch(e); return t2.status !== 200 ? Promise.reject(t2) : await t2.arrayBuffer(); }; var ht2 = async (e, t2) => { let r9 = await fetch(t2, { method: "POST", headers: { "Content-type": "application/octet-stream" }, body: e }); if (r9.status !== 200) return Promise.reject(r9); let n2 = await r9.arrayBuffer(); return new Uint8Array(n2); }; var Nt2 = (e, t2) => { x(t2, "encrypted", async (n2) => { try { let o2 = n2.initDataType; if (o2 !== "skd") { console.error(`Received unexpected initialization data type "${o2}"`); return; } if (!t2.mediaKeys) { let c3 = await navigator.requestMediaKeySystemAccess("com.apple.fps", [{ initDataTypes: [o2], videoCapabilities: [{ contentType: "application/vnd.apple.mpegurl", robustness: "" }], distinctiveIdentifier: "not-allowed", persistentState: "not-allowed", sessionTypes: ["temporary"] }]).then((d2) => { var p3; return (p3 = e.drmTypeCb) == null || p3.call(e, B2.FAIRPLAY), d2; }).catch(() => { let d2 = E("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."), p3 = new T(d2, T.MEDIA_ERR_ENCRYPTED, true); p3.errorCategory = C2.DRM, p3.muxCode = M.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM, t2.dispatchEvent(new CustomEvent("error", { detail: p3 })); }); if (!c3) return; let i3 = await c3.createMediaKeys(); try { let d2 = await kt2($e2(e, "fairplay")).catch((p3) => { if (p3 instanceof Response) { let f = U2(p3, C2.DRM, e); return console.error("mediaError", f == null ? void 0 : f.message, f == null ? void 0 : f.context), f ? Promise.reject(f) : Promise.reject(new Error("Unexpected error in app cert request")); } return Promise.reject(p3); }); await i3.setServerCertificate(d2).catch(() => { let p3 = E("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."), f = new T(p3, T.MEDIA_ERR_ENCRYPTED, true); return f.errorCategory = C2.DRM, f.muxCode = M.ENCRYPTED_UPDATE_SERVER_CERT_FAILED, Promise.reject(f); }); } catch (d2) { t2.dispatchEvent(new CustomEvent("error", { detail: d2 })); return; } await t2.setMediaKeys(i3); } let a2 = n2.initData; if (a2 == null) { console.error(`Could not start encrypted playback due to missing initData in ${n2.type} event`); return; } let s = t2.mediaKeys.createSession(); s.addEventListener("keystatuseschange", () => { s.keyStatuses.forEach((c3) => { let i3; if (c3 === "internal-error") { let d2 = E("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser."); i3 = new T(d2, T.MEDIA_ERR_ENCRYPTED, true), i3.errorCategory = C2.DRM, i3.muxCode = M.ENCRYPTED_CDM_ERROR; } else if (c3 === "output-restricted" || c3 === "output-downscaled") { let d2 = E("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen."); i3 = new T(d2, T.MEDIA_ERR_ENCRYPTED, false), i3.errorCategory = C2.DRM, i3.muxCode = M.ENCRYPTED_OUTPUT_RESTRICTED; } i3 && t2.dispatchEvent(new CustomEvent("error", { detail: i3 })); }); }); let u3 = await Promise.all([s.generateRequest(o2, a2).catch(() => { let c3 = E("Failed to generate a DRM license request. This may be an issue with the player or your protected content."), i3 = new T(c3, T.MEDIA_ERR_ENCRYPTED, true); i3.errorCategory = C2.DRM, i3.muxCode = M.ENCRYPTED_GENERATE_REQUEST_FAILED, t2.dispatchEvent(new CustomEvent("error", { detail: i3 })); }), new Promise((c3) => { s.addEventListener("message", (i3) => { c3(i3.message); }, { once: true }); })]).then(([, c3]) => c3); s.generateRequest(o2, a2); let l2 = await ht2(u3, J2(e, "fairplay")).catch((c3) => { if (c3 instanceof Response) { let i3 = U2(c3, C2.DRM, e); return console.error("mediaError", i3 == null ? void 0 : i3.message, i3 == null ? void 0 : i3.context), i3 ? Promise.reject(i3) : Promise.reject(new Error("Unexpected error in license key request")); } return Promise.reject(c3); }); await s.update(l2).catch(() => { let c3 = E("Failed to update DRM license. This may be an issue with the player or your protected content."), i3 = new T(c3, T.MEDIA_ERR_ENCRYPTED, true); return i3.errorCategory = C2.DRM, i3.muxCode = M.ENCRYPTED_UPDATE_LICENSE_FAILED, Promise.reject(i3); }); } catch (o2) { t2.dispatchEvent(new CustomEvent("error", { detail: o2 })); return; } }); }; var J2 = ({ playbackId: e, tokens: { drm: t2 } = {}, customDomain: r9 = I }, n2) => { let o2 = G(e); return `https://license.${r9.toLocaleLowerCase().endsWith(I) ? r9 : I}/license/${n2}/${o2}?token=${t2}`; }; var $e2 = ({ playbackId: e, tokens: { drm: t2 } = {}, customDomain: r9 = I }, n2) => { let o2 = G(e); return `https://license.${r9.toLocaleLowerCase().endsWith(I) ? r9 : I}/appcert/${n2}/${o2}?token=${t2}`; }; var Be = ({ playbackId: e, src: t2, customDomain: r9 }) => { if (e) return true; if (typeof t2 != "string") return false; let n2 = window == null ? void 0 : window.location.href, o2 = new URL(t2, n2).hostname.toLocaleLowerCase(); return o2.includes(I) || !!r9 && o2.includes(r9.toLocaleLowerCase()); }; var Lt2 = (e, t2, r9) => { var s; let { envKey: n2, disableTracking: o2 } = e, a2 = Be(e); if (!o2 && (n2 || a2)) { let { playerInitTime: u3, playerSoftwareName: l2, playerSoftwareVersion: c3, beaconCollectionDomain: i3, debug: d2, disableCookies: p3 } = e, f = { ...e.metadata, video_title: ((s = e == null ? void 0 : e.metadata) == null ? void 0 : s.video_title) || void 0 }, y4 = (v2) => typeof v2.player_error_code == "string" ? false : typeof e.errorTranslator == "function" ? e.errorTranslator(v2) : v2; Ed.monitor(t2, { debug: d2, beaconCollectionDomain: i3, hlsjs: r9, Hls: r9 ? R : void 0, automaticErrorTracking: false, errorTranslator: y4, disableCookies: p3, data: { ...n2 ? { env_key: n2 } : {}, player_software_name: l2, player_software: l2, player_software_version: c3, player_init_time: u3, ...f } }); } }; var It2 = (e, t2, r9) => { var c3, i3; let n2 = We(e, t2), { src: o2 } = e, a2 = () => { t2.ended || !xt2(t2, r9) || (Ye2(t2, r9) ? t2.currentTime = t2.buffered.end(t2.buffered.length - 1) : t2.dispatchEvent(new Event("ended"))); }, s, u3, l2 = () => { let d2 = Fe2(t2), p3, f; d2.length > 0 && (p3 = d2.start(0), f = d2.end(0)), (u3 !== f || s !== p3) && t2.dispatchEvent(new CustomEvent("seekablechange", { composed: true })), s = p3, u3 = f; }; if (x(t2, "durationchange", l2), t2 && n2) { let d2 = O2(e); if (typeof o2 == "string") { let p3 = () => { if (Le2(t2) !== D2.LIVE || Number.isFinite(t2.duration)) return; let y4 = setInterval(l2, 1e3); t2.addEventListener("teardown", () => { clearInterval(y4); }, { once: true }), x(t2, "durationchange", () => { Number.isFinite(t2.duration) && clearInterval(y4); }); }, f = async () => dt3(o2, t2, d2).then(p3).catch((y4) => { if (y4 instanceof Response) { let v2 = U2(y4, C2.VIDEO, e); if (v2) { t2.dispatchEvent(new CustomEvent("error", { detail: v2 })); return; } } else y4 instanceof Error; }); if (t2.preload === "none") { let y4 = () => { f(), t2.removeEventListener("loadedmetadata", v2); }, v2 = () => { f(), t2.removeEventListener("play", y4); }; x(t2, "play", y4, { once: true }), x(t2, "loadedmetadata", v2, { once: true }); } else f(); (c3 = e.tokens) != null && c3.drm ? Nt2(e, t2) : x(t2, "encrypted", () => { let y4 = E("Attempting to play DRM-protected content without providing a DRM token."), v2 = new T(y4, T.MEDIA_ERR_ENCRYPTED, true); v2.errorCategory = C2.DRM, v2.muxCode = M.ENCRYPTED_MISSING_TOKEN, t2.dispatchEvent(new CustomEvent("error", { detail: v2 })); }, { once: true }), t2.setAttribute("src", o2), e.startTime && (((i3 = _.get(t2)) != null ? i3 : {}).startTime = e.startTime, t2.addEventListener("durationchange", Je2, { once: true })); } else t2.removeAttribute("src"); t2.addEventListener("error", Ge2), t2.addEventListener("error", ae), t2.addEventListener("emptied", () => { t2.querySelectorAll("track[data-removeondestroy]").forEach((f) => { f.remove(); }); }, { once: true }), x(t2, "pause", a2), x(t2, "seeked", a2), x(t2, "play", () => { t2.ended || Ke2(t2.currentTime, t2.duration) && (t2.currentTime = t2.seekable.length ? t2.seekable.start(0) : 0); }); } else r9 && o2 ? (r9.once(R.Events.LEVEL_LOADED, (d2, p3) => { pt2(p3.details, t2, r9), l2(), Le2(t2) === D2.LIVE && !Number.isFinite(t2.duration) && (r9.on(R.Events.LEVEL_UPDATED, l2), x(t2, "durationchange", () => { Number.isFinite(t2.duration) && r9.off(R.Events.LEVELS_UPDATED, l2); })); }), r9.on(R.Events.ERROR, (d2, p3) => { t2.dispatchEvent(new CustomEvent("error", { detail: At2(p3, e) })); }), t2.addEventListener("error", ae), x(t2, "waiting", a2), Me2(e, r9), Re(t2, r9), r9.attachMedia(t2)) : console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software."); }; function Je2(e) { var n2; let t2 = e.target, r9 = (n2 = _.get(t2)) == null ? void 0 : n2.startTime; if (r9 && de2(t2.seekable, t2.duration, r9)) { let o2 = t2.preload === "auto"; o2 && (t2.preload = "none"), t2.currentTime = r9, o2 && (t2.preload = "auto"); } } async function Ge2(e) { if (!e.isTrusted) return; e.stopImmediatePropagation(); let t2 = e.target; if (!(t2 != null && t2.error)) return; let { message: r9, code: n2 } = t2.error, o2 = new T(r9, n2); if (t2.src && n2 === T.MEDIA_ERR_SRC_NOT_SUPPORTED && t2.readyState === HTMLMediaElement.HAVE_NOTHING) { setTimeout(() => { var s; let a2 = (s = Rt2(t2)) != null ? s : t2.error; (a2 == null ? void 0 : a2.code) === T.MEDIA_ERR_SRC_NOT_SUPPORTED && t2.dispatchEvent(new CustomEvent("error", { detail: o2 })); }, 500); return; } if (t2.src && (n2 !== T.MEDIA_ERR_DECODE || n2 !== void 0)) try { let { status: a2 } = await fetch(t2.src); o2.data = { response: { code: a2 } }; } catch { } t2.dispatchEvent(new CustomEvent("error", { detail: o2 })); } function ae(e) { var n2, o2; if (!(e instanceof CustomEvent) || !(e.detail instanceof T)) return; let t2 = e.target, r9 = e.detail; !r9 || !r9.fatal || (((n2 = _.get(t2)) != null ? n2 : {}).error = r9, (o2 = t2.mux) == null || o2.emit("error", { player_error_code: r9.code, player_error_message: r9.message, player_error_context: r9.context })); } var At2 = (e, t2) => { var u3, l2, c3; console.error("getErrorFromHlsErrorData()", e); let r9 = { [R.ErrorTypes.NETWORK_ERROR]: T.MEDIA_ERR_NETWORK, [R.ErrorTypes.MEDIA_ERROR]: T.MEDIA_ERR_DECODE, [R.ErrorTypes.KEY_SYSTEM_ERROR]: T.MEDIA_ERR_ENCRYPTED }, n2 = (i3) => [ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED, ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(i3.details) ? T.MEDIA_ERR_NETWORK : r9[i3.type], o2 = (i3) => { if (i3.type === ErrorTypes.KEY_SYSTEM_ERROR) return C2.DRM; if (i3.type === ErrorTypes.NETWORK_ERROR) return C2.VIDEO; }, a2, s = n2(e); if (s === T.MEDIA_ERR_NETWORK && e.response) { let i3 = (u3 = o2(e)) != null ? u3 : C2.VIDEO; a2 = (l2 = U2(e.response, i3, t2)) != null ? l2 : new T("", s); } else if (s === T.MEDIA_ERR_ENCRYPTED) if (e.details === ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE) { let i3 = E("Attempting to play DRM-protected content without providing a DRM token."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, e.fatal), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_MISSING_TOKEN; } else if (e.details === ErrorDetails.KEY_SYSTEM_NO_ACCESS) { let i3 = E("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, e.fatal), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM; } else if (e.details === ErrorDetails.KEY_SYSTEM_NO_SESSION) { let i3 = E("Failed to generate a DRM license request. This may be an issue with the player or your protected content."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, true), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_GENERATE_REQUEST_FAILED; } else if (e.details === ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED) { let i3 = E("Failed to update DRM license. This may be an issue with the player or your protected content."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, e.fatal), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_UPDATE_LICENSE_FAILED; } else if (e.details === ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED) { let i3 = E("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, e.fatal), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_UPDATE_SERVER_CERT_FAILED; } else if (e.details === ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR) { let i3 = E("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, e.fatal), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_CDM_ERROR; } else if (e.details === ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED) { let i3 = E("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen."); a2 = new T(i3, T.MEDIA_ERR_ENCRYPTED, false), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_OUTPUT_RESTRICTED; } else a2 = new T(e.error.message, T.MEDIA_ERR_ENCRYPTED, e.fatal), a2.errorCategory = C2.DRM, a2.muxCode = M.ENCRYPTED_ERROR; else a2 = new T("", s, e.fatal); return a2.context || (a2.context = `${e.url ? `url: ${e.url} ` : ""}${e.response && (e.response.code || e.response.text) ? `response: ${e.response.code}, ${e.response.text} ` : ""}${e.reason ? `failure reason: ${e.reason} ` : ""}${e.level ? `level: ${e.level} ` : ""}${e.parent ? `parent stream controller: ${e.parent} ` : ""}${e.buffer ? `buffer length: ${e.buffer} ` : ""}${e.error ? `error: ${e.error} ` : ""}${e.event ? `event: ${e.event} ` : ""}${e.err ? `error message: ${(c3 = e.err) == null ? void 0 : c3.message} ` : ""}`), a2.data = e, a2; }; // node_modules/media-chrome/dist/constants.js var MediaUIEvents = { MEDIA_PLAY_REQUEST: "mediaplayrequest", MEDIA_PAUSE_REQUEST: "mediapauserequest", MEDIA_MUTE_REQUEST: "mediamuterequest", MEDIA_UNMUTE_REQUEST: "mediaunmuterequest", MEDIA_VOLUME_REQUEST: "mediavolumerequest", MEDIA_SEEK_REQUEST: "mediaseekrequest", MEDIA_AIRPLAY_REQUEST: "mediaairplayrequest", MEDIA_ENTER_FULLSCREEN_REQUEST: "mediaenterfullscreenrequest", MEDIA_EXIT_FULLSCREEN_REQUEST: "mediaexitfullscreenrequest", MEDIA_PREVIEW_REQUEST: "mediapreviewrequest", MEDIA_ENTER_PIP_REQUEST: "mediaenterpiprequest", MEDIA_EXIT_PIP_REQUEST: "mediaexitpiprequest", MEDIA_ENTER_CAST_REQUEST: "mediaentercastrequest", MEDIA_EXIT_CAST_REQUEST: "mediaexitcastrequest", MEDIA_SHOW_TEXT_TRACKS_REQUEST: "mediashowtexttracksrequest", MEDIA_HIDE_TEXT_TRACKS_REQUEST: "mediahidetexttracksrequest", MEDIA_SHOW_SUBTITLES_REQUEST: "mediashowsubtitlesrequest", MEDIA_DISABLE_SUBTITLES_REQUEST: "mediadisablesubtitlesrequest", MEDIA_TOGGLE_SUBTITLES_REQUEST: "mediatogglesubtitlesrequest", MEDIA_PLAYBACK_RATE_REQUEST: "mediaplaybackraterequest", MEDIA_RENDITION_REQUEST: "mediarenditionrequest", MEDIA_AUDIO_TRACK_REQUEST: "mediaaudiotrackrequest", MEDIA_SEEK_TO_LIVE_REQUEST: "mediaseektoliverequest", REGISTER_MEDIA_STATE_RECEIVER: "registermediastatereceiver", UNREGISTER_MEDIA_STATE_RECEIVER: "unregistermediastatereceiver" }; var MediaStateReceiverAttributes = { MEDIA_CHROME_ATTRIBUTES: "mediachromeattributes", MEDIA_CONTROLLER: "mediacontroller" }; var MediaUIProps = { MEDIA_AIRPLAY_UNAVAILABLE: "mediaAirplayUnavailable", MEDIA_FULLSCREEN_UNAVAILABLE: "mediaFullscreenUnavailable", MEDIA_PIP_UNAVAILABLE: "mediaPipUnavailable", MEDIA_CAST_UNAVAILABLE: "mediaCastUnavailable", MEDIA_RENDITION_UNAVAILABLE: "mediaRenditionUnavailable", MEDIA_AUDIO_TRACK_UNAVAILABLE: "mediaAudioTrackUnavailable", MEDIA_WIDTH: "mediaWidth", MEDIA_HEIGHT: "mediaHeight", MEDIA_PAUSED: "mediaPaused", MEDIA_HAS_PLAYED: "mediaHasPlayed", MEDIA_ENDED: "mediaEnded", MEDIA_MUTED: "mediaMuted", MEDIA_VOLUME_LEVEL: "mediaVolumeLevel", MEDIA_VOLUME: "mediaVolume", MEDIA_VOLUME_UNAVAILABLE: "mediaVolumeUnavailable", MEDIA_IS_PIP: "mediaIsPip", MEDIA_IS_CASTING: "mediaIsCasting", MEDIA_IS_AIRPLAYING: "mediaIsAirplaying", MEDIA_SUBTITLES_LIST: "mediaSubtitlesList", MEDIA_SUBTITLES_SHOWING: "mediaSubtitlesShowing", MEDIA_IS_FULLSCREEN: "mediaIsFullscreen", MEDIA_PLAYBACK_RATE: "mediaPlaybackRate", MEDIA_CURRENT_TIME: "mediaCurrentTime", MEDIA_DURATION: "mediaDuration", MEDIA_SEEKABLE: "mediaSeekable", MEDIA_PREVIEW_TIME: "mediaPreviewTime", MEDIA_PREVIEW_IMAGE: "mediaPreviewImage", MEDIA_PREVIEW_COORDS: "mediaPreviewCoords", MEDIA_PREVIEW_CHAPTER: "mediaPreviewChapter", MEDIA_LOADING: "mediaLoading", MEDIA_BUFFERED: "mediaBuffered", MEDIA_STREAM_TYPE: "mediaStreamType", MEDIA_TARGET_LIVE_WINDOW: "mediaTargetLiveWindow", MEDIA_TIME_IS_LIVE: "mediaTimeIsLive", MEDIA_RENDITION_LIST: "mediaRenditionList", MEDIA_RENDITION_SELECTED: "mediaRenditionSelected", MEDIA_AUDIO_TRACK_LIST: "mediaAudioTrackList", MEDIA_AUDIO_TRACK_ENABLED: "mediaAudioTrackEnabled", MEDIA_CHAPTERS_CUES: "mediaChaptersCues" }; var MediaUIPropsEntries = Object.entries( MediaUIProps ); var MediaUIAttributes = MediaUIPropsEntries.reduce( (dictObj, [key, propName]) => { dictObj[key] = propName.toLowerCase(); return dictObj; }, {} ); var AdditionalStateChangeEvents = { USER_INACTIVE: "userinactivechange", BREAKPOINTS_CHANGE: "breakpointchange", BREAKPOINTS_COMPUTED: "breakpointscomputed" }; var MediaStateChangeEvents = MediaUIPropsEntries.reduce( (dictObj, [key, propName]) => { dictObj[key] = propName.toLowerCase(); return dictObj; }, { ...AdditionalStateChangeEvents } ); var StateChangeEventToAttributeMap = Object.entries( MediaStateChangeEvents ).reduce( (mapObj, [key, eventType]) => { const attrName = MediaUIAttributes[key]; if (attrName) { mapObj[eventType] = attrName; } return mapObj; }, { userinactivechange: "userinactive" } ); var AttributeToStateChangeEventMap = Object.entries( MediaUIAttributes ).reduce( (mapObj, [key, attrName]) => { const evtType = MediaStateChangeEvents[key]; if (evtType) { mapObj[attrName] = evtType; } return mapObj; }, { userinactive: "userinactivechange" } ); var TextTrackKinds = { SUBTITLES: "subtitles", CAPTIONS: "captions", DESCRIPTIONS: "descriptions", CHAPTERS: "chapters", METADATA: "metadata" }; var TextTrackModes = { DISABLED: "disabled", HIDDEN: "hidden", SHOWING: "showing" }; var PointerTypes = { MOUSE: "mouse", PEN: "pen", TOUCH: "touch" }; var AvailabilityStates = { UNAVAILABLE: "unavailable", UNSUPPORTED: "unsupported" }; var StreamTypes = { LIVE: "live", ON_DEMAND: "on-demand", UNKNOWN: "unknown" }; var WebkitPresentationModes = { INLINE: "inline", FULLSCREEN: "fullscreen", PICTURE_IN_PICTURE: "picture-in-picture" }; // node_modules/media-chrome/dist/labels/labels.js var tooltipLabels = { ENTER_AIRPLAY: "Start airplay", EXIT_AIRPLAY: "Stop airplay", AUDIO_TRACK_MENU: "Audio", CAPTIONS: "Captions", ENABLE_CAPTIONS: "Enable captions", DISABLE_CAPTIONS: "Disable captions", START_CAST: "Start casting", STOP_CAST: "Stop casting", ENTER_FULLSCREEN: "Enter fullscreen mode", EXIT_FULLSCREEN: "Exit fullscreen mode", MUTE: "Mute", UNMUTE: "Unmute", ENTER_PIP: "Enter picture in picture mode", EXIT_PIP: "Enter picture in picture mode", PLAY: "Play", PAUSE: "Pause", PLAYBACK_RATE: "Playback rate", RENDITIONS: "Quality", SEEK_BACKWARD: "Seek backward", SEEK_FORWARD: "Seek forward", SETTINGS: "Settings" }; var nouns = { AUDIO_PLAYER: () => "audio player", VIDEO_PLAYER: () => "video player", VOLUME: () => "volume", SEEK: () => "seek", CLOSED_CAPTIONS: () => "closed captions", PLAYBACK_RATE: ({ playbackRate = 1 } = {}) => `current playback rate ${playbackRate}`, PLAYBACK_TIME: () => `playback time`, MEDIA_LOADING: () => `media loading`, SETTINGS: () => `settings`, AUDIO_TRACKS: () => `audio tracks`, QUALITY: () => `quality` }; var verbs = { PLAY: () => "play", PAUSE: () => "pause", MUTE: () => "mute", UNMUTE: () => "unmute", ENTER_AIRPLAY: () => "start airplay", EXIT_AIRPLAY: () => "stop airplay", ENTER_CAST: () => "start casting", EXIT_CAST: () => "stop casting", ENTER_FULLSCREEN: () => "enter fullscreen mode", EXIT_FULLSCREEN: () => "exit fullscreen mode", ENTER_PIP: () => "enter picture in picture mode", EXIT_PIP: () => "exit picture in picture mode", SEEK_FORWARD_N_SECS: ({ seekOffset = 30 } = {}) => `seek forward ${seekOffset} seconds`, SEEK_BACK_N_SECS: ({ seekOffset = 30 } = {}) => `seek back ${seekOffset} seconds`, SEEK_LIVE: () => "seek to live", PLAYING_LIVE: () => "playing live" }; var labels_default = { ...nouns, ...verbs }; // node_modules/media-chrome/dist/utils/utils.js function stringifyRenditionList(renditions) { return renditions == null ? void 0 : renditions.map(stringifyRendition).join(" "); } function parseRenditionList(renditions) { return renditions == null ? void 0 : renditions.split(/\s+/).map(parseRendition); } function stringifyRendition(rendition) { if (rendition) { const { id, width, height } = rendition; return [id, width, height].filter((a2) => a2 != null).join(":"); } } function parseRendition(rendition) { if (rendition) { const [id, width, height] = rendition.split(":"); return { id, width: +width, height: +height }; } } function stringifyAudioTrackList(audioTracks) { return audioTracks == null ? void 0 : audioTracks.map(stringifyAudioTrack).join(" "); } function parseAudioTrackList(audioTracks) { return audioTracks == null ? void 0 : audioTracks.split(/\s+/).map(parseAudioTrack); } function stringifyAudioTrack(audioTrack) { if (audioTrack) { const { id, kind, language, label } = audioTrack; return [id, kind, language, label].filter((a2) => a2 != null).join(":"); } } function parseAudioTrack(audioTrack) { if (audioTrack) { const [id, kind, language, label] = audioTrack.split(":"); return { id, kind, language, label }; } } function camelCase(name) { return name.replace(/[-_]([a-z])/g, ($0, $1) => $1.toUpperCase()); } function isValidNumber(x2) { return typeof x2 === "number" && !Number.isNaN(x2) && Number.isFinite(x2); } function isNumericString(str) { if (typeof str != "string") return false; return !isNaN(str) && !isNaN(parseFloat(str)); } var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // node_modules/media-chrome/dist/utils/time.js var UnitLabels = [ { singular: "hour", plural: "hours" }, { singular: "minute", plural: "minutes" }, { singular: "second", plural: "seconds" } ]; var toTimeUnitPhrase = (timeUnitValue, unitIndex) => { const unitLabel = timeUnitValue === 1 ? UnitLabels[unitIndex].singular : UnitLabels[unitIndex].plural; return `${timeUnitValue} ${unitLabel}`; }; var formatAsTimePhrase = (seconds) => { if (!isValidNumber(seconds)) return ""; const positiveSeconds = Math.abs(seconds); const negative = positiveSeconds !== seconds; const secondsDateTime = new Date(0, 0, 0, 0, 0, positiveSeconds, 0); const timeParts = [ secondsDateTime.getHours(), secondsDateTime.getMinutes(), secondsDateTime.getSeconds() ]; const timeString = timeParts.map( (timeUnitValue, index2) => timeUnitValue && toTimeUnitPhrase(timeUnitValue, index2) ).filter((x2) => x2).join(", "); const negativeSuffix = negative ? " remaining" : ""; return `${timeString}${negativeSuffix}`; }; function formatTime(seconds, guide) { let negative = false; if (seconds < 0) { negative = true; seconds = 0 - seconds; } seconds = seconds < 0 ? 0 : seconds; let s = Math.floor(seconds % 60); let m2 = Math.floor(seconds / 60 % 60); let h3 = Math.floor(seconds / 3600); const gm = Math.floor(guide / 60 % 60); const gh = Math.floor(guide / 3600); if (isNaN(seconds) || seconds === Infinity) { h3 = m2 = s = "0"; } h3 = h3 > 0 || gh > 0 ? h3 + ":" : ""; m2 = ((h3 || gm >= 10) && m2 < 10 ? "0" + m2 : m2) + ":"; s = s < 10 ? "0" + s : s; return (negative ? "-" : "") + h3 + m2 + s; } var emptyTimeRanges = Object.freeze({ length: 0, start(index2) { const unsignedIdx = index2 >>> 0; if (unsignedIdx >= this.length) { throw new DOMException( `Failed to execute 'start' on 'TimeRanges': The index provided (${unsignedIdx}) is greater than or equal to the maximum bound (${this.length}).` ); } return 0; }, end(index2) { const unsignedIdx = index2 >>> 0; if (unsignedIdx >= this.length) { throw new DOMException( `Failed to execute 'end' on 'TimeRanges': The index provided (${unsignedIdx}) is greater than or equal to the maximum bound (${this.length}).` ); } return 0; } }); // node_modules/media-chrome/dist/utils/server-safe-globals.js var EventTarget2 = class { addEventListener() { } removeEventListener() { } dispatchEvent() { return true; } }; var Node = class extends EventTarget2 { }; var Element2 = class extends Node { constructor() { super(...arguments); this.role = null; } }; var ResizeObserver = class { observe() { } unobserve() { } disconnect() { } }; var documentShim = { createElement: function() { return new globalThisShim.HTMLElement(); }, createElementNS: function() { return new globalThisShim.HTMLElement(); }, addEventListener() { }, removeEventListener() { }, /** * * @param {Event} event * @returns {boolean} */ dispatchEvent(event) { return false; } }; var globalThisShim = { ResizeObserver, document: documentShim, Node, Element: Element2, HTMLElement: class HTMLElement2 extends Element2 { constructor() { super(...arguments); this.innerHTML = ""; } get content() { return new globalThisShim.DocumentFragment(); } }, DocumentFragment: class DocumentFragment2 extends EventTarget2 { }, customElements: { get: function() { }, define: function() { }, whenDefined: function() { } }, localStorage: { /** * @param {string} key * @returns {string|null} */ getItem(key) { return null; }, /** * @param {string} key * @param {string} value */ setItem(key, value) { }, // eslint-disable-line @typescript-eslint/no-unused-vars /** * @param {string} key */ removeItem(key) { } // eslint-disable-line @typescript-eslint/no-unused-vars }, CustomEvent: function CustomEvent2() { }, getComputedStyle: function() { }, navigator: { languages: [], get userAgent() { return ""; } }, /** * @param {string} media */ matchMedia(media) { return { matches: false, media }; } }; var isServer = typeof window === "undefined" || typeof window.customElements === "undefined"; var isShimmed = Object.keys(globalThisShim).every((key) => key in globalThis); var GlobalThis = isServer && !isShimmed ? globalThisShim : globalThis; var Document2 = isServer && !isShimmed ? documentShim : globalThis.document; // node_modules/media-chrome/dist/utils/resize-observer.js var callbacksMap = /* @__PURE__ */ new WeakMap(); var getCallbacks = (element) => { let callbacks = callbacksMap.get(element); if (!callbacks) callbacksMap.set(element, callbacks = /* @__PURE__ */ new Set()); return callbacks; }; var observer = new GlobalThis.ResizeObserver( (entries) => { for (const entry of entries) { for (const callback of getCallbacks(entry.target)) { callback(entry); } } } ); function observeResize(element, callback) { getCallbacks(element).add(callback); observer.observe(element); } function unobserveResize(element, callback) { const callbacks = getCallbacks(element); callbacks.delete(callback); if (!callbacks.size) { observer.unobserve(element); } } // node_modules/media-chrome/dist/utils/element-utils.js function getMediaController(host) { var _a3; return (_a3 = getAttributeMediaController(host)) != null ? _a3 : closestComposedNode(host, "media-controller"); } function getAttributeMediaController(host) { var _a3; const { MEDIA_CONTROLLER } = MediaStateReceiverAttributes; const mediaControllerId = host.getAttribute(MEDIA_CONTROLLER); if (mediaControllerId) { return (_a3 = getDocumentOrShadowRoot(host)) == null ? void 0 : _a3.getElementById( mediaControllerId ); } } var updateIconText = (svg, value, selector = ".value") => { const node2 = svg.querySelector(selector); if (!node2) return; node2.textContent = value; }; var getAllSlotted = (el, name) => { const slotSelector = `slot[name="${name}"]`; const slot = el.shadowRoot.querySelector(slotSelector); if (!slot) return []; return slot.children; }; var getSlotted = (el, name) => getAllSlotted(el, name)[0]; var containsComposedNode = (rootNode, childNode) => { if (!rootNode || !childNode) return false; if (rootNode == null ? void 0 : rootNode.contains(childNode)) return true; return containsComposedNode( rootNode, childNode.getRootNode().host ); }; var closestComposedNode = (childNode, selector) => { if (!childNode) return null; const closest = childNode.closest(selector); if (closest) return closest; return closestComposedNode( childNode.getRootNode().host, selector ); }; function getActiveElement(root = document) { var _a3; const activeEl = root == null ? void 0 : root.activeElement; if (!activeEl) return null; return (_a3 = getActiveElement(activeEl.shadowRoot)) != null ? _a3 : activeEl; } function getDocumentOrShadowRoot(node2) { var _a3; const rootNode = (_a3 = node2 == null ? void 0 : node2.getRootNode) == null ? void 0 : _a3.call(node2); if (rootNode instanceof ShadowRoot || rootNode instanceof Document) { return rootNode; } return null; } function isElementVisible(element, { depth = 3, checkOpacity = true, checkVisibilityCSS = true } = {}) { if (element.checkVisibility) { return element.checkVisibility({ checkOpacity, checkVisibilityCSS }); } let el = element; while (el && depth > 0) { const style = getComputedStyle(el); if (checkOpacity && style.opacity === "0" || checkVisibilityCSS && style.visibility === "hidden" || style.display === "none") { return false; } el = el.parentElement; depth--; } return true; } function getPointProgressOnLine(x2, y4, p1, p22) { const segment = distance(p1, p22); const toStart = distance(p1, { x: x2, y: y4 }); const toEnd = distance(p22, { x: x2, y: y4 }); if (toStart > segment || toEnd > segment) { return toStart > toEnd ? 1 : 0; } return toStart / segment; } function distance(p1, p22) { return Math.sqrt(Math.pow(p22.x - p1.x, 2) + Math.pow(p22.y - p1.y, 2)); } function getOrInsertCSSRule(styleParent, selectorText) { const cssRule = getCSSRule(styleParent, (st3) => st3 === selectorText); if (cssRule) return cssRule; return insertCSSRule(styleParent, selectorText); } function getCSSRule(styleParent, predicate) { var _a3, _b; let style; for (style of (_a3 = styleParent.querySelectorAll("style:not([media])")) != null ? _a3 : []) { let cssRules; try { cssRules = (_b = style.sheet) == null ? void 0 : _b.cssRules; } catch { continue; } for (const rule of cssRules != null ? cssRules : []) { if (predicate(rule.selectorText)) return rule; } } } function insertCSSRule(styleParent, selectorText) { var _a3, _b; const styles = (_a3 = styleParent.querySelectorAll("style:not([media])")) != null ? _a3 : []; const style = styles == null ? void 0 : styles[styles.length - 1]; if (!(style == null ? void 0 : style.sheet)) { console.warn( "Media Chrome: No style sheet found on style tag of", styleParent ); return { // @ts-ignore style: { setProperty: () => { }, removeProperty: () => "", getPropertyValue: () => "" } }; } style == null ? void 0 : style.sheet.insertRule(`${selectorText}{}`, style.sheet.cssRules.length); return ( /** @type {CSSStyleRule} */ (_b = style.sheet.cssRules) == null ? void 0 : _b[style.sheet.cssRules.length - 1] ); } function getNumericAttr(el, attrName, defaultValue = Number.NaN) { const attrVal = el.getAttribute(attrName); return attrVal != null ? +attrVal : defaultValue; } function setNumericAttr(el, attrName, value) { const nextNumericValue = +value; if (value == null || Number.isNaN(nextNumericValue)) { if (el.hasAttribute(attrName)) { el.removeAttribute(attrName); } return; } if (getNumericAttr(el, attrName, void 0) === nextNumericValue) return; el.setAttribute(attrName, `${nextNumericValue}`); } function getBooleanAttr(el, attrName) { return el.hasAttribute(attrName); } function setBooleanAttr(el, attrName, value) { if (value == null) { if (el.hasAttribute(attrName)) { el.removeAttribute(attrName); } return; } if (getBooleanAttr(el, attrName) == value) return; el.toggleAttribute(attrName, value); } function getStringAttr(el, attrName, defaultValue = null) { var _a3; return (_a3 = el.getAttribute(attrName)) != null ? _a3 : defaultValue; } function setStringAttr(el, attrName, value) { if (value == null) { if (el.hasAttribute(attrName)) { el.removeAttribute(attrName); } return; } const nextValue = `${value}`; if (getStringAttr(el, attrName, void 0) === nextValue) return; el.setAttribute(attrName, nextValue); } // node_modules/media-chrome/dist/media-gesture-receiver.js var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _mediaController; var template = Document2.createElement("template"); template.innerHTML = /*html*/ ` <style> :host { display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block)); box-sizing: border-box; } </style> `; var MediaGestureReceiver = class extends GlobalThis.HTMLElement { constructor(options2 = {}) { super(); __privateAdd(this, _mediaController, void 0); if (!this.shadowRoot) { const shadow = this.attachShadow({ mode: "open" }); const buttonHTML = template.content.cloneNode(true); this.nativeEl = buttonHTML; let slotTemplate17 = options2.slotTemplate; if (!slotTemplate17) { slotTemplate17 = Document2.createElement("template"); slotTemplate17.innerHTML = `<slot>${options2.defaultContent || ""}</slot>`; } this.nativeEl.appendChild(slotTemplate17.content.cloneNode(true)); shadow.appendChild(buttonHTML); } } // NOTE: Currently "baking in" actions + attrs until we come up with // a more robust architecture (CJP) static get observedAttributes() { return [ MediaStateReceiverAttributes.MEDIA_CONTROLLER, MediaUIAttributes.MEDIA_PAUSED ]; } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet(this, _mediaController)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet(this, _mediaController, null); } if (newValue && this.isConnected) { __privateSet(this, _mediaController, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet(this, _mediaController)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } } connectedCallback() { var _a3, _b, _c, _d; this.tabIndex = -1; this.setAttribute("aria-hidden", "true"); __privateSet(this, _mediaController, getMediaControllerEl(this)); if (this.getAttribute(MediaStateReceiverAttributes.MEDIA_CONTROLLER)) { (_b = (_a3 = __privateGet(this, _mediaController)) == null ? void 0 : _a3.associateElement) == null ? void 0 : _b.call(_a3, this); } (_c = __privateGet(this, _mediaController)) == null ? void 0 : _c.addEventListener("pointerdown", this); (_d = __privateGet(this, _mediaController)) == null ? void 0 : _d.addEventListener("click", this); } disconnectedCallback() { var _a3, _b, _c, _d; if (this.getAttribute(MediaStateReceiverAttributes.MEDIA_CONTROLLER)) { (_b = (_a3 = __privateGet(this, _mediaController)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); } (_c = __privateGet(this, _mediaController)) == null ? void 0 : _c.removeEventListener("pointerdown", this); (_d = __privateGet(this, _mediaController)) == null ? void 0 : _d.removeEventListener("click", this); __privateSet(this, _mediaController, null); } handleEvent(event) { var _a3; const composedTarget = (_a3 = event.composedPath()) == null ? void 0 : _a3[0]; const allowList = ["video", "media-controller"]; if (!allowList.includes(composedTarget == null ? void 0 : composedTarget.localName)) return; if (event.type === "pointerdown") { this._pointerType = event.pointerType; } else if (event.type === "click") { const { clientX, clientY } = event; const { left, top, width, height } = this.getBoundingClientRect(); const x2 = clientX - left; const y4 = clientY - top; if (x2 < 0 || y4 < 0 || x2 > width || y4 > height || // In case this element has no dimensions (or display: none) return. width === 0 && height === 0) { return; } const { pointerType = this._pointerType } = event; this._pointerType = void 0; if (pointerType === PointerTypes.TOUCH) { this.handleTap(event); return; } else if (pointerType === PointerTypes.MOUSE) { this.handleMouseClick(event); return; } } } /** * @type {boolean} Is the media paused */ get mediaPaused() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED); } set mediaPaused(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED, value); } // NOTE: Currently "baking in" actions + attrs until we come up with // a more robust architecture (CJP) /** * @abstract * @argument {Event} e */ handleTap(e) { } // eslint-disable-line // eslint-disable-next-line handleMouseClick(e) { const eventName = this.mediaPaused ? MediaUIEvents.MEDIA_PLAY_REQUEST : MediaUIEvents.MEDIA_PAUSE_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); } }; _mediaController = /* @__PURE__ */ new WeakMap(); function getMediaControllerEl(controlEl) { var _a3; const mediaControllerId = controlEl.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { return (_a3 = controlEl.getRootNode()) == null ? void 0 : _a3.getElementById(mediaControllerId); } return closestComposedNode(controlEl, "media-controller"); } if (!GlobalThis.customElements.get("media-gesture-receiver")) { GlobalThis.customElements.define( "media-gesture-receiver", MediaGestureReceiver ); } // node_modules/media-chrome/dist/media-container.js var __accessCheck2 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet2 = (obj, member, getter) => { __accessCheck2(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd2 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet2 = (obj, member, value, setter) => { __accessCheck2(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod = (obj, member, method) => { __accessCheck2(obj, member, "access private method"); return method; }; var _pointerDownTimeStamp; var _currentMedia; var _inactiveTimeout; var _autohide; var _handlePointerMove; var handlePointerMove_fn; var _handlePointerUp; var handlePointerUp_fn; var _setInactive; var setInactive_fn; var _setActive; var setActive_fn; var _scheduleInactive; var scheduleInactive_fn; var Attributes = { AUDIO: "audio", AUTOHIDE: "autohide", BREAKPOINTS: "breakpoints", GESTURES_DISABLED: "gesturesdisabled", KEYBOARD_CONTROL: "keyboardcontrol", NO_AUTOHIDE: "noautohide", USER_INACTIVE: "userinactive" }; var template2 = Document2.createElement("template"); template2.innerHTML = /*html*/ ` <style> ${/* * outline on media is turned off because it is allowed to get focus to faciliate hotkeys. * However, on keyboard interactions, the focus outline is shown, * which is particularly noticeable when going fullscreen via hotkeys. */ ""} :host([${MediaUIAttributes.MEDIA_IS_FULLSCREEN}]) ::slotted([slot=media]) { outline: none; } :host { box-sizing: border-box; position: relative; display: inline-block; line-height: 0; background-color: var(--media-background-color, #000); } :host(:not([${Attributes.AUDIO}])) [part~=layer]:not([part~=media-layer]) { position: absolute; top: 0; left: 0; bottom: 0; right: 0; display: flex; flex-flow: column nowrap; align-items: start; pointer-events: none; background: none; } slot[name=media] { display: var(--media-slot-display, contents); } ${/* * when in audio mode, hide the slotted media element by default */ ""} :host([${Attributes.AUDIO}]) slot[name=media] { display: var(--media-slot-display, none); } ${/* * when in audio mode, hide the gesture-layer which causes media-controller to be taller than the control bar */ ""} :host([${Attributes.AUDIO}]) [part~=layer][part~=gesture-layer] { height: 0; display: block; } ${/* * if gestures are disabled, don't accept pointer-events */ ""} :host(:not([${Attributes.AUDIO}])[${Attributes.GESTURES_DISABLED}]) ::slotted([slot=gestures-chrome]), :host(:not([${Attributes.AUDIO}])[${Attributes.GESTURES_DISABLED}]) media-gesture-receiver[slot=gestures-chrome] { display: none; } ${/* * any slotted element that isn't a poster or media slot should be pointer-events auto * we'll want to add here any slotted elements that shouldn't get pointer-events by default when slotted */ ""} ::slotted(:not([slot=media]):not([slot=poster]):not(media-loading-indicator):not([hidden])) { pointer-events: auto; } :host(:not([${Attributes.AUDIO}])) *[part~=layer][part~=centered-layer] { align-items: center; justify-content: center; } :host(:not([${Attributes.AUDIO}])) ::slotted(media-gesture-receiver[slot=gestures-chrome]), :host(:not([${Attributes.AUDIO}])) media-gesture-receiver[slot=gestures-chrome] { align-self: stretch; flex-grow: 1; } slot[name=middle-chrome] { display: inline; flex-grow: 1; pointer-events: none; background: none; } ${/* Position the media and poster elements to fill the container */ ""} ::slotted([slot=media]), ::slotted([slot=poster]) { width: 100%; height: 100%; } ${/* Video specific styles */ ""} :host(:not([${Attributes.AUDIO}])) .spacer { flex-grow: 1; } ${/* Safari needs this to actually make the element fill the window */ ""} :host(:-webkit-full-screen) { ${/* Needs to use !important otherwise easy to break */ ""} width: 100% !important; height: 100% !important; } ${/* Only add these if auto hide is not disabled */ ""} ::slotted(:not([slot=media]):not([slot=poster]):not([${Attributes.NO_AUTOHIDE}]):not([hidden])) { opacity: 1; transition: opacity 0.25s; } ${/* Hide controls when inactive, not paused, not audio and auto hide not disabled */ ""} :host([${Attributes.USER_INACTIVE}]:not([${MediaUIAttributes.MEDIA_PAUSED}]):not([${MediaUIAttributes.MEDIA_IS_AIRPLAYING}]):not([${MediaUIAttributes.MEDIA_IS_CASTING}]):not([${Attributes.AUDIO}])) ::slotted(:not([slot=media]):not([slot=poster]):not([${Attributes.NO_AUTOHIDE}])) { opacity: 0; transition: opacity 1s; } :host([${Attributes.USER_INACTIVE}]:not([${MediaUIAttributes.MEDIA_PAUSED}]):not([${MediaUIAttributes.MEDIA_IS_CASTING}]):not([${Attributes.AUDIO}])) ::slotted([slot=media]) { cursor: none; } ::slotted(media-control-bar) { align-self: stretch; } ${/* ::slotted([slot=poster]) doesn't work for slot fallback content so hide parent slot instead */ ""} :host(:not([${Attributes.AUDIO}])[${MediaUIAttributes.MEDIA_HAS_PLAYED}]) slot[name=poster] { display: none; } ::slotted([role="menu"]) { align-self: end; } ::slotted([role="dialog"]) { align-self: center; } </style> <slot name="media" part="layer media-layer"></slot> <slot name="poster" part="layer poster-layer"></slot> <slot name="gestures-chrome" part="layer gesture-layer"> <media-gesture-receiver slot="gestures-chrome"></media-gesture-receiver> </slot> <span part="layer vertical-layer"> <slot name="top-chrome" part="top chrome"></slot> <slot name="middle-chrome" part="middle chrome"></slot> <slot name="centered-chrome" part="layer centered-layer center centered chrome"></slot> ${/* default, effectively "bottom-chrome" */ ""} <slot part="bottom chrome"></slot> </span> `; var MEDIA_UI_ATTRIBUTE_NAMES = Object.values(MediaUIAttributes); var defaultBreakpoints = "sm:384 md:576 lg:768 xl:960"; function resizeCallback(entry) { setBreakpoints(entry.target, entry.contentRect.width); } function setBreakpoints(container, width) { var _a3; if (!container.isConnected) return; const breakpoints = (_a3 = container.getAttribute(Attributes.BREAKPOINTS)) != null ? _a3 : defaultBreakpoints; const ranges = createBreakpointMap(breakpoints); const activeBreakpoints = getBreakpoints(ranges, width); let changed = false; Object.keys(ranges).forEach((name) => { if (activeBreakpoints.includes(name)) { if (!container.hasAttribute(`breakpoint${name}`)) { container.setAttribute(`breakpoint${name}`, ""); changed = true; } return; } if (container.hasAttribute(`breakpoint${name}`)) { container.removeAttribute(`breakpoint${name}`); changed = true; } }); if (changed) { const evt = new CustomEvent(MediaStateChangeEvents.BREAKPOINTS_CHANGE, { detail: activeBreakpoints }); container.dispatchEvent(evt); } } function createBreakpointMap(breakpoints) { const pairs = breakpoints.split(/\s+/); return Object.fromEntries(pairs.map((pair) => pair.split(":"))); } function getBreakpoints(breakpoints, width) { return Object.keys(breakpoints).filter((name) => { return width >= parseInt(breakpoints[name]); }); } var MediaContainer = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd2(this, _handlePointerMove); __privateAdd2(this, _handlePointerUp); __privateAdd2(this, _setInactive); __privateAdd2(this, _setActive); __privateAdd2(this, _scheduleInactive); __privateAdd2(this, _pointerDownTimeStamp, 0); __privateAdd2(this, _currentMedia, null); __privateAdd2(this, _inactiveTimeout, null); __privateAdd2(this, _autohide, void 0); this.breakpointsComputed = false; if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template2.content.cloneNode(true)); } const mutationCallback = (mutationsList) => { const media = this.media; for (const mutation of mutationsList) { if (mutation.type === "childList") { mutation.removedNodes.forEach((node2) => { if (node2.slot == "media" && mutation.target == this) { let previousSibling = mutation.previousSibling && mutation.previousSibling.previousElementSibling; if (!previousSibling || !media) { this.mediaUnsetCallback(node2); } else { let wasFirst = previousSibling.slot !== "media"; while ((previousSibling = previousSibling.previousSibling) !== null) { if (previousSibling.slot == "media") wasFirst = false; } if (wasFirst) this.mediaUnsetCallback(node2); } } }); if (media) { mutation.addedNodes.forEach((node2) => { if (node2 === media) { this.handleMediaUpdated(media); } }); } } } }; const mutationObserver = new MutationObserver(mutationCallback); mutationObserver.observe(this, { childList: true, subtree: true }); let pendingResizeCb = false; const deferResizeCallback = (entry) => { if (pendingResizeCb) return; setTimeout(() => { resizeCallback(entry); pendingResizeCb = false; if (!this.breakpointsComputed) { this.breakpointsComputed = true; this.dispatchEvent( new CustomEvent(MediaStateChangeEvents.BREAKPOINTS_COMPUTED, { bubbles: true, composed: true }) ); } }, 0); pendingResizeCb = true; }; observeResize(this, deferResizeCallback); const chainedSlot = this.querySelector( ":scope > slot[slot=media]" ); if (chainedSlot) { chainedSlot.addEventListener("slotchange", () => { const slotEls = chainedSlot.assignedElements({ flatten: true }); if (!slotEls.length) { if (__privateGet2(this, _currentMedia)) { this.mediaUnsetCallback(__privateGet2(this, _currentMedia)); } return; } this.handleMediaUpdated(this.media); }); } } static get observedAttributes() { return [Attributes.AUTOHIDE, Attributes.GESTURES_DISABLED].concat(MEDIA_UI_ATTRIBUTE_NAMES).filter( (name) => ![ MediaUIAttributes.MEDIA_RENDITION_LIST, MediaUIAttributes.MEDIA_AUDIO_TRACK_LIST, MediaUIAttributes.MEDIA_CHAPTERS_CUES, MediaUIAttributes.MEDIA_WIDTH, MediaUIAttributes.MEDIA_HEIGHT ].includes(name) ); } // Could share this code with media-chrome-html-element instead attributeChangedCallback(attrName, oldValue, newValue) { if (attrName.toLowerCase() == Attributes.AUTOHIDE) { this.autohide = newValue; } } // First direct child with slot=media, or null /** * @returns {HTMLVideoElement & * {buffered, * webkitEnterFullscreen?, * webkitExitFullscreen?, * requestCast?, * webkitShowPlaybackTargetPicker?, * videoTracks?, * }} */ get media() { let media = this.querySelector(":scope > [slot=media]"); if ((media == null ? void 0 : media.nodeName) == "SLOT") media = media.assignedElements({ flatten: true })[0]; return media; } /** * @param {HTMLMediaElement} media */ async handleMediaUpdated(media) { if (!media) return; __privateSet2(this, _currentMedia, media); if (media.localName.includes("-")) { await GlobalThis.customElements.whenDefined(media.localName); } this.mediaSetCallback(media); } connectedCallback() { var _a3; const isAudioChrome = this.getAttribute(Attributes.AUDIO) != null; const label = isAudioChrome ? nouns.AUDIO_PLAYER() : nouns.VIDEO_PLAYER(); this.setAttribute("role", "region"); this.setAttribute("aria-label", label); this.handleMediaUpdated(this.media); this.setAttribute(Attributes.USER_INACTIVE, ""); this.addEventListener("pointerdown", this); this.addEventListener("pointermove", this); this.addEventListener("pointerup", this); this.addEventListener("mouseleave", this); this.addEventListener("keyup", this); (_a3 = GlobalThis.window) == null ? void 0 : _a3.addEventListener("mouseup", this); } disconnectedCallback() { var _a3; if (this.media) { this.mediaUnsetCallback(this.media); } (_a3 = GlobalThis.window) == null ? void 0 : _a3.removeEventListener("mouseup", this); } /** * @abstract * @param {HTMLMediaElement} media */ mediaSetCallback(media) { } // eslint-disable-line /** * @param {HTMLMediaElement} media */ mediaUnsetCallback(media) { __privateSet2(this, _currentMedia, null); } handleEvent(event) { switch (event.type) { case "pointerdown": __privateSet2(this, _pointerDownTimeStamp, event.timeStamp); break; case "pointermove": __privateMethod(this, _handlePointerMove, handlePointerMove_fn).call(this, event); break; case "pointerup": __privateMethod(this, _handlePointerUp, handlePointerUp_fn).call(this, event); break; case "mouseleave": __privateMethod(this, _setInactive, setInactive_fn).call(this); break; case "mouseup": this.removeAttribute(Attributes.KEYBOARD_CONTROL); break; case "keyup": __privateMethod(this, _scheduleInactive, scheduleInactive_fn).call(this); this.setAttribute(Attributes.KEYBOARD_CONTROL, ""); break; } } set autohide(seconds) { const parsedSeconds = Number(seconds); __privateSet2(this, _autohide, isNaN(parsedSeconds) ? 0 : parsedSeconds); } get autohide() { return (__privateGet2(this, _autohide) === void 0 ? 2 : __privateGet2(this, _autohide)).toString(); } }; _pointerDownTimeStamp = /* @__PURE__ */ new WeakMap(); _currentMedia = /* @__PURE__ */ new WeakMap(); _inactiveTimeout = /* @__PURE__ */ new WeakMap(); _autohide = /* @__PURE__ */ new WeakMap(); _handlePointerMove = /* @__PURE__ */ new WeakSet(); handlePointerMove_fn = function(event) { if (event.pointerType !== "mouse") { const MAX_TAP_DURATION = 250; if (event.timeStamp - __privateGet2(this, _pointerDownTimeStamp) < MAX_TAP_DURATION) return; } __privateMethod(this, _setActive, setActive_fn).call(this); clearTimeout(__privateGet2(this, _inactiveTimeout)); if ([this, this.media].includes(event.target)) { __privateMethod(this, _scheduleInactive, scheduleInactive_fn).call(this); } }; _handlePointerUp = /* @__PURE__ */ new WeakSet(); handlePointerUp_fn = function(event) { if (event.pointerType === "touch") { const controlsVisible = !this.hasAttribute(Attributes.USER_INACTIVE); if ([this, this.media].includes(event.target) && controlsVisible) { __privateMethod(this, _setInactive, setInactive_fn).call(this); } else { __privateMethod(this, _scheduleInactive, scheduleInactive_fn).call(this); } } else if (event.composedPath().some( (el) => ["media-play-button", "media-fullscreen-button"].includes( el == null ? void 0 : el.localName ) )) { __privateMethod(this, _scheduleInactive, scheduleInactive_fn).call(this); } }; _setInactive = /* @__PURE__ */ new WeakSet(); setInactive_fn = function() { if (__privateGet2(this, _autohide) < 0) return; if (this.hasAttribute(Attributes.USER_INACTIVE)) return; this.setAttribute(Attributes.USER_INACTIVE, ""); const evt = new GlobalThis.CustomEvent( MediaStateChangeEvents.USER_INACTIVE, { composed: true, bubbles: true, detail: true } ); this.dispatchEvent(evt); }; _setActive = /* @__PURE__ */ new WeakSet(); setActive_fn = function() { if (!this.hasAttribute(Attributes.USER_INACTIVE)) return; this.removeAttribute(Attributes.USER_INACTIVE); const evt = new GlobalThis.CustomEvent( MediaStateChangeEvents.USER_INACTIVE, { composed: true, bubbles: true, detail: false } ); this.dispatchEvent(evt); }; _scheduleInactive = /* @__PURE__ */ new WeakSet(); scheduleInactive_fn = function() { __privateMethod(this, _setActive, setActive_fn).call(this); clearTimeout(__privateGet2(this, _inactiveTimeout)); const autohide = parseInt(this.autohide); if (autohide < 0) return; __privateSet2(this, _inactiveTimeout, setTimeout(() => { __privateMethod(this, _setInactive, setInactive_fn).call(this); }, autohide * 1e3)); }; if (!GlobalThis.customElements.get("media-container")) { GlobalThis.customElements.define("media-container", MediaContainer); } // node_modules/media-chrome/dist/utils/attribute-token-list.js var __accessCheck3 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet3 = (obj, member, getter) => { __accessCheck3(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd3 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet3 = (obj, member, value, setter) => { __accessCheck3(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _el; var _attr; var _defaultSet; var _tokenSet; var _tokens; var tokens_get; var AttributeTokenList = class { constructor(el, attr, { defaultValue } = { defaultValue: void 0 }) { __privateAdd3(this, _tokens); __privateAdd3(this, _el, void 0); __privateAdd3(this, _attr, void 0); __privateAdd3(this, _defaultSet, void 0); __privateAdd3(this, _tokenSet, /* @__PURE__ */ new Set()); __privateSet3(this, _el, el); __privateSet3(this, _attr, attr); __privateSet3(this, _defaultSet, new Set(defaultValue)); } [Symbol.iterator]() { return __privateGet3(this, _tokens, tokens_get).values(); } get length() { return __privateGet3(this, _tokens, tokens_get).size; } get value() { var _a3; return (_a3 = [...__privateGet3(this, _tokens, tokens_get)].join(" ")) != null ? _a3 : ""; } set value(val) { var _a3; if (val === this.value) return; __privateSet3(this, _tokenSet, /* @__PURE__ */ new Set()); this.add(...(_a3 = val == null ? void 0 : val.split(" ")) != null ? _a3 : []); } toString() { return this.value; } item(index2) { return [...__privateGet3(this, _tokens, tokens_get)][index2]; } values() { return __privateGet3(this, _tokens, tokens_get).values(); } forEach(callback, thisArg) { __privateGet3(this, _tokens, tokens_get).forEach(callback, thisArg); } add(...tokens) { var _a3, _b; tokens.forEach((t2) => __privateGet3(this, _tokenSet).add(t2)); if (this.value === "" && !((_a3 = __privateGet3(this, _el)) == null ? void 0 : _a3.hasAttribute(`${__privateGet3(this, _attr)}`))) { return; } (_b = __privateGet3(this, _el)) == null ? void 0 : _b.setAttribute(`${__privateGet3(this, _attr)}`, `${this.value}`); } remove(...tokens) { var _a3; tokens.forEach((t2) => __privateGet3(this, _tokenSet).delete(t2)); (_a3 = __privateGet3(this, _el)) == null ? void 0 : _a3.setAttribute(`${__privateGet3(this, _attr)}`, `${this.value}`); } contains(token2) { return __privateGet3(this, _tokens, tokens_get).has(token2); } toggle(token2, force) { if (typeof force !== "undefined") { if (force) { this.add(token2); return true; } else { this.remove(token2); return false; } } if (this.contains(token2)) { this.remove(token2); return false; } this.add(token2); return true; } replace(oldToken, newToken) { this.remove(oldToken); this.add(newToken); return oldToken === newToken; } }; _el = /* @__PURE__ */ new WeakMap(); _attr = /* @__PURE__ */ new WeakMap(); _defaultSet = /* @__PURE__ */ new WeakMap(); _tokenSet = /* @__PURE__ */ new WeakMap(); _tokens = /* @__PURE__ */ new WeakSet(); tokens_get = function() { return __privateGet3(this, _tokenSet).size ? __privateGet3(this, _tokenSet) : __privateGet3(this, _defaultSet); }; // node_modules/media-chrome/dist/utils/captions.js var splitTextTracksStr = (textTracksStr = "") => textTracksStr.split(/\s+/); var parseTextTrackStr = (textTrackStr = "") => { const [kind, language, encodedLabel] = textTrackStr.split(":"); const label = encodedLabel ? decodeURIComponent(encodedLabel) : void 0; return { kind: kind === "cc" ? TextTrackKinds.CAPTIONS : TextTrackKinds.SUBTITLES, language, label }; }; var parseTextTracksStr = (textTracksStr = "", textTrackLikeObj = {}) => { return splitTextTracksStr(textTracksStr).map((textTrackStr) => { const textTrackObj = parseTextTrackStr(textTrackStr); return { ...textTrackLikeObj, ...textTrackObj }; }); }; var parseTracks = (trackOrTracks) => { if (!trackOrTracks) return []; if (Array.isArray(trackOrTracks)) { return trackOrTracks.map((trackObjOrStr) => { if (typeof trackObjOrStr === "string") { return parseTextTrackStr(trackObjOrStr); } return trackObjOrStr; }); } if (typeof trackOrTracks === "string") { return parseTextTracksStr(trackOrTracks); } return [trackOrTracks]; }; var formatTextTrackObj = ({ kind, label, language } = { kind: "subtitles" }) => { if (!label) return language; return `${kind === "captions" ? "cc" : "sb"}:${language}:${encodeURIComponent( label )}`; }; var stringifyTextTrackList = (textTracks = []) => { return Array.prototype.map.call(textTracks, formatTextTrackObj).join(" "); }; var isMatchingPropOf = (key, value) => (obj) => obj[key] === value; var textTrackObjAsPred = (filterObj) => { const preds = Object.entries(filterObj).map(([key, value]) => { return isMatchingPropOf(key, value); }); return (textTrack) => preds.every((pred) => pred(textTrack)); }; var updateTracksModeTo = (mode, tracks = [], tracksToUpdate = []) => { const preds = parseTracks(tracksToUpdate).map(textTrackObjAsPred); const isTrackToUpdate = (textTrack) => { return preds.some((pred) => pred(textTrack)); }; Array.from(tracks).filter(isTrackToUpdate).forEach((textTrack) => { textTrack.mode = mode; }); }; var getTextTracksList = (media, filterPredOrObj = () => true) => { if (!(media == null ? void 0 : media.textTracks)) return []; const filterPred = typeof filterPredOrObj === "function" ? filterPredOrObj : textTrackObjAsPred(filterPredOrObj); return Array.from(media.textTracks).filter(filterPred); }; var areSubsOn = (el) => { var _a3; const showingSubtitles = !!((_a3 = el.mediaSubtitlesShowing) == null ? void 0 : _a3.length) || el.hasAttribute(MediaUIAttributes.MEDIA_SUBTITLES_SHOWING); return showingSubtitles; }; // node_modules/media-chrome/dist/utils/fullscreen-api.js var enterFullscreen = (stateOwners) => { var _a3; const { media, fullscreenElement } = stateOwners; const enterFullscreenKey = fullscreenElement && "requestFullscreen" in fullscreenElement ? "requestFullscreen" : fullscreenElement && "webkitRequestFullScreen" in fullscreenElement ? "webkitRequestFullScreen" : void 0; if (enterFullscreenKey) { const maybePromise = (_a3 = fullscreenElement[enterFullscreenKey]) == null ? void 0 : _a3.call(fullscreenElement); if (maybePromise instanceof Promise) { return maybePromise.catch(() => { }); } } else if (media == null ? void 0 : media.webkitEnterFullscreen) { media.webkitEnterFullscreen(); } else if (media == null ? void 0 : media.requestFullscreen) { media.requestFullscreen(); } }; var exitFullscreenKey = "exitFullscreen" in Document2 ? "exitFullscreen" : "webkitExitFullscreen" in Document2 ? "webkitExitFullscreen" : "webkitCancelFullScreen" in Document2 ? "webkitCancelFullScreen" : void 0; var exitFullscreen = (stateOwners) => { var _a3; const { documentElement } = stateOwners; if (exitFullscreenKey) { const maybePromise = (_a3 = documentElement == null ? void 0 : documentElement[exitFullscreenKey]) == null ? void 0 : _a3.call(documentElement); if (maybePromise instanceof Promise) { return maybePromise.catch(() => { }); } } }; var fullscreenElementKey = "fullscreenElement" in Document2 ? "fullscreenElement" : "webkitFullscreenElement" in Document2 ? "webkitFullscreenElement" : void 0; var getFullscreenElement = (stateOwners) => { const { documentElement, media } = stateOwners; const docFullscreenElement = documentElement == null ? void 0 : documentElement[fullscreenElementKey]; if (!docFullscreenElement && "webkitDisplayingFullscreen" in media && "webkitPresentationMode" in media && media.webkitDisplayingFullscreen && media.webkitPresentationMode === WebkitPresentationModes.FULLSCREEN) { return media; } return docFullscreenElement; }; var isFullscreen = (stateOwners) => { var _a3; const { media, documentElement, fullscreenElement = media } = stateOwners; if (!media || !documentElement) return false; const currentFullscreenElement = getFullscreenElement(stateOwners); if (!currentFullscreenElement) return false; if (currentFullscreenElement === fullscreenElement || currentFullscreenElement === media) { return true; } if (currentFullscreenElement.localName.includes("-")) { let currentRoot = currentFullscreenElement.shadowRoot; if (!(fullscreenElementKey in currentRoot)) { return containsComposedNode( currentFullscreenElement, /** @TODO clean up type assumptions (e.g. Node) (CJP) */ // @ts-ignore fullscreenElement ); } while (currentRoot == null ? void 0 : currentRoot[fullscreenElementKey]) { if (currentRoot[fullscreenElementKey] === fullscreenElement) return true; currentRoot = (_a3 = currentRoot[fullscreenElementKey]) == null ? void 0 : _a3.shadowRoot; } } return false; }; var fullscreenEnabledKey = "fullscreenEnabled" in Document2 ? "fullscreenEnabled" : "webkitFullscreenEnabled" in Document2 ? "webkitFullscreenEnabled" : void 0; var isFullscreenEnabled = (stateOwners) => { const { documentElement, media } = stateOwners; return !!(documentElement == null ? void 0 : documentElement[fullscreenEnabledKey]) || media && "webkitSupportsFullscreen" in media; }; // node_modules/media-chrome/dist/utils/platform-tests.js var testMediaEl; var getTestMediaEl = () => { var _a3, _b; if (testMediaEl) return testMediaEl; testMediaEl = (_b = (_a3 = Document2) == null ? void 0 : _a3.createElement) == null ? void 0 : _b.call(_a3, "video"); return testMediaEl; }; var hasVolumeSupportAsync = async (mediaEl = getTestMediaEl()) => { if (!mediaEl) return false; const prevVolume = mediaEl.volume; mediaEl.volume = prevVolume / 2 + 0.1; const abortController = new AbortController(); const volumeSupported2 = await Promise.race([ dispatchedVolumeChange(mediaEl, abortController.signal), volumeChanged(mediaEl, prevVolume) ]); abortController.abort(); return volumeSupported2; }; var dispatchedVolumeChange = (mediaEl, signal) => { return new Promise((resolve) => { mediaEl.addEventListener("volumechange", () => resolve(true), { signal }); }); }; var volumeChanged = async (mediaEl, prevVolume) => { for (let i3 = 0; i3 < 10; i3++) { if (mediaEl.volume === prevVolume) return false; await delay(10); } return mediaEl.volume !== prevVolume; }; var isSafari = /.*Version\/.*Safari\/.*/.test( GlobalThis.navigator.userAgent ); var hasPipSupport = (mediaEl = getTestMediaEl()) => { if (GlobalThis.matchMedia("(display-mode: standalone)").matches && isSafari) return false; return typeof (mediaEl == null ? void 0 : mediaEl.requestPictureInPicture) === "function"; }; var hasFullscreenSupport = (mediaEl = getTestMediaEl()) => { return isFullscreenEnabled({ documentElement: Document2, media: mediaEl }); }; var fullscreenSupported = hasFullscreenSupport(); var pipSupported = hasPipSupport(); var airplaySupported = !!GlobalThis.WebKitPlaybackTargetAvailabilityEvent; var castSupported = !!GlobalThis.chrome; // node_modules/media-chrome/dist/media-store/util.js var getSubtitleTracks = (stateOwners) => { return getTextTracksList(stateOwners.media, (textTrack) => { return [TextTrackKinds.SUBTITLES, TextTrackKinds.CAPTIONS].includes( textTrack.kind ); }).sort((a2, b2) => a2.kind >= b2.kind ? 1 : -1); }; var getShowingSubtitleTracks = (stateOwners) => { return getTextTracksList(stateOwners.media, (textTrack) => { return textTrack.mode === TextTrackModes.SHOWING && [TextTrackKinds.SUBTITLES, TextTrackKinds.CAPTIONS].includes( textTrack.kind ); }); }; var toggleSubtitleTracks = (stateOwners, force) => { const tracks = getSubtitleTracks(stateOwners); const showingSubitleTracks = getShowingSubtitleTracks(stateOwners); const subtitlesShowing = !!showingSubitleTracks.length; if (!tracks.length) return; if (force === false || subtitlesShowing && force !== true) { updateTracksModeTo(TextTrackModes.DISABLED, tracks, showingSubitleTracks); } else if (force === true || !subtitlesShowing && force !== false) { let subTrack = tracks[0]; const { options: options2 } = stateOwners; if (!(options2 == null ? void 0 : options2.noSubtitlesLangPref)) { const subtitlesPref = globalThis.localStorage.getItem( "media-chrome-pref-subtitles-lang" ); const userLangPrefs = subtitlesPref ? [subtitlesPref, ...globalThis.navigator.languages] : globalThis.navigator.languages; const preferredAvailableSubs = tracks.filter((textTrack) => { return userLangPrefs.some( (lang) => textTrack.language.toLowerCase().startsWith(lang.split("-")[0]) ); }).sort((textTrackA, textTrackB) => { const idxA = userLangPrefs.findIndex( (lang) => textTrackA.language.toLowerCase().startsWith(lang.split("-")[0]) ); const idxB = userLangPrefs.findIndex( (lang) => textTrackB.language.toLowerCase().startsWith(lang.split("-")[0]) ); return idxA - idxB; }); if (preferredAvailableSubs[0]) { subTrack = preferredAvailableSubs[0]; } } const { language, label, kind } = subTrack; updateTracksModeTo(TextTrackModes.DISABLED, tracks, showingSubitleTracks); updateTracksModeTo(TextTrackModes.SHOWING, tracks, [ { language, label, kind } ]); } }; var areValuesEq = (x2, y4) => { if (x2 === y4) return true; if (typeof x2 !== typeof y4) return false; if (typeof x2 === "number" && Number.isNaN(x2) && Number.isNaN(y4)) return true; if (typeof x2 !== "object") return false; if (Array.isArray(x2)) return areArraysEq(x2, y4); return Object.entries(x2).every( // NOTE: Checking key in y to disambiguate between between missing keys and keys whose value are undefined (CJP) ([key, value]) => key in y4 && areValuesEq(value, y4[key]) ); }; var areArraysEq = (xs, ys) => { const xIsArray = Array.isArray(xs); const yIsArray = Array.isArray(ys); if (xIsArray !== yIsArray) return false; if (!(xIsArray || yIsArray)) return true; if (xs.length !== ys.length) return false; return xs.every((x2, i3) => areValuesEq(x2, ys[i3])); }; // node_modules/media-chrome/dist/media-store/state-mediator.js var StreamTypeValues = Object.values(StreamTypes); var volumeSupported; var volumeSupportPromise = hasVolumeSupportAsync().then((supported) => { volumeSupported = supported; return volumeSupported; }); var prepareStateOwners = async (...stateOwners) => { await Promise.all( stateOwners.filter((x2) => x2).map(async (stateOwner) => { if (!("localName" in stateOwner && stateOwner instanceof GlobalThis.HTMLElement)) { return; } const name = stateOwner.localName; if (!name.includes("-")) return; const classDef = GlobalThis.customElements.get(name); if (classDef && stateOwner instanceof classDef) return; await GlobalThis.customElements.whenDefined(name); GlobalThis.customElements.upgrade(stateOwner); }) ); }; var stateMediator = { mediaWidth: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.videoWidth) != null ? _a3 : 0; }, mediaEvents: ["resize"] }, mediaHeight: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.videoHeight) != null ? _a3 : 0; }, mediaEvents: ["resize"] }, mediaPaused: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.paused) != null ? _a3 : true; }, set(value, stateOwners) { var _a3; const { media } = stateOwners; if (!media) return; if (value) { media.pause(); } else { (_a3 = media.play()) == null ? void 0 : _a3.catch(() => { }); } }, mediaEvents: ["play", "playing", "pause", "emptied"] }, mediaHasPlayed: { // We want to let the user know that the media started playing at any point (`media-has-played`). // Since these propagators are all called when boostrapping state, let's verify this is // a real playing event by checking that 1) there's media and 2) it isn't currently paused. get(stateOwners, event) { const { media } = stateOwners; if (!media) return false; if (!event) return !media.paused; return event.type === "playing"; }, mediaEvents: ["playing", "emptied"] }, mediaEnded: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.ended) != null ? _a3 : false; }, mediaEvents: ["seeked", "ended", "emptied"] }, mediaPlaybackRate: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.playbackRate) != null ? _a3 : 1; }, set(value, stateOwners) { const { media } = stateOwners; if (!media) return; if (!Number.isFinite(+value)) return; media.playbackRate = +value; }, mediaEvents: ["ratechange", "loadstart"] }, mediaMuted: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.muted) != null ? _a3 : false; }, set(value, stateOwners) { const { media } = stateOwners; if (!media) return; media.muted = value; }, mediaEvents: ["volumechange"] }, mediaVolume: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.volume) != null ? _a3 : 1; }, set(value, stateOwners) { const { media } = stateOwners; if (!media) return; try { if (value == null) { GlobalThis.localStorage.removeItem("media-chrome-pref-volume"); } else { GlobalThis.localStorage.setItem( "media-chrome-pref-volume", value.toString() ); } } catch (err) { } if (!Number.isFinite(+value)) return; media.volume = +value; }, mediaEvents: ["volumechange"], stateOwnersUpdateHandlers: [ (handler, stateOwners) => { const { options: { noVolumePref } } = stateOwners; if (noVolumePref) return; try { const volumePref = GlobalThis.localStorage.getItem( "media-chrome-pref-volume" ); if (volumePref == null) return; stateMediator.mediaVolume.set(+volumePref, stateOwners); handler(+volumePref); } catch (e) { console.debug("Error getting volume pref", e); } } ] }, // NOTE: Keeping this roughly equivalent to prior impl to reduce number of changes, // however we may want to model "derived" state differently from "primary" state // (in this case, derived === mediaVolumeLevel, primary === mediaMuted, mediaVolume) (CJP) mediaVolumeLevel: { get(stateOwners) { const { media } = stateOwners; if (typeof (media == null ? void 0 : media.volume) == "undefined") return "high"; if (media.muted || media.volume === 0) return "off"; if (media.volume < 0.5) return "low"; if (media.volume < 0.75) return "medium"; return "high"; }, mediaEvents: ["volumechange"] }, mediaCurrentTime: { get(stateOwners) { var _a3; const { media } = stateOwners; return (_a3 = media == null ? void 0 : media.currentTime) != null ? _a3 : 0; }, set(value, stateOwners) { const { media } = stateOwners; if (!media || !isValidNumber(value)) return; media.currentTime = value; }, mediaEvents: ["timeupdate", "loadedmetadata"] }, mediaDuration: { get(stateOwners) { const { media, options: { defaultDuration } = {} } = stateOwners; if (defaultDuration && (!media || !media.duration || Number.isNaN(media.duration) || !Number.isFinite(media.duration))) { return defaultDuration; } return Number.isFinite(media == null ? void 0 : media.duration) ? media.duration : Number.NaN; }, mediaEvents: ["durationchange", "loadedmetadata", "emptied"] }, mediaLoading: { get(stateOwners) { const { media } = stateOwners; return (media == null ? void 0 : media.readyState) < 3; }, mediaEvents: ["waiting", "playing", "emptied"] }, mediaSeekable: { get(stateOwners) { var _a3; const { media } = stateOwners; if (!((_a3 = media == null ? void 0 : media.seekable) == null ? void 0 : _a3.length)) return void 0; const start = media.seekable.start(0); const end = media.seekable.end(media.seekable.length - 1); if (!start && !end) return void 0; return [Number(start.toFixed(3)), Number(end.toFixed(3))]; }, mediaEvents: ["loadedmetadata", "emptied", "progress", "seekablechange"] }, mediaBuffered: { get(stateOwners) { var _a3; const { media } = stateOwners; const timeRanges = (_a3 = media == null ? void 0 : media.buffered) != null ? _a3 : []; return Array.from(timeRanges).map((_3, i3) => [ Number(timeRanges.start(i3).toFixed(3)), Number(timeRanges.end(i3).toFixed(3)) ]); }, mediaEvents: ["progress", "emptied"] }, mediaStreamType: { get(stateOwners) { const { media, options: { defaultStreamType } = {} } = stateOwners; const usedDefaultStreamType = [ StreamTypes.LIVE, StreamTypes.ON_DEMAND ].includes(defaultStreamType) ? defaultStreamType : void 0; if (!media) return usedDefaultStreamType; const { streamType } = media; if (StreamTypeValues.includes(streamType)) { if (streamType === StreamTypes.UNKNOWN) { return usedDefaultStreamType; } return streamType; } const duration = media.duration; if (duration === Infinity) { return StreamTypes.LIVE; } else if (Number.isFinite(duration)) { return StreamTypes.ON_DEMAND; } return usedDefaultStreamType; }, mediaEvents: [ "emptied", "durationchange", "loadedmetadata", "streamtypechange" ] }, mediaTargetLiveWindow: { get(stateOwners) { const { media } = stateOwners; if (!media) return Number.NaN; const { targetLiveWindow } = media; const streamType = stateMediator.mediaStreamType.get(stateOwners); if ((targetLiveWindow == null || Number.isNaN(targetLiveWindow)) && streamType === StreamTypes.LIVE) { return 0; } return targetLiveWindow; }, mediaEvents: [ "emptied", "durationchange", "loadedmetadata", "streamtypechange", "targetlivewindowchange" ] }, mediaTimeIsLive: { get(stateOwners) { const { media, // Default to 10 seconds options: { liveEdgeOffset = 10 } = {} } = stateOwners; if (!media) return false; if (typeof media.liveEdgeStart === "number") { if (Number.isNaN(media.liveEdgeStart)) return false; return media.currentTime >= media.liveEdgeStart; } const live = stateMediator.mediaStreamType.get(stateOwners) === StreamTypes.LIVE; if (!live) return false; const seekable = media.seekable; if (!seekable) return true; if (!seekable.length) return false; const liveEdgeStart = seekable.end(seekable.length - 1) - liveEdgeOffset; return media.currentTime >= liveEdgeStart; }, mediaEvents: ["playing", "timeupdate", "progress", "waiting", "emptied"] }, // Text Tracks modeling mediaSubtitlesList: { get(stateOwners) { return getSubtitleTracks(stateOwners).map( ({ kind, label, language }) => ({ kind, label, language }) ); }, mediaEvents: ["loadstart"], textTracksEvents: ["addtrack", "removetrack"] }, mediaSubtitlesShowing: { get(stateOwners) { return getShowingSubtitleTracks(stateOwners).map( ({ kind, label, language }) => ({ kind, label, language }) ); }, mediaEvents: ["loadstart"], textTracksEvents: ["addtrack", "removetrack", "change"], stateOwnersUpdateHandlers: [ (_handler, stateOwners) => { var _a3, _b; const { media, options: options2 } = stateOwners; if (!media) return; const updateDefaultSubtitlesCallback = (event) => { var _a22; if (!options2.defaultSubtitles) return; const nonSubsEvent = event && ![TextTrackKinds.CAPTIONS, TextTrackKinds.SUBTITLES].includes( // @ts-ignore (_a22 = event == null ? void 0 : event.track) == null ? void 0 : _a22.kind ); if (nonSubsEvent) return; toggleSubtitleTracks(stateOwners, true); }; (_a3 = media.textTracks) == null ? void 0 : _a3.addEventListener( "addtrack", updateDefaultSubtitlesCallback ); (_b = media.textTracks) == null ? void 0 : _b.addEventListener( "removetrack", updateDefaultSubtitlesCallback ); updateDefaultSubtitlesCallback(); return () => { var _a22, _b2; (_a22 = media.textTracks) == null ? void 0 : _a22.removeEventListener( "addtrack", updateDefaultSubtitlesCallback ); (_b2 = media.textTracks) == null ? void 0 : _b2.removeEventListener( "removetrack", updateDefaultSubtitlesCallback ); }; } ] }, mediaChaptersCues: { get(stateOwners) { var _a3; const { media } = stateOwners; if (!media) return []; const [chaptersTrack] = getTextTracksList(media, { kind: TextTrackKinds.CHAPTERS }); return Array.from((_a3 = chaptersTrack == null ? void 0 : chaptersTrack.cues) != null ? _a3 : []).map( ({ text, startTime, endTime }) => ({ text, startTime, endTime }) ); }, mediaEvents: ["loadstart", "loadedmetadata"], textTracksEvents: ["addtrack", "removetrack", "change"], stateOwnersUpdateHandlers: [ (handler, stateOwners) => { var _a3; const { media } = stateOwners; if (!media) return; const chaptersTrack = media.querySelector( 'track[kind="chapters"][default][src]' ); const shadowChaptersTrack = (_a3 = media.shadowRoot) == null ? void 0 : _a3.querySelector( ':is(video,audio) > track[kind="chapters"][default][src]' ); chaptersTrack == null ? void 0 : chaptersTrack.addEventListener("load", handler); shadowChaptersTrack == null ? void 0 : shadowChaptersTrack.addEventListener("load", handler); return () => { chaptersTrack == null ? void 0 : chaptersTrack.removeEventListener("load", handler); shadowChaptersTrack == null ? void 0 : shadowChaptersTrack.removeEventListener("load", handler); }; } ] }, // Modeling state tied to root node mediaIsPip: { get(stateOwners) { var _a3, _b; const { media, documentElement } = stateOwners; if (!media || !documentElement) return false; if (!documentElement.pictureInPictureElement) return false; if (documentElement.pictureInPictureElement === media) return true; if (documentElement.pictureInPictureElement instanceof HTMLMediaElement) { if (!((_a3 = media.localName) == null ? void 0 : _a3.includes("-"))) return false; return containsComposedNode( media, documentElement.pictureInPictureElement ); } if (documentElement.pictureInPictureElement.localName.includes("-")) { let currentRoot = documentElement.pictureInPictureElement.shadowRoot; while (currentRoot == null ? void 0 : currentRoot.pictureInPictureElement) { if (currentRoot.pictureInPictureElement === media) return true; currentRoot = (_b = currentRoot.pictureInPictureElement) == null ? void 0 : _b.shadowRoot; } } return false; }, set(value, stateOwners) { const { media } = stateOwners; if (!media) return; if (value) { if (!Document2.pictureInPictureEnabled) { console.warn("MediaChrome: Picture-in-picture is not enabled"); return; } if (!media.requestPictureInPicture) { console.warn( "MediaChrome: The current media does not support picture-in-picture" ); return; } const warnNotReady = () => { console.warn( "MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0." ); }; media.requestPictureInPicture().catch((err) => { if (err.code === 11) { if (!media.src) { console.warn( "MediaChrome: The media is not ready for picture-in-picture. It must have a src set." ); return; } if (media.readyState === 0 && media.preload === "none") { const cleanup = () => { media.removeEventListener("loadedmetadata", tryPip); media.preload = "none"; }; const tryPip = () => { media.requestPictureInPicture().catch(warnNotReady); cleanup(); }; media.addEventListener("loadedmetadata", tryPip); media.preload = "metadata"; setTimeout(() => { if (media.readyState === 0) warnNotReady(); cleanup(); }, 1e3); } else { throw err; } } else { throw err; } }); } else if (Document2.pictureInPictureElement) { Document2.exitPictureInPicture(); } }, mediaEvents: ["enterpictureinpicture", "leavepictureinpicture"] }, mediaRenditionList: { get(stateOwners) { var _a3; const { media } = stateOwners; return [...(_a3 = media == null ? void 0 : media.videoRenditions) != null ? _a3 : []].map((videoRendition) => ({ ...videoRendition })); }, mediaEvents: ["emptied", "loadstart"], videoRenditionsEvents: ["addrendition", "removerendition"] }, /** @TODO Model this as a derived value? (CJP) */ mediaRenditionSelected: { get(stateOwners) { var _a3, _b, _c; const { media } = stateOwners; return (_c = (_b = media == null ? void 0 : media.videoRenditions) == null ? void 0 : _b[(_a3 = media.videoRenditions) == null ? void 0 : _a3.selectedIndex]) == null ? void 0 : _c.id; }, set(value, stateOwners) { const { media } = stateOwners; if (!(media == null ? void 0 : media.videoRenditions)) { console.warn( "MediaController: Rendition selection not supported by this media." ); return; } const renditionId = value; const index2 = Array.prototype.findIndex.call( media.videoRenditions, (r9) => r9.id == renditionId ); if (media.videoRenditions.selectedIndex != index2) { media.videoRenditions.selectedIndex = index2; } }, mediaEvents: ["emptied"], videoRenditionsEvents: ["addrendition", "removerendition", "change"] }, mediaAudioTrackList: { get(stateOwners) { var _a3; const { media } = stateOwners; return [...(_a3 = media == null ? void 0 : media.audioTracks) != null ? _a3 : []]; }, mediaEvents: ["emptied", "loadstart"], audioTracksEvents: ["addtrack", "removetrack"] }, mediaAudioTrackEnabled: { get(stateOwners) { var _a3, _b; const { media } = stateOwners; return (_b = [...(_a3 = media == null ? void 0 : media.audioTracks) != null ? _a3 : []].find( (audioTrack) => audioTrack.enabled )) == null ? void 0 : _b.id; }, set(value, stateOwners) { const { media } = stateOwners; if (!(media == null ? void 0 : media.audioTracks)) { console.warn( "MediaChrome: Audio track selection not supported by this media." ); return; } const audioTrackId = value; for (const track of media.audioTracks) { track.enabled = audioTrackId == track.id; } }, mediaEvents: ["emptied"], audioTracksEvents: ["addtrack", "removetrack", "change"] }, mediaIsFullscreen: { get(stateOwners) { return isFullscreen(stateOwners); }, set(value, stateOwners) { if (!value) { exitFullscreen(stateOwners); } else { enterFullscreen(stateOwners); } }, // older Safari version may require webkit-specific events rootEvents: ["fullscreenchange", "webkitfullscreenchange"], // iOS requires webkit-specific events on the video. mediaEvents: ["webkitbeginfullscreen", "webkitendfullscreen", "webkitpresentationmodechanged"] }, mediaIsCasting: { // Note this relies on a customized castable-video element. get(stateOwners) { var _a3; const { media } = stateOwners; if (!(media == null ? void 0 : media.remote) || ((_a3 = media.remote) == null ? void 0 : _a3.state) === "disconnected") return false; return !!media.remote.state; }, set(value, stateOwners) { var _a3, _b; const { media } = stateOwners; if (!media) return; if (value && ((_a3 = media.remote) == null ? void 0 : _a3.state) !== "disconnected") return; if (!value && ((_b = media.remote) == null ? void 0 : _b.state) !== "connected") return; if (typeof media.remote.prompt !== "function") { console.warn( "MediaChrome: Casting is not supported in this environment" ); return; } media.remote.prompt().catch(() => { }); }, remoteEvents: ["connect", "connecting", "disconnect"] }, // NOTE: Newly added state for tracking airplaying mediaIsAirplaying: { // NOTE: Cannot know if airplaying since Safari doesn't fully support HTMLMediaElement::remote yet (e.g. remote::state) (CJP) get() { return false; }, set(_value2, stateOwners) { const { media } = stateOwners; if (!media) return; if (!(media.webkitShowPlaybackTargetPicker && GlobalThis.WebKitPlaybackTargetAvailabilityEvent)) { console.warn( "MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment" ); return; } media.webkitShowPlaybackTargetPicker(); }, mediaEvents: ["webkitcurrentplaybacktargetiswirelesschanged"] }, mediaFullscreenUnavailable: { get(stateOwners) { const { media } = stateOwners; if (!fullscreenSupported || !hasFullscreenSupport(media)) return AvailabilityStates.UNSUPPORTED; return void 0; } }, mediaPipUnavailable: { get(stateOwners) { const { media } = stateOwners; if (!pipSupported || !hasPipSupport(media)) return AvailabilityStates.UNSUPPORTED; } }, mediaVolumeUnavailable: { get(stateOwners) { const { media } = stateOwners; if (volumeSupported === false || (media == null ? void 0 : media.volume) == void 0) { return AvailabilityStates.UNSUPPORTED; } return void 0; }, // NOTE: Slightly different impl here. Added generic support for // "stateOwnersUpdateHandlers" since the original impl had to hack around // race conditions. (CJP) stateOwnersUpdateHandlers: [ (handler) => { if (volumeSupported == null) { volumeSupportPromise.then( (supported) => handler(supported ? void 0 : AvailabilityStates.UNSUPPORTED) ); } } ] }, mediaCastUnavailable: { // @ts-ignore get(stateOwners, { availability = "not-available" } = {}) { var _a3; const { media } = stateOwners; if (!castSupported || !((_a3 = media == null ? void 0 : media.remote) == null ? void 0 : _a3.state)) { return AvailabilityStates.UNSUPPORTED; } if (availability == null || availability === "available") return void 0; return AvailabilityStates.UNAVAILABLE; }, stateOwnersUpdateHandlers: [ (handler, stateOwners) => { var _a3; const { media } = stateOwners; if (!media) return; const remotePlaybackDisabled = media.disableRemotePlayback || media.hasAttribute("disableremoteplayback"); if (!remotePlaybackDisabled) { (_a3 = media == null ? void 0 : media.remote) == null ? void 0 : _a3.watchAvailability((availabilityBool) => { const availability = availabilityBool ? "available" : "not-available"; handler({ availability }); }).catch((error) => { if (error.name === "NotSupportedError") { handler({ availability: null }); } else { handler({ availability: "not-available" }); } }); } return () => { var _a22; (_a22 = media == null ? void 0 : media.remote) == null ? void 0 : _a22.cancelWatchAvailability().catch(() => { }); }; } ] }, mediaAirplayUnavailable: { get(_stateOwners, event) { if (!airplaySupported) return AvailabilityStates.UNSUPPORTED; if ((event == null ? void 0 : event.availability) === "not-available") { return AvailabilityStates.UNAVAILABLE; } return void 0; }, // NOTE: Keeping this event, as it's still the documented way of monitoring // for AirPlay availability from Apple. // See: https://developer.apple.com/documentation/webkitjs/adding_an_airplay_button_to_your_safari_media_controls#2940021 (CJP) mediaEvents: ["webkitplaybacktargetavailabilitychanged"], stateOwnersUpdateHandlers: [ (handler, stateOwners) => { var _a3; const { media } = stateOwners; if (!media) return; const remotePlaybackDisabled = media.disableRemotePlayback || media.hasAttribute("disableremoteplayback"); if (!remotePlaybackDisabled) { (_a3 = media == null ? void 0 : media.remote) == null ? void 0 : _a3.watchAvailability((availabilityBool) => { const availability = availabilityBool ? "available" : "not-available"; handler({ availability }); }).catch((error) => { if (error.name === "NotSupportedError") { handler({ availability: null }); } else { handler({ availability: "not-available" }); } }); } return () => { var _a22; (_a22 = media == null ? void 0 : media.remote) == null ? void 0 : _a22.cancelWatchAvailability().catch(() => { }); }; } ] }, mediaRenditionUnavailable: { get(stateOwners) { var _a3; const { media } = stateOwners; if (!(media == null ? void 0 : media.videoRenditions)) { return AvailabilityStates.UNSUPPORTED; } if (!((_a3 = media.videoRenditions) == null ? void 0 : _a3.length)) { return AvailabilityStates.UNAVAILABLE; } return void 0; }, mediaEvents: ["emptied", "loadstart"], videoRenditionsEvents: ["addrendition", "removerendition"] }, mediaAudioTrackUnavailable: { get(stateOwners) { var _a3, _b; const { media } = stateOwners; if (!(media == null ? void 0 : media.audioTracks)) { return AvailabilityStates.UNSUPPORTED; } if (((_b = (_a3 = media.audioTracks) == null ? void 0 : _a3.length) != null ? _b : 0) <= 1) { return AvailabilityStates.UNAVAILABLE; } return void 0; }, mediaEvents: ["emptied", "loadstart"], audioTracksEvents: ["addtrack", "removetrack"] } }; // node_modules/media-chrome/dist/media-store/request-map.js var requestMap = { /** * @TODO Consider adding state to `StateMediator` for e.g. `mediaThumbnailCues` and use that for derived state here (CJP) */ [MediaUIEvents.MEDIA_PREVIEW_REQUEST](stateMediator2, stateOwners, { detail }) { var _a3, _b, _c; const { media } = stateOwners; const mediaPreviewTime = detail != null ? detail : void 0; let mediaPreviewImage = void 0; let mediaPreviewCoords = void 0; if (media && mediaPreviewTime != null) { const [track] = getTextTracksList(media, { kind: TextTrackKinds.METADATA, label: "thumbnails" }); const cue = Array.prototype.find.call((_a3 = track == null ? void 0 : track.cues) != null ? _a3 : [], (c3, i3, cs) => { if (i3 === 0) return c3.endTime > mediaPreviewTime; if (i3 === cs.length - 1) return c3.startTime <= mediaPreviewTime; return c3.startTime <= mediaPreviewTime && c3.endTime > mediaPreviewTime; }); if (cue) { const base = !/'^(?:[a-z]+:)?\/\//i.test(cue.text) ? (_b = media == null ? void 0 : media.querySelector( 'track[label="thumbnails"]' )) == null ? void 0 : _b.src : void 0; const url = new URL(cue.text, base); const previewCoordsStr = new URLSearchParams(url.hash).get("#xywh"); mediaPreviewCoords = previewCoordsStr.split(",").map((numStr) => +numStr); mediaPreviewImage = url.href; } } const mediaDuration = stateMediator2.mediaDuration.get(stateOwners); const mediaChaptersCues = stateMediator2.mediaChaptersCues.get(stateOwners); let mediaPreviewChapter = (_c = mediaChaptersCues.find((c3, i3, cs) => { if (i3 === cs.length - 1 && mediaDuration === c3.endTime) { return c3.startTime <= mediaPreviewTime && c3.endTime >= mediaPreviewTime; } return c3.startTime <= mediaPreviewTime && c3.endTime > mediaPreviewTime; })) == null ? void 0 : _c.text; if (detail != null && mediaPreviewChapter == null) { mediaPreviewChapter = ""; } return { mediaPreviewTime, mediaPreviewImage, mediaPreviewCoords, mediaPreviewChapter }; }, [MediaUIEvents.MEDIA_PAUSE_REQUEST](stateMediator2, stateOwners) { const key = "mediaPaused"; const value = true; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_PLAY_REQUEST](stateMediator2, stateOwners) { var _a3; const key = "mediaPaused"; const value = false; const live = stateMediator2.mediaStreamType.get(stateOwners) === StreamTypes.LIVE; if (live) { const notDvr = !(stateMediator2.mediaTargetLiveWindow.get(stateOwners) > 0); const liveEdgeTime = (_a3 = stateMediator2.mediaSeekable.get(stateOwners)) == null ? void 0 : _a3[1]; if (notDvr && liveEdgeTime) { stateMediator2.mediaCurrentTime.set(liveEdgeTime, stateOwners); } } stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_PLAYBACK_RATE_REQUEST](stateMediator2, stateOwners, { detail }) { const key = "mediaPlaybackRate"; const value = detail; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_MUTE_REQUEST](stateMediator2, stateOwners) { const key = "mediaMuted"; const value = true; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_UNMUTE_REQUEST](stateMediator2, stateOwners) { const key = "mediaMuted"; const value = false; if (!stateMediator2.mediaVolume.get(stateOwners)) { stateMediator2.mediaVolume.set(0.25, stateOwners); } stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_VOLUME_REQUEST](stateMediator2, stateOwners, { detail }) { const key = "mediaVolume"; const value = detail; if (value && stateMediator2.mediaMuted.get(stateOwners)) { stateMediator2.mediaMuted.set(false, stateOwners); } stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_SEEK_REQUEST](stateMediator2, stateOwners, { detail }) { const key = "mediaCurrentTime"; const value = detail; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_SEEK_TO_LIVE_REQUEST](stateMediator2, stateOwners) { var _a3; const key = "mediaCurrentTime"; const value = (_a3 = stateMediator2.mediaSeekable.get(stateOwners)) == null ? void 0 : _a3[1]; if (Number.isNaN(Number(value))) return; stateMediator2[key].set(value, stateOwners); }, // Text Tracks state change requests [MediaUIEvents.MEDIA_SHOW_SUBTITLES_REQUEST](_stateMediator, stateOwners, { detail }) { var _a3; const { options: options2 } = stateOwners; const tracks = getSubtitleTracks(stateOwners); const tracksToUpdate = parseTracks(detail); const preferredLanguage = (_a3 = tracksToUpdate[0]) == null ? void 0 : _a3.language; if (preferredLanguage && !options2.noSubtitlesLangPref) { GlobalThis.localStorage.setItem( "media-chrome-pref-subtitles-lang", preferredLanguage ); } updateTracksModeTo(TextTrackModes.SHOWING, tracks, tracksToUpdate); }, [MediaUIEvents.MEDIA_DISABLE_SUBTITLES_REQUEST](_stateMediator, stateOwners, { detail }) { const tracks = getSubtitleTracks(stateOwners); const tracksToUpdate = detail != null ? detail : []; updateTracksModeTo(TextTrackModes.DISABLED, tracks, tracksToUpdate); }, [MediaUIEvents.MEDIA_TOGGLE_SUBTITLES_REQUEST](_stateMediator, stateOwners, { detail }) { toggleSubtitleTracks(stateOwners, detail); }, // Renditions/Tracks state change requests [MediaUIEvents.MEDIA_RENDITION_REQUEST](stateMediator2, stateOwners, { detail }) { const key = "mediaRenditionSelected"; const value = detail; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_AUDIO_TRACK_REQUEST](stateMediator2, stateOwners, { detail }) { const key = "mediaAudioTrackEnabled"; const value = detail; stateMediator2[key].set(value, stateOwners); }, // State change requests dependent on root node [MediaUIEvents.MEDIA_ENTER_PIP_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsPip"; const value = true; if (stateMediator2.mediaIsFullscreen.get(stateOwners)) { stateMediator2.mediaIsFullscreen.set(false, stateOwners); } stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_EXIT_PIP_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsPip"; const value = false; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_ENTER_FULLSCREEN_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsFullscreen"; const value = true; if (stateMediator2.mediaIsPip.get(stateOwners)) { stateMediator2.mediaIsPip.set(false, stateOwners); } stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_EXIT_FULLSCREEN_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsFullscreen"; const value = false; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_ENTER_CAST_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsCasting"; const value = true; if (stateMediator2.mediaIsFullscreen.get(stateOwners)) { stateMediator2.mediaIsFullscreen.set(false, stateOwners); } stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_EXIT_CAST_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsCasting"; const value = false; stateMediator2[key].set(value, stateOwners); }, [MediaUIEvents.MEDIA_AIRPLAY_REQUEST](stateMediator2, stateOwners) { const key = "mediaIsAirplaying"; const value = true; stateMediator2[key].set(value, stateOwners); } }; // node_modules/media-chrome/dist/media-store/media-store.js var createMediaStore = ({ media, fullscreenElement, documentElement, stateMediator: stateMediator2 = stateMediator, requestMap: requestMap2 = requestMap, options: options2 = {}, monitorStateOwnersOnlyWithSubscriptions = true }) => { const callbacks = []; const stateOwners = { // Spreading options here since folks should not rely on holding onto references // for any app-level logic wrt options. options: { ...options2 } }; let state = Object.freeze({ mediaPreviewTime: void 0, mediaPreviewImage: void 0, mediaPreviewCoords: void 0, mediaPreviewChapter: void 0 }); const updateState = (nextStateDelta) => { if (nextStateDelta == void 0) return; if (areValuesEq(nextStateDelta, state)) { return; } state = Object.freeze({ ...state, ...nextStateDelta }); callbacks.forEach((cb) => cb(state)); }; const updateStateFromFacade = () => { const nextState = Object.entries(stateMediator2).reduce( (nextState2, [stateName, { get }]) => { nextState2[stateName] = get(stateOwners); return nextState2; }, {} ); updateState(nextState); }; const stateUpdateHandlers = {}; let nextStateOwners = void 0; const updateStateOwners = async (nextStateOwnersDelta, nextSubscriberCount) => { var _a3, _b, _c, _d, _e5, _f, _g, _h, _i2, _j, _k, _l, _m, _n, _o, _p; const pendingUpdate = !!nextStateOwners; nextStateOwners = { ...stateOwners, ...nextStateOwners != null ? nextStateOwners : {}, ...nextStateOwnersDelta }; if (pendingUpdate) return; await prepareStateOwners(...Object.values(nextStateOwnersDelta)); const shouldTeardownFromSubscriberCount = callbacks.length > 0 && nextSubscriberCount === 0 && monitorStateOwnersOnlyWithSubscriptions; const mediaChanged = stateOwners.media !== nextStateOwners.media; const textTracksChanged = ((_a3 = stateOwners.media) == null ? void 0 : _a3.textTracks) !== ((_b = nextStateOwners.media) == null ? void 0 : _b.textTracks); const videoRenditionsChanged = ((_c = stateOwners.media) == null ? void 0 : _c.videoRenditions) !== ((_d = nextStateOwners.media) == null ? void 0 : _d.videoRenditions); const audioTracksChanged = ((_e5 = stateOwners.media) == null ? void 0 : _e5.audioTracks) !== ((_f = nextStateOwners.media) == null ? void 0 : _f.audioTracks); const remoteChanged = ((_g = stateOwners.media) == null ? void 0 : _g.remote) !== ((_h = nextStateOwners.media) == null ? void 0 : _h.remote); const rootNodeChanged = stateOwners.documentElement !== nextStateOwners.documentElement; const teardownMedia = !!stateOwners.media && (mediaChanged || shouldTeardownFromSubscriberCount); const teardownTextTracks = !!((_i2 = stateOwners.media) == null ? void 0 : _i2.textTracks) && (textTracksChanged || shouldTeardownFromSubscriberCount); const teardownVideoRenditions = !!((_j = stateOwners.media) == null ? void 0 : _j.videoRenditions) && (videoRenditionsChanged || shouldTeardownFromSubscriberCount); const teardownAudioTracks = !!((_k = stateOwners.media) == null ? void 0 : _k.audioTracks) && (audioTracksChanged || shouldTeardownFromSubscriberCount); const teardownRemote = !!((_l = stateOwners.media) == null ? void 0 : _l.remote) && (remoteChanged || shouldTeardownFromSubscriberCount); const teardownRootNode = !!stateOwners.documentElement && (rootNodeChanged || shouldTeardownFromSubscriberCount); const teardownSomething = teardownMedia || teardownTextTracks || teardownVideoRenditions || teardownAudioTracks || teardownRemote || teardownRootNode; const shouldSetupFromSubscriberCount = callbacks.length === 0 && nextSubscriberCount === 1 && monitorStateOwnersOnlyWithSubscriptions; const setupMedia = !!nextStateOwners.media && (mediaChanged || shouldSetupFromSubscriberCount); const setupTextTracks = !!((_m = nextStateOwners.media) == null ? void 0 : _m.textTracks) && (textTracksChanged || shouldSetupFromSubscriberCount); const setupVideoRenditions = !!((_n = nextStateOwners.media) == null ? void 0 : _n.videoRenditions) && (videoRenditionsChanged || shouldSetupFromSubscriberCount); const setupAudioTracks = !!((_o = nextStateOwners.media) == null ? void 0 : _o.audioTracks) && (audioTracksChanged || shouldSetupFromSubscriberCount); const setupRemote = !!((_p = nextStateOwners.media) == null ? void 0 : _p.remote) && (remoteChanged || shouldSetupFromSubscriberCount); const setupRootNode = !!nextStateOwners.documentElement && (rootNodeChanged || shouldSetupFromSubscriberCount); const setupSomething = setupMedia || setupTextTracks || setupVideoRenditions || setupAudioTracks || setupRemote || setupRootNode; const somethingToDo = teardownSomething || setupSomething; if (!somethingToDo) { Object.entries(nextStateOwners).forEach( ([stateOwnerName, stateOwner]) => { stateOwners[stateOwnerName] = stateOwner; } ); updateStateFromFacade(); nextStateOwners = void 0; return; } Object.entries(stateMediator2).forEach( ([ stateName, { get, mediaEvents = [], textTracksEvents = [], videoRenditionsEvents = [], audioTracksEvents = [], remoteEvents = [], rootEvents = [], stateOwnersUpdateHandlers = [] } ]) => { if (!stateUpdateHandlers[stateName]) { stateUpdateHandlers[stateName] = {}; } const handler = (event) => { const nextValue = get(stateOwners, event); updateState({ [stateName]: nextValue }); }; let prevHandler; prevHandler = stateUpdateHandlers[stateName].mediaEvents; mediaEvents.forEach((eventType) => { if (prevHandler && teardownMedia) { stateOwners.media.removeEventListener(eventType, prevHandler); stateUpdateHandlers[stateName].mediaEvents = void 0; } if (setupMedia) { nextStateOwners.media.addEventListener(eventType, handler); stateUpdateHandlers[stateName].mediaEvents = handler; } }); prevHandler = stateUpdateHandlers[stateName].textTracksEvents; textTracksEvents.forEach((eventType) => { var _a22, _b2; if (prevHandler && teardownTextTracks) { (_a22 = stateOwners.media.textTracks) == null ? void 0 : _a22.removeEventListener( eventType, prevHandler ); stateUpdateHandlers[stateName].textTracksEvents = void 0; } if (setupTextTracks) { (_b2 = nextStateOwners.media.textTracks) == null ? void 0 : _b2.addEventListener( eventType, handler ); stateUpdateHandlers[stateName].textTracksEvents = handler; } }); prevHandler = stateUpdateHandlers[stateName].videoRenditionsEvents; videoRenditionsEvents.forEach((eventType) => { var _a22, _b2; if (prevHandler && teardownVideoRenditions) { (_a22 = stateOwners.media.videoRenditions) == null ? void 0 : _a22.removeEventListener( eventType, prevHandler ); stateUpdateHandlers[stateName].videoRenditionsEvents = void 0; } if (setupVideoRenditions) { (_b2 = nextStateOwners.media.videoRenditions) == null ? void 0 : _b2.addEventListener( eventType, handler ); stateUpdateHandlers[stateName].videoRenditionsEvents = handler; } }); prevHandler = stateUpdateHandlers[stateName].audioTracksEvents; audioTracksEvents.forEach((eventType) => { var _a22, _b2; if (prevHandler && teardownAudioTracks) { (_a22 = stateOwners.media.audioTracks) == null ? void 0 : _a22.removeEventListener( eventType, prevHandler ); stateUpdateHandlers[stateName].audioTracksEvents = void 0; } if (setupAudioTracks) { (_b2 = nextStateOwners.media.audioTracks) == null ? void 0 : _b2.addEventListener( eventType, handler ); stateUpdateHandlers[stateName].audioTracksEvents = handler; } }); prevHandler = stateUpdateHandlers[stateName].remoteEvents; remoteEvents.forEach((eventType) => { var _a22, _b2; if (prevHandler && teardownRemote) { (_a22 = stateOwners.media.remote) == null ? void 0 : _a22.removeEventListener( eventType, prevHandler ); stateUpdateHandlers[stateName].remoteEvents = void 0; } if (setupRemote) { (_b2 = nextStateOwners.media.remote) == null ? void 0 : _b2.addEventListener(eventType, handler); stateUpdateHandlers[stateName].remoteEvents = handler; } }); prevHandler = stateUpdateHandlers[stateName].rootEvents; rootEvents.forEach((eventType) => { if (prevHandler && teardownRootNode) { stateOwners.documentElement.removeEventListener( eventType, prevHandler ); stateUpdateHandlers[stateName].rootEvents = void 0; } if (setupRootNode) { nextStateOwners.documentElement.addEventListener( eventType, handler ); stateUpdateHandlers[stateName].rootEvents = handler; } }); const prevHandlerTeardown = stateUpdateHandlers[stateName].stateOwnersUpdateHandlers; stateOwnersUpdateHandlers.forEach((fn) => { if (prevHandlerTeardown && teardownSomething) { prevHandlerTeardown(); } if (setupSomething) { stateUpdateHandlers[stateName].stateOwnersUpdateHandlers = fn( handler, nextStateOwners ); } }); } ); Object.entries(nextStateOwners).forEach(([stateOwnerName, stateOwner]) => { stateOwners[stateOwnerName] = stateOwner; }); updateStateFromFacade(); nextStateOwners = void 0; }; updateStateOwners({ media, fullscreenElement, documentElement, options: options2 }); return { // note that none of these cases directly interact with the media element, root node, full screen element, etc. // note these "actions" could just be the events if we wanted, especially if we normalize on "detail" for // any payload-relevant values // This is roughly equivalent to our used to be in our state requests dictionary object, though much of the // "heavy lifting" is now moved into the facade `set()` dispatch(action) { const { type, detail } = action; if (requestMap2[type]) { updateState(requestMap2[type](stateMediator2, stateOwners, action)); return; } if (type === "mediaelementchangerequest") { updateStateOwners({ media: detail }); } else if (type === "fullscreenelementchangerequest") { updateStateOwners({ fullscreenElement: detail }); } else if (type === "documentelementchangerequest") { updateStateOwners({ documentElement: detail }); } else if (type === "optionschangerequest") { Object.entries(detail != null ? detail : {}).forEach(([optionName, optionValue]) => { stateOwners.options[optionName] = optionValue; }); } }, getState() { return state; }, subscribe(callback) { updateStateOwners({}, callbacks.length + 1); callbacks.push(callback); callback(state); return () => { const idx = callbacks.indexOf(callback); if (idx >= 0) { updateStateOwners({}, callbacks.length - 1); callbacks.splice(idx, 1); } }; } }; }; var media_store_default = createMediaStore; // node_modules/media-chrome/dist/media-controller.js var __accessCheck4 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet4 = (obj, member, getter) => { __accessCheck4(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd4 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet4 = (obj, member, value, setter) => { __accessCheck4(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod2 = (obj, member, method) => { __accessCheck4(obj, member, "access private method"); return method; }; var _hotKeys; var _fullscreenElement; var _mediaStore; var _mediaStateCallback; var _mediaStoreUnsubscribe; var _mediaStateEventHandler; var _setupDefaultStore; var setupDefaultStore_fn; var _keyUpHandler; var keyUpHandler_fn; var _keyDownHandler; var keyDownHandler_fn; var ButtonPressedKeys = [ "ArrowLeft", "ArrowRight", "Enter", " ", "f", "m", "k", "c" ]; var DEFAULT_SEEK_OFFSET = 10; var Attributes2 = { DEFAULT_SUBTITLES: "defaultsubtitles", DEFAULT_STREAM_TYPE: "defaultstreamtype", DEFAULT_DURATION: "defaultduration", FULLSCREEN_ELEMENT: "fullscreenelement", HOTKEYS: "hotkeys", KEYS_USED: "keysused", LIVE_EDGE_OFFSET: "liveedgeoffset", NO_AUTO_SEEK_TO_LIVE: "noautoseektolive", NO_HOTKEYS: "nohotkeys", NO_VOLUME_PREF: "novolumepref", NO_SUBTITLES_LANG_PREF: "nosubtitleslangpref", NO_DEFAULT_STORE: "nodefaultstore", KEYBOARD_FORWARD_SEEK_OFFSET: "keyboardforwardseekoffset", KEYBOARD_BACKWARD_SEEK_OFFSET: "keyboardbackwardseekoffset" }; var MediaController = class extends MediaContainer { constructor() { super(); __privateAdd4(this, _setupDefaultStore); __privateAdd4(this, _keyUpHandler); __privateAdd4(this, _keyDownHandler); this.mediaStateReceivers = []; this.associatedElementSubscriptions = /* @__PURE__ */ new Map(); __privateAdd4(this, _hotKeys, new AttributeTokenList(this, Attributes2.HOTKEYS)); __privateAdd4(this, _fullscreenElement, void 0); __privateAdd4(this, _mediaStore, void 0); __privateAdd4(this, _mediaStateCallback, void 0); __privateAdd4(this, _mediaStoreUnsubscribe, void 0); __privateAdd4(this, _mediaStateEventHandler, (event) => { var _a3; (_a3 = __privateGet4(this, _mediaStore)) == null ? void 0 : _a3.dispatch(event); }); this.associateElement(this); let prevState = {}; __privateSet4(this, _mediaStateCallback, (nextState) => { Object.entries(nextState).forEach(([stateName, stateValue]) => { if (stateName in prevState && prevState[stateName] === stateValue) return; this.propagateMediaState(stateName, stateValue); const attrName = stateName.toLowerCase(); const evt = new GlobalThis.CustomEvent( AttributeToStateChangeEventMap[attrName], { composed: true, detail: stateValue } ); this.dispatchEvent(evt); }); prevState = nextState; }); this.enableHotkeys(); } static get observedAttributes() { return super.observedAttributes.concat( Attributes2.NO_HOTKEYS, Attributes2.HOTKEYS, Attributes2.DEFAULT_STREAM_TYPE, Attributes2.DEFAULT_SUBTITLES, Attributes2.DEFAULT_DURATION ); } get mediaStore() { return __privateGet4(this, _mediaStore); } set mediaStore(value) { var _a3, _b; if (__privateGet4(this, _mediaStore)) { (_a3 = __privateGet4(this, _mediaStoreUnsubscribe)) == null ? void 0 : _a3.call(this); __privateSet4(this, _mediaStoreUnsubscribe, void 0); } __privateSet4(this, _mediaStore, value); if (!__privateGet4(this, _mediaStore) && !this.hasAttribute(Attributes2.NO_DEFAULT_STORE)) { __privateMethod2(this, _setupDefaultStore, setupDefaultStore_fn).call(this); return; } __privateSet4(this, _mediaStoreUnsubscribe, (_b = __privateGet4(this, _mediaStore)) == null ? void 0 : _b.subscribe( __privateGet4(this, _mediaStateCallback) )); } get fullscreenElement() { var _a3; return (_a3 = __privateGet4(this, _fullscreenElement)) != null ? _a3 : this; } set fullscreenElement(element) { var _a3; if (this.hasAttribute(Attributes2.FULLSCREEN_ELEMENT)) { this.removeAttribute(Attributes2.FULLSCREEN_ELEMENT); } __privateSet4(this, _fullscreenElement, element); (_a3 = __privateGet4(this, _mediaStore)) == null ? void 0 : _a3.dispatch({ type: "fullscreenelementchangerequest", detail: this.fullscreenElement }); } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5, _f; super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === Attributes2.NO_HOTKEYS) { if (newValue !== oldValue && newValue === "") { if (this.hasAttribute(Attributes2.HOTKEYS)) { console.warn( "Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled." ); } this.disableHotkeys(); } else if (newValue !== oldValue && newValue === null) { this.enableHotkeys(); } } else if (attrName === Attributes2.HOTKEYS) { __privateGet4(this, _hotKeys).value = newValue; } else if (attrName === Attributes2.DEFAULT_SUBTITLES && newValue !== oldValue) { (_a3 = __privateGet4(this, _mediaStore)) == null ? void 0 : _a3.dispatch({ type: "optionschangerequest", detail: { defaultSubtitles: this.hasAttribute(Attributes2.DEFAULT_SUBTITLES) } }); } else if (attrName === Attributes2.DEFAULT_STREAM_TYPE) { (_c = __privateGet4(this, _mediaStore)) == null ? void 0 : _c.dispatch({ type: "optionschangerequest", detail: { defaultStreamType: (_b = this.getAttribute(Attributes2.DEFAULT_STREAM_TYPE)) != null ? _b : void 0 } }); } else if (attrName === Attributes2.LIVE_EDGE_OFFSET) { (_d = __privateGet4(this, _mediaStore)) == null ? void 0 : _d.dispatch({ type: "optionschangerequest", detail: { liveEdgeOffset: this.hasAttribute(Attributes2.LIVE_EDGE_OFFSET) ? +this.getAttribute(Attributes2.LIVE_EDGE_OFFSET) : void 0 } }); } else if (attrName === Attributes2.FULLSCREEN_ELEMENT) { const el = newValue ? (_e5 = this.getRootNode()) == null ? void 0 : _e5.getElementById(newValue) : void 0; __privateSet4(this, _fullscreenElement, el); (_f = __privateGet4(this, _mediaStore)) == null ? void 0 : _f.dispatch({ type: "fullscreenelementchangerequest", detail: this.fullscreenElement }); } } connectedCallback() { var _a3, _b; if (!__privateGet4(this, _mediaStore) && !this.hasAttribute(Attributes2.NO_DEFAULT_STORE)) { __privateMethod2(this, _setupDefaultStore, setupDefaultStore_fn).call(this); } (_a3 = __privateGet4(this, _mediaStore)) == null ? void 0 : _a3.dispatch({ type: "documentelementchangerequest", detail: Document2 }); super.connectedCallback(); if (__privateGet4(this, _mediaStore) && !__privateGet4(this, _mediaStoreUnsubscribe)) { __privateSet4(this, _mediaStoreUnsubscribe, (_b = __privateGet4(this, _mediaStore)) == null ? void 0 : _b.subscribe( __privateGet4(this, _mediaStateCallback) )); } this.enableHotkeys(); } disconnectedCallback() { var _a3, _b, _c, _d; (_a3 = super.disconnectedCallback) == null ? void 0 : _a3.call(this); if (__privateGet4(this, _mediaStore)) { (_b = __privateGet4(this, _mediaStore)) == null ? void 0 : _b.dispatch({ type: "documentelementchangerequest", detail: void 0 }); (_c = __privateGet4(this, _mediaStore)) == null ? void 0 : _c.dispatch({ type: MediaUIEvents.MEDIA_TOGGLE_SUBTITLES_REQUEST, detail: false }); } if (__privateGet4(this, _mediaStoreUnsubscribe)) { (_d = __privateGet4(this, _mediaStoreUnsubscribe)) == null ? void 0 : _d.call(this); __privateSet4(this, _mediaStoreUnsubscribe, void 0); } } /** * @override * @param {HTMLMediaElement} media */ mediaSetCallback(media) { var _a3; super.mediaSetCallback(media); (_a3 = __privateGet4(this, _mediaStore)) == null ? void 0 : _a3.dispatch({ type: "mediaelementchangerequest", detail: media }); if (!media.hasAttribute("tabindex")) { media.tabIndex = -1; } } /** * @override * @param {HTMLMediaElement} media */ mediaUnsetCallback(media) { var _a3; super.mediaUnsetCallback(media); (_a3 = __privateGet4(this, _mediaStore)) == null ? void 0 : _a3.dispatch({ type: "mediaelementchangerequest", detail: void 0 }); } propagateMediaState(stateName, state) { propagateMediaState(this.mediaStateReceivers, stateName, state); } associateElement(element) { if (!element) return; const { associatedElementSubscriptions } = this; if (associatedElementSubscriptions.has(element)) return; const registerMediaStateReceiver = this.registerMediaStateReceiver.bind(this); const unregisterMediaStateReceiver = this.unregisterMediaStateReceiver.bind(this); const unsubscribe = monitorForMediaStateReceivers( element, registerMediaStateReceiver, unregisterMediaStateReceiver ); Object.values(MediaUIEvents).forEach((eventName) => { element.addEventListener(eventName, __privateGet4(this, _mediaStateEventHandler)); }); associatedElementSubscriptions.set(element, unsubscribe); } unassociateElement(element) { if (!element) return; const { associatedElementSubscriptions } = this; if (!associatedElementSubscriptions.has(element)) return; const unsubscribe = associatedElementSubscriptions.get(element); unsubscribe(); associatedElementSubscriptions.delete(element); Object.values(MediaUIEvents).forEach((eventName) => { element.removeEventListener(eventName, __privateGet4(this, _mediaStateEventHandler)); }); } registerMediaStateReceiver(el) { if (!el) return; const els = this.mediaStateReceivers; const index2 = els.indexOf(el); if (index2 > -1) return; els.push(el); if (__privateGet4(this, _mediaStore)) { Object.entries(__privateGet4(this, _mediaStore).getState()).forEach( ([stateName, stateValue]) => { propagateMediaState([el], stateName, stateValue); } ); } } unregisterMediaStateReceiver(el) { const els = this.mediaStateReceivers; const index2 = els.indexOf(el); if (index2 < 0) return; els.splice(index2, 1); } enableHotkeys() { this.addEventListener("keydown", __privateMethod2(this, _keyDownHandler, keyDownHandler_fn)); } disableHotkeys() { this.removeEventListener("keydown", __privateMethod2(this, _keyDownHandler, keyDownHandler_fn)); this.removeEventListener("keyup", __privateMethod2(this, _keyUpHandler, keyUpHandler_fn)); } get hotkeys() { return __privateGet4(this, _hotKeys); } keyboardShortcutHandler(e) { var _a3, _b, _c, _d, _e5; const target = e.target; const keysUsed = ((_c = (_b = (_a3 = target.getAttribute(Attributes2.KEYS_USED)) == null ? void 0 : _a3.split(" ")) != null ? _b : target == null ? void 0 : target.keysUsed) != null ? _c : []).map((key) => key === "Space" ? " " : key).filter(Boolean); if (keysUsed.includes(e.key)) { return; } let eventName, detail, evt; if (__privateGet4(this, _hotKeys).contains(`no${e.key.toLowerCase()}`)) return; if (e.key === " " && __privateGet4(this, _hotKeys).contains(`nospace`)) return; switch (e.key) { case " ": case "k": eventName = __privateGet4(this, _mediaStore).getState().mediaPaused ? MediaUIEvents.MEDIA_PLAY_REQUEST : MediaUIEvents.MEDIA_PAUSE_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); break; case "m": eventName = this.mediaStore.getState().mediaVolumeLevel === "off" ? MediaUIEvents.MEDIA_UNMUTE_REQUEST : MediaUIEvents.MEDIA_MUTE_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); break; case "f": eventName = this.mediaStore.getState().mediaIsFullscreen ? MediaUIEvents.MEDIA_EXIT_FULLSCREEN_REQUEST : MediaUIEvents.MEDIA_ENTER_FULLSCREEN_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); break; case "c": this.dispatchEvent( new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_TOGGLE_SUBTITLES_REQUEST, { composed: true, bubbles: true } ) ); break; case "ArrowLeft": { const offsetValue = this.hasAttribute( Attributes2.KEYBOARD_BACKWARD_SEEK_OFFSET ) ? +this.getAttribute(Attributes2.KEYBOARD_BACKWARD_SEEK_OFFSET) : DEFAULT_SEEK_OFFSET; detail = Math.max( ((_d = this.mediaStore.getState().mediaCurrentTime) != null ? _d : 0) - offsetValue, 0 ); evt = new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_SEEK_REQUEST, { composed: true, bubbles: true, detail }); this.dispatchEvent(evt); break; } case "ArrowRight": { const offsetValue = this.hasAttribute( Attributes2.KEYBOARD_FORWARD_SEEK_OFFSET ) ? +this.getAttribute(Attributes2.KEYBOARD_FORWARD_SEEK_OFFSET) : DEFAULT_SEEK_OFFSET; detail = Math.max( ((_e5 = this.mediaStore.getState().mediaCurrentTime) != null ? _e5 : 0) + offsetValue, 0 ); evt = new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_SEEK_REQUEST, { composed: true, bubbles: true, detail }); this.dispatchEvent(evt); break; } default: break; } } }; _hotKeys = /* @__PURE__ */ new WeakMap(); _fullscreenElement = /* @__PURE__ */ new WeakMap(); _mediaStore = /* @__PURE__ */ new WeakMap(); _mediaStateCallback = /* @__PURE__ */ new WeakMap(); _mediaStoreUnsubscribe = /* @__PURE__ */ new WeakMap(); _mediaStateEventHandler = /* @__PURE__ */ new WeakMap(); _setupDefaultStore = /* @__PURE__ */ new WeakSet(); setupDefaultStore_fn = function() { var _a3; this.mediaStore = media_store_default({ media: this.media, fullscreenElement: this.fullscreenElement, options: { defaultSubtitles: this.hasAttribute(Attributes2.DEFAULT_SUBTITLES), defaultDuration: this.hasAttribute(Attributes2.DEFAULT_DURATION) ? +this.getAttribute(Attributes2.DEFAULT_DURATION) : void 0, defaultStreamType: ( /** @type {import('./media-store/state-mediator.js').StreamTypeValue} */ (_a3 = this.getAttribute( Attributes2.DEFAULT_STREAM_TYPE )) != null ? _a3 : void 0 ), liveEdgeOffset: this.hasAttribute(Attributes2.LIVE_EDGE_OFFSET) ? +this.getAttribute(Attributes2.LIVE_EDGE_OFFSET) : void 0, // NOTE: This wasn't updated if it was changed later. Should it be? (CJP) noVolumePref: this.hasAttribute(Attributes2.NO_VOLUME_PREF), noSubtitlesLangPref: this.hasAttribute( Attributes2.NO_SUBTITLES_LANG_PREF ) } }); }; _keyUpHandler = /* @__PURE__ */ new WeakSet(); keyUpHandler_fn = function(e) { const { key } = e; if (!ButtonPressedKeys.includes(key)) { this.removeEventListener("keyup", __privateMethod2(this, _keyUpHandler, keyUpHandler_fn)); return; } this.keyboardShortcutHandler(e); }; _keyDownHandler = /* @__PURE__ */ new WeakSet(); keyDownHandler_fn = function(e) { const { metaKey, altKey, key } = e; if (metaKey || altKey || !ButtonPressedKeys.includes(key)) { this.removeEventListener("keyup", __privateMethod2(this, _keyUpHandler, keyUpHandler_fn)); return; } if ([" ", "ArrowLeft", "ArrowRight"].includes(key) && !(__privateGet4(this, _hotKeys).contains(`no${key.toLowerCase()}`) || key === " " && __privateGet4(this, _hotKeys).contains("nospace"))) { e.preventDefault(); } this.addEventListener("keyup", __privateMethod2(this, _keyUpHandler, keyUpHandler_fn), { once: true }); }; var MEDIA_UI_ATTRIBUTE_NAMES2 = Object.values(MediaUIAttributes); var MEDIA_UI_PROP_NAMES = Object.values(MediaUIProps); var getMediaUIAttributesFrom = (child) => { var _a3, _b, _c, _d; let { observedAttributes } = child.constructor; if (!observedAttributes && ((_a3 = child.nodeName) == null ? void 0 : _a3.includes("-"))) { GlobalThis.customElements.upgrade(child); ({ observedAttributes } = child.constructor); } const mediaChromeAttributesList = (_d = (_c = (_b = child == null ? void 0 : child.getAttribute) == null ? void 0 : _b.call(child, MediaStateReceiverAttributes.MEDIA_CHROME_ATTRIBUTES)) == null ? void 0 : _c.split) == null ? void 0 : _d.call(_c, /\s+/); if (!Array.isArray(observedAttributes || mediaChromeAttributesList)) return []; return (observedAttributes || mediaChromeAttributesList).filter( (attrName) => MEDIA_UI_ATTRIBUTE_NAMES2.includes(attrName) ); }; var hasMediaUIProps = (mediaStateReceiverCandidate) => { var _a3, _b; if (((_a3 = mediaStateReceiverCandidate.nodeName) == null ? void 0 : _a3.includes("-")) && !!GlobalThis.customElements.get( (_b = mediaStateReceiverCandidate.nodeName) == null ? void 0 : _b.toLowerCase() ) && !(mediaStateReceiverCandidate instanceof GlobalThis.customElements.get( mediaStateReceiverCandidate.nodeName.toLowerCase() ))) { GlobalThis.customElements.upgrade(mediaStateReceiverCandidate); } return MEDIA_UI_PROP_NAMES.some( (propName) => propName in mediaStateReceiverCandidate ); }; var isMediaStateReceiver = (child) => { return hasMediaUIProps(child) || !!getMediaUIAttributesFrom(child).length; }; var serializeTuple = (tuple) => { var _a3; return (_a3 = tuple == null ? void 0 : tuple.join) == null ? void 0 : _a3.call(tuple, ":"); }; var CustomAttrSerializer = { [MediaUIAttributes.MEDIA_SUBTITLES_LIST]: stringifyTextTrackList, [MediaUIAttributes.MEDIA_SUBTITLES_SHOWING]: stringifyTextTrackList, [MediaUIAttributes.MEDIA_SEEKABLE]: serializeTuple, [MediaUIAttributes.MEDIA_BUFFERED]: (tuples) => tuples == null ? void 0 : tuples.map(serializeTuple).join(" "), [MediaUIAttributes.MEDIA_PREVIEW_COORDS]: (coords) => coords == null ? void 0 : coords.join(" "), [MediaUIAttributes.MEDIA_RENDITION_LIST]: stringifyRenditionList, [MediaUIAttributes.MEDIA_AUDIO_TRACK_LIST]: stringifyAudioTrackList }; var setAttr = async (child, attrName, attrValue) => { var _a3, _b; if (!child.isConnected) { await delay(0); } if (typeof attrValue === "boolean" || attrValue == null) { return setBooleanAttr(child, attrName, attrValue); } if (typeof attrValue === "number") { return setNumericAttr(child, attrName, attrValue); } if (typeof attrValue === "string") { return setStringAttr(child, attrName, attrValue); } if (Array.isArray(attrValue) && !attrValue.length) { return child.removeAttribute(attrName); } const val = (_b = (_a3 = CustomAttrSerializer[attrName]) == null ? void 0 : _a3.call(CustomAttrSerializer, attrValue)) != null ? _b : attrValue; return child.setAttribute(attrName, val); }; var isMediaSlotElementDescendant = (el) => { var _a3; return !!((_a3 = el.closest) == null ? void 0 : _a3.call(el, '*[slot="media"]')); }; var traverseForMediaStateReceivers = (rootNode, mediaStateReceiverCallback) => { if (isMediaSlotElementDescendant(rootNode)) { return; } const traverseForMediaStateReceiversSync = (rootNode2, mediaStateReceiverCallback2) => { var _a3, _b; if (isMediaStateReceiver(rootNode2)) { mediaStateReceiverCallback2(rootNode2); } const { children = [] } = rootNode2 != null ? rootNode2 : {}; const shadowChildren = (_b = (_a3 = rootNode2 == null ? void 0 : rootNode2.shadowRoot) == null ? void 0 : _a3.children) != null ? _b : []; const allChildren = [...children, ...shadowChildren]; allChildren.forEach( (child) => traverseForMediaStateReceivers( child, mediaStateReceiverCallback2 ) ); }; const name = rootNode == null ? void 0 : rootNode.nodeName.toLowerCase(); if (name.includes("-") && !isMediaStateReceiver(rootNode)) { GlobalThis.customElements.whenDefined(name).then(() => { traverseForMediaStateReceiversSync(rootNode, mediaStateReceiverCallback); }); return; } traverseForMediaStateReceiversSync(rootNode, mediaStateReceiverCallback); }; var propagateMediaState = (els, stateName, val) => { els.forEach((el) => { if (stateName in el) { el[stateName] = val; return; } const relevantAttrs = getMediaUIAttributesFrom(el); const attrName = stateName.toLowerCase(); if (!relevantAttrs.includes(attrName)) return; setAttr(el, attrName, val); }); }; var monitorForMediaStateReceivers = (rootNode, registerMediaStateReceiver, unregisterMediaStateReceiver) => { traverseForMediaStateReceivers(rootNode, registerMediaStateReceiver); const registerMediaStateReceiverHandler = (evt) => { var _a3; const el = (_a3 = evt == null ? void 0 : evt.composedPath()[0]) != null ? _a3 : evt.target; registerMediaStateReceiver(el); }; const unregisterMediaStateReceiverHandler = (evt) => { var _a3; const el = (_a3 = evt == null ? void 0 : evt.composedPath()[0]) != null ? _a3 : evt.target; unregisterMediaStateReceiver(el); }; rootNode.addEventListener( MediaUIEvents.REGISTER_MEDIA_STATE_RECEIVER, registerMediaStateReceiverHandler ); rootNode.addEventListener( MediaUIEvents.UNREGISTER_MEDIA_STATE_RECEIVER, unregisterMediaStateReceiverHandler ); const mutationCallback = (mutationsList) => { mutationsList.forEach((mutationRecord) => { const { addedNodes = [], removedNodes = [], type, target, attributeName } = mutationRecord; if (type === "childList") { Array.prototype.forEach.call( addedNodes, (node2) => traverseForMediaStateReceivers( node2, registerMediaStateReceiver ) ); Array.prototype.forEach.call( removedNodes, (node2) => traverseForMediaStateReceivers( node2, unregisterMediaStateReceiver ) ); } else if (type === "attributes" && attributeName === MediaStateReceiverAttributes.MEDIA_CHROME_ATTRIBUTES) { if (isMediaStateReceiver(target)) { registerMediaStateReceiver(target); } else { unregisterMediaStateReceiver(target); } } }); }; let prevSlotted = []; const slotChangeHandler = (event) => { const slotEl = event.target; if (slotEl.name === "media") return; prevSlotted.forEach( (node2) => traverseForMediaStateReceivers(node2, unregisterMediaStateReceiver) ); prevSlotted = [ ...slotEl.assignedElements({ flatten: true }) ]; prevSlotted.forEach( (node2) => traverseForMediaStateReceivers(node2, registerMediaStateReceiver) ); }; rootNode.addEventListener("slotchange", slotChangeHandler); const observer2 = new MutationObserver(mutationCallback); observer2.observe(rootNode, { childList: true, attributes: true, subtree: true }); const unsubscribe = () => { traverseForMediaStateReceivers(rootNode, unregisterMediaStateReceiver); rootNode.removeEventListener("slotchange", slotChangeHandler); observer2.disconnect(); rootNode.removeEventListener( MediaUIEvents.REGISTER_MEDIA_STATE_RECEIVER, registerMediaStateReceiverHandler ); rootNode.removeEventListener( MediaUIEvents.UNREGISTER_MEDIA_STATE_RECEIVER, unregisterMediaStateReceiverHandler ); }; return unsubscribe; }; if (!GlobalThis.customElements.get("media-controller")) { GlobalThis.customElements.define("media-controller", MediaController); } var media_controller_default = MediaController; // node_modules/media-chrome/dist/media-chrome-button.js var __accessCheck5 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet5 = (obj, member, getter) => { __accessCheck5(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd5 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet5 = (obj, member, value, setter) => { __accessCheck5(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod3 = (obj, member, method) => { __accessCheck5(obj, member, "access private method"); return method; }; var _mediaController2; var _clickListener; var _positionTooltip; var _keyupListener; var _keydownListener; var _setupTooltip; var setupTooltip_fn; var Attributes3 = { TOOLTIP_PLACEMENT: "tooltipplacement" }; var template3 = Document2.createElement("template"); template3.innerHTML = /*html*/ ` <style> :host { position: relative; font: var(--media-font, var(--media-font-weight, bold) var(--media-font-size, 14px) / var(--media-text-content-height, var(--media-control-height, 24px)) var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif)); color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238))); background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7))); padding: var(--media-button-padding, var(--media-control-padding, 10px)); justify-content: var(--media-button-justify-content, center); display: inline-flex; align-items: center; vertical-align: middle; box-sizing: border-box; transition: background .15s linear; pointer-events: auto; cursor: pointer; -webkit-tap-highlight-color: transparent; } ${/* Only show outline when keyboard focusing. https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo */ ""} :host(:focus-visible) { box-shadow: inset 0 0 0 2px rgb(27 127 204 / .9); outline: 0; } ${/* * hide default focus ring, particularly when using mouse */ ""} :host(:where(:focus)) { box-shadow: none; outline: 0; } :host(:hover) { background: var(--media-control-hover-background, rgba(50 50 70 / .7)); } svg, img, ::slotted(svg), ::slotted(img) { width: var(--media-button-icon-width); height: var(--media-button-icon-height, var(--media-control-height, 24px)); transform: var(--media-button-icon-transform); transition: var(--media-button-icon-transition); fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238))); vertical-align: middle; max-width: 100%; max-height: 100%; min-width: 100%; } media-tooltip { ${/** Make sure unpositioned tooltip doesn't cause page overflow (scroll). */ ""} max-width: 0; overflow-x: clip; opacity: 0; transition: opacity .3s, max-width 0s 9s; } :host(:hover) media-tooltip, :host(:focus-visible) media-tooltip { max-width: 100vw; opacity: 1; transition: opacity .3s; } :host([notooltip]) slot[name="tooltip"] { display: none; } </style> <slot name="tooltip"> <media-tooltip part="tooltip" aria-hidden="true"> <slot name="tooltip-content"></slot> </media-tooltip> </slot> `; var MediaChromeButton = class extends GlobalThis.HTMLElement { constructor(options2 = {}) { var _a3; super(); __privateAdd5(this, _setupTooltip); __privateAdd5(this, _mediaController2, void 0); this.preventClick = false; this.tooltipEl = null; this.tooltipContent = ""; __privateAdd5(this, _clickListener, (e) => { if (!this.preventClick) { this.handleClick(e); } setTimeout(__privateGet5(this, _positionTooltip), 0); }); __privateAdd5(this, _positionTooltip, () => { var _a4, _b; (_b = (_a4 = this.tooltipEl) == null ? void 0 : _a4.updateXOffset) == null ? void 0 : _b.call(_a4); }); __privateAdd5(this, _keyupListener, (e) => { const { key } = e; if (!this.keysUsed.includes(key)) { this.removeEventListener("keyup", __privateGet5(this, _keyupListener)); return; } if (!this.preventClick) { this.handleClick(e); } }); __privateAdd5(this, _keydownListener, (e) => { const { metaKey, altKey, key } = e; if (metaKey || altKey || !this.keysUsed.includes(key)) { this.removeEventListener("keyup", __privateGet5(this, _keyupListener)); return; } this.addEventListener("keyup", __privateGet5(this, _keyupListener), { once: true }); }); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); const buttonHTML = template3.content.cloneNode(true); this.nativeEl = buttonHTML; let slotTemplate17 = options2.slotTemplate; if (!slotTemplate17) { slotTemplate17 = Document2.createElement("template"); slotTemplate17.innerHTML = `<slot>${options2.defaultContent || ""}</slot>`; } if (options2.tooltipContent) { buttonHTML.querySelector('slot[name="tooltip-content"]').innerHTML = (_a3 = options2.tooltipContent) != null ? _a3 : ""; this.tooltipContent = options2.tooltipContent; } this.nativeEl.appendChild(slotTemplate17.content.cloneNode(true)); this.shadowRoot.appendChild(buttonHTML); } this.tooltipEl = this.shadowRoot.querySelector("media-tooltip"); } static get observedAttributes() { return [ "disabled", Attributes3.TOOLTIP_PLACEMENT, MediaStateReceiverAttributes.MEDIA_CONTROLLER ]; } enable() { this.addEventListener("click", __privateGet5(this, _clickListener)); this.addEventListener("keydown", __privateGet5(this, _keydownListener)); this.tabIndex = 0; } disable() { this.removeEventListener("click", __privateGet5(this, _clickListener)); this.removeEventListener("keydown", __privateGet5(this, _keydownListener)); this.removeEventListener("keyup", __privateGet5(this, _keyupListener)); this.tabIndex = -1; } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet5(this, _mediaController2)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet5(this, _mediaController2, null); } if (newValue && this.isConnected) { __privateSet5(this, _mediaController2, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet5(this, _mediaController2)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } else if (attrName === "disabled" && newValue !== oldValue) { if (newValue == null) { this.enable(); } else { this.disable(); } } else if (attrName === Attributes3.TOOLTIP_PLACEMENT && this.tooltipEl && newValue !== oldValue) { this.tooltipEl.placement = newValue; } __privateGet5(this, _positionTooltip).call(this); } connectedCallback() { var _a3, _b, _c; const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); style.setProperty( "display", `var(--media-control-display, var(--${this.localName}-display, inline-flex))` ); if (!this.hasAttribute("disabled")) { this.enable(); } this.setAttribute("role", "button"); const mediaControllerId = this.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { __privateSet5( this, _mediaController2, // @ts-ignore (_a3 = this.getRootNode()) == null ? void 0 : _a3.getElementById(mediaControllerId) ); (_c = (_b = __privateGet5(this, _mediaController2)) == null ? void 0 : _b.associateElement) == null ? void 0 : _c.call(_b, this); } GlobalThis.customElements.whenDefined("media-tooltip").then(() => __privateMethod3(this, _setupTooltip, setupTooltip_fn).call(this)); } disconnectedCallback() { var _a3, _b; this.disable(); (_b = (_a3 = __privateGet5(this, _mediaController2)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet5(this, _mediaController2, null); this.removeEventListener("mouseenter", __privateGet5(this, _positionTooltip)); this.removeEventListener("focus", __privateGet5(this, _positionTooltip)); this.removeEventListener("click", __privateGet5(this, _clickListener)); } get keysUsed() { return ["Enter", " "]; } /** * Get or set tooltip placement */ get tooltipPlacement() { return getStringAttr(this, Attributes3.TOOLTIP_PLACEMENT); } set tooltipPlacement(value) { setStringAttr(this, Attributes3.TOOLTIP_PLACEMENT, value); } /** * @abstract * @argument {Event} e */ handleClick(e) { } // eslint-disable-line }; _mediaController2 = /* @__PURE__ */ new WeakMap(); _clickListener = /* @__PURE__ */ new WeakMap(); _positionTooltip = /* @__PURE__ */ new WeakMap(); _keyupListener = /* @__PURE__ */ new WeakMap(); _keydownListener = /* @__PURE__ */ new WeakMap(); _setupTooltip = /* @__PURE__ */ new WeakSet(); setupTooltip_fn = function() { this.addEventListener("mouseenter", __privateGet5(this, _positionTooltip)); this.addEventListener("focus", __privateGet5(this, _positionTooltip)); this.addEventListener("click", __privateGet5(this, _clickListener)); const initialPlacement = this.tooltipPlacement; if (initialPlacement && this.tooltipEl) { this.tooltipEl.placement = initialPlacement; } }; if (!GlobalThis.customElements.get("media-chrome-button")) { GlobalThis.customElements.define("media-chrome-button", MediaChromeButton); } // node_modules/media-chrome/dist/media-airplay-button.js var airplayIcon = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M22.13 3H3.87a.87.87 0 0 0-.87.87v13.26a.87.87 0 0 0 .87.87h3.4L9 16H5V5h16v11h-4l1.72 2h3.4a.87.87 0 0 0 .87-.87V3.87a.87.87 0 0 0-.86-.87Zm-8.75 11.44a.5.5 0 0 0-.76 0l-4.91 5.73a.5.5 0 0 0 .38.83h9.82a.501.501 0 0 0 .38-.83l-4.91-5.73Z"/> </svg> `; var slotTemplate = Document2.createElement("template"); slotTemplate.innerHTML = /*html*/ ` <style> :host([${MediaUIAttributes.MEDIA_IS_AIRPLAYING}]) slot[name=icon] slot:not([name=exit]) { display: none !important; } ${/* Double negative, but safer if display doesn't equal 'block' */ ""} :host(:not([${MediaUIAttributes.MEDIA_IS_AIRPLAYING}])) slot[name=icon] slot:not([name=enter]) { display: none !important; } :host([${MediaUIAttributes.MEDIA_IS_AIRPLAYING}]) slot[name=tooltip-enter], :host(:not([${MediaUIAttributes.MEDIA_IS_AIRPLAYING}])) slot[name=tooltip-exit] { display: none; } </style> <slot name="icon"> <slot name="enter">${airplayIcon}</slot> <slot name="exit">${airplayIcon}</slot> </slot> `; var tooltipContent = ( /*html*/ ` <slot name="tooltip-enter">${tooltipLabels.ENTER_AIRPLAY}</slot> <slot name="tooltip-exit">${tooltipLabels.EXIT_AIRPLAY}</slot> ` ); var updateAriaLabel = (el) => { const label = el.mediaIsAirplaying ? verbs.EXIT_AIRPLAY() : verbs.ENTER_AIRPLAY(); el.setAttribute("aria-label", label); }; var MediaAirplayButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_IS_AIRPLAYING, MediaUIAttributes.MEDIA_AIRPLAY_UNAVAILABLE ]; } constructor(options2 = {}) { super({ slotTemplate, tooltipContent, ...options2 }); } connectedCallback() { super.connectedCallback(); updateAriaLabel(this); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_IS_AIRPLAYING) { updateAriaLabel(this); } } /** * Are we currently airplaying */ get mediaIsAirplaying() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_IS_AIRPLAYING); } set mediaIsAirplaying(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_IS_AIRPLAYING, value); } /** * Airplay unavailability state */ get mediaAirplayUnavailable() { return getStringAttr(this, MediaUIAttributes.MEDIA_AIRPLAY_UNAVAILABLE); } set mediaAirplayUnavailable(value) { setStringAttr(this, MediaUIAttributes.MEDIA_AIRPLAY_UNAVAILABLE, value); } handleClick() { const evt = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_AIRPLAY_REQUEST, { composed: true, bubbles: true } ); this.dispatchEvent(evt); } }; if (!GlobalThis.customElements.get("media-airplay-button")) { GlobalThis.customElements.define("media-airplay-button", MediaAirplayButton); } // node_modules/media-chrome/dist/media-captions-button.js var ccIconOn = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/> </svg>`; var ccIconOff = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/> </svg>`; var slotTemplate2 = Document2.createElement("template"); slotTemplate2.innerHTML = /*html*/ ` <style> :host([aria-checked="true"]) slot[name=off] { display: none !important; } ${/* Double negative, but safer if display doesn't equal 'block' */ ""} :host(:not([aria-checked="true"])) slot[name=on] { display: none !important; } :host([aria-checked="true"]) slot[name=tooltip-enable], :host(:not([aria-checked="true"])) slot[name=tooltip-disable] { display: none; } </style> <slot name="icon"> <slot name="on">${ccIconOn}</slot> <slot name="off">${ccIconOff}</slot> </slot> `; var tooltipContent2 = ( /*html*/ ` <slot name="tooltip-enable">${tooltipLabels.ENABLE_CAPTIONS}</slot> <slot name="tooltip-disable">${tooltipLabels.DISABLE_CAPTIONS}</slot> ` ); var updateAriaChecked = (el) => { el.setAttribute("aria-checked", areSubsOn(el).toString()); }; var MediaCaptionsButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_SUBTITLES_LIST, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate2, tooltipContent: tooltipContent2, ...options2 }); this._captionsReady = false; } connectedCallback() { super.connectedCallback(); this.setAttribute("role", "switch"); this.setAttribute("aria-label", nouns.CLOSED_CAPTIONS()); updateAriaChecked(this); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_SUBTITLES_SHOWING) { updateAriaChecked(this); } } /** * An array of TextTrack-like objects. * Objects must have the properties: kind, language, and label. */ get mediaSubtitlesList() { return getSubtitlesListAttr(this, MediaUIAttributes.MEDIA_SUBTITLES_LIST); } set mediaSubtitlesList(list) { setSubtitlesListAttr(this, MediaUIAttributes.MEDIA_SUBTITLES_LIST, list); } /** * An array of TextTrack-like objects. * Objects must have the properties: kind, language, and label. */ get mediaSubtitlesShowing() { return getSubtitlesListAttr( this, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ); } set mediaSubtitlesShowing(list) { setSubtitlesListAttr(this, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING, list); } handleClick() { this.dispatchEvent( new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_TOGGLE_SUBTITLES_REQUEST, { composed: true, bubbles: true }) ); } }; var getSubtitlesListAttr = (el, attrName) => { const attrVal = el.getAttribute(attrName); return attrVal ? parseTextTracksStr(attrVal) : []; }; var setSubtitlesListAttr = (el, attrName, list) => { if (!(list == null ? void 0 : list.length)) { el.removeAttribute(attrName); return; } const newValStr = stringifyTextTrackList(list); const oldVal = el.getAttribute(attrName); if (oldVal === newValStr) return; el.setAttribute(attrName, newValStr); }; if (!GlobalThis.customElements.get("media-captions-button")) { GlobalThis.customElements.define( "media-captions-button", MediaCaptionsButton ); } // node_modules/media-chrome/dist/media-cast-button.js var enterIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/></g></svg>`; var exitIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/><path class="cast_caf_icon_boxfill" d="M5,7 L5,8.63 C8,8.6 13.37,14 13.37,17 L19,17 L19,7 Z"/></g></svg>`; var slotTemplate3 = Document2.createElement("template"); slotTemplate3.innerHTML = /*html*/ ` <style> :host([${MediaUIAttributes.MEDIA_IS_CASTING}]) slot[name=icon] slot:not([name=exit]) { display: none !important; } ${/* Double negative, but safer if display doesn't equal 'block' */ ""} :host(:not([${MediaUIAttributes.MEDIA_IS_CASTING}])) slot[name=icon] slot:not([name=enter]) { display: none !important; } :host([${MediaUIAttributes.MEDIA_IS_CASTING}]) slot[name=tooltip-enter], :host(:not([${MediaUIAttributes.MEDIA_IS_CASTING}])) slot[name=tooltip-exit] { display: none; } </style> <slot name="icon"> <slot name="enter">${enterIcon}</slot> <slot name="exit">${exitIcon}</slot> </slot> `; var tooltipContent3 = ( /*html*/ ` <slot name="tooltip-enter">${tooltipLabels.START_CAST}</slot> <slot name="tooltip-exit">${tooltipLabels.STOP_CAST}</slot> ` ); var updateAriaLabel2 = (el) => { const label = el.mediaIsCasting ? verbs.EXIT_CAST() : verbs.ENTER_CAST(); el.setAttribute("aria-label", label); }; var MediaCastButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_IS_CASTING, MediaUIAttributes.MEDIA_CAST_UNAVAILABLE ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate3, tooltipContent: tooltipContent3, ...options2 }); } connectedCallback() { super.connectedCallback(); updateAriaLabel2(this); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_IS_CASTING) { updateAriaLabel2(this); } } /** * @type {boolean} Are we currently casting */ get mediaIsCasting() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_IS_CASTING); } set mediaIsCasting(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_IS_CASTING, value); } /** * @type {string | undefined} Cast unavailability state */ get mediaCastUnavailable() { return getStringAttr(this, MediaUIAttributes.MEDIA_CAST_UNAVAILABLE); } set mediaCastUnavailable(value) { setStringAttr(this, MediaUIAttributes.MEDIA_CAST_UNAVAILABLE, value); } handleClick() { const eventName = this.mediaIsCasting ? MediaUIEvents.MEDIA_EXIT_CAST_REQUEST : MediaUIEvents.MEDIA_ENTER_CAST_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); } }; if (!GlobalThis.customElements.get("media-cast-button")) { GlobalThis.customElements.define("media-cast-button", MediaCastButton); } // node_modules/media-chrome/dist/media-chrome-dialog.js var __accessCheck6 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet6 = (obj, member, getter) => { __accessCheck6(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd6 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet6 = (obj, member, value, setter) => { __accessCheck6(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod4 = (obj, member, method) => { __accessCheck6(obj, member, "access private method"); return method; }; var _previouslyFocused; var _invokerElement; var _handleOpen; var handleOpen_fn; var _handleClosed; var handleClosed_fn; var _handleInvoke; var handleInvoke_fn; var _handleFocusOut; var handleFocusOut_fn; var _handleKeyDown; var handleKeyDown_fn; var template4 = Document2.createElement("template"); template4.innerHTML = /*html*/ ` <style> :host { font: var(--media-font, var(--media-font-weight, normal) var(--media-font-size, 14px) / var(--media-text-content-height, var(--media-control-height, 24px)) var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif)); color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238))); background: var(--media-dialog-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .8)))); border-radius: var(--media-dialog-border-radius); border: var(--media-dialog-border, none); display: var(--media-dialog-display, inline-flex); transition: var(--media-dialog-transition-in, visibility 0s, opacity .2s ease-out, transform .15s ease-out ) !important; ${/* ^^Prevent transition override by media-container */ ""} visibility: var(--media-dialog-visibility, visible); opacity: var(--media-dialog-opacity, 1); transform: var(--media-dialog-transform-in, translateY(0) scale(1)); } :host([hidden]) { transition: var(--media-dialog-transition-out, visibility .15s ease-in, opacity .15s ease-in, transform .15s ease-in ) !important; visibility: var(--media-dialog-hidden-visibility, hidden); opacity: var(--media-dialog-hidden-opacity, 0); transform: var(--media-dialog-transform-out, translateY(2px) scale(.99)); pointer-events: none; } </style> <slot></slot> `; var Attributes4 = { HIDDEN: "hidden", ANCHOR: "anchor" }; var MediaChromeDialog = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd6(this, _handleOpen); __privateAdd6(this, _handleClosed); __privateAdd6(this, _handleInvoke); __privateAdd6(this, _handleFocusOut); __privateAdd6(this, _handleKeyDown); __privateAdd6(this, _previouslyFocused, null); __privateAdd6(this, _invokerElement, null); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.nativeEl = this.constructor.template.content.cloneNode(true); this.shadowRoot.append(this.nativeEl); } this.addEventListener("invoke", this); this.addEventListener("focusout", this); this.addEventListener("keydown", this); } static get observedAttributes() { return [Attributes4.HIDDEN, Attributes4.ANCHOR]; } handleEvent(event) { switch (event.type) { case "invoke": __privateMethod4(this, _handleInvoke, handleInvoke_fn).call(this, event); break; case "focusout": __privateMethod4(this, _handleFocusOut, handleFocusOut_fn).call(this, event); break; case "keydown": __privateMethod4(this, _handleKeyDown, handleKeyDown_fn).call(this, event); break; } } connectedCallback() { if (!this.role) { this.role = "dialog"; } } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === Attributes4.HIDDEN && newValue !== oldValue) { if (this.hidden) { __privateMethod4(this, _handleClosed, handleClosed_fn).call(this); } else { __privateMethod4(this, _handleOpen, handleOpen_fn).call(this); } } } focus() { __privateSet6(this, _previouslyFocused, getActiveElement()); const focusable = this.querySelector( '[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]' ); focusable == null ? void 0 : focusable.focus(); } get keysUsed() { return ["Escape", "Tab"]; } }; _previouslyFocused = /* @__PURE__ */ new WeakMap(); _invokerElement = /* @__PURE__ */ new WeakMap(); _handleOpen = /* @__PURE__ */ new WeakSet(); handleOpen_fn = function() { var _a3; (_a3 = __privateGet6(this, _invokerElement)) == null ? void 0 : _a3.setAttribute("aria-expanded", "true"); this.addEventListener("transitionend", () => this.focus(), { once: true }); }; _handleClosed = /* @__PURE__ */ new WeakSet(); handleClosed_fn = function() { var _a3; (_a3 = __privateGet6(this, _invokerElement)) == null ? void 0 : _a3.setAttribute("aria-expanded", "false"); }; _handleInvoke = /* @__PURE__ */ new WeakSet(); handleInvoke_fn = function(event) { __privateSet6(this, _invokerElement, event.relatedTarget); if (!containsComposedNode(this, event.relatedTarget)) { this.hidden = !this.hidden; } }; _handleFocusOut = /* @__PURE__ */ new WeakSet(); handleFocusOut_fn = function(event) { var _a3; if (!containsComposedNode(this, event.relatedTarget)) { (_a3 = __privateGet6(this, _previouslyFocused)) == null ? void 0 : _a3.focus(); if (__privateGet6(this, _invokerElement) && __privateGet6(this, _invokerElement) !== event.relatedTarget && !this.hidden) { this.hidden = true; } } }; _handleKeyDown = /* @__PURE__ */ new WeakSet(); handleKeyDown_fn = function(event) { var _a3, _b, _c, _d, _e5; const { key, ctrlKey, altKey, metaKey } = event; if (ctrlKey || altKey || metaKey) { return; } if (!this.keysUsed.includes(key)) { return; } event.preventDefault(); event.stopPropagation(); if (key === "Tab") { if (event.shiftKey) { (_b = (_a3 = this.previousElementSibling) == null ? void 0 : _a3.focus) == null ? void 0 : _b.call(_a3); } else { (_d = (_c = this.nextElementSibling) == null ? void 0 : _c.focus) == null ? void 0 : _d.call(_c); } this.blur(); } else if (key === "Escape") { (_e5 = __privateGet6(this, _previouslyFocused)) == null ? void 0 : _e5.focus(); this.hidden = true; } }; MediaChromeDialog.template = template4; if (!GlobalThis.customElements.get("media-chrome-dialog")) { GlobalThis.customElements.define("media-chrome-dialog", MediaChromeDialog); } // node_modules/media-chrome/dist/media-chrome-range.js var __accessCheck7 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet7 = (obj, member, getter) => { __accessCheck7(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd7 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet7 = (obj, member, value, setter) => { __accessCheck7(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod5 = (obj, member, method) => { __accessCheck7(obj, member, "access private method"); return method; }; var _mediaController3; var _isInputTarget; var _startpoint; var _endpoint; var _cssRules; var _segments; var _onFocusIn; var _onFocusOut; var _updateComputedStyles; var _updateActiveSegment; var updateActiveSegment_fn; var _enableUserEvents; var enableUserEvents_fn; var _disableUserEvents; var disableUserEvents_fn; var _handlePointerDown; var handlePointerDown_fn; var _handlePointerEnter; var handlePointerEnter_fn; var _handlePointerUp2; var handlePointerUp_fn2; var _handlePointerLeave; var handlePointerLeave_fn; var _handlePointerMove2; var handlePointerMove_fn2; var template5 = Document2.createElement("template"); template5.innerHTML = /*html*/ ` <style> :host { --_focus-box-shadow: var(--media-focus-box-shadow, inset 0 0 0 2px rgb(27 127 204 / .9)); --_media-range-padding: var(--media-range-padding, var(--media-control-padding, 10px)); box-shadow: var(--_focus-visible-box-shadow, none); background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7))); height: calc(var(--media-control-height, 24px) + 2 * var(--_media-range-padding)); display: inline-flex; align-items: center; ${/* Don't horizontal align w/ justify-content! #container can go negative on the x-axis w/ small width. */ ""} vertical-align: middle; box-sizing: border-box; position: relative; width: 100px; transition: background .15s linear; cursor: pointer; pointer-events: auto; touch-action: none; ${/* Prevent scrolling when dragging on mobile. */ ""} z-index: 1; ${/* Apply z-index to overlap buttons below. */ ""} } ${/* Reset before `outline` on track could be set by a CSS var */ ""} input[type=range]:focus { outline: 0; } input[type=range]:focus::-webkit-slider-runnable-track { outline: 0; } :host(:hover) { background: var(--media-control-hover-background, rgb(50 50 70 / .7)); } #leftgap { padding-left: var(--media-range-padding-left, var(--_media-range-padding)); } #rightgap { padding-right: var(--media-range-padding-right, var(--_media-range-padding)); } #startpoint, #endpoint { position: absolute; } #endpoint { right: 0; } #container { ${/* Not using the CSS `padding` prop makes it easier for slide open volume ranges so the width can be zero. */ ""} width: var(--media-range-track-width, 100%); transform: translate(var(--media-range-track-translate-x, 0px), var(--media-range-track-translate-y, 0px)); position: relative; height: 100%; display: flex; align-items: center; min-width: 40px; } #range { ${/* The input range acts as a hover and hit zone for input events. */ ""} display: var(--media-time-range-hover-display, block); bottom: var(--media-time-range-hover-bottom, -7px); height: var(--media-time-range-hover-height, max(100% + 7px, 25px)); width: 100%; position: absolute; cursor: pointer; -webkit-appearance: none; ${/* Hides the slider so that custom slider can be made */ ""} -webkit-tap-highlight-color: transparent; background: transparent; ${/* Otherwise white in Chrome */ ""} margin: 0; z-index: 1; } @media (hover: hover) { #range { bottom: var(--media-time-range-hover-bottom, -5px); height: var(--media-time-range-hover-height, max(100% + 5px, 20px)); } } ${/* Special styling for WebKit/Blink */ ""} ${/* Make thumb width/height small so it has no effect on range click position. */ ""} #range::-webkit-slider-thumb { -webkit-appearance: none; background: transparent; width: .1px; height: .1px; } ${/* The thumb is not positioned relative to the track in Firefox */ ""} #range::-moz-range-thumb { background: transparent; border: transparent; width: .1px; height: .1px; } #appearance { height: var(--media-range-track-height, 4px); display: flex; flex-direction: column; justify-content: center; width: 100%; position: absolute; ${/* Required for Safari to stop glitching track height on hover */ ""} will-change: transform; } #track { background: var(--media-range-track-background, rgb(255 255 255 / .2)); border-radius: var(--media-range-track-border-radius, 1px); border: var(--media-range-track-border, none); outline: var(--media-range-track-outline); outline-offset: var(--media-range-track-outline-offset); backdrop-filter: var(--media-range-track-backdrop-filter); -webkit-backdrop-filter: var(--media-range-track-backdrop-filter); box-shadow: var(--media-range-track-box-shadow, none); position: absolute; width: 100%; height: 100%; overflow: hidden; } #progress, #pointer { position: absolute; height: 100%; will-change: width; } #progress { background: var(--media-range-bar-color, var(--media-primary-color, rgb(238 238 238))); transition: var(--media-range-track-transition); } #pointer { background: var(--media-range-track-pointer-background); border-right: var(--media-range-track-pointer-border-right); transition: visibility .25s, opacity .25s; visibility: hidden; opacity: 0; } @media (hover: hover) { :host(:hover) #pointer { transition: visibility .5s, opacity .5s; visibility: visible; opacity: 1; } } #thumb { width: var(--media-range-thumb-width, 10px); height: var(--media-range-thumb-height, 10px); margin-left: calc(var(--media-range-thumb-width, 10px) / -2); border: var(--media-range-thumb-border, none); border-radius: var(--media-range-thumb-border-radius, 10px); background: var(--media-range-thumb-background, var(--media-primary-color, rgb(238 238 238))); box-shadow: var(--media-range-thumb-box-shadow, 1px 1px 1px transparent); transition: var(--media-range-thumb-transition); transform: var(--media-range-thumb-transform, none); opacity: var(--media-range-thumb-opacity, 1); position: absolute; left: 0; cursor: pointer; } :host([disabled]) #thumb { background-color: #777; } .segments #appearance { height: var(--media-range-segment-hover-height, 7px); } #track { clip-path: url(#segments-clipping); } #segments { --segments-gap: var(--media-range-segments-gap, 2px); position: absolute; width: 100%; height: 100%; } #segments-clipping { transform: translateX(calc(var(--segments-gap) / 2)); } #segments-clipping:empty { display: none; } #segments-clipping rect { height: var(--media-range-track-height, 4px); y: calc((var(--media-range-segment-hover-height, 7px) - var(--media-range-track-height, 4px)) / 2); transition: var(--media-range-segment-transition, transform .1s ease-in-out); transform: var(--media-range-segment-transform, scaleY(1)); transform-origin: center; } </style> <div id="leftgap"></div> <div id="container"> <div id="startpoint"></div> <div id="endpoint"></div> <div id="appearance"> <div id="track" part="track"> <div id="pointer"></div> <div id="progress" part="progress"></div> </div> <div id="thumb" part="thumb"></div> <svg id="segments"><clipPath id="segments-clipping"></clipPath></svg> </div> <input id="range" type="range" min="0" max="1" step="any" value="0"> </div> <div id="rightgap"></div> `; var MediaChromeRange = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd7(this, _updateActiveSegment); __privateAdd7(this, _enableUserEvents); __privateAdd7(this, _disableUserEvents); __privateAdd7(this, _handlePointerDown); __privateAdd7(this, _handlePointerEnter); __privateAdd7(this, _handlePointerUp2); __privateAdd7(this, _handlePointerLeave); __privateAdd7(this, _handlePointerMove2); __privateAdd7(this, _mediaController3, void 0); __privateAdd7(this, _isInputTarget, void 0); __privateAdd7(this, _startpoint, void 0); __privateAdd7(this, _endpoint, void 0); __privateAdd7(this, _cssRules, {}); __privateAdd7(this, _segments, []); __privateAdd7(this, _onFocusIn, () => { if (this.range.matches(":focus-visible")) { const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); style.setProperty( "--_focus-visible-box-shadow", "var(--_focus-box-shadow)" ); } }); __privateAdd7(this, _onFocusOut, () => { const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); style.removeProperty("--_focus-visible-box-shadow"); }); __privateAdd7(this, _updateComputedStyles, () => { const clipping = this.shadowRoot.querySelector("#segments-clipping"); if (clipping) clipping.parentNode.append(clipping); }); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template5.content.cloneNode(true)); } this.container = this.shadowRoot.querySelector("#container"); __privateSet7(this, _startpoint, this.shadowRoot.querySelector("#startpoint")); __privateSet7(this, _endpoint, this.shadowRoot.querySelector("#endpoint")); this.range = this.shadowRoot.querySelector("#range"); this.appearance = this.shadowRoot.querySelector("#appearance"); } static get observedAttributes() { return [ "disabled", "aria-disabled", MediaStateReceiverAttributes.MEDIA_CONTROLLER ]; } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet7(this, _mediaController3)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet7(this, _mediaController3, null); } if (newValue && this.isConnected) { __privateSet7(this, _mediaController3, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet7(this, _mediaController3)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } else if (attrName === "disabled" || attrName === "aria-disabled" && oldValue !== newValue) { if (newValue == null) { this.range.removeAttribute(attrName); __privateMethod5(this, _enableUserEvents, enableUserEvents_fn).call(this); } else { this.range.setAttribute(attrName, newValue); __privateMethod5(this, _disableUserEvents, disableUserEvents_fn).call(this); } } } connectedCallback() { var _a3, _b, _c; const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); style.setProperty( "display", `var(--media-control-display, var(--${this.localName}-display, inline-flex))` ); __privateGet7(this, _cssRules).pointer = getOrInsertCSSRule(this.shadowRoot, "#pointer"); __privateGet7(this, _cssRules).progress = getOrInsertCSSRule(this.shadowRoot, "#progress"); __privateGet7(this, _cssRules).thumb = getOrInsertCSSRule(this.shadowRoot, "#thumb"); __privateGet7(this, _cssRules).activeSegment = getOrInsertCSSRule( this.shadowRoot, "#segments-clipping rect:nth-child(0)" ); const mediaControllerId = this.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { __privateSet7(this, _mediaController3, (_a3 = this.getRootNode()) == null ? void 0 : _a3.getElementById( mediaControllerId )); (_c = (_b = __privateGet7(this, _mediaController3)) == null ? void 0 : _b.associateElement) == null ? void 0 : _c.call(_b, this); } this.updateBar(); this.shadowRoot.addEventListener("focusin", __privateGet7(this, _onFocusIn)); this.shadowRoot.addEventListener("focusout", __privateGet7(this, _onFocusOut)); __privateMethod5(this, _enableUserEvents, enableUserEvents_fn).call(this); observeResize(this.container, __privateGet7(this, _updateComputedStyles)); } disconnectedCallback() { var _a3, _b; __privateMethod5(this, _disableUserEvents, disableUserEvents_fn).call(this); (_b = (_a3 = __privateGet7(this, _mediaController3)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet7(this, _mediaController3, null); this.shadowRoot.removeEventListener("focusin", __privateGet7(this, _onFocusIn)); this.shadowRoot.removeEventListener("focusout", __privateGet7(this, _onFocusOut)); unobserveResize(this.container, __privateGet7(this, _updateComputedStyles)); } updatePointerBar(evt) { var _a3; (_a3 = __privateGet7(this, _cssRules).pointer) == null ? void 0 : _a3.style.setProperty( "width", `${this.getPointerRatio(evt) * 100}%` ); } updateBar() { var _a3, _b; const rangePercent = this.range.valueAsNumber * 100; (_a3 = __privateGet7(this, _cssRules).progress) == null ? void 0 : _a3.style.setProperty("width", `${rangePercent}%`); (_b = __privateGet7(this, _cssRules).thumb) == null ? void 0 : _b.style.setProperty("left", `${rangePercent}%`); } updateSegments(segments) { const clipping = this.shadowRoot.querySelector("#segments-clipping"); clipping.textContent = ""; this.container.classList.toggle("segments", !!(segments == null ? void 0 : segments.length)); if (!(segments == null ? void 0 : segments.length)) return; const normalized = [ .../* @__PURE__ */ new Set([ +this.range.min, ...segments.flatMap((s) => [s.start, s.end]), +this.range.max ]) ]; __privateSet7(this, _segments, [...normalized]); const lastMarker = normalized.pop(); for (const [i3, marker] of normalized.entries()) { const [isFirst, isLast] = [i3 === 0, i3 === normalized.length - 1]; const x2 = isFirst ? "calc(var(--segments-gap) / -1)" : `${marker * 100}%`; const x22 = isLast ? lastMarker : normalized[i3 + 1]; const width = `calc(${(x22 - marker) * 100}%${isFirst || isLast ? "" : ` - var(--segments-gap)`})`; const segmentEl = Document2.createElementNS( "http://www.w3.org/2000/svg", "rect" ); const cssRule = getOrInsertCSSRule( this.shadowRoot, `#segments-clipping rect:nth-child(${i3 + 1})` ); cssRule.style.setProperty("x", x2); cssRule.style.setProperty("width", width); clipping.append(segmentEl); } } getPointerRatio(evt) { const pointerRatio = getPointProgressOnLine( evt.clientX, evt.clientY, __privateGet7(this, _startpoint).getBoundingClientRect(), __privateGet7(this, _endpoint).getBoundingClientRect() ); return Math.max(0, Math.min(1, pointerRatio)); } get dragging() { return this.hasAttribute("dragging"); } handleEvent(evt) { switch (evt.type) { case "pointermove": __privateMethod5(this, _handlePointerMove2, handlePointerMove_fn2).call(this, evt); break; case "input": this.updateBar(); break; case "pointerenter": __privateMethod5(this, _handlePointerEnter, handlePointerEnter_fn).call(this, evt); break; case "pointerdown": __privateMethod5(this, _handlePointerDown, handlePointerDown_fn).call(this, evt); break; case "pointerup": __privateMethod5(this, _handlePointerUp2, handlePointerUp_fn2).call(this); break; case "pointerleave": __privateMethod5(this, _handlePointerLeave, handlePointerLeave_fn).call(this); break; } } get keysUsed() { return ["ArrowUp", "ArrowRight", "ArrowDown", "ArrowLeft"]; } }; _mediaController3 = /* @__PURE__ */ new WeakMap(); _isInputTarget = /* @__PURE__ */ new WeakMap(); _startpoint = /* @__PURE__ */ new WeakMap(); _endpoint = /* @__PURE__ */ new WeakMap(); _cssRules = /* @__PURE__ */ new WeakMap(); _segments = /* @__PURE__ */ new WeakMap(); _onFocusIn = /* @__PURE__ */ new WeakMap(); _onFocusOut = /* @__PURE__ */ new WeakMap(); _updateComputedStyles = /* @__PURE__ */ new WeakMap(); _updateActiveSegment = /* @__PURE__ */ new WeakSet(); updateActiveSegment_fn = function(evt) { const rule = __privateGet7(this, _cssRules).activeSegment; if (!rule) return; const pointerRatio = this.getPointerRatio(evt); const segmentIndex = __privateGet7(this, _segments).findIndex((start, i3, arr) => { const end = arr[i3 + 1]; return end != null && pointerRatio >= start && pointerRatio <= end; }); const selectorText = `#segments-clipping rect:nth-child(${segmentIndex + 1})`; if (rule.selectorText != selectorText || !rule.style.transform) { rule.selectorText = selectorText; rule.style.setProperty( "transform", "var(--media-range-segment-hover-transform, scaleY(2))" ); } }; _enableUserEvents = /* @__PURE__ */ new WeakSet(); enableUserEvents_fn = function() { if (this.hasAttribute("disabled")) return; this.addEventListener("input", this); this.addEventListener("pointerdown", this); this.addEventListener("pointerenter", this); }; _disableUserEvents = /* @__PURE__ */ new WeakSet(); disableUserEvents_fn = function() { var _a3, _b; this.removeEventListener("input", this); this.removeEventListener("pointerdown", this); this.removeEventListener("pointerenter", this); (_a3 = GlobalThis.window) == null ? void 0 : _a3.removeEventListener("pointerup", this); (_b = GlobalThis.window) == null ? void 0 : _b.removeEventListener("pointermove", this); }; _handlePointerDown = /* @__PURE__ */ new WeakSet(); handlePointerDown_fn = function(evt) { var _a3; __privateSet7(this, _isInputTarget, evt.composedPath().includes(this.range)); (_a3 = GlobalThis.window) == null ? void 0 : _a3.addEventListener("pointerup", this); }; _handlePointerEnter = /* @__PURE__ */ new WeakSet(); handlePointerEnter_fn = function(evt) { var _a3; if (evt.pointerType !== "mouse") __privateMethod5(this, _handlePointerDown, handlePointerDown_fn).call(this, evt); this.addEventListener("pointerleave", this); (_a3 = GlobalThis.window) == null ? void 0 : _a3.addEventListener("pointermove", this); }; _handlePointerUp2 = /* @__PURE__ */ new WeakSet(); handlePointerUp_fn2 = function() { var _a3; (_a3 = GlobalThis.window) == null ? void 0 : _a3.removeEventListener("pointerup", this); this.toggleAttribute("dragging", false); this.range.disabled = this.hasAttribute("disabled"); }; _handlePointerLeave = /* @__PURE__ */ new WeakSet(); handlePointerLeave_fn = function() { var _a3, _b; this.removeEventListener("pointerleave", this); (_a3 = GlobalThis.window) == null ? void 0 : _a3.removeEventListener("pointermove", this); this.toggleAttribute("dragging", false); this.range.disabled = this.hasAttribute("disabled"); (_b = __privateGet7(this, _cssRules).activeSegment) == null ? void 0 : _b.style.removeProperty("transform"); }; _handlePointerMove2 = /* @__PURE__ */ new WeakSet(); handlePointerMove_fn2 = function(evt) { this.toggleAttribute( "dragging", evt.buttons === 1 || evt.pointerType !== "mouse" ); this.updatePointerBar(evt); __privateMethod5(this, _updateActiveSegment, updateActiveSegment_fn).call(this, evt); if (this.dragging && (evt.pointerType !== "mouse" || !__privateGet7(this, _isInputTarget))) { this.range.disabled = true; this.range.valueAsNumber = this.getPointerRatio(evt); this.range.dispatchEvent( new Event("input", { bubbles: true, composed: true }) ); } }; if (!GlobalThis.customElements.get("media-chrome-range")) { GlobalThis.customElements.define("media-chrome-range", MediaChromeRange); } // node_modules/media-chrome/dist/media-control-bar.js var __accessCheck8 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet8 = (obj, member, getter) => { __accessCheck8(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd8 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet8 = (obj, member, value, setter) => { __accessCheck8(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _mediaController4; var template6 = Document2.createElement("template"); template6.innerHTML = /*html*/ ` <style> :host { ${/* Need position to display above video for some reason */ ""} box-sizing: border-box; display: var(--media-control-display, var(--media-control-bar-display, inline-flex)); color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238))); --media-loading-indicator-icon-height: 44px; } ::slotted(media-time-range), ::slotted(media-volume-range) { min-height: 100%; } ::slotted(media-time-range), ::slotted(media-clip-selector) { flex-grow: 1; } ::slotted([role="menu"]) { position: absolute; } </style> <slot></slot> `; var MediaControlBar = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd8(this, _mediaController4, void 0); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template6.content.cloneNode(true)); } } static get observedAttributes() { return [MediaStateReceiverAttributes.MEDIA_CONTROLLER]; } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet8(this, _mediaController4)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet8(this, _mediaController4, null); } if (newValue && this.isConnected) { __privateSet8(this, _mediaController4, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet8(this, _mediaController4)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } } connectedCallback() { var _a3, _b, _c; const mediaControllerId = this.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { __privateSet8(this, _mediaController4, (_a3 = this.getRootNode()) == null ? void 0 : _a3.getElementById( mediaControllerId )); (_c = (_b = __privateGet8(this, _mediaController4)) == null ? void 0 : _b.associateElement) == null ? void 0 : _c.call(_b, this); } } disconnectedCallback() { var _a3, _b; (_b = (_a3 = __privateGet8(this, _mediaController4)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet8(this, _mediaController4, null); } }; _mediaController4 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-control-bar")) { GlobalThis.customElements.define("media-control-bar", MediaControlBar); } // node_modules/media-chrome/dist/media-text-display.js var __accessCheck9 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet9 = (obj, member, getter) => { __accessCheck9(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd9 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet9 = (obj, member, value, setter) => { __accessCheck9(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _mediaController5; var template7 = Document2.createElement("template"); template7.innerHTML = /*html*/ ` <style> :host { font: var(--media-font, var(--media-font-weight, normal) var(--media-font-size, 14px) / var(--media-text-content-height, var(--media-control-height, 24px)) var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif)); color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238))); background: var(--media-text-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)))); padding: var(--media-control-padding, 10px); display: inline-flex; justify-content: center; align-items: center; vertical-align: middle; box-sizing: border-box; text-align: center; pointer-events: auto; } ${/* Only show outline when keyboard focusing. https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo */ ""} :host(:focus-visible) { box-shadow: inset 0 0 0 2px rgb(27 127 204 / .9); outline: 0; } ${/* * hide default focus ring, particularly when using mouse */ ""} :host(:where(:focus)) { box-shadow: none; outline: 0; } </style> <slot></slot> `; var MediaTextDisplay = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd9(this, _mediaController5, void 0); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template7.content.cloneNode(true)); } } static get observedAttributes() { return [MediaStateReceiverAttributes.MEDIA_CONTROLLER]; } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet9(this, _mediaController5)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet9(this, _mediaController5, null); } if (newValue && this.isConnected) { __privateSet9(this, _mediaController5, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet9(this, _mediaController5)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } } connectedCallback() { var _a3, _b, _c; const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); style.setProperty( "display", `var(--media-control-display, var(--${this.localName}-display, inline-flex))` ); const mediaControllerId = this.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { __privateSet9(this, _mediaController5, (_a3 = this.getRootNode()) == null ? void 0 : _a3.getElementById( mediaControllerId )); (_c = (_b = __privateGet9(this, _mediaController5)) == null ? void 0 : _b.associateElement) == null ? void 0 : _c.call(_b, this); } } disconnectedCallback() { var _a3, _b; (_b = (_a3 = __privateGet9(this, _mediaController5)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet9(this, _mediaController5, null); } }; _mediaController5 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-text-display")) { GlobalThis.customElements.define("media-text-display", MediaTextDisplay); } // node_modules/media-chrome/dist/media-duration-display.js var __accessCheck10 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet10 = (obj, member, getter) => { __accessCheck10(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd10 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet10 = (obj, member, value, setter) => { __accessCheck10(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _slot; var MediaDurationDisplay = class extends MediaTextDisplay { constructor() { super(); __privateAdd10(this, _slot, void 0); __privateSet10(this, _slot, this.shadowRoot.querySelector("slot")); __privateGet10(this, _slot).textContent = formatTime(0); } static get observedAttributes() { return [...super.observedAttributes, MediaUIAttributes.MEDIA_DURATION]; } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === MediaUIAttributes.MEDIA_DURATION) { __privateGet10(this, _slot).textContent = formatTime(+newValue); } super.attributeChangedCallback(attrName, oldValue, newValue); } /** * @type {number | undefined} In seconds */ get mediaDuration() { return getNumericAttr(this, MediaUIAttributes.MEDIA_DURATION); } set mediaDuration(time) { setNumericAttr(this, MediaUIAttributes.MEDIA_DURATION, time); } }; _slot = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-duration-display")) { GlobalThis.customElements.define( "media-duration-display", MediaDurationDisplay ); } // node_modules/media-chrome/dist/media-fullscreen-button.js var enterFullscreenIcon = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M16 3v2.5h3.5V9H22V3h-6ZM4 9h2.5V5.5H10V3H4v6Zm15.5 9.5H16V21h6v-6h-2.5v3.5ZM6.5 15H4v6h6v-2.5H6.5V15Z"/> </svg>`; var exitFullscreenIcon = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M18.5 6.5V3H16v6h6V6.5h-3.5ZM16 21h2.5v-3.5H22V15h-6v6ZM4 17.5h3.5V21H10v-6H4v2.5Zm3.5-11H4V9h6V3H7.5v3.5Z"/> </svg>`; var slotTemplate4 = Document2.createElement("template"); slotTemplate4.innerHTML = /*html*/ ` <style> :host([${MediaUIAttributes.MEDIA_IS_FULLSCREEN}]) slot[name=icon] slot:not([name=exit]) { display: none !important; } ${/* Double negative, but safer if display doesn't equal 'block' */ ""} :host(:not([${MediaUIAttributes.MEDIA_IS_FULLSCREEN}])) slot[name=icon] slot:not([name=enter]) { display: none !important; } :host([${MediaUIAttributes.MEDIA_IS_FULLSCREEN}]) slot[name=tooltip-enter], :host(:not([${MediaUIAttributes.MEDIA_IS_FULLSCREEN}])) slot[name=tooltip-exit] { display: none; } </style> <slot name="icon"> <slot name="enter">${enterFullscreenIcon}</slot> <slot name="exit">${exitFullscreenIcon}</slot> </slot> `; var tooltipContent4 = ( /*html*/ ` <slot name="tooltip-enter">${tooltipLabels.ENTER_FULLSCREEN}</slot> <slot name="tooltip-exit">${tooltipLabels.EXIT_FULLSCREEN}</slot> ` ); var updateAriaLabel3 = (el) => { const label = el.mediaIsFullscreen ? verbs.EXIT_FULLSCREEN() : verbs.ENTER_FULLSCREEN(); el.setAttribute("aria-label", label); }; var MediaFullscreenButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_IS_FULLSCREEN, MediaUIAttributes.MEDIA_FULLSCREEN_UNAVAILABLE ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate4, tooltipContent: tooltipContent4, ...options2 }); } connectedCallback() { super.connectedCallback(); updateAriaLabel3(this); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_IS_FULLSCREEN) { updateAriaLabel3(this); } } /** * @type {string | undefined} Fullscreen unavailability state */ get mediaFullscreenUnavailable() { return getStringAttr(this, MediaUIAttributes.MEDIA_FULLSCREEN_UNAVAILABLE); } set mediaFullscreenUnavailable(value) { setStringAttr(this, MediaUIAttributes.MEDIA_FULLSCREEN_UNAVAILABLE, value); } /** * @type {boolean} Whether fullscreen is available */ get mediaIsFullscreen() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_IS_FULLSCREEN); } set mediaIsFullscreen(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_IS_FULLSCREEN, value); } handleClick() { const eventName = this.mediaIsFullscreen ? MediaUIEvents.MEDIA_EXIT_FULLSCREEN_REQUEST : MediaUIEvents.MEDIA_ENTER_FULLSCREEN_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); } }; if (!GlobalThis.customElements.get("media-fullscreen-button")) { GlobalThis.customElements.define( "media-fullscreen-button", MediaFullscreenButton ); } // node_modules/media-chrome/dist/media-live-button.js var { MEDIA_TIME_IS_LIVE, MEDIA_PAUSED } = MediaUIAttributes; var { MEDIA_SEEK_TO_LIVE_REQUEST, MEDIA_PLAY_REQUEST } = MediaUIEvents; var indicatorSVG = '<svg viewBox="0 0 6 12"><circle cx="3" cy="6" r="2"></circle></svg>'; var slotTemplate5 = Document2.createElement("template"); slotTemplate5.innerHTML = /*html*/ ` <style> :host { --media-tooltip-display: none; } slot[name=indicator] > *, :host ::slotted([slot=indicator]) { ${/* Override styles for icon-only buttons */ ""} min-width: auto; fill: var(--media-live-button-icon-color, rgb(140, 140, 140)); color: var(--media-live-button-icon-color, rgb(140, 140, 140)); } :host([${MEDIA_TIME_IS_LIVE}]:not([${MEDIA_PAUSED}])) slot[name=indicator] > *, :host([${MEDIA_TIME_IS_LIVE}]:not([${MEDIA_PAUSED}])) ::slotted([slot=indicator]) { fill: var(--media-live-button-indicator-color, rgb(255, 0, 0)); color: var(--media-live-button-indicator-color, rgb(255, 0, 0)); } :host([${MEDIA_TIME_IS_LIVE}]:not([${MEDIA_PAUSED}])) { cursor: not-allowed; } </style> <slot name="indicator">${indicatorSVG}</slot> ${/* A new line between spacer and text creates inconsistent spacing between slotted items and default slots. */ ""} <slot name="spacer"> </slot><slot name="text">LIVE</slot> `; var updateAriaAttributes = (el) => { const isPausedOrNotLive = el.mediaPaused || !el.mediaTimeIsLive; const label = isPausedOrNotLive ? verbs.SEEK_LIVE() : verbs.PLAYING_LIVE(); el.setAttribute("aria-label", label); isPausedOrNotLive ? el.removeAttribute("aria-disabled") : el.setAttribute("aria-disabled", "true"); }; var MediaLiveButton = class extends MediaChromeButton { static get observedAttributes() { return [...super.observedAttributes, MEDIA_PAUSED, MEDIA_TIME_IS_LIVE]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate5, ...options2 }); } connectedCallback() { updateAriaAttributes(this); super.connectedCallback(); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); updateAriaAttributes(this); } /** * @type {boolean} Is the media paused */ get mediaPaused() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED); } set mediaPaused(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED, value); } /** * @type {boolean} Is the media playback currently live */ get mediaTimeIsLive() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_TIME_IS_LIVE); } set mediaTimeIsLive(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_TIME_IS_LIVE, value); } handleClick() { if (!this.mediaPaused && this.mediaTimeIsLive) return; this.dispatchEvent( new GlobalThis.CustomEvent(MEDIA_SEEK_TO_LIVE_REQUEST, { composed: true, bubbles: true }) ); if (this.hasAttribute(MEDIA_PAUSED)) { this.dispatchEvent( new GlobalThis.CustomEvent(MEDIA_PLAY_REQUEST, { composed: true, bubbles: true }) ); } } }; if (!GlobalThis.customElements.get("media-live-button")) { GlobalThis.customElements.define("media-live-button", MediaLiveButton); } // node_modules/media-chrome/dist/media-loading-indicator.js var __accessCheck11 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet11 = (obj, member, getter) => { __accessCheck11(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd11 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet11 = (obj, member, value, setter) => { __accessCheck11(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _mediaController6; var _delay; var Attributes5 = { LOADING_DELAY: "loadingdelay" }; var DEFAULT_LOADING_DELAY = 500; var template8 = Document2.createElement("template"); var loadingIndicatorIcon = ` <svg aria-hidden="true" viewBox="0 0 100 100"> <path d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50"> <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s" from="0 50 50" to="360 50 50" repeatCount="indefinite" /> </path> </svg> `; template8.innerHTML = /*html*/ ` <style> :host { display: var(--media-control-display, var(--media-loading-indicator-display, inline-block)); vertical-align: middle; box-sizing: border-box; --_loading-indicator-delay: var(--media-loading-indicator-transition-delay, ${DEFAULT_LOADING_DELAY}ms); } #status { color: rgba(0,0,0,0); width: 0px; height: 0px; } :host slot[name=icon] > *, :host ::slotted([slot=icon]) { opacity: var(--media-loading-indicator-opacity, 0); transition: opacity 0.15s; } :host([${MediaUIAttributes.MEDIA_LOADING}]:not([${MediaUIAttributes.MEDIA_PAUSED}])) slot[name=icon] > *, :host([${MediaUIAttributes.MEDIA_LOADING}]:not([${MediaUIAttributes.MEDIA_PAUSED}])) ::slotted([slot=icon]) { opacity: var(--media-loading-indicator-opacity, 1); transition: opacity 0.15s var(--_loading-indicator-delay); } :host #status { visibility: var(--media-loading-indicator-opacity, hidden); transition: visibility 0.15s; } :host([${MediaUIAttributes.MEDIA_LOADING}]:not([${MediaUIAttributes.MEDIA_PAUSED}])) #status { visibility: var(--media-loading-indicator-opacity, visible); transition: visibility 0.15s var(--_loading-indicator-delay); } svg, img, ::slotted(svg), ::slotted(img) { width: var(--media-loading-indicator-icon-width); height: var(--media-loading-indicator-icon-height, 100px); fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238))); vertical-align: middle; } </style> <slot name="icon">${loadingIndicatorIcon}</slot> <div id="status" role="status" aria-live="polite">${nouns.MEDIA_LOADING()}</div> `; var MediaLoadingIndicator = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd11(this, _mediaController6, void 0); __privateAdd11(this, _delay, DEFAULT_LOADING_DELAY); if (!this.shadowRoot) { const shadow = this.attachShadow({ mode: "open" }); const indicatorHTML = template8.content.cloneNode(true); shadow.appendChild(indicatorHTML); } } static get observedAttributes() { return [ MediaStateReceiverAttributes.MEDIA_CONTROLLER, MediaUIAttributes.MEDIA_PAUSED, MediaUIAttributes.MEDIA_LOADING, Attributes5.LOADING_DELAY ]; } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if (attrName === Attributes5.LOADING_DELAY && oldValue !== newValue) { this.loadingDelay = Number(newValue); } else if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet11(this, _mediaController6)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet11(this, _mediaController6, null); } if (newValue && this.isConnected) { __privateSet11(this, _mediaController6, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet11(this, _mediaController6)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } } connectedCallback() { var _a3, _b, _c; const mediaControllerId = this.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { __privateSet11(this, _mediaController6, (_a3 = this.getRootNode()) == null ? void 0 : _a3.getElementById( mediaControllerId )); (_c = (_b = __privateGet11(this, _mediaController6)) == null ? void 0 : _b.associateElement) == null ? void 0 : _c.call(_b, this); } } disconnectedCallback() { var _a3, _b; (_b = (_a3 = __privateGet11(this, _mediaController6)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet11(this, _mediaController6, null); } /** * Delay in ms */ get loadingDelay() { return __privateGet11(this, _delay); } set loadingDelay(delay2) { __privateSet11(this, _delay, delay2); const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); style.setProperty( "--_loading-indicator-delay", `var(--media-loading-indicator-transition-delay, ${delay2}ms)` ); } /** * Is the media paused */ get mediaPaused() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED); } set mediaPaused(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED, value); } /** * Is the media loading */ get mediaLoading() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_LOADING); } set mediaLoading(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_LOADING, value); } }; _mediaController6 = /* @__PURE__ */ new WeakMap(); _delay = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-loading-indicator")) { GlobalThis.customElements.define( "media-loading-indicator", MediaLoadingIndicator ); } // node_modules/media-chrome/dist/media-mute-button.js var { MEDIA_VOLUME_LEVEL } = MediaUIAttributes; var offIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M16.5 12A4.5 4.5 0 0 0 14 8v2.18l2.45 2.45a4.22 4.22 0 0 0 .05-.63Zm2.5 0a6.84 6.84 0 0 1-.54 2.64L20 16.15A8.8 8.8 0 0 0 21 12a9 9 0 0 0-7-8.77v2.06A7 7 0 0 1 19 12ZM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25A6.92 6.92 0 0 1 14 18.7v2.06A9 9 0 0 0 17.69 19l2 2.05L21 19.73l-9-9L4.27 3ZM12 4 9.91 6.09 12 8.18V4Z"/> </svg>`; var lowIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4Z"/> </svg>`; var highIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4ZM14 3.23v2.06a7 7 0 0 1 0 13.42v2.06a9 9 0 0 0 0-17.54Z"/> </svg>`; var slotTemplate6 = Document2.createElement("template"); slotTemplate6.innerHTML = /*html*/ ` <style> ${/* Default to High slot/icon. */ ""} :host(:not([${MEDIA_VOLUME_LEVEL}])) slot[name=icon] slot:not([name=high]), :host([${MEDIA_VOLUME_LEVEL}=high]) slot[name=icon] slot:not([name=high]) { display: none !important; } :host([${MEDIA_VOLUME_LEVEL}=off]) slot[name=icon] slot:not([name=off]) { display: none !important; } :host([${MEDIA_VOLUME_LEVEL}=low]) slot[name=icon] slot:not([name=low]) { display: none !important; } :host([${MEDIA_VOLUME_LEVEL}=medium]) slot[name=icon] slot:not([name=medium]) { display: none !important; } :host(:not([${MEDIA_VOLUME_LEVEL}=off])) slot[name=tooltip-unmute], :host([${MEDIA_VOLUME_LEVEL}=off]) slot[name=tooltip-mute] { display: none; } </style> <slot name="icon"> <slot name="off">${offIcon}</slot> <slot name="low">${lowIcon}</slot> <slot name="medium">${lowIcon}</slot> <slot name="high">${highIcon}</slot> </slot> `; var tooltipContent5 = ( /*html*/ ` <slot name="tooltip-mute">${tooltipLabels.MUTE}</slot> <slot name="tooltip-unmute">${tooltipLabels.UNMUTE}</slot> ` ); var updateAriaLabel4 = (el) => { const muted = el.mediaVolumeLevel === "off"; const label = muted ? verbs.UNMUTE() : verbs.MUTE(); el.setAttribute("aria-label", label); }; var MediaMuteButton = class extends MediaChromeButton { static get observedAttributes() { return [...super.observedAttributes, MediaUIAttributes.MEDIA_VOLUME_LEVEL]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate6, tooltipContent: tooltipContent5, ...options2 }); } connectedCallback() { updateAriaLabel4(this); super.connectedCallback(); } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === MediaUIAttributes.MEDIA_VOLUME_LEVEL) { updateAriaLabel4(this); } super.attributeChangedCallback(attrName, oldValue, newValue); } /** * @type {string | undefined} */ get mediaVolumeLevel() { return getStringAttr(this, MediaUIAttributes.MEDIA_VOLUME_LEVEL); } set mediaVolumeLevel(value) { setStringAttr(this, MediaUIAttributes.MEDIA_VOLUME_LEVEL, value); } handleClick() { const eventName = this.mediaVolumeLevel === "off" ? MediaUIEvents.MEDIA_UNMUTE_REQUEST : MediaUIEvents.MEDIA_MUTE_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); } }; if (!GlobalThis.customElements.get("media-mute-button")) { GlobalThis.customElements.define("media-mute-button", MediaMuteButton); } // node_modules/media-chrome/dist/media-pip-button.js var pipIcon = `<svg aria-hidden="true" viewBox="0 0 28 24"> <path d="M24 3H4a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1Zm-1 16H5V5h18v14Zm-3-8h-7v5h7v-5Z"/> </svg>`; var slotTemplate7 = Document2.createElement("template"); slotTemplate7.innerHTML = /*html*/ ` <style> :host([${MediaUIAttributes.MEDIA_IS_PIP}]) slot[name=icon] slot:not([name=exit]) { display: none !important; } ${/* Double negative, but safer if display doesn't equal 'block' */ ""} :host(:not([${MediaUIAttributes.MEDIA_IS_PIP}])) slot[name=icon] slot:not([name=enter]) { display: none !important; } :host([${MediaUIAttributes.MEDIA_IS_PIP}]) slot[name=tooltip-enter], :host(:not([${MediaUIAttributes.MEDIA_IS_PIP}])) slot[name=tooltip-exit] { display: none; } </style> <slot name="icon"> <slot name="enter">${pipIcon}</slot> <slot name="exit">${pipIcon}</slot> </slot> `; var tooltipContent6 = ( /*html*/ ` <slot name="tooltip-enter">${tooltipLabels.ENTER_PIP}</slot> <slot name="tooltip-exit">${tooltipLabels.EXIT_PIP}</slot> ` ); var updateAriaLabel5 = (el) => { const label = el.mediaIsPip ? verbs.EXIT_PIP() : verbs.ENTER_PIP(); el.setAttribute("aria-label", label); }; var MediaPipButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_IS_PIP, MediaUIAttributes.MEDIA_PIP_UNAVAILABLE ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate7, tooltipContent: tooltipContent6, ...options2 }); } connectedCallback() { updateAriaLabel5(this); super.connectedCallback(); } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === MediaUIAttributes.MEDIA_IS_PIP) { updateAriaLabel5(this); } super.attributeChangedCallback(attrName, oldValue, newValue); } /** * @type {string | undefined} Pip unavailability state */ get mediaPipUnavailable() { return getStringAttr(this, MediaUIAttributes.MEDIA_PIP_UNAVAILABLE); } set mediaPipUnavailable(value) { setStringAttr(this, MediaUIAttributes.MEDIA_PIP_UNAVAILABLE, value); } /** * @type {boolean} Is the media currently playing picture-in-picture */ get mediaIsPip() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_IS_PIP); } set mediaIsPip(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_IS_PIP, value); } handleClick() { const eventName = this.mediaIsPip ? MediaUIEvents.MEDIA_EXIT_PIP_REQUEST : MediaUIEvents.MEDIA_ENTER_PIP_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); } }; if (!GlobalThis.customElements.get("media-pip-button")) { GlobalThis.customElements.define("media-pip-button", MediaPipButton); } // node_modules/media-chrome/dist/media-playback-rate-button.js var __accessCheck12 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet12 = (obj, member, getter) => { __accessCheck12(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd12 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var _rates; var Attributes6 = { RATES: "rates" }; var DEFAULT_RATES = [1, 1.2, 1.5, 1.7, 2]; var DEFAULT_RATE = 1; var slotTemplate8 = Document2.createElement("template"); slotTemplate8.innerHTML = /*html*/ ` <style> :host { min-width: 5ch; padding: var(--media-button-padding, var(--media-control-padding, 10px 5px)); } </style> <slot name="icon"></slot> `; var MediaPlaybackRateButton = class extends MediaChromeButton { constructor(options2 = {}) { super({ slotTemplate: slotTemplate8, tooltipContent: tooltipLabels.PLAYBACK_RATE, ...options2 }); __privateAdd12(this, _rates, new AttributeTokenList(this, Attributes6.RATES, { defaultValue: DEFAULT_RATES })); this.container = this.shadowRoot.querySelector('slot[name="icon"]'); this.container.innerHTML = `${DEFAULT_RATE}x`; } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_PLAYBACK_RATE, Attributes6.RATES ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === Attributes6.RATES) { __privateGet12(this, _rates).value = newValue; } if (attrName === MediaUIAttributes.MEDIA_PLAYBACK_RATE) { const newPlaybackRate = newValue ? +newValue : Number.NaN; const playbackRate = !Number.isNaN(newPlaybackRate) ? newPlaybackRate : DEFAULT_RATE; this.container.innerHTML = `${playbackRate}x`; this.setAttribute("aria-label", nouns.PLAYBACK_RATE({ playbackRate })); } } /** * @type { AttributeTokenList | Array<number> | undefined} Will return a DOMTokenList. * Setting a value will accept an array of numbers. */ get rates() { return __privateGet12(this, _rates); } set rates(value) { if (!value) { __privateGet12(this, _rates).value = ""; } else if (Array.isArray(value)) { __privateGet12(this, _rates).value = value.join(" "); } } /** * @type {number} The current playback rate */ get mediaPlaybackRate() { return getNumericAttr( this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, DEFAULT_RATE ); } set mediaPlaybackRate(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, value); } handleClick() { var _a3, _b; const availableRates = Array.from(this.rates.values(), (str) => +str).sort( (a2, b2) => a2 - b2 ); const detail = (_b = (_a3 = availableRates.find((r9) => r9 > this.mediaPlaybackRate)) != null ? _a3 : availableRates[0]) != null ? _b : DEFAULT_RATE; const evt = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_PLAYBACK_RATE_REQUEST, { composed: true, bubbles: true, detail } ); this.dispatchEvent(evt); } }; _rates = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-playback-rate-button")) { GlobalThis.customElements.define( "media-playback-rate-button", MediaPlaybackRateButton ); } // node_modules/media-chrome/dist/media-play-button.js var playIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="m6 21 15-9L6 3v18Z"/> </svg>`; var pauseIcon = `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M6 20h4V4H6v16Zm8-16v16h4V4h-4Z"/> </svg>`; var slotTemplate9 = Document2.createElement("template"); slotTemplate9.innerHTML = /*html*/ ` <style> :host([${MediaUIAttributes.MEDIA_PAUSED}]) slot[name=pause], :host(:not([${MediaUIAttributes.MEDIA_PAUSED}])) slot[name=play] { display: none !important; } :host([${MediaUIAttributes.MEDIA_PAUSED}]) slot[name=tooltip-pause], :host(:not([${MediaUIAttributes.MEDIA_PAUSED}])) slot[name=tooltip-play] { display: none; } </style> <slot name="icon"> <slot name="play">${playIcon}</slot> <slot name="pause">${pauseIcon}</slot> </slot> `; var tooltipContent7 = ( /*html*/ ` <slot name="tooltip-play">${tooltipLabels.PLAY}</slot> <slot name="tooltip-pause">${tooltipLabels.PAUSE}</slot> ` ); var updateAriaLabel6 = (el) => { const label = el.mediaPaused ? verbs.PLAY() : verbs.PAUSE(); el.setAttribute("aria-label", label); }; var MediaPlayButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_PAUSED, MediaUIAttributes.MEDIA_ENDED ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate9, tooltipContent: tooltipContent7, ...options2 }); } connectedCallback() { updateAriaLabel6(this); super.connectedCallback(); } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === MediaUIAttributes.MEDIA_PAUSED) { updateAriaLabel6(this); } super.attributeChangedCallback(attrName, oldValue, newValue); } /** * Is the media paused */ get mediaPaused() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED); } set mediaPaused(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED, value); } handleClick() { const eventName = this.mediaPaused ? MediaUIEvents.MEDIA_PLAY_REQUEST : MediaUIEvents.MEDIA_PAUSE_REQUEST; this.dispatchEvent( new GlobalThis.CustomEvent(eventName, { composed: true, bubbles: true }) ); } }; if (!GlobalThis.customElements.get("media-play-button")) { GlobalThis.customElements.define("media-play-button", MediaPlayButton); } // node_modules/media-chrome/dist/media-poster-image.js var Attributes7 = { PLACEHOLDER_SRC: "placeholdersrc", SRC: "src" }; var template9 = Document2.createElement("template"); template9.innerHTML = /*html*/ ` <style> :host { pointer-events: none; display: var(--media-poster-image-display, inline-block); box-sizing: border-box; } img { max-width: 100%; max-height: 100%; min-width: 100%; min-height: 100%; background-repeat: no-repeat; background-position: var(--media-poster-image-background-position, var(--media-object-position, center)); background-size: var(--media-poster-image-background-size, var(--media-object-fit, contain)); object-fit: var(--media-object-fit, contain); object-position: var(--media-object-position, center); } </style> <img part="poster img" aria-hidden="true" id="image"/> `; var unsetBackgroundImage = (el) => { el.style.removeProperty("background-image"); }; var setBackgroundImage = (el, image) => { el.style["background-image"] = `url('${image}')`; }; var MediaPosterImage = class extends GlobalThis.HTMLElement { static get observedAttributes() { return [Attributes7.PLACEHOLDER_SRC, Attributes7.SRC]; } constructor() { super(); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template9.content.cloneNode(true)); } this.image = this.shadowRoot.querySelector("#image"); } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === Attributes7.SRC) { if (newValue == null) { this.image.removeAttribute(Attributes7.SRC); } else { this.image.setAttribute(Attributes7.SRC, newValue); } } if (attrName === Attributes7.PLACEHOLDER_SRC) { if (newValue == null) { unsetBackgroundImage(this.image); } else { setBackgroundImage(this.image, newValue); } } } /** * */ get placeholderSrc() { return getStringAttr(this, Attributes7.PLACEHOLDER_SRC); } set placeholderSrc(value) { setStringAttr(this, Attributes7.SRC, value); } /** * */ get src() { return getStringAttr(this, Attributes7.SRC); } set src(value) { setStringAttr(this, Attributes7.SRC, value); } }; if (!GlobalThis.customElements.get("media-poster-image")) { GlobalThis.customElements.define("media-poster-image", MediaPosterImage); } // node_modules/media-chrome/dist/media-preview-chapter-display.js var __accessCheck13 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet13 = (obj, member, getter) => { __accessCheck13(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd13 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet12 = (obj, member, value, setter) => { __accessCheck13(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _slot2; var MediaPreviewChapterDisplay = class extends MediaTextDisplay { constructor() { super(); __privateAdd13(this, _slot2, void 0); __privateSet12(this, _slot2, this.shadowRoot.querySelector("slot")); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_PREVIEW_CHAPTER ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_PREVIEW_CHAPTER) { if (newValue !== oldValue && newValue != null) { __privateGet13(this, _slot2).textContent = newValue; if (newValue !== "") { this.setAttribute("aria-valuetext", `chapter: ${newValue}`); } else { this.removeAttribute("aria-valuetext"); } } } } /** * @type {string | undefined} Timeline preview chapter */ get mediaPreviewChapter() { return getStringAttr(this, MediaUIAttributes.MEDIA_PREVIEW_CHAPTER); } set mediaPreviewChapter(value) { setStringAttr(this, MediaUIAttributes.MEDIA_PREVIEW_CHAPTER, value); } }; _slot2 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-preview-chapter-display")) { GlobalThis.customElements.define( "media-preview-chapter-display", MediaPreviewChapterDisplay ); } // node_modules/media-chrome/dist/media-preview-thumbnail.js var __accessCheck14 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet14 = (obj, member, getter) => { __accessCheck14(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd14 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet13 = (obj, member, value, setter) => { __accessCheck14(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _mediaController7; var template10 = Document2.createElement("template"); template10.innerHTML = /*html*/ ` <style> :host { box-sizing: border-box; display: var(--media-control-display, var(--media-preview-thumbnail-display, inline-block)); overflow: hidden; } img { display: none; position: relative; } </style> <img crossorigin loading="eager" decoding="async"> `; var MediaPreviewThumbnail = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd14(this, _mediaController7, void 0); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template10.content.cloneNode(true)); } } static get observedAttributes() { return [ MediaStateReceiverAttributes.MEDIA_CONTROLLER, MediaUIAttributes.MEDIA_PREVIEW_IMAGE, MediaUIAttributes.MEDIA_PREVIEW_COORDS ]; } connectedCallback() { var _a3, _b, _c; const mediaControllerId = this.getAttribute( MediaStateReceiverAttributes.MEDIA_CONTROLLER ); if (mediaControllerId) { __privateSet13( this, _mediaController7, // @ts-ignore (_a3 = this.getRootNode()) == null ? void 0 : _a3.getElementById(mediaControllerId) ); (_c = (_b = __privateGet14(this, _mediaController7)) == null ? void 0 : _b.associateElement) == null ? void 0 : _c.call(_b, this); } } disconnectedCallback() { var _a3, _b; (_b = (_a3 = __privateGet14(this, _mediaController7)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet13(this, _mediaController7, null); } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d, _e5; if ([ MediaUIAttributes.MEDIA_PREVIEW_IMAGE, MediaUIAttributes.MEDIA_PREVIEW_COORDS ].includes(attrName)) { this.update(); } if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet14(this, _mediaController7)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet13(this, _mediaController7, null); } if (newValue && this.isConnected) { __privateSet13(this, _mediaController7, (_c = this.getRootNode()) == null ? void 0 : _c.getElementById(newValue)); (_e5 = (_d = __privateGet14(this, _mediaController7)) == null ? void 0 : _d.associateElement) == null ? void 0 : _e5.call(_d, this); } } } /** * @type {string | undefined} The url of the preview image */ get mediaPreviewImage() { return getStringAttr(this, MediaUIAttributes.MEDIA_PREVIEW_IMAGE); } set mediaPreviewImage(value) { setStringAttr(this, MediaUIAttributes.MEDIA_PREVIEW_IMAGE, value); } /** * @type {Array<number> | undefined} Fixed length array [x, y, width, height] or undefined */ get mediaPreviewCoords() { const attrVal = this.getAttribute(MediaUIAttributes.MEDIA_PREVIEW_COORDS); if (!attrVal) return void 0; return attrVal.split(/\s+/).map((coord) => +coord); } set mediaPreviewCoords(value) { if (!value) { this.removeAttribute(MediaUIAttributes.MEDIA_PREVIEW_COORDS); return; } this.setAttribute(MediaUIAttributes.MEDIA_PREVIEW_COORDS, value.join(" ")); } update() { const coords = this.mediaPreviewCoords; const previewImage = this.mediaPreviewImage; if (!(coords && previewImage)) return; const [x2, y4, w4, h3] = coords; const src = previewImage.split("#")[0]; const computedStyle = getComputedStyle(this); const { maxWidth, maxHeight, minWidth, minHeight } = computedStyle; const maxRatio = Math.min(parseInt(maxWidth) / w4, parseInt(maxHeight) / h3); const minRatio = Math.max(parseInt(minWidth) / w4, parseInt(minHeight) / h3); const isScalingDown = maxRatio < 1; const scale2 = isScalingDown ? maxRatio : minRatio > 1 ? minRatio : 1; const { style } = getOrInsertCSSRule(this.shadowRoot, ":host"); const imgStyle = getOrInsertCSSRule(this.shadowRoot, "img").style; const img = this.shadowRoot.querySelector("img"); const extremum = isScalingDown ? "min" : "max"; style.setProperty(`${extremum}-width`, "initial", "important"); style.setProperty(`${extremum}-height`, "initial", "important"); style.width = `${w4 * scale2}px`; style.height = `${h3 * scale2}px`; const resize2 = () => { imgStyle.width = `${this.imgWidth * scale2}px`; imgStyle.height = `${this.imgHeight * scale2}px`; imgStyle.display = "block"; }; if (img.src !== src) { img.onload = () => { this.imgWidth = img.naturalWidth; this.imgHeight = img.naturalHeight; resize2(); }; img.src = src; resize2(); } resize2(); imgStyle.transform = `translate(-${x2 * scale2}px, -${y4 * scale2}px)`; } }; _mediaController7 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-preview-thumbnail")) { GlobalThis.customElements.define( "media-preview-thumbnail", MediaPreviewThumbnail ); } // node_modules/media-chrome/dist/media-preview-time-display.js var __accessCheck15 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet15 = (obj, member, getter) => { __accessCheck15(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd15 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet14 = (obj, member, value, setter) => { __accessCheck15(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _slot3; var MediaPreviewTimeDisplay = class extends MediaTextDisplay { constructor() { super(); __privateAdd15(this, _slot3, void 0); __privateSet14(this, _slot3, this.shadowRoot.querySelector("slot")); __privateGet15(this, _slot3).textContent = formatTime(0); } static get observedAttributes() { return [...super.observedAttributes, MediaUIAttributes.MEDIA_PREVIEW_TIME]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_PREVIEW_TIME && newValue != null) { __privateGet15(this, _slot3).textContent = formatTime(parseFloat(newValue)); } } /** * Timeline preview time */ get mediaPreviewTime() { return getNumericAttr(this, MediaUIAttributes.MEDIA_PREVIEW_TIME); } set mediaPreviewTime(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_PREVIEW_TIME, value); } }; _slot3 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-preview-time-display")) { GlobalThis.customElements.define( "media-preview-time-display", MediaPreviewTimeDisplay ); } // node_modules/media-chrome/dist/media-seek-backward-button.js var Attributes8 = { SEEK_OFFSET: "seekoffset" }; var DEFAULT_SEEK_OFFSET2 = 30; var backwardIcon = `<svg aria-hidden="true" viewBox="0 0 20 24"><defs><style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style></defs><text class="text value" transform="translate(2.18 19.87)">${DEFAULT_SEEK_OFFSET2}</text><path d="M10 6V3L4.37 7 10 10.94V8a5.54 5.54 0 0 1 1.9 10.48v2.12A7.5 7.5 0 0 0 10 6Z"/></svg>`; var slotTemplate10 = Document2.createElement("template"); slotTemplate10.innerHTML = ` <slot name="icon">${backwardIcon}</slot> `; var DEFAULT_TIME = 0; var MediaSeekBackwardButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_CURRENT_TIME, Attributes8.SEEK_OFFSET ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate10, tooltipContent: tooltipLabels.SEEK_BACKWARD, ...options2 }); } connectedCallback() { this.seekOffset = getNumericAttr( this, Attributes8.SEEK_OFFSET, DEFAULT_SEEK_OFFSET2 ); super.connectedCallback(); } attributeChangedCallback(attrName, _oldValue, newValue) { if (attrName === Attributes8.SEEK_OFFSET) { this.seekOffset = getNumericAttr( this, Attributes8.SEEK_OFFSET, DEFAULT_SEEK_OFFSET2 ); } super.attributeChangedCallback(attrName, _oldValue, newValue); } // Own props /** * Seek amount in seconds */ get seekOffset() { return getNumericAttr(this, Attributes8.SEEK_OFFSET, DEFAULT_SEEK_OFFSET2); } set seekOffset(value) { setNumericAttr(this, Attributes8.SEEK_OFFSET, value); this.setAttribute( "aria-label", verbs.SEEK_BACK_N_SECS({ seekOffset: this.seekOffset }) ); updateIconText(getSlotted(this, "icon"), this.seekOffset); } // Props derived from Media UI Attributes /** * The current time in seconds */ get mediaCurrentTime() { return getNumericAttr( this, MediaUIAttributes.MEDIA_CURRENT_TIME, DEFAULT_TIME ); } set mediaCurrentTime(time) { setNumericAttr(this, MediaUIAttributes.MEDIA_CURRENT_TIME, time); } handleClick() { const detail = Math.max(this.mediaCurrentTime - this.seekOffset, 0); const evt = new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_SEEK_REQUEST, { composed: true, bubbles: true, detail }); this.dispatchEvent(evt); } }; if (!GlobalThis.customElements.get("media-seek-backward-button")) { GlobalThis.customElements.define( "media-seek-backward-button", MediaSeekBackwardButton ); } // node_modules/media-chrome/dist/media-seek-forward-button.js var Attributes9 = { SEEK_OFFSET: "seekoffset" }; var DEFAULT_SEEK_OFFSET3 = 30; var forwardIcon = `<svg aria-hidden="true" viewBox="0 0 20 24"><defs><style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style></defs><text class="text value" transform="translate(8.9 19.87)">${DEFAULT_SEEK_OFFSET3}</text><path d="M10 6V3l5.61 4L10 10.94V8a5.54 5.54 0 0 0-1.9 10.48v2.12A7.5 7.5 0 0 1 10 6Z"/></svg>`; var slotTemplate11 = Document2.createElement("template"); slotTemplate11.innerHTML = ` <slot name="icon">${forwardIcon}</slot> `; var DEFAULT_TIME2 = 0; var MediaSeekForwardButton = class extends MediaChromeButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_CURRENT_TIME, Attributes9.SEEK_OFFSET ]; } constructor(options2 = {}) { super({ slotTemplate: slotTemplate11, tooltipContent: tooltipLabels.SEEK_FORWARD, ...options2 }); } connectedCallback() { this.seekOffset = getNumericAttr( this, Attributes9.SEEK_OFFSET, DEFAULT_SEEK_OFFSET3 ); super.connectedCallback(); } attributeChangedCallback(attrName, _oldValue, newValue) { if (attrName === Attributes9.SEEK_OFFSET) { this.seekOffset = getNumericAttr( this, Attributes9.SEEK_OFFSET, DEFAULT_SEEK_OFFSET3 ); } super.attributeChangedCallback(attrName, _oldValue, newValue); } // Own props /** * Seek amount in seconds */ get seekOffset() { return getNumericAttr(this, Attributes9.SEEK_OFFSET, DEFAULT_SEEK_OFFSET3); } set seekOffset(value) { setNumericAttr(this, Attributes9.SEEK_OFFSET, value); this.setAttribute( "aria-label", verbs.SEEK_FORWARD_N_SECS({ seekOffset: this.seekOffset }) ); updateIconText(getSlotted(this, "icon"), this.seekOffset); } // Props derived from Media UI Attributes /** * The current time in seconds */ get mediaCurrentTime() { return getNumericAttr( this, MediaUIAttributes.MEDIA_CURRENT_TIME, DEFAULT_TIME2 ); } set mediaCurrentTime(time) { setNumericAttr(this, MediaUIAttributes.MEDIA_CURRENT_TIME, time); } handleClick() { const detail = this.mediaCurrentTime + this.seekOffset; const evt = new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_SEEK_REQUEST, { composed: true, bubbles: true, detail }); this.dispatchEvent(evt); } }; if (!GlobalThis.customElements.get("media-seek-forward-button")) { GlobalThis.customElements.define( "media-seek-forward-button", MediaSeekForwardButton ); } // node_modules/media-chrome/dist/media-time-display.js var __accessCheck16 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet16 = (obj, member, getter) => { __accessCheck16(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd16 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet15 = (obj, member, value, setter) => { __accessCheck16(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _slot4; var Attributes10 = { REMAINING: "remaining", SHOW_DURATION: "showduration", NO_TOGGLE: "notoggle" }; var CombinedAttributes = [ ...Object.values(Attributes10), MediaUIAttributes.MEDIA_CURRENT_TIME, MediaUIAttributes.MEDIA_DURATION, MediaUIAttributes.MEDIA_SEEKABLE ]; var ButtonPressedKeys2 = ["Enter", " "]; var DEFAULT_TIMES_SEP = " / "; var formatTimesLabel = (el, { timesSep = DEFAULT_TIMES_SEP } = {}) => { var _a3, _b; const showRemaining = el.hasAttribute(Attributes10.REMAINING); const showDuration = el.hasAttribute(Attributes10.SHOW_DURATION); const currentTime = (_a3 = el.mediaCurrentTime) != null ? _a3 : 0; const [, seekableEnd] = (_b = el.mediaSeekable) != null ? _b : []; let endTime = 0; if (Number.isFinite(el.mediaDuration)) { endTime = el.mediaDuration; } else if (Number.isFinite(seekableEnd)) { endTime = seekableEnd; } const timeLabel = showRemaining ? formatTime(0 - (endTime - currentTime)) : formatTime(currentTime); if (!showDuration) return timeLabel; return `${timeLabel}${timesSep}${formatTime(endTime)}`; }; var DEFAULT_MISSING_TIME_PHRASE = "video not loaded, unknown time."; var updateAriaValueText = (el) => { var _a3; const currentTime = el.mediaCurrentTime; const [, seekableEnd] = (_a3 = el.mediaSeekable) != null ? _a3 : []; let endTime = null; if (Number.isFinite(el.mediaDuration)) { endTime = el.mediaDuration; } else if (Number.isFinite(seekableEnd)) { endTime = seekableEnd; } if (currentTime == null || endTime === null) { el.setAttribute("aria-valuetext", DEFAULT_MISSING_TIME_PHRASE); return; } const showRemaining = el.hasAttribute(Attributes10.REMAINING); const showDuration = el.hasAttribute(Attributes10.SHOW_DURATION); const currentTimePhrase = showRemaining ? formatAsTimePhrase(0 - (endTime - currentTime)) : formatAsTimePhrase(currentTime); if (!showDuration) { el.setAttribute("aria-valuetext", currentTimePhrase); return; } const totalTimePhrase = formatAsTimePhrase(endTime); const fullPhrase = `${currentTimePhrase} of ${totalTimePhrase}`; el.setAttribute("aria-valuetext", fullPhrase); }; var MediaTimeDisplay = class extends MediaTextDisplay { constructor() { super(); __privateAdd16(this, _slot4, void 0); __privateSet15(this, _slot4, this.shadowRoot.querySelector("slot")); __privateGet16(this, _slot4).innerHTML = `${formatTimesLabel(this)}`; } static get observedAttributes() { return [...super.observedAttributes, ...CombinedAttributes, "disabled"]; } connectedCallback() { const { style } = getOrInsertCSSRule( this.shadowRoot, ":host(:hover:not([notoggle]))" ); style.setProperty("cursor", "pointer"); style.setProperty( "background", "var(--media-control-hover-background, rgba(50 50 70 / .7))" ); if (!this.hasAttribute("disabled")) { this.enable(); } this.setAttribute("role", "progressbar"); this.setAttribute("aria-label", nouns.PLAYBACK_TIME()); const keyUpHandler = (evt) => { const { key } = evt; if (!ButtonPressedKeys2.includes(key)) { this.removeEventListener("keyup", keyUpHandler); return; } this.toggleTimeDisplay(); }; this.addEventListener("keydown", (evt) => { const { metaKey, altKey, key } = evt; if (metaKey || altKey || !ButtonPressedKeys2.includes(key)) { this.removeEventListener("keyup", keyUpHandler); return; } this.addEventListener("keyup", keyUpHandler); }); this.addEventListener("click", this.toggleTimeDisplay); super.connectedCallback(); } toggleTimeDisplay() { if (this.noToggle) { return; } if (this.hasAttribute("remaining")) { this.removeAttribute("remaining"); } else { this.setAttribute("remaining", ""); } } disconnectedCallback() { this.disable(); super.disconnectedCallback(); } attributeChangedCallback(attrName, oldValue, newValue) { if (CombinedAttributes.includes(attrName)) { this.update(); } else if (attrName === "disabled" && newValue !== oldValue) { if (newValue == null) { this.enable(); } else { this.disable(); } } super.attributeChangedCallback(attrName, oldValue, newValue); } enable() { this.tabIndex = 0; } disable() { this.tabIndex = -1; } // Own props /** * Whether to show the remaining time */ get remaining() { return getBooleanAttr(this, Attributes10.REMAINING); } set remaining(show) { setBooleanAttr(this, Attributes10.REMAINING, show); } /** * Whether to show the duration */ get showDuration() { return getBooleanAttr(this, Attributes10.SHOW_DURATION); } set showDuration(show) { setBooleanAttr(this, Attributes10.SHOW_DURATION, show); } /** * Disable the default behavior that toggles between current and remaining time */ get noToggle() { return getBooleanAttr(this, Attributes10.NO_TOGGLE); } set noToggle(noToggle) { setBooleanAttr(this, Attributes10.NO_TOGGLE, noToggle); } // Props derived from media UI attributes /** * Get the duration */ get mediaDuration() { return getNumericAttr(this, MediaUIAttributes.MEDIA_DURATION); } set mediaDuration(time) { setNumericAttr(this, MediaUIAttributes.MEDIA_DURATION, time); } /** * The current time in seconds */ get mediaCurrentTime() { return getNumericAttr(this, MediaUIAttributes.MEDIA_CURRENT_TIME); } set mediaCurrentTime(time) { setNumericAttr(this, MediaUIAttributes.MEDIA_CURRENT_TIME, time); } /** * Range of values that can be seeked to. * An array of two numbers [start, end] */ get mediaSeekable() { const seekable = this.getAttribute(MediaUIAttributes.MEDIA_SEEKABLE); if (!seekable) return void 0; return seekable.split(":").map((time) => +time); } set mediaSeekable(range) { if (range == null) { this.removeAttribute(MediaUIAttributes.MEDIA_SEEKABLE); return; } this.setAttribute(MediaUIAttributes.MEDIA_SEEKABLE, range.join(":")); } update() { const timesLabel = formatTimesLabel(this); updateAriaValueText(this); if (timesLabel !== __privateGet16(this, _slot4).innerHTML) { __privateGet16(this, _slot4).innerHTML = timesLabel; } } }; _slot4 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-time-display")) { GlobalThis.customElements.define("media-time-display", MediaTimeDisplay); } // node_modules/media-chrome/dist/utils/range-animation.js var __accessCheck17 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet17 = (obj, member, getter) => { __accessCheck17(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd17 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet16 = (obj, member, value, setter) => { __accessCheck17(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateWrapper = (obj, member, setter, getter) => ({ set _(value) { __privateSet16(obj, member, value, setter); }, get _() { return __privateGet17(obj, member, getter); } }); var _range; var _startTime; var _previousTime; var _deltaTime; var _frameCount; var _updateTimestamp; var _updateStartValue; var _lastRangeIncrease; var _id; var _animate; var RangeAnimation = class { constructor(range, callback, fps) { __privateAdd17(this, _range, void 0); __privateAdd17(this, _startTime, void 0); __privateAdd17(this, _previousTime, void 0); __privateAdd17(this, _deltaTime, void 0); __privateAdd17(this, _frameCount, void 0); __privateAdd17(this, _updateTimestamp, void 0); __privateAdd17(this, _updateStartValue, void 0); __privateAdd17(this, _lastRangeIncrease, void 0); __privateAdd17(this, _id, 0); __privateAdd17(this, _animate, (now2 = performance.now()) => { __privateSet16(this, _id, requestAnimationFrame(__privateGet17(this, _animate))); __privateSet16(this, _deltaTime, performance.now() - __privateGet17(this, _previousTime)); const fpsInterval = 1e3 / this.fps; if (__privateGet17(this, _deltaTime) > fpsInterval) { __privateSet16(this, _previousTime, now2 - __privateGet17(this, _deltaTime) % fpsInterval); const fps2 = 1e3 / ((now2 - __privateGet17(this, _startTime)) / ++__privateWrapper(this, _frameCount)._); const delta = (now2 - __privateGet17(this, _updateTimestamp)) / 1e3 / this.duration; let value = __privateGet17(this, _updateStartValue) + delta * this.playbackRate; const increase = value - __privateGet17(this, _range).valueAsNumber; if (increase > 0) { __privateSet16(this, _lastRangeIncrease, this.playbackRate / this.duration / fps2); } else { __privateSet16(this, _lastRangeIncrease, 0.995 * __privateGet17(this, _lastRangeIncrease)); value = __privateGet17(this, _range).valueAsNumber + __privateGet17(this, _lastRangeIncrease); } this.callback(value); } }); __privateSet16(this, _range, range); this.callback = callback; this.fps = fps; } start() { if (__privateGet17(this, _id) !== 0) return; __privateSet16(this, _previousTime, performance.now()); __privateSet16(this, _startTime, __privateGet17(this, _previousTime)); __privateSet16(this, _frameCount, 0); __privateGet17(this, _animate).call(this); } stop() { if (__privateGet17(this, _id) === 0) return; cancelAnimationFrame(__privateGet17(this, _id)); __privateSet16(this, _id, 0); } update({ start, duration, playbackRate }) { const increase = start - __privateGet17(this, _range).valueAsNumber; const durationDelta = Math.abs(duration - this.duration); if (increase > 0 || increase < -0.03 || durationDelta >= 0.5) { this.callback(start); } __privateSet16(this, _updateStartValue, start); __privateSet16(this, _updateTimestamp, performance.now()); this.duration = duration; this.playbackRate = playbackRate; } }; _range = /* @__PURE__ */ new WeakMap(); _startTime = /* @__PURE__ */ new WeakMap(); _previousTime = /* @__PURE__ */ new WeakMap(); _deltaTime = /* @__PURE__ */ new WeakMap(); _frameCount = /* @__PURE__ */ new WeakMap(); _updateTimestamp = /* @__PURE__ */ new WeakMap(); _updateStartValue = /* @__PURE__ */ new WeakMap(); _lastRangeIncrease = /* @__PURE__ */ new WeakMap(); _id = /* @__PURE__ */ new WeakMap(); _animate = /* @__PURE__ */ new WeakMap(); // node_modules/media-chrome/dist/media-time-range.js var __accessCheck18 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet18 = (obj, member, getter) => { __accessCheck18(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd18 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet17 = (obj, member, value, setter) => { __accessCheck18(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod6 = (obj, member, method) => { __accessCheck18(obj, member, "access private method"); return method; }; var _rootNode; var _animation; var _boxes; var _previewTime; var _previewBox; var _currentBox; var _boxPaddingLeft; var _boxPaddingRight; var _mediaChaptersCues; var _toggleRangeAnimation; var toggleRangeAnimation_fn; var _shouldRangeAnimate; var shouldRangeAnimate_fn; var _updateRange; var _getElementRects; var getElementRects_fn; var _getBoxPosition; var getBoxPosition_fn; var _getBoxShiftPosition; var getBoxShiftPosition_fn; var _handlePointerMove3; var handlePointerMove_fn3; var _previewRequest; var previewRequest_fn; var _seekRequest; var seekRequest_fn; var DEFAULT_MISSING_TIME_PHRASE2 = "video not loaded, unknown time."; var updateAriaValueText2 = (el) => { const range = el.range; const currentTimePhrase = formatAsTimePhrase(+calcTimeFromRangeValue(el)); const totalTimePhrase = formatAsTimePhrase(+el.mediaSeekableEnd); const fullPhrase = !(currentTimePhrase && totalTimePhrase) ? DEFAULT_MISSING_TIME_PHRASE2 : `${currentTimePhrase} of ${totalTimePhrase}`; range.setAttribute("aria-valuetext", fullPhrase); }; var template11 = Document2.createElement("template"); template11.innerHTML = /*html*/ ` <style> :host { --media-box-border-radius: 4px; --media-box-padding-left: 10px; --media-box-padding-right: 10px; --media-preview-border-radius: var(--media-box-border-radius); --media-box-arrow-offset: var(--media-box-border-radius); --_control-background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7))); --_preview-background: var(--media-preview-background, var(--_control-background)); ${/* 1% rail width trick was off in Safari, contain: layout seems to prevent the horizontal overflow as well. */ ""} contain: layout; } #buffered { background: var(--media-time-range-buffered-color, rgb(255 255 255 / .4)); position: absolute; height: 100%; will-change: width; } #preview-rail, #current-rail { width: 100%; position: absolute; left: 0; bottom: 100%; pointer-events: none; will-change: transform; } [part~="box"] { width: min-content; ${/* absolute position is needed here so the box doesn't overflow the bounds */ ""} position: absolute; bottom: 100%; flex-direction: column; align-items: center; transform: translateX(-50%); } [part~="current-box"] { display: var(--media-current-box-display, var(--media-box-display, flex)); margin: var(--media-current-box-margin, var(--media-box-margin, 0 0 5px)); visibility: hidden; } [part~="preview-box"] { display: var(--media-preview-box-display, var(--media-box-display, flex)); margin: var(--media-preview-box-margin, var(--media-box-margin, 0 0 5px)); transition-property: var(--media-preview-transition-property, visibility, opacity); transition-duration: var(--media-preview-transition-duration-out, .25s); transition-delay: var(--media-preview-transition-delay-out, 0s); visibility: hidden; opacity: 0; } :host(:is([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}], [${MediaUIAttributes.MEDIA_PREVIEW_TIME}])[dragging]) [part~="preview-box"] { transition-duration: var(--media-preview-transition-duration-in, .5s); transition-delay: var(--media-preview-transition-delay-in, .25s); visibility: visible; opacity: 1; } @media (hover: hover) { :host(:is([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}], [${MediaUIAttributes.MEDIA_PREVIEW_TIME}]):hover) [part~="preview-box"] { transition-duration: var(--media-preview-transition-duration-in, .5s); transition-delay: var(--media-preview-transition-delay-in, .25s); visibility: visible; opacity: 1; } } media-preview-thumbnail, ::slotted(media-preview-thumbnail) { visibility: hidden; ${/* delay changing these CSS props until the preview box transition is ended */ ""} transition: visibility 0s .25s; transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s)); background: var(--media-preview-thumbnail-background, var(--_preview-background)); box-shadow: var(--media-preview-thumbnail-box-shadow, 0 0 4px rgb(0 0 0 / .2)); max-width: var(--media-preview-thumbnail-max-width, 180px); max-height: var(--media-preview-thumbnail-max-height, 160px); min-width: var(--media-preview-thumbnail-min-width, 120px); min-height: var(--media-preview-thumbnail-min-height, 80px); border: var(--media-preview-thumbnail-border); border-radius: var(--media-preview-thumbnail-border-radius, var(--media-preview-border-radius) var(--media-preview-border-radius) 0 0); } :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}][dragging]) media-preview-thumbnail, :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}][dragging]) ::slotted(media-preview-thumbnail) { transition-delay: var(--media-preview-transition-delay-in, .25s); visibility: visible; } @media (hover: hover) { :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}]:hover) media-preview-thumbnail, :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}]:hover) ::slotted(media-preview-thumbnail) { transition-delay: var(--media-preview-transition-delay-in, .25s); visibility: visible; } :host([${MediaUIAttributes.MEDIA_PREVIEW_TIME}]:hover) { --media-time-range-hover-display: block; } } media-preview-chapter-display, ::slotted(media-preview-chapter-display) { font-size: var(--media-font-size, 13px); line-height: 17px; min-width: 0; visibility: hidden; ${/* delay changing these CSS props until the preview box transition is ended */ ""} transition: min-width 0s, border-radius 0s, margin 0s, padding 0s, visibility 0s; transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s)); background: var(--media-preview-chapter-background, var(--_preview-background)); border-radius: var(--media-preview-chapter-border-radius, var(--media-preview-border-radius) var(--media-preview-border-radius) var(--media-preview-border-radius) var(--media-preview-border-radius)); padding: var(--media-preview-chapter-padding, 3.5px 9px); margin: var(--media-preview-chapter-margin, 0 0 5px); text-shadow: var(--media-preview-chapter-text-shadow, 0 0 4px rgb(0 0 0 / .75)); } :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}]) media-preview-chapter-display, :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}]) ::slotted(media-preview-chapter-display) { transition-delay: var(--media-preview-transition-delay-in, .25s); border-radius: var(--media-preview-chapter-border-radius, 0); padding: var(--media-preview-chapter-padding, 3.5px 9px 0); margin: var(--media-preview-chapter-margin, 0); min-width: 100%; } media-preview-chapter-display[${MediaUIAttributes.MEDIA_PREVIEW_CHAPTER}], ::slotted(media-preview-chapter-display[${MediaUIAttributes.MEDIA_PREVIEW_CHAPTER}]) { visibility: visible; } media-preview-chapter-display:not([aria-valuetext]), ::slotted(media-preview-chapter-display:not([aria-valuetext])) { display: none; } media-preview-time-display, ::slotted(media-preview-time-display), media-time-display, ::slotted(media-time-display) { font-size: var(--media-font-size, 13px); line-height: 17px; min-width: 0; ${/* delay changing these CSS props until the preview box transition is ended */ ""} transition: min-width 0s, border-radius 0s; transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s)); background: var(--media-preview-time-background, var(--_preview-background)); border-radius: var(--media-preview-time-border-radius, var(--media-preview-border-radius) var(--media-preview-border-radius) var(--media-preview-border-radius) var(--media-preview-border-radius)); padding: var(--media-preview-time-padding, 3.5px 9px); margin: var(--media-preview-time-margin, 0); text-shadow: var(--media-preview-time-text-shadow, 0 0 4px rgb(0 0 0 / .75)); transform: translateX(min( max(calc(50% - var(--_box-width) / 2), calc(var(--_box-shift, 0))), calc(var(--_box-width) / 2 - 50%) )); } :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}]) media-preview-time-display, :host([${MediaUIAttributes.MEDIA_PREVIEW_IMAGE}]) ::slotted(media-preview-time-display) { transition-delay: var(--media-preview-transition-delay-in, .25s); border-radius: var(--media-preview-time-border-radius, 0 0 var(--media-preview-border-radius) var(--media-preview-border-radius)); min-width: 100%; } :host([${MediaUIAttributes.MEDIA_PREVIEW_TIME}]:hover) { --media-time-range-hover-display: block; } [part~="arrow"], ::slotted([part~="arrow"]) { display: var(--media-box-arrow-display, inline-block); transform: translateX(min( max(calc(50% - var(--_box-width) / 2 + var(--media-box-arrow-offset)), calc(var(--_box-shift, 0))), calc(var(--_box-width) / 2 - 50% - var(--media-box-arrow-offset)) )); ${/* border-color has to come before border-top-color! */ ""} border-color: transparent; border-top-color: var(--media-box-arrow-background, var(--_control-background)); border-width: var(--media-box-arrow-border-width, var(--media-box-arrow-height, 5px) var(--media-box-arrow-width, 6px) 0); border-style: solid; justify-content: center; height: 0; } </style> <div id="preview-rail"> <slot name="preview" part="box preview-box"> <media-preview-thumbnail></media-preview-thumbnail> <media-preview-chapter-display></media-preview-chapter-display> <media-preview-time-display></media-preview-time-display> <slot name="preview-arrow"><div part="arrow"></div></slot> </slot> </div> <div id="current-rail"> <slot name="current" part="box current-box"> ${/* Example: add the current time w/ arrow to the playhead <media-time-display slot="current"></media-time-display> <div part="arrow" slot="current"></div> */ ""} </slot> </div> `; var calcRangeValueFromTime = (el, time = el.mediaCurrentTime) => { const startTime = Number.isFinite(el.mediaSeekableStart) ? el.mediaSeekableStart : 0; const endTime = Number.isFinite(el.mediaDuration) ? el.mediaDuration : el.mediaSeekableEnd; if (Number.isNaN(endTime)) return 0; const value = (time - startTime) / (endTime - startTime); return Math.max(0, Math.min(value, 1)); }; var calcTimeFromRangeValue = (el, value = el.range.valueAsNumber) => { const startTime = Number.isFinite(el.mediaSeekableStart) ? el.mediaSeekableStart : 0; const endTime = Number.isFinite(el.mediaDuration) ? el.mediaDuration : el.mediaSeekableEnd; if (Number.isNaN(endTime)) return 0; return value * (endTime - startTime) + startTime; }; var MediaTimeRange = class extends MediaChromeRange { constructor() { super(); __privateAdd18(this, _toggleRangeAnimation); __privateAdd18(this, _shouldRangeAnimate); __privateAdd18(this, _getElementRects); __privateAdd18(this, _getBoxPosition); __privateAdd18(this, _getBoxShiftPosition); __privateAdd18(this, _handlePointerMove3); __privateAdd18(this, _previewRequest); __privateAdd18(this, _seekRequest); __privateAdd18(this, _rootNode, void 0); __privateAdd18(this, _animation, void 0); __privateAdd18(this, _boxes, void 0); __privateAdd18(this, _previewTime, void 0); __privateAdd18(this, _previewBox, void 0); __privateAdd18(this, _currentBox, void 0); __privateAdd18(this, _boxPaddingLeft, void 0); __privateAdd18(this, _boxPaddingRight, void 0); __privateAdd18(this, _mediaChaptersCues, void 0); __privateAdd18(this, _updateRange, (value) => { if (this.dragging) return; if (isValidNumber(value)) { this.range.valueAsNumber = value; } this.updateBar(); }); this.container.appendChild(template11.content.cloneNode(true)); const track = this.shadowRoot.querySelector("#track"); track.insertAdjacentHTML("afterbegin", '<div id="buffered" part="buffered"></div>'); __privateSet17(this, _boxes, this.shadowRoot.querySelectorAll('[part~="box"]')); __privateSet17(this, _previewBox, this.shadowRoot.querySelector('[part~="preview-box"]')); __privateSet17(this, _currentBox, this.shadowRoot.querySelector('[part~="current-box"]')); const computedStyle = getComputedStyle(this); __privateSet17(this, _boxPaddingLeft, parseInt( computedStyle.getPropertyValue("--media-box-padding-left") )); __privateSet17(this, _boxPaddingRight, parseInt( computedStyle.getPropertyValue("--media-box-padding-right") )); __privateSet17(this, _animation, new RangeAnimation(this.range, __privateGet18(this, _updateRange), 60)); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_PAUSED, MediaUIAttributes.MEDIA_DURATION, MediaUIAttributes.MEDIA_SEEKABLE, MediaUIAttributes.MEDIA_CURRENT_TIME, MediaUIAttributes.MEDIA_PREVIEW_IMAGE, MediaUIAttributes.MEDIA_PREVIEW_TIME, MediaUIAttributes.MEDIA_PREVIEW_CHAPTER, MediaUIAttributes.MEDIA_BUFFERED, MediaUIAttributes.MEDIA_PLAYBACK_RATE, MediaUIAttributes.MEDIA_LOADING, MediaUIAttributes.MEDIA_ENDED ]; } connectedCallback() { var _a3; super.connectedCallback(); this.range.setAttribute("aria-label", nouns.SEEK()); __privateMethod6(this, _toggleRangeAnimation, toggleRangeAnimation_fn).call(this); __privateSet17(this, _rootNode, this.getRootNode()); (_a3 = __privateGet18(this, _rootNode)) == null ? void 0 : _a3.addEventListener("transitionstart", this); } disconnectedCallback() { var _a3; super.disconnectedCallback(); __privateMethod6(this, _toggleRangeAnimation, toggleRangeAnimation_fn).call(this); (_a3 = __privateGet18(this, _rootNode)) == null ? void 0 : _a3.removeEventListener("transitionstart", this); __privateSet17(this, _rootNode, null); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (oldValue == newValue) return; if (attrName === MediaUIAttributes.MEDIA_CURRENT_TIME || attrName === MediaUIAttributes.MEDIA_PAUSED || attrName === MediaUIAttributes.MEDIA_ENDED || attrName === MediaUIAttributes.MEDIA_LOADING || attrName === MediaUIAttributes.MEDIA_DURATION || attrName === MediaUIAttributes.MEDIA_SEEKABLE) { __privateGet18(this, _animation).update({ start: calcRangeValueFromTime(this), duration: this.mediaSeekableEnd - this.mediaSeekableStart, playbackRate: this.mediaPlaybackRate }); __privateMethod6(this, _toggleRangeAnimation, toggleRangeAnimation_fn).call(this); updateAriaValueText2(this); } else if (attrName === MediaUIAttributes.MEDIA_BUFFERED) { this.updateBufferedBar(); } if (attrName === MediaUIAttributes.MEDIA_DURATION || attrName === MediaUIAttributes.MEDIA_SEEKABLE) { this.mediaChaptersCues = __privateGet18(this, _mediaChaptersCues); this.updateBar(); } } get mediaChaptersCues() { return __privateGet18(this, _mediaChaptersCues); } set mediaChaptersCues(value) { var _a3; __privateSet17(this, _mediaChaptersCues, value); this.updateSegments( (_a3 = __privateGet18(this, _mediaChaptersCues)) == null ? void 0 : _a3.map((c3) => ({ start: calcRangeValueFromTime(this, c3.startTime), end: calcRangeValueFromTime(this, c3.endTime) })) ); } /** * Is the media paused */ get mediaPaused() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED); } set mediaPaused(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_PAUSED, value); } /** * Is the media loading */ get mediaLoading() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_LOADING); } set mediaLoading(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_LOADING, value); } /** * */ get mediaDuration() { return getNumericAttr(this, MediaUIAttributes.MEDIA_DURATION); } set mediaDuration(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_DURATION, value); } /** * */ get mediaCurrentTime() { return getNumericAttr(this, MediaUIAttributes.MEDIA_CURRENT_TIME); } set mediaCurrentTime(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_CURRENT_TIME, value); } /** * */ get mediaPlaybackRate() { return getNumericAttr(this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, 1); } set mediaPlaybackRate(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, value); } /** * An array of ranges, each range being an array of two numbers. * e.g. [[1, 2], [3, 4]] */ get mediaBuffered() { const buffered = this.getAttribute(MediaUIAttributes.MEDIA_BUFFERED); if (!buffered) return []; return buffered.split(" ").map((timePair) => timePair.split(":").map((timeStr) => +timeStr)); } set mediaBuffered(list) { if (!list) { this.removeAttribute(MediaUIAttributes.MEDIA_BUFFERED); return; } const strVal = list.map((tuple) => tuple.join(":")).join(" "); this.setAttribute(MediaUIAttributes.MEDIA_BUFFERED, strVal); } /** * Range of values that can be seeked to * An array of two numbers [start, end] */ get mediaSeekable() { const seekable = this.getAttribute(MediaUIAttributes.MEDIA_SEEKABLE); if (!seekable) return void 0; return seekable.split(":").map((time) => +time); } set mediaSeekable(range) { if (range == null) { this.removeAttribute(MediaUIAttributes.MEDIA_SEEKABLE); return; } this.setAttribute(MediaUIAttributes.MEDIA_SEEKABLE, range.join(":")); } /** * */ get mediaSeekableEnd() { var _a3; const [, end = this.mediaDuration] = (_a3 = this.mediaSeekable) != null ? _a3 : []; return end; } get mediaSeekableStart() { var _a3; const [start = 0] = (_a3 = this.mediaSeekable) != null ? _a3 : []; return start; } /** * The url of the preview image */ get mediaPreviewImage() { return getStringAttr(this, MediaUIAttributes.MEDIA_PREVIEW_IMAGE); } set mediaPreviewImage(value) { setStringAttr(this, MediaUIAttributes.MEDIA_PREVIEW_IMAGE, value); } /** * */ get mediaPreviewTime() { return getNumericAttr(this, MediaUIAttributes.MEDIA_PREVIEW_TIME); } set mediaPreviewTime(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_PREVIEW_TIME, value); } /** * */ get mediaEnded() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_ENDED); } set mediaEnded(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_ENDED, value); } /* Add a buffered progress bar */ updateBar() { super.updateBar(); this.updateBufferedBar(); this.updateCurrentBox(); } updateBufferedBar() { var _a3; const buffered = this.mediaBuffered; if (!buffered.length) { return; } let relativeBufferedEnd; if (!this.mediaEnded) { const currentTime = this.mediaCurrentTime; const [, bufferedEnd = this.mediaSeekableStart] = (_a3 = buffered.find( ([start, end]) => start <= currentTime && currentTime <= end )) != null ? _a3 : []; relativeBufferedEnd = calcRangeValueFromTime(this, bufferedEnd); } else { relativeBufferedEnd = 1; } const { style } = getOrInsertCSSRule(this.shadowRoot, "#buffered"); style.setProperty("width", `${relativeBufferedEnd * 100}%`); } updateCurrentBox() { const currentSlot = this.shadowRoot.querySelector( 'slot[name="current"]' ); if (!currentSlot.assignedElements().length) return; const currentRailRule = getOrInsertCSSRule( this.shadowRoot, "#current-rail" ); const currentBoxRule = getOrInsertCSSRule( this.shadowRoot, '[part~="current-box"]' ); const rects = __privateMethod6(this, _getElementRects, getElementRects_fn).call(this, __privateGet18(this, _currentBox)); const boxPos = __privateMethod6(this, _getBoxPosition, getBoxPosition_fn).call(this, rects, this.range.valueAsNumber); const boxShift = __privateMethod6(this, _getBoxShiftPosition, getBoxShiftPosition_fn).call(this, rects, this.range.valueAsNumber); currentRailRule.style.transform = `translateX(${boxPos})`; currentRailRule.style.setProperty("--_range-width", `${rects.range.width}`); currentBoxRule.style.setProperty("--_box-shift", `${boxShift}`); currentBoxRule.style.setProperty("--_box-width", `${rects.box.width}px`); currentBoxRule.style.setProperty("visibility", "initial"); } handleEvent(evt) { super.handleEvent(evt); switch (evt.type) { case "input": __privateMethod6(this, _seekRequest, seekRequest_fn).call(this); break; case "pointermove": __privateMethod6(this, _handlePointerMove3, handlePointerMove_fn3).call(this, evt); break; case "pointerup": case "pointerleave": __privateMethod6(this, _previewRequest, previewRequest_fn).call(this, null); break; case "transitionstart": if (containsComposedNode(evt.target, this)) { setTimeout(() => __privateMethod6(this, _toggleRangeAnimation, toggleRangeAnimation_fn).call(this), 0); } break; } } }; _rootNode = /* @__PURE__ */ new WeakMap(); _animation = /* @__PURE__ */ new WeakMap(); _boxes = /* @__PURE__ */ new WeakMap(); _previewTime = /* @__PURE__ */ new WeakMap(); _previewBox = /* @__PURE__ */ new WeakMap(); _currentBox = /* @__PURE__ */ new WeakMap(); _boxPaddingLeft = /* @__PURE__ */ new WeakMap(); _boxPaddingRight = /* @__PURE__ */ new WeakMap(); _mediaChaptersCues = /* @__PURE__ */ new WeakMap(); _toggleRangeAnimation = /* @__PURE__ */ new WeakSet(); toggleRangeAnimation_fn = function() { if (__privateMethod6(this, _shouldRangeAnimate, shouldRangeAnimate_fn).call(this)) { __privateGet18(this, _animation).start(); } else { __privateGet18(this, _animation).stop(); } }; _shouldRangeAnimate = /* @__PURE__ */ new WeakSet(); shouldRangeAnimate_fn = function() { return this.isConnected && !this.mediaPaused && !this.mediaLoading && !this.mediaEnded && this.mediaSeekableEnd > 0 && isElementVisible(this); }; _updateRange = /* @__PURE__ */ new WeakMap(); _getElementRects = /* @__PURE__ */ new WeakSet(); getElementRects_fn = function(box) { var _a3; const bounds = (_a3 = this.getAttribute("bounds") ? closestComposedNode(this, `#${this.getAttribute("bounds")}`) : this.parentElement) != null ? _a3 : this; const boundsRect = bounds.getBoundingClientRect(); const rangeRect = this.range.getBoundingClientRect(); const width = box.offsetWidth; const min = -(rangeRect.left - boundsRect.left - width / 2); const max = boundsRect.right - rangeRect.left - width / 2; return { box: { width, min, max }, bounds: boundsRect, range: rangeRect }; }; _getBoxPosition = /* @__PURE__ */ new WeakSet(); getBoxPosition_fn = function(rects, ratio) { let position2 = `${ratio * 100}%`; const { width, min, max } = rects.box; if (!width) return position2; if (!Number.isNaN(min)) { const pad = `var(--media-box-padding-left)`; const minPos = `calc(1 / var(--_range-width) * 100 * ${min}% + ${pad})`; position2 = `max(${minPos}, ${position2})`; } if (!Number.isNaN(max)) { const pad = `var(--media-box-padding-right)`; const maxPos = `calc(1 / var(--_range-width) * 100 * ${max}% - ${pad})`; position2 = `min(${position2}, ${maxPos})`; } return position2; }; _getBoxShiftPosition = /* @__PURE__ */ new WeakSet(); getBoxShiftPosition_fn = function(rects, ratio) { const { width, min, max } = rects.box; const pointerX = ratio * rects.range.width; if (pointerX < min + __privateGet18(this, _boxPaddingLeft)) { const offset = rects.range.left - rects.bounds.left - __privateGet18(this, _boxPaddingLeft); return `${pointerX - width / 2 + offset}px`; } if (pointerX > max - __privateGet18(this, _boxPaddingRight)) { const offset = rects.bounds.right - rects.range.right - __privateGet18(this, _boxPaddingRight); return `${pointerX + width / 2 - offset - rects.range.width}px`; } return 0; }; _handlePointerMove3 = /* @__PURE__ */ new WeakSet(); handlePointerMove_fn3 = function(evt) { const isOverBoxes = [...__privateGet18(this, _boxes)].some( (b2) => evt.composedPath().includes(b2) ); if (!this.dragging && (isOverBoxes || !evt.composedPath().includes(this))) { __privateMethod6(this, _previewRequest, previewRequest_fn).call(this, null); return; } const duration = this.mediaSeekableEnd; if (!duration) return; const previewRailRule = getOrInsertCSSRule( this.shadowRoot, "#preview-rail" ); const previewBoxRule = getOrInsertCSSRule( this.shadowRoot, '[part~="preview-box"]' ); const rects = __privateMethod6(this, _getElementRects, getElementRects_fn).call(this, __privateGet18(this, _previewBox)); let pointerRatio = (evt.clientX - rects.range.left) / rects.range.width; pointerRatio = Math.max(0, Math.min(1, pointerRatio)); const boxPos = __privateMethod6(this, _getBoxPosition, getBoxPosition_fn).call(this, rects, pointerRatio); const boxShift = __privateMethod6(this, _getBoxShiftPosition, getBoxShiftPosition_fn).call(this, rects, pointerRatio); previewRailRule.style.transform = `translateX(${boxPos})`; previewRailRule.style.setProperty("--_range-width", `${rects.range.width}`); previewBoxRule.style.setProperty("--_box-shift", `${boxShift}`); previewBoxRule.style.setProperty("--_box-width", `${rects.box.width}px`); const diff = Math.round(__privateGet18(this, _previewTime)) - Math.round(pointerRatio * duration); if (Math.abs(diff) < 1 && pointerRatio > 0.01 && pointerRatio < 0.99) return; __privateSet17(this, _previewTime, pointerRatio * duration); __privateMethod6(this, _previewRequest, previewRequest_fn).call(this, __privateGet18(this, _previewTime)); }; _previewRequest = /* @__PURE__ */ new WeakSet(); previewRequest_fn = function(detail) { this.dispatchEvent( new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_PREVIEW_REQUEST, { composed: true, bubbles: true, detail }) ); }; _seekRequest = /* @__PURE__ */ new WeakSet(); seekRequest_fn = function() { __privateGet18(this, _animation).stop(); const detail = calcTimeFromRangeValue(this); this.dispatchEvent( new GlobalThis.CustomEvent(MediaUIEvents.MEDIA_SEEK_REQUEST, { composed: true, bubbles: true, detail }) ); }; if (!GlobalThis.customElements.get("media-time-range")) { GlobalThis.customElements.define("media-time-range", MediaTimeRange); } // node_modules/media-chrome/dist/media-tooltip.js var Attributes11 = { PLACEMENT: "placement", BOUNDS: "bounds" }; var template12 = Document2.createElement("template"); template12.innerHTML = /*html*/ ` <style> :host { --_tooltip-background-color: var(--media-tooltip-background-color, var(--media-secondary-color, rgba(20, 20, 30, .7))); --_tooltip-background: var(--media-tooltip-background, var(--_tooltip-background-color)); --_tooltip-arrow-half-width: calc(var(--media-tooltip-arrow-width, 12px) / 2); --_tooltip-arrow-height: var(--media-tooltip-arrow-height, 5px); --_tooltip-arrow-background: var(--media-tooltip-arrow-color, var(--_tooltip-background-color)); position: relative; pointer-events: none; display: var(--media-tooltip-display, inline-flex); justify-content: center; align-items: center; box-sizing: border-box; z-index: var(--media-tooltip-z-index, 1); background: var(--_tooltip-background); color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238))); font: var(--media-font, var(--media-font-weight, 400) var(--media-font-size, 13px) / var(--media-text-content-height, var(--media-control-height, 18px)) var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif)); padding: var(--media-tooltip-padding, .35em .7em); border: var(--media-tooltip-border, none); border-radius: var(--media-tooltip-border-radius, 5px); filter: var(--media-tooltip-filter, drop-shadow(0 0 4px rgba(0, 0, 0, .2))); white-space: var(--media-tooltip-white-space, nowrap); } :host([hidden]) { display: none; } img, svg { display: inline-block; } #arrow { position: absolute; width: 0px; height: 0px; border-style: solid; display: var(--media-tooltip-arrow-display, block); } :host(:not([placement])), :host([placement="top"]) { position: absolute; bottom: calc(100% + var(--media-tooltip-distance, 12px)); left: 50%; transform: translate(calc(-50% - var(--media-tooltip-offset-x, 0px)), 0); } :host(:not([placement])) #arrow, :host([placement="top"]) #arrow { top: 100%; left: 50%; border-width: var(--_tooltip-arrow-height) var(--_tooltip-arrow-half-width) 0 var(--_tooltip-arrow-half-width); border-color: var(--_tooltip-arrow-background) transparent transparent transparent; transform: translate(calc(-50% + var(--media-tooltip-offset-x, 0px)), 0); } :host([placement="right"]) { position: absolute; left: calc(100% + var(--media-tooltip-distance, 12px)); top: 50%; transform: translate(0, -50%); } :host([placement="right"]) #arrow { top: 50%; right: 100%; border-width: var(--_tooltip-arrow-half-width) var(--_tooltip-arrow-height) var(--_tooltip-arrow-half-width) 0; border-color: transparent var(--_tooltip-arrow-background) transparent transparent; transform: translate(0, -50%); } :host([placement="bottom"]) { position: absolute; top: calc(100% + var(--media-tooltip-distance, 12px)); left: 50%; transform: translate(calc(-50% - var(--media-tooltip-offset-x, 0px)), 0); } :host([placement="bottom"]) #arrow { bottom: 100%; left: 50%; border-width: 0 var(--_tooltip-arrow-half-width) var(--_tooltip-arrow-height) var(--_tooltip-arrow-half-width); border-color: transparent transparent var(--_tooltip-arrow-background) transparent; transform: translate(calc(-50% + var(--media-tooltip-offset-x, 0px)), 0); } :host([placement="left"]) { position: absolute; right: calc(100% + var(--media-tooltip-distance, 12px)); top: 50%; transform: translate(0, -50%); } :host([placement="left"]) #arrow { top: 50%; left: 100%; border-width: var(--_tooltip-arrow-half-width) 0 var(--_tooltip-arrow-half-width) var(--_tooltip-arrow-height); border-color: transparent transparent transparent var(--_tooltip-arrow-background); transform: translate(0, -50%); } :host([placement="none"]) #arrow { display: none; } </style> <slot></slot> <div id="arrow"></div> `; var MediaTooltip = class extends GlobalThis.HTMLElement { constructor() { super(); this.updateXOffset = () => { var _a3; if (!isElementVisible(this, { checkOpacity: false, checkVisibilityCSS: false })) return; const placement = this.placement; if (placement === "left" || placement === "right") { this.style.removeProperty("--media-tooltip-offset-x"); return; } const tooltipStyle = getComputedStyle(this); const containingEl = (_a3 = closestComposedNode(this, "#" + this.bounds)) != null ? _a3 : getMediaController(this); if (!containingEl) return; const { x: containerX, width: containerWidth } = containingEl.getBoundingClientRect(); const { x: tooltipX, width: tooltipWidth } = this.getBoundingClientRect(); const tooltipRight = tooltipX + tooltipWidth; const containerRight = containerX + containerWidth; const offsetXVal = tooltipStyle.getPropertyValue( "--media-tooltip-offset-x" ); const currOffsetX = offsetXVal ? parseFloat(offsetXVal.replace("px", "")) : 0; const marginVal = tooltipStyle.getPropertyValue( "--media-tooltip-container-margin" ); const currMargin = marginVal ? parseFloat(marginVal.replace("px", "")) : 0; const leftDiff = tooltipX - containerX + currOffsetX - currMargin; const rightDiff = tooltipRight - containerRight + currOffsetX + currMargin; if (leftDiff < 0) { this.style.setProperty("--media-tooltip-offset-x", `${leftDiff}px`); return; } if (rightDiff > 0) { this.style.setProperty("--media-tooltip-offset-x", `${rightDiff}px`); return; } this.style.removeProperty("--media-tooltip-offset-x"); }; if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template12.content.cloneNode(true)); } this.arrowEl = this.shadowRoot.querySelector("#arrow"); if (Object.prototype.hasOwnProperty.call(this, "placement")) { const placement = this.placement; delete this.placement; this.placement = placement; } } static get observedAttributes() { return [Attributes11.PLACEMENT, Attributes11.BOUNDS]; } /** * Get or set tooltip placement */ get placement() { return getStringAttr(this, Attributes11.PLACEMENT); } set placement(value) { setStringAttr(this, Attributes11.PLACEMENT, value); } /** * Get or set tooltip container ID selector that will constrain the tooltips * horizontal position. */ get bounds() { return getStringAttr(this, Attributes11.BOUNDS); } set bounds(value) { setStringAttr(this, Attributes11.BOUNDS, value); } }; if (!GlobalThis.customElements.get("media-tooltip")) { GlobalThis.customElements.define("media-tooltip", MediaTooltip); } // node_modules/media-chrome/dist/media-volume-range.js var DEFAULT_VOLUME = 1; var toVolume = (el) => { if (el.mediaMuted) return 0; return el.mediaVolume; }; var formatAsPercentString = (value) => `${Math.round(value * 100)}%`; var MediaVolumeRange = class extends MediaChromeRange { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_VOLUME, MediaUIAttributes.MEDIA_MUTED, MediaUIAttributes.MEDIA_VOLUME_UNAVAILABLE ]; } constructor() { super(); this.range.addEventListener("input", () => { const detail = this.range.value; const evt = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_VOLUME_REQUEST, { composed: true, bubbles: true, detail } ); this.dispatchEvent(evt); }); } connectedCallback() { super.connectedCallback(); this.range.setAttribute("aria-label", nouns.VOLUME()); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_VOLUME || attrName === MediaUIAttributes.MEDIA_MUTED) { this.range.valueAsNumber = toVolume(this); this.range.setAttribute( "aria-valuetext", formatAsPercentString(this.range.valueAsNumber) ); this.updateBar(); } } /** * */ get mediaVolume() { return getNumericAttr(this, MediaUIAttributes.MEDIA_VOLUME, DEFAULT_VOLUME); } set mediaVolume(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_VOLUME, value); } /** * Is the media currently muted */ get mediaMuted() { return getBooleanAttr(this, MediaUIAttributes.MEDIA_MUTED); } set mediaMuted(value) { setBooleanAttr(this, MediaUIAttributes.MEDIA_MUTED, value); } /** * The volume unavailability state */ get mediaVolumeUnavailable() { return getStringAttr(this, MediaUIAttributes.MEDIA_VOLUME_UNAVAILABLE); } set mediaVolumeUnavailable(value) { setStringAttr(this, MediaUIAttributes.MEDIA_VOLUME_UNAVAILABLE, value); } }; if (!GlobalThis.customElements.get("media-volume-range")) { GlobalThis.customElements.define("media-volume-range", MediaVolumeRange); } // node_modules/@mux/mux-video/dist/index.mjs var di2 = Object.defineProperty; var ui2 = Object.getPrototypeOf; var ci2 = Reflect.get; var hi2 = (e, r9, t2) => r9 in e ? di2(e, r9, { enumerable: true, configurable: true, writable: true, value: t2 }) : e[r9] = t2; var E2 = (e, r9, t2) => (hi2(e, typeof r9 != "symbol" ? r9 + "" : r9, t2), t2); var ge3 = (e, r9, t2) => { if (!r9.has(e)) throw TypeError("Cannot " + t2); }; var i = (e, r9, t2) => (ge3(e, r9, "read from private field"), t2 ? t2.call(e) : r9.get(e)); var u = (e, r9, t2) => { if (r9.has(e)) throw TypeError("Cannot add the same private member more than once"); r9 instanceof WeakSet ? r9.add(e) : r9.set(e, t2); }; var h = (e, r9, t2, s) => (ge3(e, r9, "write to private field"), s ? s.call(e, t2) : r9.set(e, t2), t2); var A3 = (e, r9, t2) => (ge3(e, r9, "access private method"), t2); var Jt2 = (e, r9, t2) => ci2(ui2(e), t2, r9); var Et3 = class { addEventListener() { } removeEventListener() { } dispatchEvent(r9) { return true; } }; if (typeof DocumentFragment == "undefined") { class e extends Et3 { } globalThis.DocumentFragment = e; } var wt2 = class extends Et3 { }; var Ee2 = class extends Et3 { }; var li2 = { get(e) { }, define(e, r9, t2) { }, getName(e) { return null; }, upgrade(e) { }, whenDefined(e) { return Promise.resolve(wt2); } }; var xt3; var Te2 = class { constructor(r9, t2 = {}) { u(this, xt3, void 0); h(this, xt3, t2 == null ? void 0 : t2.detail); } get detail() { return i(this, xt3); } initCustomEvent() { } }; xt3 = /* @__PURE__ */ new WeakMap(); function fi2(e, r9) { return new wt2(); } var Oe3 = { document: { createElement: fi2 }, DocumentFragment, customElements: li2, CustomEvent: Te2, EventTarget: Et3, HTMLElement: wt2, HTMLVideoElement: Ee2 }; var Pe3 = typeof window == "undefined" || typeof globalThis.customElements == "undefined"; var Qt2 = Pe3 ? Oe3 : globalThis; var $i = Pe3 ? Oe3.document : globalThis.document; var mi2 = () => { try { return "0.22.0"; } catch { } return "UNKNOWN"; }; var pi2 = mi2(); var Ie3 = () => pi2; var ve3 = ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "encrypted", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting", "waitingforkey", "resize", "enterpictureinpicture", "leavepictureinpicture", "webkitbeginfullscreen", "webkitendfullscreen", "webkitpresentationmodechanged"]; function gi2(e) { return ` <style> :host { display: inline-flex; line-height: 0; flex-direction: column; justify-content: end; } audio { width: 100%; } </style> <slot name="media"> <audio${Ve2(e)}></audio> </slot> <slot></slot> `; } function Ei2(e) { return ` <style> :host { display: inline-block; line-height: 0; } video { max-width: 100%; max-height: 100%; min-width: 100%; min-height: 100%; object-fit: var(--media-object-fit, contain); object-position: var(--media-object-position, 50% 50%); } video::-webkit-media-text-track-container { transform: var(--media-webkit-text-track-transform); transition: var(--media-webkit-text-track-transition); } </style> <slot name="media"> <video${Ve2(e)}></video> </slot> <slot></slot> `; } var we2 = (e, { tag: r9, is: t2 }) => { var l2, f, d2, T3, C4, xe3, mt4, x2, a2, m2, nt4, w4, be3, L2, Ne4, O3, De4; let s = (f = (l2 = globalThis.document) == null ? void 0 : l2.createElement) == null ? void 0 : f.call(l2, r9, { is: t2 }), n2 = s ? Ti2(s) : []; return d2 = class extends e { constructor() { super(); u(this, m2); u(this, w4); u(this, L2); u(this, O3); u(this, mt4, void 0); u(this, x2, void 0); u(this, a2, /* @__PURE__ */ new Map()); } static get observedAttributes() { var g2, v2, P2; return A3(g2 = d2, C4, xe3).call(g2), [...(P2 = (v2 = s == null ? void 0 : s.constructor) == null ? void 0 : v2.observedAttributes) != null ? P2 : [], "autopictureinpicture", "disablepictureinpicture", "disableremoteplayback", "autoplay", "controls", "controlslist", "crossorigin", "loop", "muted", "playsinline", "poster", "preload", "src"]; } get nativeEl() { var p3, g2, v2; return A3(this, m2, nt4).call(this), (v2 = (g2 = (p3 = i(this, x2)) != null ? p3 : this.shadowRoot.querySelector(r9)) != null ? g2 : this.querySelector(":scope > [slot=media]")) != null ? v2 : this.querySelector(r9); } set nativeEl(p3) { h(this, x2, p3); } get defaultMuted() { return this.hasAttribute("muted"); } set defaultMuted(p3) { this.toggleAttribute("muted", !!p3); } get src() { return this.getAttribute("src"); } set src(p3) { this.setAttribute("src", `${p3}`); } get preload() { var p3, g2; return (g2 = this.getAttribute("preload")) != null ? g2 : (p3 = this.nativeEl) == null ? void 0 : p3.preload; } set preload(p3) { this.setAttribute("preload", `${p3}`); } init() { var p3, g2; if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); let v2 = bi2(this.attributes); t2 && (v2.is = t2), r9 && (v2.part = r9), this.shadowRoot.innerHTML = this.constructor.getTemplateHTML(v2); } this.nativeEl.muted = this.hasAttribute("muted"); for (let v2 of n2) A3(this, L2, Ne4).call(this, v2); this.shadowRoot.addEventListener("slotchange", this), A3(this, w4, be3).call(this); for (let v2 of this.constructor.Events) (g2 = (p3 = this.shadowRoot).addEventListener) == null || g2.call(p3, v2, this, true); } handleEvent(p3) { if (p3.type === "slotchange") { A3(this, w4, be3).call(this); return; } p3.target === this.nativeEl && this.dispatchEvent(new CustomEvent(p3.type, { detail: p3.detail })); } attributeChangedCallback(p3, g2, v2) { A3(this, m2, nt4).call(this), A3(this, O3, De4).call(this, p3, g2, v2); } connectedCallback() { A3(this, m2, nt4).call(this); } }, T3 = /* @__PURE__ */ new WeakMap(), C4 = /* @__PURE__ */ new WeakSet(), xe3 = function() { if (i(this, T3)) return; h(this, T3, true); let p3 = new Set(this.observedAttributes); p3.delete("muted"); for (let g2 of n2) { if (g2 in this.prototype) continue; if (typeof s[g2] == "function") this.prototype[g2] = function(...P2) { return A3(this, m2, nt4).call(this), this.call ? this.call(g2, ...P2) : this.nativeEl[g2].apply(this.nativeEl, P2); }; else { let P2 = { get() { var D4, Lt4, Mt3; A3(this, m2, nt4).call(this); let _3 = g2.toLowerCase(); if (p3.has(_3)) { let gt4 = this.getAttribute(_3); return gt4 === null ? false : gt4 === "" ? true : gt4; } return (Mt3 = (D4 = this.get) == null ? void 0 : D4.call(this, g2)) != null ? Mt3 : (Lt4 = this.nativeEl) == null ? void 0 : Lt4[g2]; } }; g2 !== g2.toUpperCase() && (P2.set = function(_3) { A3(this, m2, nt4).call(this); let D4 = g2.toLowerCase(); if (p3.has(D4)) { _3 === true || _3 === false || _3 == null ? this.toggleAttribute(D4, !!_3) : this.setAttribute(D4, _3); return; } if (this.set) { this.set(g2, _3); return; } this.nativeEl[g2] = _3; }), Object.defineProperty(this.prototype, g2, P2); } } }, mt4 = /* @__PURE__ */ new WeakMap(), x2 = /* @__PURE__ */ new WeakMap(), a2 = /* @__PURE__ */ new WeakMap(), m2 = /* @__PURE__ */ new WeakSet(), nt4 = function() { i(this, mt4) || (h(this, mt4, true), this.init()); }, w4 = /* @__PURE__ */ new WeakSet(), be3 = function() { let p3 = new Map(i(this, a2)); this.shadowRoot.querySelector("slot:not([name])").assignedElements({ flatten: true }).filter((g2) => ["track", "source"].includes(g2.localName)).forEach((g2) => { var P2, _3; p3.delete(g2); let v2 = i(this, a2).get(g2); v2 || (v2 = g2.cloneNode(), i(this, a2).set(g2, v2)), (_3 = (P2 = this.nativeEl).append) == null || _3.call(P2, v2), v2.localName === "track" && v2.default && (v2.kind === "chapters" || v2.kind === "metadata") && v2.track.mode === "disabled" && (v2.track.mode = "hidden"); }), p3.forEach((g2) => g2.remove()); }, L2 = /* @__PURE__ */ new WeakSet(), Ne4 = function(p3) { if (Object.prototype.hasOwnProperty.call(this, p3)) { let g2 = this[p3]; delete this[p3], this[p3] = g2; } }, O3 = /* @__PURE__ */ new WeakSet(), De4 = function(p3, g2, v2) { var P2, _3, D4, Lt4, Mt3, gt4; ["id", "class"].includes(p3) || !d2.observedAttributes.includes(p3) && this.constructor.observedAttributes.includes(p3) || (v2 === null ? (_3 = (P2 = this.nativeEl).removeAttribute) == null || _3.call(P2, p3) : ((Lt4 = (D4 = this.nativeEl).getAttribute) == null ? void 0 : Lt4.call(D4, p3)) != v2 && ((gt4 = (Mt3 = this.nativeEl).setAttribute) == null || gt4.call(Mt3, p3, v2))); }, u(d2, C4), E2(d2, "getTemplateHTML", r9.endsWith("audio") ? gi2 : Ei2), E2(d2, "shadowRootOptions", { mode: "open" }), E2(d2, "Events", ve3), u(d2, T3, void 0), d2; }; function Ti2(e) { let r9 = []; for (let t2 = Object.getPrototypeOf(e); t2 && t2 !== HTMLElement.prototype; t2 = Object.getPrototypeOf(t2)) r9.push(...Object.getOwnPropertyNames(t2)); return r9; } function Ve2(e) { let r9 = ""; for (let t2 in e) { let s = e[t2]; s === "" ? r9 += ` ${t2}` : r9 += ` ${t2}="${s}"`; } return r9; } function bi2(e) { let r9 = {}; for (let t2 of e) r9[t2.name] = t2.value; return r9; } var Le3; var Zt2 = we2((Le3 = globalThis.HTMLElement) != null ? Le3 : class { }, { tag: "video" }); var Me3; var Qi = we2((Me3 = globalThis.HTMLElement) != null ? Me3 : class { }, { tag: "audio" }); var V3 = /* @__PURE__ */ new WeakMap(); var Tt3 = class extends Error { }; var te3 = class extends Error { }; var Ge3 = globalThis.WeakRef ? class extends Set { add(e) { super.add(new WeakRef(e)); } forEach(e) { super.forEach((r9) => { let t2 = r9.deref(); t2 && e(t2); }); } } : Set; function Be2(e) { var r9, t2, s; (t2 = (r9 = globalThis.chrome) == null ? void 0 : r9.cast) != null && t2.isAvailable ? (s = globalThis.cast) != null && s.framework ? e() : customElements.whenDefined("google-cast-button").then(e) : globalThis.__onGCastApiAvailable = () => { customElements.whenDefined("google-cast-button").then(e); }; } function Ke3() { return globalThis.chrome; } function qe() { var t2; let e = "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"; if ((t2 = globalThis.chrome) != null && t2.cast || document.querySelector(`script[src="${e}"]`)) return; let r9 = document.createElement("script"); r9.src = e, document.head.append(r9); } function U3() { var e, r9; return (r9 = (e = globalThis.cast) == null ? void 0 : e.framework) == null ? void 0 : r9.CastContext.getInstance(); } function Nt3() { var e; return (e = U3()) == null ? void 0 : e.getCurrentSession(); } function ee3() { var e; return (e = Nt3()) == null ? void 0 : e.getSessionObj().media[0]; } function Fe3(e) { return new Promise((r9, t2) => { ee3().editTracksInfo(e, r9, t2); }); } function Ue3(e) { return new Promise((r9, t2) => { ee3().getStatus(e, r9, t2); }); } function ye3(e) { return U3().setOptions({ ...Ae3(), ...e }); } function Ae3() { return { receiverApplicationId: "CC1AD845", autoJoinPolicy: "origin_scoped", androidReceiverCompatible: false, language: "en-US", resumeSavedSession: true }; } var ie3 = new Ge3(); var Y3 = /* @__PURE__ */ new WeakSet(); var R2; Be2(() => { var e, r9, t2, s; if (!((r9 = (e = globalThis.chrome) == null ? void 0 : e.cast) != null && r9.isAvailable)) { console.debug("chrome.cast.isAvailable", (s = (t2 = globalThis.chrome) == null ? void 0 : t2.cast) == null ? void 0 : s.isAvailable); return; } R2 || (R2 = cast.framework, U3().addEventListener(R2.CastContextEventType.CAST_STATE_CHANGED, (n2) => { ie3.forEach((l2) => { var f, d2; return (d2 = (f = V3.get(l2)).onCastStateChanged) == null ? void 0 : d2.call(f, n2); }); }), U3().addEventListener(R2.CastContextEventType.SESSION_STATE_CHANGED, (n2) => { ie3.forEach((l2) => { var f, d2; return (d2 = (f = V3.get(l2)).onSessionStateChanged) == null ? void 0 : d2.call(f, n2); }); }), ie3.forEach((n2) => { var l2, f; return (f = (l2 = V3.get(n2)).init) == null ? void 0 : f.call(l2); })); }); var Ye3 = 0; var y; var Dt3; var I2; var G2; var at2; var dt4; var j2; var se2; var B3; var ot3; var ne3; var je2; var Vt3; var ke3; var oe2; var We2; var Gt2; var Se3; var ae2; var He3; var Bt2; var Re2; var re3 = class extends EventTarget { constructor(t2) { super(); u(this, B3); u(this, ne3); u(this, Vt3); u(this, oe2); u(this, Gt2); u(this, ae2); u(this, Bt2); u(this, y, void 0); u(this, Dt3, void 0); u(this, I2, void 0); u(this, G2, void 0); u(this, at2, "disconnected"); u(this, dt4, false); u(this, j2, /* @__PURE__ */ new Set()); u(this, se2, /* @__PURE__ */ new WeakMap()); h(this, y, t2), ie3.add(this), V3.set(this, { init: () => A3(this, Gt2, Se3).call(this), onCastStateChanged: () => A3(this, Vt3, ke3).call(this), onSessionStateChanged: () => A3(this, oe2, We2).call(this), getCastPlayer: () => i(this, B3, ot3) }), A3(this, Gt2, Se3).call(this); } get state() { return i(this, at2); } async watchAvailability(t2) { if (i(this, y).disableRemotePlayback) throw new Tt3("disableRemotePlayback attribute is present."); return i(this, se2).set(t2, ++Ye3), i(this, j2).add(t2), Ye3; } async cancelWatchAvailability(t2) { if (i(this, y).disableRemotePlayback) throw new Tt3("disableRemotePlayback attribute is present."); t2 ? i(this, j2).delete(t2) : i(this, j2).clear(); } async prompt() { var s, n2, l2, f; if (i(this, y).disableRemotePlayback) throw new Tt3("disableRemotePlayback attribute is present."); if (!((n2 = (s = globalThis.chrome) == null ? void 0 : s.cast) != null && n2.isAvailable)) throw new te3("The RemotePlayback API is disabled on this platform."); let t2 = Y3.has(i(this, y)); Y3.add(i(this, y)), ye3(i(this, y).castOptions), Object.entries(i(this, G2)).forEach(([d2, T3]) => { i(this, I2).controller.addEventListener(d2, T3); }); try { await U3().requestSession(); } catch (d2) { if (d2 === "cancel") { t2 || Y3.delete(i(this, y)); return; } throw new Error(d2); } (f = (l2 = V3.get(i(this, y))) == null ? void 0 : l2.loadOnPrompt) == null || f.call(l2); } }; y = /* @__PURE__ */ new WeakMap(), Dt3 = /* @__PURE__ */ new WeakMap(), I2 = /* @__PURE__ */ new WeakMap(), G2 = /* @__PURE__ */ new WeakMap(), at2 = /* @__PURE__ */ new WeakMap(), dt4 = /* @__PURE__ */ new WeakMap(), j2 = /* @__PURE__ */ new WeakMap(), se2 = /* @__PURE__ */ new WeakMap(), B3 = /* @__PURE__ */ new WeakSet(), ot3 = function() { if (Y3.has(i(this, y))) return i(this, I2); }, ne3 = /* @__PURE__ */ new WeakSet(), je2 = function() { Y3.has(i(this, y)) && (Object.entries(i(this, G2)).forEach(([t2, s]) => { i(this, I2).controller.removeEventListener(t2, s); }), Y3.delete(i(this, y)), i(this, y).muted = i(this, I2).isMuted, i(this, y).currentTime = i(this, I2).savedPlayerState.currentTime, i(this, I2).savedPlayerState.isPaused === false && i(this, y).play()); }, Vt3 = /* @__PURE__ */ new WeakSet(), ke3 = function() { let t2 = U3().getCastState(); if (Y3.has(i(this, y)) && t2 === "CONNECTING" && (h(this, at2, "connecting"), this.dispatchEvent(new Event("connecting"))), !i(this, dt4) && (t2 != null && t2.includes("CONNECT"))) { h(this, dt4, true); for (let s of i(this, j2)) s(true); } else if (i(this, dt4) && (!t2 || t2 === "NO_DEVICES_AVAILABLE")) { h(this, dt4, false); for (let s of i(this, j2)) s(false); } }, oe2 = /* @__PURE__ */ new WeakSet(), We2 = async function() { var s; let { SESSION_RESUMED: t2 } = R2.SessionState; if (U3().getSessionState() === t2 && i(this, y).castSrc === ((s = ee3()) == null ? void 0 : s.media.contentId)) { Y3.add(i(this, y)), Object.entries(i(this, G2)).forEach(([n2, l2]) => { i(this, I2).controller.addEventListener(n2, l2); }); try { await Ue3(new chrome.cast.media.GetStatusRequest()); } catch (n2) { console.error(n2); } i(this, G2)[R2.RemotePlayerEventType.IS_PAUSED_CHANGED](), i(this, G2)[R2.RemotePlayerEventType.PLAYER_STATE_CHANGED](); } }, Gt2 = /* @__PURE__ */ new WeakSet(), Se3 = function() { !R2 || i(this, Dt3) || (h(this, Dt3, true), ye3(i(this, y).castOptions), i(this, y).textTracks.addEventListener("change", () => A3(this, Bt2, Re2).call(this)), A3(this, Vt3, ke3).call(this), h(this, I2, new R2.RemotePlayer()), new R2.RemotePlayerController(i(this, I2)), h(this, G2, { [R2.RemotePlayerEventType.IS_CONNECTED_CHANGED]: ({ value: t2 }) => { t2 === true ? (h(this, at2, "connected"), this.dispatchEvent(new Event("connect"))) : (A3(this, ne3, je2).call(this), h(this, at2, "disconnected"), this.dispatchEvent(new Event("disconnect"))); }, [R2.RemotePlayerEventType.DURATION_CHANGED]: () => { i(this, y).dispatchEvent(new Event("durationchange")); }, [R2.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]: () => { i(this, y).dispatchEvent(new Event("volumechange")); }, [R2.RemotePlayerEventType.IS_MUTED_CHANGED]: () => { i(this, y).dispatchEvent(new Event("volumechange")); }, [R2.RemotePlayerEventType.CURRENT_TIME_CHANGED]: () => { var t2; (t2 = i(this, B3, ot3)) != null && t2.isMediaLoaded && i(this, y).dispatchEvent(new Event("timeupdate")); }, [R2.RemotePlayerEventType.VIDEO_INFO_CHANGED]: () => { i(this, y).dispatchEvent(new Event("resize")); }, [R2.RemotePlayerEventType.IS_PAUSED_CHANGED]: () => { i(this, y).dispatchEvent(new Event(this.paused ? "pause" : "play")); }, [R2.RemotePlayerEventType.PLAYER_STATE_CHANGED]: () => { var t2, s; ((t2 = i(this, B3, ot3)) == null ? void 0 : t2.playerState) !== chrome.cast.media.PlayerState.PAUSED && i(this, y).dispatchEvent(new Event({ [chrome.cast.media.PlayerState.PLAYING]: "playing", [chrome.cast.media.PlayerState.BUFFERING]: "waiting", [chrome.cast.media.PlayerState.IDLE]: "emptied" }[(s = i(this, B3, ot3)) == null ? void 0 : s.playerState])); }, [R2.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]: async () => { var t2; (t2 = i(this, B3, ot3)) != null && t2.isMediaLoaded && (await Promise.resolve(), A3(this, ae2, He3).call(this)); } })); }, ae2 = /* @__PURE__ */ new WeakSet(), He3 = function() { A3(this, Bt2, Re2).call(this); }, Bt2 = /* @__PURE__ */ new WeakSet(), Re2 = async function() { var x2, a2, m2, S3, w4; if (!i(this, B3, ot3)) return; let s = ((a2 = (x2 = i(this, I2).mediaInfo) == null ? void 0 : x2.tracks) != null ? a2 : []).filter(({ type: k3 }) => k3 === chrome.cast.media.TrackType.TEXT), n2 = [...i(this, y).textTracks].filter(({ kind: k3 }) => k3 === "subtitles" || k3 === "captions"), l2 = s.map(({ language: k3, name: L2, trackId: pt4 }) => { var st3; let { mode: O3 } = (st3 = n2.find((N2) => N2.language === k3 && N2.label === L2)) != null ? st3 : {}; return O3 ? { mode: O3, trackId: pt4 } : false; }).filter(Boolean), d2 = l2.filter(({ mode: k3 }) => k3 !== "showing").map(({ trackId: k3 }) => k3), T3 = l2.find(({ mode: k3 }) => k3 === "showing"), C4 = (w4 = (S3 = (m2 = Nt3()) == null ? void 0 : m2.getSessionObj().media[0]) == null ? void 0 : S3.activeTrackIds) != null ? w4 : [], F4 = C4; if (C4.length && (F4 = F4.filter((k3) => !d2.includes(k3))), T3 != null && T3.trackId && (F4 = [...F4, T3.trackId]), F4 = [...new Set(F4)], !((k3, L2) => k3.length === L2.length && k3.every((pt4) => L2.includes(pt4)))(C4, F4)) try { let k3 = new chrome.cast.media.EditTracksInfoRequest(F4); await Fe3(k3); } catch (k3) { console.error(k3); } }; var $e3 = (e) => { var r9, t2, s, n2, l2, f, d2, b2, C4, ze3; return t2 = class extends e { constructor() { super(...arguments); u(this, d2); u(this, C4); u(this, s, { paused: false }); u(this, n2, Ae3()); u(this, l2, void 0); u(this, f, void 0); } get remote() { return i(this, f) ? i(this, f) : Ke3() ? (qe(), V3.set(this, { loadOnPrompt: () => A3(this, C4, ze3).call(this) }), h(this, f, new re3(this))) : super.remote; } attributeChangedCallback(a2, m2, S3) { if (super.attributeChangedCallback(a2, m2, S3), a2 === "cast-receiver" && S3) { i(this, n2).receiverApplicationId = S3; return; } if (i(this, d2, b2)) switch (a2) { case "cast-stream-type": case "cast-src": this.load(); break; } } async load() { var L2, pt4; if (!i(this, d2, b2)) return super.load(); let a2 = new chrome.cast.media.MediaInfo(this.castSrc, this.castContentType); a2.customData = this.castCustomData; let m2 = [...this.querySelectorAll("track")].filter(({ kind: O3, src: st3 }) => st3 && (O3 === "subtitles" || O3 === "captions")), S3 = [], w4 = 0; m2.length && (a2.tracks = m2.map((O3) => { let st3 = ++w4; S3.length === 0 && O3.track.mode === "showing" && S3.push(st3); let N2 = new chrome.cast.media.Track(st3, chrome.cast.media.TrackType.TEXT); return N2.trackContentId = O3.src, N2.trackContentType = "text/vtt", N2.subtype = O3.kind === "captions" ? chrome.cast.media.TextTrackType.CAPTIONS : chrome.cast.media.TextTrackType.SUBTITLES, N2.name = O3.label, N2.language = O3.srclang, N2; })), this.castStreamType === "live" ? a2.streamType = chrome.cast.media.StreamType.LIVE : a2.streamType = chrome.cast.media.StreamType.BUFFERED, a2.metadata = new chrome.cast.media.GenericMediaMetadata(), a2.metadata.title = this.title, a2.metadata.images = [{ url: this.poster }]; let k3 = new chrome.cast.media.LoadRequest(a2); k3.currentTime = (L2 = super.currentTime) != null ? L2 : 0, k3.autoplay = !i(this, s).paused, k3.activeTrackIds = S3, await ((pt4 = Nt3()) == null ? void 0 : pt4.loadMedia(k3)), this.dispatchEvent(new Event("volumechange")); } play() { var a2; if (i(this, d2, b2)) { i(this, d2, b2).isPaused && ((a2 = i(this, d2, b2).controller) == null || a2.playOrPause()); return; } return super.play(); } pause() { var a2; if (i(this, d2, b2)) { i(this, d2, b2).isPaused || (a2 = i(this, d2, b2).controller) == null || a2.playOrPause(); return; } super.pause(); } get castOptions() { return i(this, n2); } get castReceiver() { var a2; return (a2 = this.getAttribute("cast-receiver")) != null ? a2 : void 0; } set castReceiver(a2) { this.castReceiver != a2 && this.setAttribute("cast-receiver", `${a2}`); } get castSrc() { var a2, m2, S3; return (S3 = (m2 = this.getAttribute("cast-src")) != null ? m2 : (a2 = this.querySelector("source")) == null ? void 0 : a2.src) != null ? S3 : this.currentSrc; } set castSrc(a2) { this.castSrc != a2 && this.setAttribute("cast-src", `${a2}`); } get castContentType() { var a2; return (a2 = this.getAttribute("cast-content-type")) != null ? a2 : void 0; } set castContentType(a2) { this.setAttribute("cast-content-type", `${a2}`); } get castStreamType() { var a2, m2; return (m2 = (a2 = this.getAttribute("cast-stream-type")) != null ? a2 : this.streamType) != null ? m2 : void 0; } set castStreamType(a2) { this.setAttribute("cast-stream-type", `${a2}`); } get castCustomData() { return i(this, l2); } set castCustomData(a2) { let m2 = typeof a2; if (!["object", "undefined"].includes(m2)) { console.error(`castCustomData must be nullish or an object but value was of type ${m2}`); return; } h(this, l2, a2); } get readyState() { if (i(this, d2, b2)) switch (i(this, d2, b2).playerState) { case chrome.cast.media.PlayerState.IDLE: return 0; case chrome.cast.media.PlayerState.BUFFERING: return 2; default: return 3; } return super.readyState; } get paused() { return i(this, d2, b2) ? i(this, d2, b2).isPaused : super.paused; } get muted() { var a2; return i(this, d2, b2) ? (a2 = i(this, d2, b2)) == null ? void 0 : a2.isMuted : super.muted; } set muted(a2) { var m2; if (i(this, d2, b2)) { (a2 && !i(this, d2, b2).isMuted || !a2 && i(this, d2, b2).isMuted) && ((m2 = i(this, d2, b2).controller) == null || m2.muteOrUnmute()); return; } super.muted = a2; } get volume() { var a2, m2; return i(this, d2, b2) ? (m2 = (a2 = i(this, d2, b2)) == null ? void 0 : a2.volumeLevel) != null ? m2 : 1 : super.volume; } set volume(a2) { var m2; if (i(this, d2, b2)) { i(this, d2, b2).volumeLevel = +a2, (m2 = i(this, d2, b2).controller) == null || m2.setVolumeLevel(); return; } super.volume = a2; } get duration() { var a2, m2, S3; return i(this, d2, b2) && ((a2 = i(this, d2, b2)) != null && a2.isMediaLoaded) ? (S3 = (m2 = i(this, d2, b2)) == null ? void 0 : m2.duration) != null ? S3 : NaN : super.duration; } get currentTime() { var a2, m2, S3; return i(this, d2, b2) && ((a2 = i(this, d2, b2)) != null && a2.isMediaLoaded) ? (S3 = (m2 = i(this, d2, b2)) == null ? void 0 : m2.currentTime) != null ? S3 : 0 : super.currentTime; } set currentTime(a2) { var m2; if (i(this, d2, b2)) { i(this, d2, b2).currentTime = a2, (m2 = i(this, d2, b2).controller) == null || m2.seek(); return; } super.currentTime = a2; } }, s = /* @__PURE__ */ new WeakMap(), n2 = /* @__PURE__ */ new WeakMap(), l2 = /* @__PURE__ */ new WeakMap(), f = /* @__PURE__ */ new WeakMap(), d2 = /* @__PURE__ */ new WeakSet(), b2 = function() { var a2, m2; return (m2 = (a2 = V3.get(this.remote)) == null ? void 0 : a2.getCastPlayer) == null ? void 0 : m2.call(a2); }, C4 = /* @__PURE__ */ new WeakSet(), ze3 = async function() { i(this, s).paused = Jt2(t2.prototype, this, "paused"), Jt2(t2.prototype, this, "pause").call(this), this.muted = Jt2(t2.prototype, this, "muted"); try { await this.load(); } catch (a2) { console.error(a2); } }, E2(t2, "observedAttributes", [...(r9 = e.observedAttributes) != null ? r9 : [], "cast-src", "cast-content-type", "cast-stream-type", "cast-receiver"]), t2; }; var K2 = class extends Event { constructor(t2, s) { super(t2); E2(this, "track"); this.track = s.track; } }; var Ce3 = /* @__PURE__ */ new WeakMap(); function c(e) { var r9; return (r9 = Ce3.get(e)) != null ? r9 : vi3(e, {}); } function vi3(e, r9) { let t2 = Ce3.get(e); return t2 || Ce3.set(e, t2 = {}), Object.assign(t2, r9); } function de3(e, r9) { let t2 = e.videoTracks; c(r9).media = e, c(r9).renditionSet || (c(r9).renditionSet = /* @__PURE__ */ new Set()); let s = c(t2).trackSet; s.add(r9); let n2 = s.size - 1; n2 in ct3.prototype || Object.defineProperty(ct3.prototype, n2, { get() { return [...c(this).trackSet][n2]; } }), queueMicrotask(() => { t2.dispatchEvent(new K2("addtrack", { track: r9 })); }); } function ue2(e) { var s; let r9 = (s = c(e).media) == null ? void 0 : s.videoTracks; if (!r9) return; c(r9).trackSet.delete(e), queueMicrotask(() => { r9.dispatchEvent(new K2("removetrack", { track: e })); }); } function Xe3(e) { var s; let r9 = (s = c(e).media.videoTracks) != null ? s : [], t2 = false; for (let n2 of r9) n2 !== e && (n2.selected = false, t2 = true); if (t2) { if (c(r9).changeRequested) return; c(r9).changeRequested = true, queueMicrotask(() => { delete c(r9).changeRequested, r9.dispatchEvent(new Event("change")); }); } } var W3; var H3; var $3; var ut3; var Kt2; var ct3 = class extends EventTarget { constructor() { super(); u(this, ut3); u(this, W3, void 0); u(this, H3, void 0); u(this, $3, void 0); c(this).trackSet = /* @__PURE__ */ new Set(); } [Symbol.iterator]() { return i(this, ut3, Kt2).values(); } get length() { return i(this, ut3, Kt2).size; } getTrackById(t2) { var s; return (s = [...i(this, ut3, Kt2)].find((n2) => n2.id === t2)) != null ? s : null; } get selectedIndex() { return [...i(this, ut3, Kt2)].findIndex((t2) => t2.selected); } get onaddtrack() { return i(this, W3); } set onaddtrack(t2) { i(this, W3) && (this.removeEventListener("addtrack", i(this, W3)), h(this, W3, void 0)), typeof t2 == "function" && (h(this, W3, t2), this.addEventListener("addtrack", t2)); } get onremovetrack() { return i(this, H3); } set onremovetrack(t2) { i(this, H3) && (this.removeEventListener("removetrack", i(this, H3)), h(this, H3, void 0)), typeof t2 == "function" && (h(this, H3, t2), this.addEventListener("removetrack", t2)); } get onchange() { return i(this, $3); } set onchange(t2) { i(this, $3) && (this.removeEventListener("change", i(this, $3)), h(this, $3, void 0)), typeof t2 == "function" && (h(this, $3, t2), this.addEventListener("change", t2)); } }; W3 = /* @__PURE__ */ new WeakMap(), H3 = /* @__PURE__ */ new WeakMap(), $3 = /* @__PURE__ */ new WeakMap(), ut3 = /* @__PURE__ */ new WeakSet(), Kt2 = function() { return c(this).trackSet; }; var q3 = class extends Event { constructor(t2, s) { super(t2); E2(this, "rendition"); this.rendition = s.rendition; } }; function Je3(e, r9) { let t2 = c(e).media.videoRenditions; c(r9).media = c(e).media, c(r9).track = e; let s = c(e).renditionSet; s.add(r9); let n2 = s.size - 1; n2 in ht3.prototype || Object.defineProperty(ht3.prototype, n2, { get() { return bt3(this)[n2]; } }), queueMicrotask(() => { e.selected && t2.dispatchEvent(new q3("addrendition", { rendition: r9 })); }); } function Qe3(e) { let r9 = c(e).media.videoRenditions, t2 = c(e).track; c(t2).renditionSet.delete(e), queueMicrotask(() => { c(e).track.selected && r9.dispatchEvent(new q3("removerendition", { rendition: e })); }); } function Ze3(e) { let r9 = c(e).media.videoRenditions; !r9 || c(r9).changeRequested || (c(r9).changeRequested = true, queueMicrotask(() => { delete c(r9).changeRequested, c(e).track.selected && r9.dispatchEvent(new Event("change")); })); } function bt3(e) { return [...c(e).media.videoTracks].filter((t2) => t2.selected).flatMap((t2) => [...c(t2).renditionSet]); } var z2; var X3; var J3; var ht3 = class extends EventTarget { constructor() { super(...arguments); u(this, z2, void 0); u(this, X3, void 0); u(this, J3, void 0); } [Symbol.iterator]() { return bt3(this).values(); } get length() { return bt3(this).length; } getRenditionById(t2) { var s; return (s = bt3(this).find((n2) => `${n2.id}` == `${t2}`)) != null ? s : null; } get selectedIndex() { return bt3(this).findIndex((t2) => t2.selected); } set selectedIndex(t2) { for (let [s, n2] of bt3(this).entries()) n2.selected = s === t2; } get onaddrendition() { return i(this, z2); } set onaddrendition(t2) { i(this, z2) && (this.removeEventListener("addrendition", i(this, z2)), h(this, z2, void 0)), typeof t2 == "function" && (h(this, z2, t2), this.addEventListener("addrendition", t2)); } get onremoverendition() { return i(this, X3); } set onremoverendition(t2) { i(this, X3) && (this.removeEventListener("removerendition", i(this, X3)), h(this, X3, void 0)), typeof t2 == "function" && (h(this, X3, t2), this.addEventListener("removerendition", t2)); } get onchange() { return i(this, J3); } set onchange(t2) { i(this, J3) && (this.removeEventListener("change", i(this, J3)), h(this, J3, void 0)), typeof t2 == "function" && (h(this, J3, t2), this.addEventListener("change", t2)); } }; z2 = /* @__PURE__ */ new WeakMap(), X3 = /* @__PURE__ */ new WeakMap(), J3 = /* @__PURE__ */ new WeakMap(); var vt3; var qt2 = class { constructor() { E2(this, "src"); E2(this, "id"); E2(this, "width"); E2(this, "height"); E2(this, "bitrate"); E2(this, "frameRate"); E2(this, "codec"); u(this, vt3, false); } get selected() { return i(this, vt3); } set selected(r9) { i(this, vt3) !== r9 && (h(this, vt3, r9), Ze3(this)); } }; vt3 = /* @__PURE__ */ new WeakMap(); var yt2; var At3 = class { constructor() { E2(this, "id"); E2(this, "kind"); E2(this, "label", ""); E2(this, "language", ""); E2(this, "sourceBuffer"); u(this, yt2, false); } addRendition(r9, t2, s, n2, l2, f) { let d2 = new qt2(); return d2.src = r9, d2.width = t2, d2.height = s, d2.frameRate = f, d2.bitrate = l2, d2.codec = n2, Je3(this, d2), d2; } removeRendition(r9) { Qe3(r9); } get selected() { return i(this, yt2); } set selected(r9) { i(this, yt2) !== r9 && (h(this, yt2, r9), r9 === true && Xe3(this)); } }; yt2 = /* @__PURE__ */ new WeakMap(); function ti(e, r9) { let t2 = c(e).media.audioRenditions; c(r9).media = c(e).media, c(r9).track = e; let s = c(e).renditionSet; s.add(r9); let n2 = s.size - 1; n2 in lt3.prototype || Object.defineProperty(lt3.prototype, n2, { get() { return kt3(this)[n2]; } }), queueMicrotask(() => { e.enabled && t2.dispatchEvent(new q3("addrendition", { rendition: r9 })); }); } function ei(e) { let r9 = c(e).media.audioRenditions, t2 = c(e).track; c(t2).renditionSet.delete(e), queueMicrotask(() => { c(e).track.enabled && r9.dispatchEvent(new q3("removerendition", { rendition: e })); }); } function ii2(e) { let r9 = c(e).media.audioRenditions; !r9 || c(r9).changeRequested || (c(r9).changeRequested = true, queueMicrotask(() => { delete c(r9).changeRequested, c(e).track.enabled && r9.dispatchEvent(new Event("change")); })); } function kt3(e) { return [...c(e).media.audioTracks].filter((t2) => t2.enabled).flatMap((t2) => [...c(t2).renditionSet]); } var Q3; var Z2; var tt2; var lt3 = class extends EventTarget { constructor() { super(...arguments); u(this, Q3, void 0); u(this, Z2, void 0); u(this, tt2, void 0); } [Symbol.iterator]() { return kt3(this).values(); } get length() { return kt3(this).length; } getRenditionById(t2) { var s; return (s = kt3(this).find((n2) => `${n2.id}` == `${t2}`)) != null ? s : null; } get selectedIndex() { return kt3(this).findIndex((t2) => t2.selected); } set selectedIndex(t2) { for (let [s, n2] of kt3(this).entries()) n2.selected = s === t2; } get onaddrendition() { return i(this, Q3); } set onaddrendition(t2) { i(this, Q3) && (this.removeEventListener("addrendition", i(this, Q3)), h(this, Q3, void 0)), typeof t2 == "function" && (h(this, Q3, t2), this.addEventListener("addrendition", t2)); } get onremoverendition() { return i(this, Z2); } set onremoverendition(t2) { i(this, Z2) && (this.removeEventListener("removerendition", i(this, Z2)), h(this, Z2, void 0)), typeof t2 == "function" && (h(this, Z2, t2), this.addEventListener("removerendition", t2)); } get onchange() { return i(this, tt2); } set onchange(t2) { i(this, tt2) && (this.removeEventListener("change", i(this, tt2)), h(this, tt2, void 0)), typeof t2 == "function" && (h(this, tt2, t2), this.addEventListener("change", t2)); } }; Q3 = /* @__PURE__ */ new WeakMap(), Z2 = /* @__PURE__ */ new WeakMap(), tt2 = /* @__PURE__ */ new WeakMap(); var St2; var Ft2 = class { constructor() { E2(this, "src"); E2(this, "id"); E2(this, "bitrate"); E2(this, "codec"); u(this, St2, false); } get selected() { return i(this, St2); } set selected(r9) { i(this, St2) !== r9 && (h(this, St2, r9), ii2(this)); } }; St2 = /* @__PURE__ */ new WeakMap(); function he3(e, r9) { let t2 = e.audioTracks; c(r9).media = e, c(r9).renditionSet || (c(r9).renditionSet = /* @__PURE__ */ new Set()); let s = c(t2).trackSet; s.add(r9); let n2 = s.size - 1; n2 in ft3.prototype || Object.defineProperty(ft3.prototype, n2, { get() { return [...c(this).trackSet][n2]; } }), queueMicrotask(() => { t2.dispatchEvent(new K2("addtrack", { track: r9 })); }); } function le3(e) { var s; let r9 = (s = c(e).media) == null ? void 0 : s.audioTracks; if (!r9) return; c(r9).trackSet.delete(e), queueMicrotask(() => { r9.dispatchEvent(new K2("removetrack", { track: e })); }); } function ri(e) { let r9 = c(e).media.audioTracks; !r9 || c(r9).changeRequested || (c(r9).changeRequested = true, queueMicrotask(() => { delete c(r9).changeRequested, r9.dispatchEvent(new Event("change")); })); } var et2; var it2; var rt3; var Rt3; var ce2; var ft3 = class extends EventTarget { constructor() { super(); u(this, Rt3); u(this, et2, void 0); u(this, it2, void 0); u(this, rt3, void 0); c(this).trackSet = /* @__PURE__ */ new Set(); } [Symbol.iterator]() { return i(this, Rt3, ce2).values(); } get length() { return i(this, Rt3, ce2).size; } getTrackById(t2) { var s; return (s = [...i(this, Rt3, ce2)].find((n2) => n2.id === t2)) != null ? s : null; } get onaddtrack() { return i(this, et2); } set onaddtrack(t2) { i(this, et2) && (this.removeEventListener("addtrack", i(this, et2)), h(this, et2, void 0)), typeof t2 == "function" && (h(this, et2, t2), this.addEventListener("addtrack", t2)); } get onremovetrack() { return i(this, it2); } set onremovetrack(t2) { i(this, it2) && (this.removeEventListener("removetrack", i(this, it2)), h(this, it2, void 0)), typeof t2 == "function" && (h(this, it2, t2), this.addEventListener("removetrack", t2)); } get onchange() { return i(this, rt3); } set onchange(t2) { i(this, rt3) && (this.removeEventListener("change", i(this, rt3)), h(this, rt3, void 0)), typeof t2 == "function" && (h(this, rt3, t2), this.addEventListener("change", t2)); } }; et2 = /* @__PURE__ */ new WeakMap(), it2 = /* @__PURE__ */ new WeakMap(), rt3 = /* @__PURE__ */ new WeakMap(), Rt3 = /* @__PURE__ */ new WeakSet(), ce2 = function() { return c(this).trackSet; }; var Ct3; var _t3 = class { constructor() { E2(this, "id"); E2(this, "kind"); E2(this, "label", ""); E2(this, "language", ""); E2(this, "sourceBuffer"); u(this, Ct3, false); } addRendition(r9, t2, s) { let n2 = new Ft2(); return n2.src = r9, n2.codec = t2, n2.bitrate = s, ti(this, n2), n2; } removeRendition(r9) { ei(r9); } get enabled() { return i(this, Ct3); } set enabled(r9) { i(this, Ct3) !== r9 && (h(this, Ct3, r9), ri(this)); } }; Ct3 = /* @__PURE__ */ new WeakMap(); var si2 = fe3(globalThis.HTMLMediaElement, "video"); var ni2 = fe3(globalThis.HTMLMediaElement, "audio"); function oi2(e) { if (!(e != null && e.prototype)) return e; let r9 = fe3(e, "video"); (!r9 || `${r9}`.includes("[native code]")) && Object.defineProperty(e.prototype, "videoTracks", { get() { return yi2(this); } }); let t2 = fe3(e, "audio"); (!t2 || `${t2}`.includes("[native code]")) && Object.defineProperty(e.prototype, "audioTracks", { get() { return Ai2(this); } }), "addVideoTrack" in e.prototype || (e.prototype.addVideoTrack = function(l2, f = "", d2 = "") { let T3 = new At3(); return T3.kind = l2, T3.label = f, T3.language = d2, de3(this, T3), T3; }), "removeVideoTrack" in e.prototype || (e.prototype.removeVideoTrack = ue2), "addAudioTrack" in e.prototype || (e.prototype.addAudioTrack = function(l2, f = "", d2 = "") { let T3 = new _t3(); return T3.kind = l2, T3.label = f, T3.language = d2, he3(this, T3), T3; }), "removeAudioTrack" in e.prototype || (e.prototype.removeAudioTrack = le3), "videoRenditions" in e.prototype || Object.defineProperty(e.prototype, "videoRenditions", { get() { return s(this); } }); let s = (l2) => { let f = c(l2).videoRenditions; return f || (f = new ht3(), c(f).media = l2, c(l2).videoRenditions = f), f; }; "audioRenditions" in e.prototype || Object.defineProperty(e.prototype, "audioRenditions", { get() { return n2(this); } }); let n2 = (l2) => { let f = c(l2).audioRenditions; return f || (f = new lt3(), c(f).media = l2, c(l2).audioRenditions = f), f; }; return e; } function fe3(e, r9) { var t2; if (e != null && e.prototype) return (t2 = Object.getOwnPropertyDescriptor(e.prototype, `${r9}Tracks`)) == null ? void 0 : t2.get; } function yi2(e) { var t2; let r9 = c(e).videoTracks; if (!r9 && (r9 = new ct3(), c(e).videoTracks = r9, si2)) { let s = si2.call((t2 = e.nativeEl) != null ? t2 : e); for (let n2 of s) de3(e, n2); s.addEventListener("change", () => { r9.dispatchEvent(new Event("change")); }), s.addEventListener("addtrack", (n2) => { if ([...r9].some((l2) => l2 instanceof At3)) { for (let l2 of s) ue2(l2); return; } de3(e, n2.track); }), s.addEventListener("removetrack", (n2) => { ue2(n2.track); }); } return r9; } function Ai2(e) { var t2; let r9 = c(e).audioTracks; if (!r9 && (r9 = new ft3(), c(e).audioTracks = r9, ni2)) { let s = ni2.call((t2 = e.nativeEl) != null ? t2 : e); for (let n2 of s) he3(e, n2); s.addEventListener("change", () => { r9.dispatchEvent(new Event("change")); }), s.addEventListener("addtrack", (n2) => { if ([...r9].some((l2) => l2 instanceof _t3)) { for (let l2 of s) le3(l2); return; } he3(e, n2.track); }), s.addEventListener("removetrack", (n2) => { le3(n2.track); }); } return r9; } ve3.push("castchange", "entercast", "leavecast"); var o = { BEACON_COLLECTION_DOMAIN: "beacon-collection-domain", CUSTOM_DOMAIN: "custom-domain", DEBUG: "debug", DISABLE_TRACKING: "disable-tracking", DISABLE_COOKIES: "disable-cookies", DRM_TOKEN: "drm-token", PLAYBACK_TOKEN: "playback-token", ENV_KEY: "env-key", MAX_RESOLUTION: "max-resolution", MIN_RESOLUTION: "min-resolution", RENDITION_ORDER: "rendition-order", PROGRAM_START_TIME: "program-start-time", PROGRAM_END_TIME: "program-end-time", ASSET_START_TIME: "asset-start-time", ASSET_END_TIME: "asset-end-time", METADATA_URL: "metadata-url", PLAYBACK_ID: "playback-id", PLAYER_SOFTWARE_NAME: "player-software-name", PLAYER_SOFTWARE_VERSION: "player-software-version", PREFER_CMCD: "prefer-cmcd", PREFER_PLAYBACK: "prefer-playback", START_TIME: "start-time", STREAM_TYPE: "stream-type", TARGET_LIVE_WINDOW: "target-live-window", LIVE_EDGE_OFFSET: "live-edge-offset", TYPE: "type" }; var Ui = Object.values(o); var Yi = Ie3(); var ji = "mux-video"; var M2; var Ot2; var Yt2; var Pt3; var jt2; var Wt2; var Ht3; var $t2; var zt2; var It3; var pe3; var _e3 = class extends Zt2 { constructor() { super(); u(this, It3); u(this, M2, void 0); u(this, Ot2, void 0); u(this, Yt2, void 0); u(this, Pt3, {}); u(this, jt2, {}); u(this, Wt2, void 0); u(this, Ht3, void 0); u(this, $t2, void 0); u(this, zt2, void 0); h(this, Yt2, Nr()); } static get observedAttributes() { var t2; return [...Ui, ...(t2 = Zt2.observedAttributes) != null ? t2 : []]; } get preferCmcd() { var t2; return (t2 = this.getAttribute(o.PREFER_CMCD)) != null ? t2 : void 0; } set preferCmcd(t2) { t2 !== this.preferCmcd && (t2 ? Ut2.includes(t2) ? this.setAttribute(o.PREFER_CMCD, t2) : console.warn(`Invalid value for preferCmcd. Must be one of ${Ut2.join()}`) : this.removeAttribute(o.PREFER_CMCD)); } get playerInitTime() { return i(this, Yt2); } get playerSoftwareName() { var t2; return (t2 = i(this, $t2)) != null ? t2 : ji; } set playerSoftwareName(t2) { h(this, $t2, t2); } get playerSoftwareVersion() { var t2; return (t2 = i(this, Ht3)) != null ? t2 : Yi; } set playerSoftwareVersion(t2) { h(this, Ht3, t2); } get _hls() { var t2; return (t2 = i(this, M2)) == null ? void 0 : t2.engine; } get mux() { var t2; return (t2 = this.nativeEl) == null ? void 0 : t2.mux; } get error() { var t2; return (t2 = Rt2(this.nativeEl)) != null ? t2 : null; } get errorTranslator() { return i(this, zt2); } set errorTranslator(t2) { h(this, zt2, t2); } get src() { return this.getAttribute("src"); } set src(t2) { t2 !== this.src && (t2 == null ? this.removeAttribute("src") : this.setAttribute("src", t2)); } get type() { var t2; return (t2 = this.getAttribute(o.TYPE)) != null ? t2 : void 0; } set type(t2) { t2 !== this.type && (t2 ? this.setAttribute(o.TYPE, t2) : this.removeAttribute(o.TYPE)); } get autoplay() { let t2 = this.getAttribute("autoplay"); return t2 === null ? false : t2 === "" ? true : t2; } set autoplay(t2) { let s = this.autoplay; t2 !== s && (t2 ? this.setAttribute("autoplay", typeof t2 == "string" ? t2 : "") : this.removeAttribute("autoplay")); } get preload() { let t2 = this.getAttribute("preload"); return t2 === "" ? "auto" : ["none", "metadata", "auto"].includes(t2) ? t2 : super.preload; } set preload(t2) { t2 != this.getAttribute("preload") && (["", "none", "metadata", "auto"].includes(t2) ? this.setAttribute("preload", t2) : this.removeAttribute("preload")); } get debug() { return this.getAttribute(o.DEBUG) != null; } set debug(t2) { t2 !== this.debug && (t2 ? this.setAttribute(o.DEBUG, "") : this.removeAttribute(o.DEBUG)); } get disableTracking() { return this.hasAttribute(o.DISABLE_TRACKING); } set disableTracking(t2) { t2 !== this.disableTracking && this.toggleAttribute(o.DISABLE_TRACKING, !!t2); } get disableCookies() { return this.hasAttribute(o.DISABLE_COOKIES); } set disableCookies(t2) { t2 !== this.disableCookies && (t2 ? this.setAttribute(o.DISABLE_COOKIES, "") : this.removeAttribute(o.DISABLE_COOKIES)); } get startTime() { let t2 = this.getAttribute(o.START_TIME); if (t2 == null) return; let s = +t2; return Number.isNaN(s) ? void 0 : s; } set startTime(t2) { t2 !== this.startTime && (t2 == null ? this.removeAttribute(o.START_TIME) : this.setAttribute(o.START_TIME, `${t2}`)); } get playbackId() { var t2; return this.hasAttribute(o.PLAYBACK_ID) ? this.getAttribute(o.PLAYBACK_ID) : (t2 = gt2(this.src)) != null ? t2 : void 0; } set playbackId(t2) { t2 !== this.playbackId && (t2 ? this.setAttribute(o.PLAYBACK_ID, t2) : this.removeAttribute(o.PLAYBACK_ID)); } get maxResolution() { var t2; return (t2 = this.getAttribute(o.MAX_RESOLUTION)) != null ? t2 : void 0; } set maxResolution(t2) { t2 !== this.maxResolution && (t2 ? this.setAttribute(o.MAX_RESOLUTION, t2) : this.removeAttribute(o.MAX_RESOLUTION)); } get minResolution() { var t2; return (t2 = this.getAttribute(o.MIN_RESOLUTION)) != null ? t2 : void 0; } set minResolution(t2) { t2 !== this.minResolution && (t2 ? this.setAttribute(o.MIN_RESOLUTION, t2) : this.removeAttribute(o.MIN_RESOLUTION)); } get renditionOrder() { var t2; return (t2 = this.getAttribute(o.RENDITION_ORDER)) != null ? t2 : void 0; } set renditionOrder(t2) { t2 !== this.renditionOrder && (t2 ? this.setAttribute(o.RENDITION_ORDER, t2) : this.removeAttribute(o.RENDITION_ORDER)); } get programStartTime() { let t2 = this.getAttribute(o.PROGRAM_START_TIME); if (t2 == null) return; let s = +t2; return Number.isNaN(s) ? void 0 : s; } set programStartTime(t2) { t2 == null ? this.removeAttribute(o.PROGRAM_START_TIME) : this.setAttribute(o.PROGRAM_START_TIME, `${t2}`); } get programEndTime() { let t2 = this.getAttribute(o.PROGRAM_END_TIME); if (t2 == null) return; let s = +t2; return Number.isNaN(s) ? void 0 : s; } set programEndTime(t2) { t2 == null ? this.removeAttribute(o.PROGRAM_END_TIME) : this.setAttribute(o.PROGRAM_END_TIME, `${t2}`); } get assetStartTime() { let t2 = this.getAttribute(o.ASSET_START_TIME); if (t2 == null) return; let s = +t2; return Number.isNaN(s) ? void 0 : s; } set assetStartTime(t2) { t2 == null ? this.removeAttribute(o.ASSET_START_TIME) : this.setAttribute(o.ASSET_START_TIME, `${t2}`); } get assetEndTime() { let t2 = this.getAttribute(o.ASSET_END_TIME); if (t2 == null) return; let s = +t2; return Number.isNaN(s) ? void 0 : s; } set assetEndTime(t2) { t2 == null ? this.removeAttribute(o.ASSET_END_TIME) : this.setAttribute(o.ASSET_END_TIME, `${t2}`); } get customDomain() { var t2; return (t2 = this.getAttribute(o.CUSTOM_DOMAIN)) != null ? t2 : void 0; } set customDomain(t2) { t2 !== this.customDomain && (t2 ? this.setAttribute(o.CUSTOM_DOMAIN, t2) : this.removeAttribute(o.CUSTOM_DOMAIN)); } get drmToken() { var t2; return (t2 = this.getAttribute(o.DRM_TOKEN)) != null ? t2 : void 0; } set drmToken(t2) { t2 !== this.drmToken && (t2 ? this.setAttribute(o.DRM_TOKEN, t2) : this.removeAttribute(o.DRM_TOKEN)); } get playbackToken() { var t2, s, n2, l2; if (this.hasAttribute(o.PLAYBACK_TOKEN)) return (t2 = this.getAttribute(o.PLAYBACK_TOKEN)) != null ? t2 : void 0; if (this.hasAttribute(o.PLAYBACK_ID)) { let [, f] = Y2((s = this.playbackId) != null ? s : ""); return (n2 = new URLSearchParams(f).get("token")) != null ? n2 : void 0; } if (this.src) return (l2 = new URLSearchParams(this.src).get("token")) != null ? l2 : void 0; } set playbackToken(t2) { t2 !== this.playbackToken && (t2 ? this.setAttribute(o.PLAYBACK_TOKEN, t2) : this.removeAttribute(o.PLAYBACK_TOKEN)); } get tokens() { let t2 = this.getAttribute(o.PLAYBACK_TOKEN), s = this.getAttribute(o.DRM_TOKEN); return { ...i(this, jt2), ...t2 != null ? { playback: t2 } : {}, ...s != null ? { drm: s } : {} }; } set tokens(t2) { h(this, jt2, t2 != null ? t2 : {}); } get ended() { return xt2(this.nativeEl, this._hls); } get envKey() { var t2; return (t2 = this.getAttribute(o.ENV_KEY)) != null ? t2 : void 0; } set envKey(t2) { t2 !== this.envKey && (t2 ? this.setAttribute(o.ENV_KEY, t2) : this.removeAttribute(o.ENV_KEY)); } get beaconCollectionDomain() { var t2; return (t2 = this.getAttribute(o.BEACON_COLLECTION_DOMAIN)) != null ? t2 : void 0; } set beaconCollectionDomain(t2) { t2 !== this.beaconCollectionDomain && (t2 ? this.setAttribute(o.BEACON_COLLECTION_DOMAIN, t2) : this.removeAttribute(o.BEACON_COLLECTION_DOMAIN)); } get streamType() { var t2; return (t2 = this.getAttribute(o.STREAM_TYPE)) != null ? t2 : Le2(this.nativeEl); } set streamType(t2) { t2 !== this.streamType && (t2 ? this.setAttribute(o.STREAM_TYPE, t2) : this.removeAttribute(o.STREAM_TYPE)); } get targetLiveWindow() { return this.hasAttribute(o.TARGET_LIVE_WINDOW) ? +this.getAttribute(o.TARGET_LIVE_WINDOW) : Ir(this.nativeEl); } set targetLiveWindow(t2) { t2 != this.targetLiveWindow && (t2 == null ? this.removeAttribute(o.TARGET_LIVE_WINDOW) : this.setAttribute(o.TARGET_LIVE_WINDOW, `${+t2}`)); } get liveEdgeStart() { var t2, s; if (this.hasAttribute(o.LIVE_EDGE_OFFSET)) { let { liveEdgeOffset: n2 } = this, l2 = (t2 = this.nativeEl.seekable.end(0)) != null ? t2 : 0, f = (s = this.nativeEl.seekable.start(0)) != null ? s : 0; return Math.max(f, l2 - n2); } return Ar2(this.nativeEl); } get liveEdgeOffset() { if (this.hasAttribute(o.LIVE_EDGE_OFFSET)) return +this.getAttribute(o.LIVE_EDGE_OFFSET); } set liveEdgeOffset(t2) { t2 != this.targetLiveWindow && (t2 == null ? this.removeAttribute(o.LIVE_EDGE_OFFSET) : this.setAttribute(o.LIVE_EDGE_OFFSET, `${+t2}`)); } get seekable() { return Fe2(this.nativeEl); } async addCuePoints(t2) { return xe(this.nativeEl, t2); } get activeCuePoint() { return ve2(this.nativeEl); } get cuePoints() { return et(this.nativeEl); } async addChapters(t2) { return _e2(this.nativeEl, t2); } get activeChapter() { return ke2(this.nativeEl); } get chapters() { return tt(this.nativeEl); } getStartDate() { return rt2(this.nativeEl, this._hls); } get currentPdt() { return nt3(this.nativeEl, this._hls); } get preferPlayback() { let t2 = this.getAttribute(o.PREFER_PLAYBACK); if (t2 === q2.MSE || t2 === q2.NATIVE) return t2; } set preferPlayback(t2) { t2 !== this.preferPlayback && (t2 === q2.MSE || t2 === q2.NATIVE ? this.setAttribute(o.PREFER_PLAYBACK, t2) : this.removeAttribute(o.PREFER_PLAYBACK)); } get metadata() { return { ...this.getAttributeNames().filter((s) => s.startsWith("metadata-") && ![o.METADATA_URL].includes(s)).reduce((s, n2) => { let l2 = this.getAttribute(n2); return l2 != null && (s[n2.replace(/^metadata-/, "").replace(/-/g, "_")] = l2), s; }, {}), ...i(this, Pt3) }; } set metadata(t2) { h(this, Pt3, t2 != null ? t2 : {}), this.mux && this.mux.emit("hb", i(this, Pt3)); } get _hlsConfig() { return i(this, Wt2); } set _hlsConfig(t2) { h(this, Wt2, t2); } load() { h(this, M2, Sr(this, this.nativeEl, i(this, M2))); } unload() { vt2(this.nativeEl, i(this, M2)), h(this, M2, void 0); } attributeChangedCallback(t2, s, n2) { var f, d2; switch (Zt2.observedAttributes.includes(t2) && !["src", "autoplay", "preload"].includes(t2) && super.attributeChangedCallback(t2, s, n2), t2) { case o.PLAYER_SOFTWARE_NAME: this.playerSoftwareName = n2 != null ? n2 : void 0; break; case o.PLAYER_SOFTWARE_VERSION: this.playerSoftwareVersion = n2 != null ? n2 : void 0; break; case "src": { let T3 = !!s, C4 = !!n2; !T3 && C4 ? A3(this, It3, pe3).call(this) : T3 && !C4 ? this.unload() : T3 && C4 && (this.unload(), A3(this, It3, pe3).call(this)); break; } case "autoplay": if (n2 === s) break; (f = i(this, M2)) == null || f.setAutoplay(this.autoplay); break; case "preload": if (n2 === s) break; (d2 = i(this, M2)) == null || d2.setPreload(n2); break; case o.PLAYBACK_ID: this.src = Lr2(this); break; case o.DEBUG: { let T3 = this.debug; this.mux && console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."), this._hls && (this._hls.config.debug = T3); break; } case o.METADATA_URL: n2 && fetch(n2).then((T3) => T3.json()).then((T3) => this.metadata = T3).catch(() => console.error(`Unable to load or parse metadata JSON from metadata-url ${n2}!`)); break; case o.STREAM_TYPE: (n2 == null || n2 !== s) && this.dispatchEvent(new CustomEvent("streamtypechange", { composed: true, bubbles: true })); break; case o.TARGET_LIVE_WINDOW: (n2 == null || n2 !== s) && this.dispatchEvent(new CustomEvent("targetlivewindowchange", { composed: true, bubbles: true, detail: this.targetLiveWindow })); break; default: break; } } connectedCallback() { var t2; (t2 = super.connectedCallback) == null || t2.call(this), this.nativeEl && this.src && !i(this, M2) && A3(this, It3, pe3).call(this); } disconnectedCallback() { this.unload(); } }; M2 = /* @__PURE__ */ new WeakMap(), Ot2 = /* @__PURE__ */ new WeakMap(), Yt2 = /* @__PURE__ */ new WeakMap(), Pt3 = /* @__PURE__ */ new WeakMap(), jt2 = /* @__PURE__ */ new WeakMap(), Wt2 = /* @__PURE__ */ new WeakMap(), Ht3 = /* @__PURE__ */ new WeakMap(), $t2 = /* @__PURE__ */ new WeakMap(), zt2 = /* @__PURE__ */ new WeakMap(), It3 = /* @__PURE__ */ new WeakSet(), pe3 = async function() { i(this, Ot2) || (await h(this, Ot2, Promise.resolve()), h(this, Ot2, null), this.load()); }; var Xt2; var Ut3 = class extends $e3(oi2(_e3)) { constructor() { super(...arguments); u(this, Xt2, void 0); } get muxCastCustomData() { return { mux: { playbackId: this.playbackId, minResolution: this.minResolution, maxResolution: this.maxResolution, renditionOrder: this.renditionOrder, customDomain: this.customDomain, tokens: { drm: this.drmToken }, envKey: this.envKey, metadata: this.metadata, disableCookies: this.disableCookies, disableTracking: this.disableTracking, beaconCollectionDomain: this.beaconCollectionDomain, startTime: this.startTime, preferCmcd: this.preferCmcd } }; } get castCustomData() { var t2; return (t2 = i(this, Xt2)) != null ? t2 : this.muxCastCustomData; } set castCustomData(t2) { h(this, Xt2, t2); } }; Xt2 = /* @__PURE__ */ new WeakMap(); Qt2.customElements.get("mux-video") || (Qt2.customElements.define("mux-video", Ut3), Qt2.MuxVideoElement = Ut3); var Cs = Ut3; // node_modules/media-chrome/dist/utils/template-parts.js var __accessCheck19 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet19 = (obj, member, getter) => { __accessCheck19(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd19 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet18 = (obj, member, value, setter) => { __accessCheck19(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _parts; var _processor; var _items; var _value; var _element; var _attributeName; var _namespaceURI; var _list; var list_get; var _parentNode; var _nodes; var ELEMENT = 1; var STRING2 = 0; var PART = 1; var defaultProcessor = { processCallback(instance, parts, state) { if (!state) return; for (const [expression, part] of parts) { if (expression in state) { const value = state[expression]; if (typeof value === "boolean" && part instanceof AttrPart && typeof part.element[part.attributeName] === "boolean") { part.booleanValue = value; } else if (typeof value === "function" && part instanceof AttrPart) { part.element[part.attributeName] = value; } else { part.value = value; } } } } }; var TemplateInstance = class extends GlobalThis.DocumentFragment { constructor(template18, state, processor2 = defaultProcessor) { var _a3; super(); __privateAdd19(this, _parts, void 0); __privateAdd19(this, _processor, void 0); this.append(template18.content.cloneNode(true)); __privateSet18(this, _parts, parse2(this)); __privateSet18(this, _processor, processor2); (_a3 = processor2.createCallback) == null ? void 0 : _a3.call(processor2, this, __privateGet19(this, _parts), state); processor2.processCallback(this, __privateGet19(this, _parts), state); } update(state) { __privateGet19(this, _processor).processCallback(this, __privateGet19(this, _parts), state); } }; _parts = /* @__PURE__ */ new WeakMap(); _processor = /* @__PURE__ */ new WeakMap(); var parse2 = (element, parts = []) => { let type, value; for (const attr of element.attributes || []) { if (attr.value.includes("{{")) { const list = new AttrPartList(); for ([type, value] of tokenize2(attr.value)) { if (!type) list.append(value); else { const part = new AttrPart(element, attr.name, attr.namespaceURI); list.append(part); parts.push([value, part]); } } attr.value = list.toString(); } } for (const node2 of element.childNodes) { if (node2.nodeType === ELEMENT && !(node2 instanceof HTMLTemplateElement)) { parse2(node2, parts); } else { const data = node2.data; if (node2.nodeType === ELEMENT || data.includes("{{")) { const items = []; if (data) { for ([type, value] of tokenize2(data)) if (!type) items.push(new Text(value)); else { const part = new ChildNodePart(element); items.push(part); parts.push([value, part]); } } else if (node2 instanceof HTMLTemplateElement) { const part = new InnerTemplatePart(element, node2); items.push(part); parts.push([part.expression, part]); } node2.replaceWith( ...items.flatMap((part) => part.replacementNodes || [part]) ); } } } return parts; }; var mem = {}; var tokenize2 = (text) => { let value = "", open = 0, tokens = mem[text], i3 = 0, c3; if (tokens) return tokens; else tokens = []; for (; c3 = text[i3]; i3++) { if (c3 === "{" && text[i3 + 1] === "{" && text[i3 - 1] !== "\\" && text[i3 + 2] && ++open == 1) { if (value) tokens.push([STRING2, value]); value = ""; i3++; } else if (c3 === "}" && text[i3 + 1] === "}" && text[i3 - 1] !== "\\" && !--open) { tokens.push([PART, value.trim()]); value = ""; i3++; } else value += c3 || ""; } if (value) tokens.push([STRING2, (open > 0 ? "{{" : "") + value]); return mem[text] = tokens; }; var FRAGMENT = 11; var Part2 = class { get value() { return ""; } set value(val) { } toString() { return this.value; } }; var attrPartToList = /* @__PURE__ */ new WeakMap(); var AttrPartList = class { constructor() { __privateAdd19(this, _items, []); } [Symbol.iterator]() { return __privateGet19(this, _items).values(); } get length() { return __privateGet19(this, _items).length; } item(index2) { return __privateGet19(this, _items)[index2]; } append(...items) { for (const item of items) { if (item instanceof AttrPart) { attrPartToList.set(item, this); } __privateGet19(this, _items).push(item); } } toString() { return __privateGet19(this, _items).join(""); } }; _items = /* @__PURE__ */ new WeakMap(); var AttrPart = class extends Part2 { constructor(element, attributeName, namespaceURI) { super(); __privateAdd19(this, _list); __privateAdd19(this, _value, ""); __privateAdd19(this, _element, void 0); __privateAdd19(this, _attributeName, void 0); __privateAdd19(this, _namespaceURI, void 0); __privateSet18(this, _element, element); __privateSet18(this, _attributeName, attributeName); __privateSet18(this, _namespaceURI, namespaceURI); } get attributeName() { return __privateGet19(this, _attributeName); } get attributeNamespace() { return __privateGet19(this, _namespaceURI); } get element() { return __privateGet19(this, _element); } get value() { return __privateGet19(this, _value); } set value(newValue) { if (__privateGet19(this, _value) === newValue) return; __privateSet18(this, _value, newValue); if (!__privateGet19(this, _list, list_get) || __privateGet19(this, _list, list_get).length === 1) { if (newValue == null) { __privateGet19(this, _element).removeAttributeNS( __privateGet19(this, _namespaceURI), __privateGet19(this, _attributeName) ); } else { __privateGet19(this, _element).setAttributeNS( __privateGet19(this, _namespaceURI), __privateGet19(this, _attributeName), newValue ); } } else { __privateGet19(this, _element).setAttributeNS( __privateGet19(this, _namespaceURI), __privateGet19(this, _attributeName), __privateGet19(this, _list, list_get).toString() ); } } get booleanValue() { return __privateGet19(this, _element).hasAttributeNS( __privateGet19(this, _namespaceURI), __privateGet19(this, _attributeName) ); } set booleanValue(value) { if (!__privateGet19(this, _list, list_get) || __privateGet19(this, _list, list_get).length === 1) this.value = value ? "" : null; else throw new DOMException("Value is not fully templatized"); } }; _value = /* @__PURE__ */ new WeakMap(); _element = /* @__PURE__ */ new WeakMap(); _attributeName = /* @__PURE__ */ new WeakMap(); _namespaceURI = /* @__PURE__ */ new WeakMap(); _list = /* @__PURE__ */ new WeakSet(); list_get = function() { return attrPartToList.get(this); }; var ChildNodePart = class extends Part2 { constructor(parentNode, nodes) { super(); __privateAdd19(this, _parentNode, void 0); __privateAdd19(this, _nodes, void 0); __privateSet18(this, _parentNode, parentNode); __privateSet18(this, _nodes, nodes ? [...nodes] : [new Text()]); } get replacementNodes() { return __privateGet19(this, _nodes); } get parentNode() { return __privateGet19(this, _parentNode); } get nextSibling() { return __privateGet19(this, _nodes)[__privateGet19(this, _nodes).length - 1].nextSibling; } get previousSibling() { return __privateGet19(this, _nodes)[0].previousSibling; } // FIXME: not sure why do we need string serialization here? Just because parent class has type DOMString? get value() { return __privateGet19(this, _nodes).map((node2) => node2.textContent).join(""); } set value(newValue) { this.replace(newValue); } replace(...nodes) { const normalisedNodes = nodes.flat().flatMap( (node2) => node2 == null ? [new Text()] : node2.forEach ? [...node2] : node2.nodeType === FRAGMENT ? [...node2.childNodes] : node2.nodeType ? [node2] : [new Text(node2)] ); if (!normalisedNodes.length) normalisedNodes.push(new Text()); __privateSet18(this, _nodes, swapdom( __privateGet19(this, _nodes)[0].parentNode, __privateGet19(this, _nodes), normalisedNodes, this.nextSibling )); } }; _parentNode = /* @__PURE__ */ new WeakMap(); _nodes = /* @__PURE__ */ new WeakMap(); var InnerTemplatePart = class extends ChildNodePart { constructor(parentNode, template18) { const directive = template18.getAttribute("directive") || template18.getAttribute("type"); let expression = template18.getAttribute("expression") || template18.getAttribute(directive) || ""; if (expression.startsWith("{{")) expression = expression.trim().slice(2, -2).trim(); super(parentNode); this.expression = expression; this.template = template18; this.directive = directive; } }; function swapdom(parent, a2, b2, end = null) { let i3 = 0, cur, next2, bi3, n2 = b2.length, m2 = a2.length; while (i3 < n2 && i3 < m2 && a2[i3] == b2[i3]) i3++; while (i3 < n2 && i3 < m2 && b2[n2 - 1] == a2[m2 - 1]) end = b2[--m2, --n2]; if (i3 == m2) while (i3 < n2) parent.insertBefore(b2[i3++], end); if (i3 == n2) while (i3 < m2) parent.removeChild(a2[i3++]); else { cur = a2[i3]; while (i3 < n2) { bi3 = b2[i3++], next2 = cur ? cur.nextSibling : end; if (cur == bi3) cur = next2; else if (i3 < n2 && b2[i3] == next2) parent.replaceChild(bi3, cur), cur = next2; else parent.insertBefore(bi3, cur); } while (cur != end) next2 = cur.nextSibling, parent.removeChild(cur), cur = next2; } return b2; } // node_modules/media-chrome/dist/utils/template-processor.js var pipeModifiers = { string: (value) => String(value) }; var PartialTemplate = class { constructor(template18) { this.template = template18; this.state = void 0; } }; var templates = /* @__PURE__ */ new WeakMap(); var templateInstances = /* @__PURE__ */ new WeakMap(); var Directives = { partial: (part, state) => { state[part.expression] = new PartialTemplate(part.template); }, if: (part, state) => { var _a3; if (evaluateExpression(part.expression, state)) { if (templates.get(part) !== part.template) { templates.set(part, part.template); const tpl = new TemplateInstance(part.template, state, processor); part.replace(tpl); templateInstances.set(part, tpl); } else { (_a3 = templateInstances.get(part)) == null ? void 0 : _a3.update(state); } } else { part.replace(""); templates.delete(part); templateInstances.delete(part); } } }; var DirectiveNames = Object.keys(Directives); var processor = { processCallback(instance, parts, state) { var _a3, _b; if (!state) return; for (const [expression, part] of parts) { if (part instanceof InnerTemplatePart) { if (!part.directive) { const directive = DirectiveNames.find( (n2) => part.template.hasAttribute(n2) ); if (directive) { part.directive = directive; part.expression = part.template.getAttribute(directive); } } (_a3 = Directives[part.directive]) == null ? void 0 : _a3.call(Directives, part, state); continue; } let value = evaluateExpression(expression, state); if (value instanceof PartialTemplate) { if (templates.get(part) !== value.template) { templates.set(part, value.template); value = new TemplateInstance(value.template, value.state, processor); part.value = value; templateInstances.set(part, value); } else { (_b = templateInstances.get(part)) == null ? void 0 : _b.update(value.state); } continue; } if (value) { if (part instanceof AttrPart) { if (part.attributeName.startsWith("aria-")) { value = String(value); } } if (part instanceof AttrPart) { if (typeof value === "boolean") { part.booleanValue = value; } else if (typeof value === "function") { part.element[part.attributeName] = value; } else { part.value = value; } } else { part.value = value; templates.delete(part); templateInstances.delete(part); } } else { if (part instanceof AttrPart) { part.value = void 0; } else { part.value = void 0; templates.delete(part); templateInstances.delete(part); } } } } }; var operators = { "!": (a2) => !a2, "!!": (a2) => !!a2, "==": (a2, b2) => a2 == b2, "!=": (a2, b2) => a2 != b2, ">": (a2, b2) => a2 > b2, ">=": (a2, b2) => a2 >= b2, "<": (a2, b2) => a2 < b2, "<=": (a2, b2) => a2 <= b2, "??": (a2, b2) => a2 != null ? a2 : b2, "|": (a2, b2) => { var _a3; return (_a3 = pipeModifiers[b2]) == null ? void 0 : _a3.call(pipeModifiers, a2); } }; function tokenizeExpression(expr) { return tokenize3(expr, { boolean: /true|false/, number: /-?\d+\.?\d*/, string: /(["'])((?:\\.|[^\\])*?)\1/, operator: /[!=><][=!]?|\?\?|\|/, ws: /\s+/, param: /[$a-z_][$\w]*/i }).filter(({ type }) => type !== "ws"); } function evaluateExpression(expr, state = {}) { var _a3, _b, _c, _d, _e5, _f, _g; const tokens = tokenizeExpression(expr); if (tokens.length === 0 || tokens.some(({ type }) => !type)) { return invalidExpression(expr); } if (((_a3 = tokens[0]) == null ? void 0 : _a3.token) === ">") { const partial = state[(_b = tokens[1]) == null ? void 0 : _b.token]; if (!partial) { return invalidExpression(expr); } const partialState = { ...state }; partial.state = partialState; const args = tokens.slice(2); for (let i3 = 0; i3 < args.length; i3 += 3) { const name = (_c = args[i3]) == null ? void 0 : _c.token; const operator = (_d = args[i3 + 1]) == null ? void 0 : _d.token; const value = (_e5 = args[i3 + 2]) == null ? void 0 : _e5.token; if (name && operator === "=") { partialState[name] = getParamValue(value, state); } } return partial; } if (tokens.length === 1) { if (!isValidParam(tokens[0])) { return invalidExpression(expr); } return getParamValue(tokens[0].token, state); } if (tokens.length === 2) { const operator = (_f = tokens[0]) == null ? void 0 : _f.token; const run = operators[operator]; if (!run || !isValidParam(tokens[1])) { return invalidExpression(expr); } const a2 = getParamValue(tokens[1].token, state); return run(a2); } if (tokens.length === 3) { const operator = (_g = tokens[1]) == null ? void 0 : _g.token; const run = operators[operator]; if (!run || !isValidParam(tokens[0]) || !isValidParam(tokens[2])) { return invalidExpression(expr); } const a2 = getParamValue(tokens[0].token, state); if (operator === "|") { return run(a2, tokens[2].token); } const b2 = getParamValue(tokens[2].token, state); return run(a2, b2); } } function invalidExpression(expr) { console.warn(`Warning: invalid expression \`${expr}\``); return false; } function isValidParam({ type }) { return ["number", "boolean", "string", "param"].includes(type); } function getParamValue(raw, state) { const firstChar = raw[0]; const lastChar = raw.slice(-1); if (raw === "true" || raw === "false") { return raw === "true"; } if (firstChar === lastChar && [`'`, `"`].includes(firstChar)) { return raw.slice(1, -1); } if (isNumericString(raw)) { return parseFloat(raw); } return state[raw]; } function tokenize3(str, parsers) { let len, match2, token2; const tokens = []; while (str) { token2 = null; len = str.length; for (const key in parsers) { match2 = parsers[key].exec(str); if (match2 && match2.index < len) { token2 = { token: match2[0], type: key, matches: match2.slice(1) }; len = match2.index; } } if (len) { tokens.push({ token: str.substr(0, len), type: void 0 }); } if (token2) { tokens.push(token2); } str = str.substr(len + (token2 ? token2.token.length : 0)); } return tokens; } // node_modules/media-chrome/dist/media-theme-element.js var __accessCheck20 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet20 = (obj, member, getter) => { __accessCheck20(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd20 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet19 = (obj, member, value, setter) => { __accessCheck20(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod7 = (obj, member, method) => { __accessCheck20(obj, member, "access private method"); return method; }; var _template; var _prevTemplate; var _prevTemplateId; var _upgradeProperty; var upgradeProperty_fn; var _updateTemplate; var updateTemplate_fn; var observedMediaAttributes = { mediatargetlivewindow: "targetlivewindow", mediastreamtype: "streamtype" }; var prependTemplate = Document2.createElement("template"); prependTemplate.innerHTML = /*html*/ ` <style> :host { display: inline-block; line-height: 0; /* Hide theme element until the breakpoints are available to avoid flicker. */ visibility: hidden; } media-controller { width: 100%; height: 100%; } media-captions-button:not([mediasubtitleslist]), media-captions-menu:not([mediasubtitleslist]), media-captions-menu-button:not([mediasubtitleslist]), media-audio-track-menu[mediaaudiotrackunavailable], media-audio-track-menu-button[mediaaudiotrackunavailable], media-rendition-menu[mediarenditionunavailable], media-rendition-menu-button[mediarenditionunavailable], media-volume-range[mediavolumeunavailable], media-airplay-button[mediaairplayunavailable], media-fullscreen-button[mediafullscreenunavailable], media-cast-button[mediacastunavailable], media-pip-button[mediapipunavailable] { display: none; } </style> `; var MediaThemeElement = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd20(this, _upgradeProperty); __privateAdd20(this, _updateTemplate); __privateAdd20(this, _template, void 0); __privateAdd20(this, _prevTemplate, void 0); __privateAdd20(this, _prevTemplateId, void 0); if (this.shadowRoot) { this.renderRoot = this.shadowRoot; } else { this.renderRoot = this.attachShadow({ mode: "open" }); this.createRenderer(); } const observer2 = new MutationObserver((mutationList) => { var _a3; if (this.mediaController && !((_a3 = this.mediaController) == null ? void 0 : _a3.breakpointsComputed)) return; if (mutationList.some((mutation) => { const target = mutation.target; if (target === this) return true; if (target.localName !== "media-controller") return false; if (observedMediaAttributes[mutation.attributeName]) return true; if (mutation.attributeName.startsWith("breakpoint")) return true; return false; })) { this.render(); } }); observer2.observe(this, { attributes: true }); observer2.observe(this.renderRoot, { attributes: true, subtree: true }); this.addEventListener( MediaStateChangeEvents.BREAKPOINTS_COMPUTED, this.render ); __privateMethod7(this, _upgradeProperty, upgradeProperty_fn).call(this, "template"); } /** @type {HTMLElement & { breakpointsComputed?: boolean }} */ get mediaController() { return this.renderRoot.querySelector("media-controller"); } get template() { var _a3; return (_a3 = __privateGet20(this, _template)) != null ? _a3 : this.constructor.template; } set template(element) { __privateSet19(this, _prevTemplateId, null); __privateSet19(this, _template, element); this.createRenderer(); } get props() { var _a3, _b, _c; const observedAttributes = [ ...Array.from((_b = (_a3 = this.mediaController) == null ? void 0 : _a3.attributes) != null ? _b : []).filter( ({ name }) => { return observedMediaAttributes[name] || name.startsWith("breakpoint"); } ), ...Array.from(this.attributes) ]; const props = {}; for (const attr of observedAttributes) { const name = (_c = observedMediaAttributes[attr.name]) != null ? _c : camelCase(attr.name); let { value } = attr; if (value != null) { if (isNumericString(value)) { value = parseFloat(value); } props[name] = value === "" ? true : value; } else { props[name] = false; } } return props; } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === "template" && oldValue != newValue) { __privateMethod7(this, _updateTemplate, updateTemplate_fn).call(this); } } connectedCallback() { __privateMethod7(this, _updateTemplate, updateTemplate_fn).call(this); } createRenderer() { if (this.template && this.template !== __privateGet20(this, _prevTemplate)) { __privateSet19(this, _prevTemplate, this.template); this.renderer = new TemplateInstance( this.template, this.props, // @ts-ignore this.constructor.processor ); this.renderRoot.textContent = ""; this.renderRoot.append( prependTemplate.content.cloneNode(true), this.renderer ); } } render() { var _a3; (_a3 = this.renderer) == null ? void 0 : _a3.update(this.props); if (this.renderRoot.isConnected) { const { style } = getOrInsertCSSRule(this.renderRoot, ":host"); if (style.visibility === "hidden") { style.removeProperty("visibility"); } } } }; _template = /* @__PURE__ */ new WeakMap(); _prevTemplate = /* @__PURE__ */ new WeakMap(); _prevTemplateId = /* @__PURE__ */ new WeakMap(); _upgradeProperty = /* @__PURE__ */ new WeakSet(); upgradeProperty_fn = function(prop) { if (Object.prototype.hasOwnProperty.call(this, prop)) { const value = this[prop]; delete this[prop]; this[prop] = value; } }; _updateTemplate = /* @__PURE__ */ new WeakSet(); updateTemplate_fn = function() { var _a3; const templateId = this.getAttribute("template"); if (!templateId || templateId === __privateGet20(this, _prevTemplateId)) return; const rootNode = this.getRootNode(); const template18 = (_a3 = rootNode == null ? void 0 : rootNode.getElementById) == null ? void 0 : _a3.call(rootNode, templateId); if (template18) { __privateSet19(this, _prevTemplateId, templateId); __privateSet19(this, _template, template18); this.createRenderer(); return; } if (isValidUrl(templateId)) { __privateSet19(this, _prevTemplateId, templateId); request(templateId).then((data) => { const template22 = Document2.createElement("template"); template22.innerHTML = data; __privateSet19(this, _template, template22); this.createRenderer(); }).catch(console.error); } }; MediaThemeElement.observedAttributes = ["template"]; MediaThemeElement.processor = processor; function isValidUrl(url) { if (!/^(\/|\.\/|https?:\/\/)/.test(url)) return false; const base = /^https?:\/\//.test(url) ? void 0 : location.origin; try { new URL(url, base); } catch (e) { return false; } return true; } async function request(resource) { const response = await fetch(resource); if (response.status !== 200) { throw new Error( `Failed to load resource: the server responded with a status of ${response.status}` ); } return response.text(); } if (!GlobalThis.customElements.get("media-theme")) { GlobalThis.customElements.define("media-theme", MediaThemeElement); } // node_modules/media-chrome/dist/utils/anchor-utils.js function computePosition({ anchor, floating, placement }) { const rects = getElementRects({ anchor, floating }); const { x: x2, y: y4 } = computeCoordsFromPlacement(rects, placement); return { x: x2, y: y4 }; } function getElementRects({ anchor, floating }) { return { anchor: getRectRelativeToOffsetParent(anchor, floating.offsetParent), floating: { x: 0, y: 0, width: floating.offsetWidth, height: floating.offsetHeight } }; } function getRectRelativeToOffsetParent(element, offsetParent) { var _a3; const rect = element.getBoundingClientRect(); const offsetRect = (_a3 = offsetParent == null ? void 0 : offsetParent.getBoundingClientRect()) != null ? _a3 : { x: 0, y: 0 }; return { x: rect.x - offsetRect.x, y: rect.y - offsetRect.y, width: rect.width, height: rect.height }; } function computeCoordsFromPlacement({ anchor, floating }, placement) { const alignmentAxis = getSideAxis(placement) === "x" ? "y" : "x"; const alignLength = alignmentAxis === "y" ? "height" : "width"; const side = getSide(placement); const commonX = anchor.x + anchor.width / 2 - floating.width / 2; const commonY = anchor.y + anchor.height / 2 - floating.height / 2; const commonAlign = anchor[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case "top": coords = { x: commonX, y: anchor.y - floating.height }; break; case "bottom": coords = { x: commonX, y: anchor.y + anchor.height }; break; case "right": coords = { x: anchor.x + anchor.width, y: commonY }; break; case "left": coords = { x: anchor.x - floating.width, y: commonY }; break; default: coords = { x: anchor.x, y: anchor.y }; } switch (placement.split("-")[1]) { case "start": coords[alignmentAxis] -= commonAlign; break; case "end": coords[alignmentAxis] += commonAlign; break; } return coords; } function getSide(placement) { return placement.split("-")[0]; } function getSideAxis(placement) { return ["top", "bottom"].includes(getSide(placement)) ? "y" : "x"; } // node_modules/media-chrome/dist/utils/events.js var InvokeEvent = class extends Event { /** * @param init - The event options. */ constructor({ action = "auto", relatedTarget, ...options2 }) { super("invoke", options2); this.action = action; this.relatedTarget = relatedTarget; } }; var ToggleEvent = class extends Event { /** * @param init - The event options. */ constructor({ newState, oldState, ...options2 }) { super("toggle", options2); this.newState = newState; this.oldState = oldState; } }; // node_modules/media-chrome/dist/menu/media-chrome-menu.js var __accessCheck21 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet21 = (obj, member, getter) => { __accessCheck21(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd21 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet20 = (obj, member, value, setter) => { __accessCheck21(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod8 = (obj, member, method) => { __accessCheck21(obj, member, "access private method"); return method; }; var _mediaController8; var _previouslyFocused2; var _invokerElement2; var _previousItems; var _mutationObserver; var _isPopover; var _cssRule; var _handleSlotChange; var handleSlotChange_fn; var _handleMenuItems; var _updateLayoutStyle; var updateLayoutStyle_fn; var _handleInvoke2; var handleInvoke_fn2; var _handleOpen2; var handleOpen_fn2; var _handleClosed2; var handleClosed_fn2; var _handleBoundsResize; var _handleMenuResize; var _positionMenu; var positionMenu_fn; var _resizeMenu; var resizeMenu_fn; var _handleClick; var handleClick_fn; var _backButtonElement; var backButtonElement_get; var _handleToggle; var handleToggle_fn; var _checkSubmenuHasExpanded; var checkSubmenuHasExpanded_fn; var _handleFocusOut2; var handleFocusOut_fn2; var _handleKeyDown2; var handleKeyDown_fn2; var _getItem; var getItem_fn; var _getTabItem; var getTabItem_fn; var _setTabItem; var setTabItem_fn; var _selectItem; var selectItem_fn; function createMenuItem({ type, text, value, checked }) { const item = Document2.createElement( "media-chrome-menu-item" ); item.type = type != null ? type : ""; item.part.add("menu-item"); if (type) item.part.add(type); item.value = value; item.checked = checked; const label = Document2.createElement("span"); label.textContent = text; item.append(label); return item; } function createIndicator(el, name) { let customIndicator = el.querySelector(`:scope > [slot="${name}"]`); if ((customIndicator == null ? void 0 : customIndicator.nodeName) == "SLOT") customIndicator = customIndicator.assignedElements({ flatten: true })[0]; if (customIndicator) { customIndicator = customIndicator.cloneNode(true); return customIndicator; } const fallbackIndicator = el.shadowRoot.querySelector( `[name="${name}"] > svg` ); if (fallbackIndicator) { return fallbackIndicator.cloneNode(true); } return ""; } var template13 = Document2.createElement("template"); template13.innerHTML = /*html*/ ` <style> :host { font: var(--media-font, var(--media-font-weight, normal) var(--media-font-size, 14px) / var(--media-text-content-height, var(--media-control-height, 24px)) var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif)); color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238))); background: var(--media-menu-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .8)))); border-radius: var(--media-menu-border-radius); border: var(--media-menu-border, none); display: var(--media-menu-display, inline-flex); transition: var(--media-menu-transition-in, visibility 0s, opacity .2s ease-out, transform .15s ease-out, left .2s ease-in-out, min-width .2s ease-in-out, min-height .2s ease-in-out ) !important; ${/* ^^Prevent transition override by media-container */ ""} visibility: var(--media-menu-visibility, visible); opacity: var(--media-menu-opacity, 1); max-height: var(--media-menu-max-height, var(--_menu-max-height, 300px)); transform: var(--media-menu-transform-in, translateY(0) scale(1)); flex-direction: column; ${/* Prevent overflowing a flex container */ ""} min-height: 0; position: relative; bottom: var(--_menu-bottom); box-sizing: border-box; } :host([hidden]) { transition: var(--media-menu-transition-out, visibility .15s ease-in, opacity .15s ease-in, transform .15s ease-in ) !important; visibility: var(--media-menu-hidden-visibility, hidden); opacity: var(--media-menu-hidden-opacity, 0); max-height: var(--media-menu-hidden-max-height, var(--media-menu-max-height, var(--_menu-max-height, 300px))); transform: var(--media-menu-transform-out, translateY(2px) scale(.99)); pointer-events: none; } :host([slot="submenu"]) { background: none; width: 100%; min-height: 100%; position: absolute; bottom: 0; right: -100%; } #container { display: flex; flex-direction: column; min-height: 0; transition: transform .2s ease-out; transform: translate(0, 0); } #container.has-expanded { transition: transform .2s ease-in; transform: translate(-100%, 0); } button { background: none; color: inherit; border: none; padding: 0; font: inherit; outline: inherit; display: inline-flex; align-items: center; } slot[name="header"][hidden] { display: none; } slot[name="header"] > *, slot[name="header"]::slotted(*) { padding: .4em .7em; border-bottom: 1px solid rgb(255 255 255 / .25); cursor: default; } slot[name="header"] > button[part~="back"], slot[name="header"]::slotted(button[part~="back"]) { cursor: pointer; } svg[part~="back"] { height: var(--media-menu-icon-height, var(--media-control-height, 24px)); fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238))); display: block; margin-right: .5ch; } slot:not([name]) { gap: var(--media-menu-gap); flex-direction: var(--media-menu-flex-direction, column); overflow: var(--media-menu-overflow, hidden auto); display: flex; min-height: 0; } :host([role="menu"]) slot:not([name]) { padding-block: .4em; } slot:not([name])::slotted([role="menu"]) { background: none; } media-chrome-menu-item > span { margin-right: .5ch; max-width: var(--media-menu-item-max-width); text-overflow: ellipsis; overflow: hidden; } </style> <style id="layout-row" media="width:0"> slot[name="header"] > *, slot[name="header"]::slotted(*) { padding: .4em .5em; } slot:not([name]) { gap: var(--media-menu-gap, .25em); flex-direction: var(--media-menu-flex-direction, row); padding-inline: .5em; } media-chrome-menu-item { padding: .3em .5em; } media-chrome-menu-item[aria-checked="true"] { background: var(--media-menu-item-checked-background, rgb(255 255 255 / .2)); } ${/* In row layout hide the checked indicator completely. */ ""} media-chrome-menu-item::part(checked-indicator) { display: var(--media-menu-item-checked-indicator-display, none); } </style> <div id="container"> <slot name="header" hidden> <button part="back button" aria-label="Back to previous menu"> <slot name="back-icon"> <svg aria-hidden="true" viewBox="0 0 20 24" part="back indicator"> <path d="m11.88 17.585.742-.669-4.2-4.665 4.2-4.666-.743-.669-4.803 5.335 4.803 5.334Z"/> </svg> </slot> <slot name="title"></slot> </button> </slot> <slot></slot> </div> <slot name="checked-indicator" hidden></slot> `; var Attributes12 = { STYLE: "style", HIDDEN: "hidden", DISABLED: "disabled", ANCHOR: "anchor" }; var MediaChromeMenu = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd21(this, _handleSlotChange); __privateAdd21(this, _updateLayoutStyle); __privateAdd21(this, _handleInvoke2); __privateAdd21(this, _handleOpen2); __privateAdd21(this, _handleClosed2); __privateAdd21(this, _positionMenu); __privateAdd21(this, _resizeMenu); __privateAdd21(this, _handleClick); __privateAdd21(this, _backButtonElement); __privateAdd21(this, _handleToggle); __privateAdd21(this, _checkSubmenuHasExpanded); __privateAdd21(this, _handleFocusOut2); __privateAdd21(this, _handleKeyDown2); __privateAdd21(this, _getItem); __privateAdd21(this, _getTabItem); __privateAdd21(this, _setTabItem); __privateAdd21(this, _selectItem); __privateAdd21(this, _mediaController8, null); __privateAdd21(this, _previouslyFocused2, null); __privateAdd21(this, _invokerElement2, null); __privateAdd21(this, _previousItems, /* @__PURE__ */ new Set()); __privateAdd21(this, _mutationObserver, void 0); __privateAdd21(this, _isPopover, false); __privateAdd21(this, _cssRule, null); __privateAdd21(this, _handleMenuItems, () => { const previousItems = __privateGet21(this, _previousItems); const currentItems = new Set(this.items); for (const item of previousItems) { if (!currentItems.has(item)) { this.dispatchEvent(new CustomEvent("removemenuitem", { detail: item })); } } for (const item of currentItems) { if (!previousItems.has(item)) { this.dispatchEvent(new CustomEvent("addmenuitem", { detail: item })); } } __privateSet20(this, _previousItems, currentItems); }); __privateAdd21(this, _handleBoundsResize, () => { __privateMethod8(this, _positionMenu, positionMenu_fn).call(this); __privateMethod8(this, _resizeMenu, resizeMenu_fn).call(this, false); }); __privateAdd21(this, _handleMenuResize, () => { __privateMethod8(this, _positionMenu, positionMenu_fn).call(this); }); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.nativeEl = this.constructor.template.content.cloneNode(true); this.shadowRoot.append(this.nativeEl); } this.container = this.shadowRoot.querySelector("#container"); this.defaultSlot = this.shadowRoot.querySelector( "slot:not([name])" ); this.shadowRoot.addEventListener("slotchange", this); __privateSet20(this, _mutationObserver, new MutationObserver(__privateGet21(this, _handleMenuItems))); __privateGet21(this, _mutationObserver).observe(this.defaultSlot, { childList: true }); } static get observedAttributes() { return [ Attributes12.DISABLED, Attributes12.HIDDEN, Attributes12.STYLE, Attributes12.ANCHOR, MediaStateReceiverAttributes.MEDIA_CONTROLLER ]; } static formatMenuItemText(text) { return text; } enable() { this.addEventListener("click", this); this.addEventListener("focusout", this); this.addEventListener("keydown", this); this.addEventListener("invoke", this); this.addEventListener("toggle", this); } disable() { this.removeEventListener("click", this); this.removeEventListener("focusout", this); this.removeEventListener("keyup", this); this.removeEventListener("invoke", this); this.removeEventListener("toggle", this); } handleEvent(event) { switch (event.type) { case "slotchange": __privateMethod8(this, _handleSlotChange, handleSlotChange_fn).call(this, event); break; case "invoke": __privateMethod8(this, _handleInvoke2, handleInvoke_fn2).call(this, event); break; case "click": __privateMethod8(this, _handleClick, handleClick_fn).call(this, event); break; case "toggle": __privateMethod8(this, _handleToggle, handleToggle_fn).call(this, event); break; case "focusout": __privateMethod8(this, _handleFocusOut2, handleFocusOut_fn2).call(this, event); break; case "keydown": __privateMethod8(this, _handleKeyDown2, handleKeyDown_fn2).call(this, event); break; } } connectedCallback() { var _a3, _b; __privateSet20(this, _cssRule, insertCSSRule(this.shadowRoot, ":host")); __privateMethod8(this, _updateLayoutStyle, updateLayoutStyle_fn).call(this); if (!this.hasAttribute("disabled")) { this.enable(); } if (!this.role) { this.role = "menu"; } __privateSet20(this, _mediaController8, getAttributeMediaController(this)); (_b = (_a3 = __privateGet21(this, _mediaController8)) == null ? void 0 : _a3.associateElement) == null ? void 0 : _b.call(_a3, this); if (!this.hidden) { observeResize(getBoundsElement(this), __privateGet21(this, _handleBoundsResize)); observeResize(this, __privateGet21(this, _handleMenuResize)); } } disconnectedCallback() { var _a3, _b; unobserveResize(getBoundsElement(this), __privateGet21(this, _handleBoundsResize)); unobserveResize(this, __privateGet21(this, _handleMenuResize)); this.disable(); (_b = (_a3 = __privateGet21(this, _mediaController8)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet20(this, _mediaController8, null); } attributeChangedCallback(attrName, oldValue, newValue) { var _a3, _b, _c, _d; if (attrName === Attributes12.HIDDEN && newValue !== oldValue) { if (!__privateGet21(this, _isPopover)) __privateSet20(this, _isPopover, true); if (this.hidden) { __privateMethod8(this, _handleClosed2, handleClosed_fn2).call(this); } else { __privateMethod8(this, _handleOpen2, handleOpen_fn2).call(this); } this.dispatchEvent( new ToggleEvent({ oldState: this.hidden ? "open" : "closed", newState: this.hidden ? "closed" : "open", bubbles: true }) ); } else if (attrName === MediaStateReceiverAttributes.MEDIA_CONTROLLER) { if (oldValue) { (_b = (_a3 = __privateGet21(this, _mediaController8)) == null ? void 0 : _a3.unassociateElement) == null ? void 0 : _b.call(_a3, this); __privateSet20(this, _mediaController8, null); } if (newValue && this.isConnected) { __privateSet20(this, _mediaController8, getAttributeMediaController(this)); (_d = (_c = __privateGet21(this, _mediaController8)) == null ? void 0 : _c.associateElement) == null ? void 0 : _d.call(_c, this); } } else if (attrName === Attributes12.DISABLED && newValue !== oldValue) { if (newValue == null) { this.enable(); } else { this.disable(); } } else if (attrName === Attributes12.STYLE && newValue !== oldValue) { __privateMethod8(this, _updateLayoutStyle, updateLayoutStyle_fn).call(this); } } formatMenuItemText(text, data) { return this.constructor.formatMenuItemText(text, data); } get anchor() { return this.getAttribute("anchor"); } set anchor(value) { this.setAttribute("anchor", `${value}`); } /** * Returns the anchor element when it is a floating menu. */ get anchorElement() { var _a3; if (this.anchor) { return (_a3 = getDocumentOrShadowRoot(this)) == null ? void 0 : _a3.querySelector(`#${this.anchor}`); } return null; } /** * Returns the menu items. */ get items() { return this.defaultSlot.assignedElements({ flatten: true }).filter(isMenuItem); } get radioGroupItems() { return this.items.filter((item) => item.role === "menuitemradio"); } get checkedItems() { return this.items.filter((item) => item.checked); } get value() { var _a3, _b; return (_b = (_a3 = this.checkedItems[0]) == null ? void 0 : _a3.value) != null ? _b : ""; } set value(newValue) { const item = this.items.find((item2) => item2.value === newValue); if (!item) return; __privateMethod8(this, _selectItem, selectItem_fn).call(this, item); } focus() { __privateSet20(this, _previouslyFocused2, getActiveElement()); if (this.items.length) { __privateMethod8(this, _setTabItem, setTabItem_fn).call(this, this.items[0]); this.items[0].focus(); return; } const focusable = this.querySelector( '[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]' ); focusable == null ? void 0 : focusable.focus(); } handleSelect(event) { var _a3; const item = __privateMethod8(this, _getItem, getItem_fn).call(this, event); if (!item) return; __privateMethod8(this, _selectItem, selectItem_fn).call(this, item, item.type === "checkbox"); if (__privateGet21(this, _invokerElement2) && !this.hidden) { (_a3 = __privateGet21(this, _previouslyFocused2)) == null ? void 0 : _a3.focus(); this.hidden = true; } } get keysUsed() { return [ "Enter", "Escape", "Tab", " ", "ArrowDown", "ArrowUp", "Home", "End" ]; } handleMove(event) { var _a3, _b; const { key } = event; const items = this.items; const currentItem = (_b = (_a3 = __privateMethod8(this, _getItem, getItem_fn).call(this, event)) != null ? _a3 : __privateMethod8(this, _getTabItem, getTabItem_fn).call(this)) != null ? _b : items[0]; const currentIndex = items.indexOf(currentItem); let index2 = Math.max(0, currentIndex); if (key === "ArrowDown") { index2++; } else if (key === "ArrowUp") { index2--; } else if (event.key === "Home") { index2 = 0; } else if (event.key === "End") { index2 = items.length - 1; } if (index2 < 0) { index2 = items.length - 1; } if (index2 > items.length - 1) { index2 = 0; } __privateMethod8(this, _setTabItem, setTabItem_fn).call(this, items[index2]); items[index2].focus(); } }; _mediaController8 = /* @__PURE__ */ new WeakMap(); _previouslyFocused2 = /* @__PURE__ */ new WeakMap(); _invokerElement2 = /* @__PURE__ */ new WeakMap(); _previousItems = /* @__PURE__ */ new WeakMap(); _mutationObserver = /* @__PURE__ */ new WeakMap(); _isPopover = /* @__PURE__ */ new WeakMap(); _cssRule = /* @__PURE__ */ new WeakMap(); _handleSlotChange = /* @__PURE__ */ new WeakSet(); handleSlotChange_fn = function(event) { const slot = event.target; for (const node2 of slot.assignedNodes({ flatten: true })) { if (node2.nodeType === 3 && node2.textContent.trim() === "") { node2.remove(); } } if (["header", "title"].includes(slot.name)) { const header = this.shadowRoot.querySelector( 'slot[name="header"]' ); header.hidden = slot.assignedNodes().length === 0; } if (!slot.name) { __privateGet21(this, _handleMenuItems).call(this); } }; _handleMenuItems = /* @__PURE__ */ new WeakMap(); _updateLayoutStyle = /* @__PURE__ */ new WeakSet(); updateLayoutStyle_fn = function() { var _a3; const layoutRowStyle = this.shadowRoot.querySelector("#layout-row"); const menuLayout = (_a3 = getComputedStyle(this).getPropertyValue("--media-menu-layout")) == null ? void 0 : _a3.trim(); layoutRowStyle.setAttribute("media", menuLayout === "row" ? "" : "width:0"); }; _handleInvoke2 = /* @__PURE__ */ new WeakSet(); handleInvoke_fn2 = function(event) { __privateSet20(this, _invokerElement2, event.relatedTarget); if (!containsComposedNode(this, event.relatedTarget)) { this.hidden = !this.hidden; } }; _handleOpen2 = /* @__PURE__ */ new WeakSet(); handleOpen_fn2 = function() { var _a3; (_a3 = __privateGet21(this, _invokerElement2)) == null ? void 0 : _a3.setAttribute("aria-expanded", "true"); this.addEventListener("transitionend", () => this.focus(), { once: true }); observeResize(getBoundsElement(this), __privateGet21(this, _handleBoundsResize)); observeResize(this, __privateGet21(this, _handleMenuResize)); }; _handleClosed2 = /* @__PURE__ */ new WeakSet(); handleClosed_fn2 = function() { var _a3; (_a3 = __privateGet21(this, _invokerElement2)) == null ? void 0 : _a3.setAttribute("aria-expanded", "false"); unobserveResize(getBoundsElement(this), __privateGet21(this, _handleBoundsResize)); unobserveResize(this, __privateGet21(this, _handleMenuResize)); }; _handleBoundsResize = /* @__PURE__ */ new WeakMap(); _handleMenuResize = /* @__PURE__ */ new WeakMap(); _positionMenu = /* @__PURE__ */ new WeakSet(); positionMenu_fn = function(menuWidth) { if (this.hasAttribute("mediacontroller") && !this.anchor) return; if (this.hidden || !this.anchorElement) return; const { x: x2, y: y4 } = computePosition({ anchor: this.anchorElement, floating: this, placement: "top-start" }); menuWidth != null ? menuWidth : menuWidth = this.offsetWidth; const bounds = getBoundsElement(this); const boundsRect = bounds.getBoundingClientRect(); const right = boundsRect.width - x2 - menuWidth; const bottom = boundsRect.height - y4 - this.offsetHeight; const { style } = __privateGet21(this, _cssRule); style.setProperty("position", "absolute"); style.setProperty("right", `${Math.max(0, right)}px`); style.setProperty("--_menu-bottom", `${bottom}px`); const computedStyle = getComputedStyle(this); const isBottomCalc = style.getPropertyValue("--_menu-bottom") === computedStyle.bottom; const realBottom = isBottomCalc ? bottom : parseFloat(computedStyle.bottom); const maxHeight = boundsRect.height - realBottom - parseFloat(computedStyle.marginBottom); this.style.setProperty("--_menu-max-height", `${maxHeight}px`); }; _resizeMenu = /* @__PURE__ */ new WeakSet(); resizeMenu_fn = function(animate) { const expandedMenuItem = this.querySelector( '[role="menuitem"][aria-haspopup][aria-expanded="true"]' ); const expandedSubmenu = expandedMenuItem == null ? void 0 : expandedMenuItem.querySelector( '[role="menu"]' ); const { style } = __privateGet21(this, _cssRule); if (!animate) { style.setProperty("--media-menu-transition-in", "none"); } if (expandedSubmenu) { const height = expandedSubmenu.offsetHeight; const width = Math.max( expandedSubmenu.offsetWidth, expandedMenuItem.offsetWidth ); this.style.setProperty("min-width", `${width}px`); this.style.setProperty("min-height", `${height}px`); __privateMethod8(this, _positionMenu, positionMenu_fn).call(this, width); } else { this.style.removeProperty("min-width"); this.style.removeProperty("min-height"); __privateMethod8(this, _positionMenu, positionMenu_fn).call(this); } style.removeProperty("--media-menu-transition-in"); }; _handleClick = /* @__PURE__ */ new WeakSet(); handleClick_fn = function(event) { var _a3; event.stopPropagation(); if (event.composedPath().includes(__privateGet21(this, _backButtonElement, backButtonElement_get))) { (_a3 = __privateGet21(this, _previouslyFocused2)) == null ? void 0 : _a3.focus(); this.hidden = true; return; } const item = __privateMethod8(this, _getItem, getItem_fn).call(this, event); if (!item || item.hasAttribute("disabled")) return; __privateMethod8(this, _setTabItem, setTabItem_fn).call(this, item); this.handleSelect(event); }; _backButtonElement = /* @__PURE__ */ new WeakSet(); backButtonElement_get = function() { var _a3; const headerSlot = this.shadowRoot.querySelector( 'slot[name="header"]' ); return (_a3 = headerSlot.assignedElements({ flatten: true })) == null ? void 0 : _a3.find( (el) => el.matches('button[part~="back"]') ); }; _handleToggle = /* @__PURE__ */ new WeakSet(); handleToggle_fn = function(event) { if (event.target === this) return; __privateMethod8(this, _checkSubmenuHasExpanded, checkSubmenuHasExpanded_fn).call(this); const menuItemsWithSubmenu = Array.from( this.querySelectorAll('[role="menuitem"][aria-haspopup]') ); for (const item of menuItemsWithSubmenu) { if (item.invokeTargetElement == event.target) continue; if (event.newState == "open" && item.getAttribute("aria-expanded") == "true" && !item.invokeTargetElement.hidden) { item.invokeTargetElement.dispatchEvent( new InvokeEvent({ relatedTarget: item }) ); } } for (const item of menuItemsWithSubmenu) { item.setAttribute("aria-expanded", `${!item.submenuElement.hidden}`); } __privateMethod8(this, _resizeMenu, resizeMenu_fn).call(this, true); }; _checkSubmenuHasExpanded = /* @__PURE__ */ new WeakSet(); checkSubmenuHasExpanded_fn = function() { const selector = '[role="menuitem"] > [role="menu"]:not([hidden])'; const expandedMenuItem = this.querySelector(selector); this.container.classList.toggle("has-expanded", !!expandedMenuItem); }; _handleFocusOut2 = /* @__PURE__ */ new WeakSet(); handleFocusOut_fn2 = function(event) { var _a3; if (!containsComposedNode(this, event.relatedTarget)) { if (__privateGet21(this, _isPopover)) { (_a3 = __privateGet21(this, _previouslyFocused2)) == null ? void 0 : _a3.focus(); } if (__privateGet21(this, _invokerElement2) && __privateGet21(this, _invokerElement2) !== event.relatedTarget && !this.hidden) { this.hidden = true; } } }; _handleKeyDown2 = /* @__PURE__ */ new WeakSet(); handleKeyDown_fn2 = function(event) { var _a3, _b, _c, _d, _e5; const { key, ctrlKey, altKey, metaKey } = event; if (ctrlKey || altKey || metaKey) { return; } if (!this.keysUsed.includes(key)) { return; } event.preventDefault(); event.stopPropagation(); if (key === "Tab") { if (__privateGet21(this, _isPopover)) { this.hidden = true; return; } if (event.shiftKey) { (_b = (_a3 = this.previousElementSibling) == null ? void 0 : _a3.focus) == null ? void 0 : _b.call(_a3); } else { (_d = (_c = this.nextElementSibling) == null ? void 0 : _c.focus) == null ? void 0 : _d.call(_c); } this.blur(); } else if (key === "Escape") { (_e5 = __privateGet21(this, _previouslyFocused2)) == null ? void 0 : _e5.focus(); if (__privateGet21(this, _isPopover)) { this.hidden = true; } } else if (key === "Enter" || key === " ") { this.handleSelect(event); } else { this.handleMove(event); } }; _getItem = /* @__PURE__ */ new WeakSet(); getItem_fn = function(event) { return event.composedPath().find((el) => { return ["menuitemradio", "menuitemcheckbox"].includes( el.role ); }); }; _getTabItem = /* @__PURE__ */ new WeakSet(); getTabItem_fn = function() { return this.items.find((item) => item.tabIndex === 0); }; _setTabItem = /* @__PURE__ */ new WeakSet(); setTabItem_fn = function(tabItem) { for (const item of this.items) { item.tabIndex = item === tabItem ? 0 : -1; } }; _selectItem = /* @__PURE__ */ new WeakSet(); selectItem_fn = function(item, toggle) { const oldCheckedItems = [...this.checkedItems]; if (item.type === "radio") { this.radioGroupItems.forEach((el) => el.checked = false); } if (toggle) { item.checked = !item.checked; } else { item.checked = true; } if (this.checkedItems.some((opt, i3) => opt != oldCheckedItems[i3])) { this.dispatchEvent( new Event("change", { bubbles: true, composed: true }) ); } }; MediaChromeMenu.template = template13; function isMenuItem(element) { return ["menuitem", "menuitemradio", "menuitemcheckbox"].includes( element == null ? void 0 : element.role ); } function getBoundsElement(host) { var _a3; return (_a3 = host.getAttribute("bounds") ? closestComposedNode(host, `#${host.getAttribute("bounds")}`) : getMediaController(host) || host.parentElement) != null ? _a3 : host; } if (!GlobalThis.customElements.get("media-chrome-menu")) { GlobalThis.customElements.define("media-chrome-menu", MediaChromeMenu); } // node_modules/media-chrome/dist/menu/media-chrome-menu-item.js var __accessCheck22 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet22 = (obj, member, getter) => { __accessCheck22(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd22 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet21 = (obj, member, value, setter) => { __accessCheck22(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod9 = (obj, member, method) => { __accessCheck22(obj, member, "access private method"); return method; }; var _dirty; var _ownerElement; var _handleSlotChange2; var handleSlotChange_fn2; var _submenuConnected; var submenuConnected_fn; var _submenuDisconnected; var submenuDisconnected_fn; var _handleMenuItem; var _handleKeyUp; var handleKeyUp_fn; var _handleKeyDown3; var handleKeyDown_fn3; var _reset; var reset_fn; var template14 = Document2.createElement("template"); template14.innerHTML = /*html*/ ` <style> :host { transition: var(--media-menu-item-transition, background .15s linear, opacity .2s ease-in-out ); outline: var(--media-menu-item-outline, 0); outline-offset: var(--media-menu-item-outline-offset, -1px); cursor: pointer; display: flex; align-items: center; align-self: stretch; justify-self: stretch; white-space: nowrap; white-space-collapse: collapse; text-wrap: nowrap; padding: .4em .8em .4em 1em; } :host(:focus-visible) { box-shadow: var(--media-menu-item-focus-shadow, inset 0 0 0 2px rgb(27 127 204 / .9)); outline: var(--media-menu-item-hover-outline, 0); outline-offset: var(--media-menu-item-hover-outline-offset, var(--media-menu-item-outline-offset, -1px)); } :host(:hover) { cursor: pointer; background: var(--media-menu-item-hover-background, rgb(92 92 102 / .5)); outline: var(--media-menu-item-hover-outline); outline-offset: var(--media-menu-item-hover-outline-offset, var(--media-menu-item-outline-offset, -1px)); } :host([aria-checked="true"]) { background: var(--media-menu-item-checked-background); } :host([hidden]) { display: none; } :host([disabled]) { pointer-events: none; color: rgba(255, 255, 255, .3); } slot:not([name]) { width: 100%; } slot:not([name="submenu"]) { display: inline-flex; align-items: center; transition: inherit; opacity: var(--media-menu-item-opacity, 1); } slot[name="description"] { justify-content: end; } slot[name="description"] > span { display: inline-block; margin-inline: 1em .2em; max-width: var(--media-menu-item-description-max-width, 100px); text-overflow: ellipsis; overflow: hidden; font-size: .8em; font-weight: 400; text-align: right; position: relative; top: .04em; } slot[name="checked-indicator"] { display: none; } :host(:is([role="menuitemradio"],[role="menuitemcheckbox"])) slot[name="checked-indicator"] { display: var(--media-menu-item-checked-indicator-display, inline-block); } ${/* For all slotted icons in prefix and suffix. */ ""} svg, img, ::slotted(svg), ::slotted(img) { height: var(--media-menu-item-icon-height, var(--media-control-height, 24px)); fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238))); display: block; } ${/* Only for indicator icons like checked-indicator or captions-indicator. */ ""} [part~="indicator"], ::slotted([part~="indicator"]) { fill: var(--media-menu-item-indicator-fill, var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)))); height: var(--media-menu-item-indicator-height, 1.25em); margin-right: .5ch; } [part~="checked-indicator"] { visibility: hidden; } :host([aria-checked="true"]) [part~="checked-indicator"] { visibility: visible; } </style> <slot name="checked-indicator"> <svg aria-hidden="true" viewBox="0 1 24 24" part="checked-indicator indicator"> <path d="m10 15.17 9.193-9.191 1.414 1.414-10.606 10.606-6.364-6.364 1.414-1.414 4.95 4.95Z"/> </svg> </slot> <slot name="prefix"></slot> <slot></slot> <slot name="description"></slot> <slot name="suffix"></slot> <slot name="submenu"></slot> `; var Attributes13 = { TYPE: "type", VALUE: "value", CHECKED: "checked", DISABLED: "disabled" }; var MediaChromeMenuItem = class extends GlobalThis.HTMLElement { constructor() { super(); __privateAdd22(this, _handleSlotChange2); __privateAdd22(this, _submenuConnected); __privateAdd22(this, _submenuDisconnected); __privateAdd22(this, _handleKeyUp); __privateAdd22(this, _handleKeyDown3); __privateAdd22(this, _reset); __privateAdd22(this, _dirty, false); __privateAdd22(this, _ownerElement, void 0); __privateAdd22(this, _handleMenuItem, () => { var _a3, _b; this.setAttribute("submenusize", `${this.submenuElement.items.length}`); const descriptionSlot = this.shadowRoot.querySelector( 'slot[name="description"]' ); const checkedItem = (_a3 = this.submenuElement.checkedItems) == null ? void 0 : _a3[0]; const description = (_b = checkedItem == null ? void 0 : checkedItem.dataset.description) != null ? _b : checkedItem == null ? void 0 : checkedItem.text; const span = Document2.createElement("span"); span.textContent = description != null ? description : ""; descriptionSlot.replaceChildren(span); }); if (!this.shadowRoot) { this.attachShadow({ mode: "open" }); this.shadowRoot.append(this.constructor.template.content.cloneNode(true)); } this.shadowRoot.addEventListener("slotchange", this); } static get observedAttributes() { return [ Attributes13.TYPE, Attributes13.DISABLED, Attributes13.CHECKED, Attributes13.VALUE ]; } enable() { if (!this.hasAttribute("tabindex")) { this.setAttribute("tabindex", "-1"); } if (isCheckable(this) && !this.hasAttribute("aria-checked")) { this.setAttribute("aria-checked", "false"); } this.addEventListener("click", this); this.addEventListener("keydown", this); } disable() { this.removeAttribute("tabindex"); this.removeEventListener("click", this); this.removeEventListener("keydown", this); this.removeEventListener("keyup", this); } handleEvent(event) { switch (event.type) { case "slotchange": __privateMethod9(this, _handleSlotChange2, handleSlotChange_fn2).call(this, event); break; case "click": this.handleClick(event); break; case "keydown": __privateMethod9(this, _handleKeyDown3, handleKeyDown_fn3).call(this, event); break; case "keyup": __privateMethod9(this, _handleKeyUp, handleKeyUp_fn).call(this, event); break; } } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === Attributes13.CHECKED && isCheckable(this) && !__privateGet22(this, _dirty)) { this.setAttribute("aria-checked", newValue != null ? "true" : "false"); } else if (attrName === Attributes13.TYPE && newValue !== oldValue) { this.role = "menuitem" + newValue; } else if (attrName === Attributes13.DISABLED && newValue !== oldValue) { if (newValue == null) { this.enable(); } else { this.disable(); } } } connectedCallback() { if (!this.hasAttribute(Attributes13.DISABLED)) { this.enable(); } this.role = "menuitem" + this.type; __privateSet21(this, _ownerElement, closestMenuItemsContainer(this, this.parentNode)); __privateMethod9(this, _reset, reset_fn).call(this); } disconnectedCallback() { this.disable(); __privateMethod9(this, _reset, reset_fn).call(this); __privateSet21(this, _ownerElement, null); } get invokeTarget() { return this.getAttribute("invoketarget"); } set invokeTarget(value) { this.setAttribute("invoketarget", `${value}`); } /** * Returns the element with the id specified by the `invoketarget` attribute * or the slotted submenu element. */ get invokeTargetElement() { var _a3; if (this.invokeTarget) { return (_a3 = getDocumentOrShadowRoot(this)) == null ? void 0 : _a3.querySelector( `#${this.invokeTarget}` ); } return this.submenuElement; } /** * Returns the slotted submenu element. */ get submenuElement() { const submenuSlot = this.shadowRoot.querySelector( 'slot[name="submenu"]' ); return submenuSlot.assignedElements({ flatten: true })[0]; } get type() { var _a3; return (_a3 = this.getAttribute(Attributes13.TYPE)) != null ? _a3 : ""; } set type(val) { this.setAttribute(Attributes13.TYPE, `${val}`); } get value() { var _a3; return (_a3 = this.getAttribute(Attributes13.VALUE)) != null ? _a3 : this.text; } set value(val) { this.setAttribute(Attributes13.VALUE, val); } get text() { var _a3; return ((_a3 = this.textContent) != null ? _a3 : "").trim(); } get checked() { if (!isCheckable(this)) return void 0; return this.getAttribute("aria-checked") === "true"; } set checked(value) { if (!isCheckable(this)) return; __privateSet21(this, _dirty, true); this.setAttribute("aria-checked", value ? "true" : "false"); if (value) { this.part.add("checked"); } else { this.part.remove("checked"); } } handleClick(event) { if (isCheckable(this)) return; if (this.invokeTargetElement && containsComposedNode(this, event.target)) { this.invokeTargetElement.dispatchEvent( new InvokeEvent({ relatedTarget: this }) ); } } get keysUsed() { return ["Enter", " "]; } }; _dirty = /* @__PURE__ */ new WeakMap(); _ownerElement = /* @__PURE__ */ new WeakMap(); _handleSlotChange2 = /* @__PURE__ */ new WeakSet(); handleSlotChange_fn2 = function(event) { const slot = event.target; const isDefaultSlot = !(slot == null ? void 0 : slot.name); if (isDefaultSlot) { for (const node2 of slot.assignedNodes({ flatten: true })) { if (node2 instanceof Text && node2.textContent.trim() === "") { node2.remove(); } } } if (slot.name === "submenu") { if (this.submenuElement) { __privateMethod9(this, _submenuConnected, submenuConnected_fn).call(this); } else { __privateMethod9(this, _submenuDisconnected, submenuDisconnected_fn).call(this); } } }; _submenuConnected = /* @__PURE__ */ new WeakSet(); submenuConnected_fn = async function() { this.setAttribute("aria-haspopup", "menu"); this.setAttribute("aria-expanded", `${!this.submenuElement.hidden}`); this.submenuElement.addEventListener("change", __privateGet22(this, _handleMenuItem)); this.submenuElement.addEventListener("addmenuitem", __privateGet22(this, _handleMenuItem)); this.submenuElement.addEventListener( "removemenuitem", __privateGet22(this, _handleMenuItem) ); __privateGet22(this, _handleMenuItem).call(this); }; _submenuDisconnected = /* @__PURE__ */ new WeakSet(); submenuDisconnected_fn = function() { this.removeAttribute("aria-haspopup"); this.removeAttribute("aria-expanded"); this.submenuElement.removeEventListener("change", __privateGet22(this, _handleMenuItem)); this.submenuElement.removeEventListener( "addmenuitem", __privateGet22(this, _handleMenuItem) ); this.submenuElement.removeEventListener( "removemenuitem", __privateGet22(this, _handleMenuItem) ); __privateGet22(this, _handleMenuItem).call(this); }; _handleMenuItem = /* @__PURE__ */ new WeakMap(); _handleKeyUp = /* @__PURE__ */ new WeakSet(); handleKeyUp_fn = function(event) { const { key } = event; if (!this.keysUsed.includes(key)) { this.removeEventListener("keyup", __privateMethod9(this, _handleKeyUp, handleKeyUp_fn)); return; } this.handleClick(event); }; _handleKeyDown3 = /* @__PURE__ */ new WeakSet(); handleKeyDown_fn3 = function(event) { const { metaKey, altKey, key } = event; if (metaKey || altKey || !this.keysUsed.includes(key)) { this.removeEventListener("keyup", __privateMethod9(this, _handleKeyUp, handleKeyUp_fn)); return; } this.addEventListener("keyup", __privateMethod9(this, _handleKeyUp, handleKeyUp_fn), { once: true }); }; _reset = /* @__PURE__ */ new WeakSet(); reset_fn = function() { var _a3; const items = (_a3 = __privateGet22(this, _ownerElement)) == null ? void 0 : _a3.radioGroupItems; if (!items) return; let checkedItem = items.filter((item) => item.getAttribute("aria-checked") === "true").pop(); if (!checkedItem) checkedItem = items[0]; for (const item of items) { item.setAttribute("aria-checked", "false"); } checkedItem == null ? void 0 : checkedItem.setAttribute("aria-checked", "true"); }; MediaChromeMenuItem.template = template14; function isCheckable(item) { return item.type === "radio" || item.type === "checkbox"; } function closestMenuItemsContainer(childNode, parentNode) { if (!childNode) return null; const { host } = childNode.getRootNode(); if (!parentNode && host) return closestMenuItemsContainer(childNode, host); if (parentNode == null ? void 0 : parentNode.items) return parentNode; return closestMenuItemsContainer(parentNode, parentNode == null ? void 0 : parentNode.parentNode); } if (!GlobalThis.customElements.get("media-chrome-menu-item")) { GlobalThis.customElements.define( "media-chrome-menu-item", MediaChromeMenuItem ); } // node_modules/media-chrome/dist/menu/media-settings-menu.js var template15 = Document2.createElement("template"); template15.innerHTML = MediaChromeMenu.template.innerHTML + /*html*/ ` <style> :host { background: var(--media-settings-menu-background, var(--media-menu-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .8))))); min-width: var(--media-settings-menu-min-width, 170px); border-radius: 2px 2px 0 0; overflow: hidden; } :host([role="menu"]) { ${/* Bottom fix setting menu items for animation when the height expands. */ ""} justify-content: end; } slot:not([name]) { justify-content: var(--media-settings-menu-justify-content); flex-direction: var(--media-settings-menu-flex-direction, column); overflow: visible; } #container.has-expanded { --media-settings-menu-item-opacity: 0; } </style> `; var MediaSettingsMenu = class extends MediaChromeMenu { /** * Returns the anchor element when it is a floating menu. */ get anchorElement() { if (this.anchor !== "auto") return super.anchorElement; return getMediaController(this).querySelector("media-settings-menu-button"); } }; MediaSettingsMenu.template = template15; if (!GlobalThis.customElements.get("media-settings-menu")) { GlobalThis.customElements.define("media-settings-menu", MediaSettingsMenu); } // node_modules/media-chrome/dist/menu/media-settings-menu-item.js var _a2; var template16 = Document2.createElement("template"); template16.innerHTML = MediaChromeMenuItem.template.innerHTML + /*html*/ ` <style> slot:not([name="submenu"]) { opacity: var(--media-settings-menu-item-opacity, var(--media-menu-item-opacity)); } :host([aria-expanded="true"]:hover) { background: transparent; } </style> `; if ((_a2 = template16.content) == null ? void 0 : _a2.querySelector) { template16.content.querySelector('slot[name="suffix"]').innerHTML = /*html*/ ` <svg aria-hidden="true" viewBox="0 0 20 24"> <path d="m8.12 17.585-.742-.669 4.2-4.665-4.2-4.666.743-.669 4.803 5.335-4.803 5.334Z"/> </svg> `; } var MediaSettingsMenuItem = class extends MediaChromeMenuItem { }; MediaSettingsMenuItem.template = template16; if (!GlobalThis.customElements.get("media-settings-menu-item")) { GlobalThis.customElements.define( "media-settings-menu-item", MediaSettingsMenuItem ); } // node_modules/media-chrome/dist/menu/media-chrome-menu-button.js var MediaChromeMenuButton = class extends MediaChromeButton { connectedCallback() { super.connectedCallback(); if (this.invokeTargetElement) { this.setAttribute("aria-haspopup", "menu"); } } get invokeTarget() { return this.getAttribute("invoketarget"); } set invokeTarget(value) { this.setAttribute("invoketarget", `${value}`); } /** * Returns the element with the id specified by the `invoketarget` attribute. * @return {HTMLElement | null} */ get invokeTargetElement() { var _a3; if (this.invokeTarget) { return (_a3 = getDocumentOrShadowRoot(this)) == null ? void 0 : _a3.querySelector( `#${this.invokeTarget}` ); } return null; } handleClick() { var _a3; (_a3 = this.invokeTargetElement) == null ? void 0 : _a3.dispatchEvent( new InvokeEvent({ relatedTarget: this }) ); } }; if (!GlobalThis.customElements.get("media-chrome-menu-button")) { GlobalThis.customElements.define( "media-chrome-menu-button", MediaChromeMenuButton ); } // node_modules/media-chrome/dist/menu/media-settings-menu-button.js var slotTemplate12 = Document2.createElement("template"); slotTemplate12.innerHTML = /*html*/ ` <style> :host([aria-expanded="true"]) slot[name=tooltip] { display: none; } </style> <slot name="icon"> <svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M4.5 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"/> </svg> </slot> `; var MediaSettingsMenuButton = class extends MediaChromeMenuButton { static get observedAttributes() { return [...super.observedAttributes, "target"]; } constructor() { super({ slotTemplate: slotTemplate12, tooltipContent: tooltipLabels.SETTINGS }); } connectedCallback() { super.connectedCallback(); this.setAttribute("aria-label", nouns.SETTINGS()); } /** * Returns the element with the id specified by the `invoketarget` attribute. * @return {HTMLElement | null} */ get invokeTargetElement() { if (this.invokeTarget != void 0) return super.invokeTargetElement; return getMediaController(this).querySelector("media-settings-menu"); } }; if (!GlobalThis.customElements.get("media-settings-menu-button")) { GlobalThis.customElements.define( "media-settings-menu-button", MediaSettingsMenuButton ); } // node_modules/media-chrome/dist/menu/media-audio-track-menu.js var __accessCheck23 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet23 = (obj, member, getter) => { __accessCheck23(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd23 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet22 = (obj, member, value, setter) => { __accessCheck23(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod10 = (obj, member, method) => { __accessCheck23(obj, member, "access private method"); return method; }; var _audioTrackList; var _prevState; var _render; var render_fn; var _onChange; var onChange_fn; var MediaAudioTrackMenu = class extends MediaChromeMenu { constructor() { super(...arguments); __privateAdd23(this, _render); __privateAdd23(this, _onChange); __privateAdd23(this, _audioTrackList, []); __privateAdd23(this, _prevState, void 0); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_AUDIO_TRACK_LIST, MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED, MediaUIAttributes.MEDIA_AUDIO_TRACK_UNAVAILABLE ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED && oldValue !== newValue) { this.value = newValue; } else if (attrName === MediaUIAttributes.MEDIA_AUDIO_TRACK_LIST && oldValue !== newValue) { __privateSet22(this, _audioTrackList, parseAudioTrackList(newValue != null ? newValue : "")); __privateMethod10(this, _render, render_fn).call(this); } } connectedCallback() { super.connectedCallback(); this.addEventListener("change", __privateMethod10(this, _onChange, onChange_fn)); } disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener("change", __privateMethod10(this, _onChange, onChange_fn)); } /** * Returns the anchor element when it is a floating menu. */ get anchorElement() { var _a3; if (this.anchor !== "auto") return super.anchorElement; return (_a3 = getMediaController(this)) == null ? void 0 : _a3.querySelector( "media-audio-track-menu-button" ); } get mediaAudioTrackList() { return __privateGet23(this, _audioTrackList); } set mediaAudioTrackList(list) { __privateSet22(this, _audioTrackList, list); __privateMethod10(this, _render, render_fn).call(this); } /** * Get enabled audio track id. */ get mediaAudioTrackEnabled() { var _a3; return (_a3 = getStringAttr(this, MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED)) != null ? _a3 : ""; } set mediaAudioTrackEnabled(id) { setStringAttr(this, MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED, id); } }; _audioTrackList = /* @__PURE__ */ new WeakMap(); _prevState = /* @__PURE__ */ new WeakMap(); _render = /* @__PURE__ */ new WeakSet(); render_fn = function() { if (__privateGet23(this, _prevState) === JSON.stringify(this.mediaAudioTrackList)) return; __privateSet22(this, _prevState, JSON.stringify(this.mediaAudioTrackList)); const audioTrackList = this.mediaAudioTrackList; this.defaultSlot.textContent = ""; for (const audioTrack of audioTrackList) { const text = this.formatMenuItemText(audioTrack.label, audioTrack); const item = createMenuItem({ type: "radio", text, value: `${audioTrack.id}`, checked: audioTrack.enabled }); item.prepend(createIndicator(this, "checked-indicator")); this.defaultSlot.append(item); } }; _onChange = /* @__PURE__ */ new WeakSet(); onChange_fn = function() { if (this.value == null) return; const event = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_AUDIO_TRACK_REQUEST, { composed: true, bubbles: true, detail: this.value } ); this.dispatchEvent(event); }; if (!GlobalThis.customElements.get("media-audio-track-menu")) { GlobalThis.customElements.define( "media-audio-track-menu", MediaAudioTrackMenu ); } // node_modules/media-chrome/dist/menu/media-audio-track-menu-button.js var audioTrackIcon = ( /*html*/ `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M11 17H9.5V7H11v10Zm-3-3H6.5v-4H8v4Zm6-5h-1.5v6H14V9Zm3 7h-1.5V8H17v8Z"/> <path d="M22 12c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2s10 4.477 10 10Zm-2 0a8 8 0 1 0-16 0 8 8 0 0 0 16 0Z"/> </svg>` ); var slotTemplate13 = Document2.createElement("template"); slotTemplate13.innerHTML = /*html*/ ` <style> :host([aria-expanded="true"]) slot[name=tooltip] { display: none; } </style> <slot name="icon">${audioTrackIcon}</slot> `; var MediaAudioTrackMenuButton = class extends MediaChromeMenuButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED, MediaUIAttributes.MEDIA_AUDIO_TRACK_UNAVAILABLE ]; } constructor() { super({ slotTemplate: slotTemplate13, tooltipContent: tooltipLabels.AUDIO_TRACK_MENU }); } connectedCallback() { super.connectedCallback(); this.setAttribute("aria-label", nouns.AUDIO_TRACKS()); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); } /** * Returns the element with the id specified by the `invoketarget` attribute. * @return {HTMLElement | null} */ get invokeTargetElement() { var _a3; if (this.invokeTarget != void 0) return super.invokeTargetElement; return (_a3 = getMediaController(this)) == null ? void 0 : _a3.querySelector("media-audio-track-menu"); } /** * Get enabled audio track id. * @return {string} */ get mediaAudioTrackEnabled() { var _a3; return (_a3 = getStringAttr(this, MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED)) != null ? _a3 : ""; } set mediaAudioTrackEnabled(id) { setStringAttr(this, MediaUIAttributes.MEDIA_AUDIO_TRACK_ENABLED, id); } }; if (!GlobalThis.customElements.get("media-audio-track-menu-button")) { GlobalThis.customElements.define( "media-audio-track-menu-button", MediaAudioTrackMenuButton ); } // node_modules/media-chrome/dist/menu/media-captions-menu.js var __accessCheck24 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet24 = (obj, member, getter) => { __accessCheck24(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd24 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet23 = (obj, member, value, setter) => { __accessCheck24(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod11 = (obj, member, method) => { __accessCheck24(obj, member, "access private method"); return method; }; var _prevState2; var _render2; var render_fn2; var _onChange2; var onChange_fn2; var ccIcon = ( /*html*/ ` <svg aria-hidden="true" viewBox="0 0 26 24" part="captions-indicator indicator"> <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/> </svg>` ); var template17 = Document2.createElement("template"); template17.innerHTML = MediaChromeMenu.template.innerHTML + /*html*/ ` <slot name="captions-indicator" hidden>${ccIcon}</slot>`; var MediaCaptionsMenu = class extends MediaChromeMenu { constructor() { super(...arguments); __privateAdd24(this, _render2); __privateAdd24(this, _onChange2); __privateAdd24(this, _prevState2, void 0); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_SUBTITLES_LIST, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_SUBTITLES_LIST && oldValue !== newValue) { __privateMethod11(this, _render2, render_fn2).call(this); } else if (attrName === MediaUIAttributes.MEDIA_SUBTITLES_SHOWING && oldValue !== newValue) { this.value = newValue; } } connectedCallback() { super.connectedCallback(); this.addEventListener("change", __privateMethod11(this, _onChange2, onChange_fn2)); } disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener("change", __privateMethod11(this, _onChange2, onChange_fn2)); } /** * Returns the anchor element when it is a floating menu. */ get anchorElement() { if (this.anchor !== "auto") return super.anchorElement; return getMediaController(this).querySelector("media-captions-menu-button"); } /** * @type {Array<object>} An array of TextTrack-like objects. * Objects must have the properties: kind, language, and label. */ get mediaSubtitlesList() { return getSubtitlesListAttr2(this, MediaUIAttributes.MEDIA_SUBTITLES_LIST); } set mediaSubtitlesList(list) { setSubtitlesListAttr2(this, MediaUIAttributes.MEDIA_SUBTITLES_LIST, list); } /** * An array of TextTrack-like objects. * Objects must have the properties: kind, language, and label. */ get mediaSubtitlesShowing() { return getSubtitlesListAttr2( this, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ); } set mediaSubtitlesShowing(list) { setSubtitlesListAttr2(this, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING, list); } }; _prevState2 = /* @__PURE__ */ new WeakMap(); _render2 = /* @__PURE__ */ new WeakSet(); render_fn2 = function() { var _a3; if (__privateGet24(this, _prevState2) === JSON.stringify(this.mediaSubtitlesList)) return; __privateSet23(this, _prevState2, JSON.stringify(this.mediaSubtitlesList)); this.defaultSlot.textContent = ""; const isOff = !this.value; const item = createMenuItem({ type: "radio", text: this.formatMenuItemText("Off"), value: "off", checked: isOff }); item.prepend(createIndicator(this, "checked-indicator")); this.defaultSlot.append(item); const subtitlesList = this.mediaSubtitlesList; for (const subs of subtitlesList) { const item2 = createMenuItem({ type: "radio", text: this.formatMenuItemText(subs.label, subs), value: formatTextTrackObj(subs), checked: this.value == formatTextTrackObj(subs) }); item2.prepend(createIndicator(this, "checked-indicator")); const type = (_a3 = subs.kind) != null ? _a3 : "subs"; if (type === "captions") { item2.append(createIndicator(this, "captions-indicator")); } this.defaultSlot.append(item2); } }; _onChange2 = /* @__PURE__ */ new WeakSet(); onChange_fn2 = function() { const showingSubs = this.mediaSubtitlesShowing; const showingSubsStr = this.getAttribute( MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ); const localStateChange = this.value !== showingSubsStr; if ((showingSubs == null ? void 0 : showingSubs.length) && localStateChange) { this.dispatchEvent( new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_DISABLE_SUBTITLES_REQUEST, { composed: true, bubbles: true, detail: showingSubs } ) ); } if (!this.value || !localStateChange) return; const event = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_SHOW_SUBTITLES_REQUEST, { composed: true, bubbles: true, detail: this.value } ); this.dispatchEvent(event); }; MediaCaptionsMenu.template = template17; var getSubtitlesListAttr2 = (el, attrName) => { const attrVal = el.getAttribute(attrName); return attrVal ? parseTextTracksStr(attrVal) : []; }; var setSubtitlesListAttr2 = (el, attrName, list) => { if (!(list == null ? void 0 : list.length)) { el.removeAttribute(attrName); return; } const newValStr = stringifyTextTrackList(list); const oldVal = el.getAttribute(attrName); if (oldVal === newValStr) return; el.setAttribute(attrName, newValStr); }; if (!GlobalThis.customElements.get("media-captions-menu")) { GlobalThis.customElements.define("media-captions-menu", MediaCaptionsMenu); } // node_modules/media-chrome/dist/menu/media-captions-menu-button.js var __accessCheck25 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateAdd25 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet24 = (obj, member, value, setter) => { __accessCheck25(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var _captionsReady; var ccIconOn2 = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/> </svg>`; var ccIconOff2 = `<svg aria-hidden="true" viewBox="0 0 26 24"> <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/> </svg>`; var slotTemplate14 = Document2.createElement("template"); slotTemplate14.innerHTML = /*html*/ ` <style> :host([aria-checked="true"]) slot[name=off] { display: none !important; } ${/* Double negative, but safer if display doesn't equal 'block' */ ""} :host(:not([aria-checked="true"])) slot[name=on] { display: none !important; } :host([aria-expanded="true"]) slot[name=tooltip] { display: none; } </style> <slot name="icon"> <slot name="on">${ccIconOn2}</slot> <slot name="off">${ccIconOff2}</slot> </slot> `; var updateAriaChecked2 = (el) => { el.setAttribute("aria-checked", areSubsOn(el).toString()); }; var MediaCaptionsMenuButton = class extends MediaChromeMenuButton { constructor(options2 = {}) { super({ slotTemplate: slotTemplate14, tooltipContent: tooltipLabels.CAPTIONS, ...options2 }); __privateAdd25(this, _captionsReady, void 0); __privateSet24(this, _captionsReady, false); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_SUBTITLES_LIST, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ]; } connectedCallback() { super.connectedCallback(); this.setAttribute("aria-label", nouns.CLOSED_CAPTIONS()); updateAriaChecked2(this); } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_SUBTITLES_SHOWING) { updateAriaChecked2(this); } } /** * Returns the element with the id specified by the `invoketarget` attribute. * @return {HTMLElement | null} */ get invokeTargetElement() { var _a3; if (this.invokeTarget != void 0) return super.invokeTargetElement; return (_a3 = getMediaController(this)) == null ? void 0 : _a3.querySelector("media-captions-menu"); } /** * An array of TextTrack-like objects. * Objects must have the properties: kind, language, and label. */ get mediaSubtitlesList() { return getSubtitlesListAttr3(this, MediaUIAttributes.MEDIA_SUBTITLES_LIST); } set mediaSubtitlesList(list) { setSubtitlesListAttr3(this, MediaUIAttributes.MEDIA_SUBTITLES_LIST, list); } /** * An array of TextTrack-like objects. * Objects must have the properties: kind, language, and label. */ get mediaSubtitlesShowing() { return getSubtitlesListAttr3( this, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING ); } set mediaSubtitlesShowing(list) { setSubtitlesListAttr3(this, MediaUIAttributes.MEDIA_SUBTITLES_SHOWING, list); } }; _captionsReady = /* @__PURE__ */ new WeakMap(); var getSubtitlesListAttr3 = (el, attrName) => { const attrVal = el.getAttribute(attrName); return attrVal ? parseTextTracksStr(attrVal) : []; }; var setSubtitlesListAttr3 = (el, attrName, list) => { if (!(list == null ? void 0 : list.length)) { el.removeAttribute(attrName); return; } const newValStr = stringifyTextTrackList(list); const oldVal = el.getAttribute(attrName); if (oldVal === newValStr) return; el.setAttribute(attrName, newValStr); }; if (!GlobalThis.customElements.get("media-captions-menu-button")) { GlobalThis.customElements.define( "media-captions-menu-button", MediaCaptionsMenuButton ); } // node_modules/media-chrome/dist/menu/media-playback-rate-menu.js var __accessCheck26 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet25 = (obj, member, getter) => { __accessCheck26(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd26 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateMethod12 = (obj, member, method) => { __accessCheck26(obj, member, "access private method"); return method; }; var _rates2; var _render3; var render_fn3; var _onChange3; var onChange_fn3; var Attributes14 = { RATES: "rates" }; var MediaPlaybackRateMenu = class extends MediaChromeMenu { constructor() { super(); __privateAdd26(this, _render3); __privateAdd26(this, _onChange3); __privateAdd26(this, _rates2, new AttributeTokenList(this, Attributes14.RATES, { defaultValue: DEFAULT_RATES })); __privateMethod12(this, _render3, render_fn3).call(this); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_PLAYBACK_RATE, Attributes14.RATES ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_PLAYBACK_RATE && oldValue != newValue) { this.value = newValue; } else if (attrName === Attributes14.RATES && oldValue != newValue) { __privateGet25(this, _rates2).value = newValue; __privateMethod12(this, _render3, render_fn3).call(this); } } connectedCallback() { super.connectedCallback(); this.addEventListener("change", __privateMethod12(this, _onChange3, onChange_fn3)); } disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener("change", __privateMethod12(this, _onChange3, onChange_fn3)); } /** * Returns the anchor element when it is a floating menu. */ get anchorElement() { if (this.anchor !== "auto") return super.anchorElement; return getMediaController(this).querySelector( "media-playback-rate-menu-button" ); } /** * Will return a DOMTokenList. * Setting a value will accept an array of numbers. */ get rates() { return __privateGet25(this, _rates2); } set rates(value) { if (!value) { __privateGet25(this, _rates2).value = ""; } else if (Array.isArray(value)) { __privateGet25(this, _rates2).value = value.join(" "); } __privateMethod12(this, _render3, render_fn3).call(this); } /** * The current playback rate */ get mediaPlaybackRate() { return getNumericAttr( this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, DEFAULT_RATE ); } set mediaPlaybackRate(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, value); } }; _rates2 = /* @__PURE__ */ new WeakMap(); _render3 = /* @__PURE__ */ new WeakSet(); render_fn3 = function() { this.defaultSlot.textContent = ""; for (const rate of this.rates) { const item = createMenuItem({ type: "radio", text: this.formatMenuItemText(`${rate}x`, rate), value: rate, checked: this.mediaPlaybackRate == rate }); item.prepend(createIndicator(this, "checked-indicator")); this.defaultSlot.append(item); } }; _onChange3 = /* @__PURE__ */ new WeakSet(); onChange_fn3 = function() { if (!this.value) return; const event = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_PLAYBACK_RATE_REQUEST, { composed: true, bubbles: true, detail: this.value } ); this.dispatchEvent(event); }; if (!GlobalThis.customElements.get("media-playback-rate-menu")) { GlobalThis.customElements.define( "media-playback-rate-menu", MediaPlaybackRateMenu ); } // node_modules/media-chrome/dist/menu/media-playback-rate-menu-button.js var __accessCheck27 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet26 = (obj, member, getter) => { __accessCheck27(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd27 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var _rates3; var Attributes15 = { RATES: "rates" }; var DEFAULT_RATES2 = [1, 1.2, 1.5, 1.7, 2]; var DEFAULT_RATE2 = 1; var slotTemplate15 = Document2.createElement("template"); slotTemplate15.innerHTML = /*html*/ ` <style> :host { min-width: 5ch; padding: var(--media-button-padding, var(--media-control-padding, 10px 5px)); } :host([aria-expanded="true"]) slot[name=tooltip] { display: none; } </style> <slot name="icon"></slot> `; var MediaPlaybackRateMenuButton = class extends MediaChromeMenuButton { constructor(options2 = {}) { super({ slotTemplate: slotTemplate15, tooltipContent: tooltipLabels.PLAYBACK_RATE, ...options2 }); __privateAdd27(this, _rates3, new AttributeTokenList(this, Attributes15.RATES, { defaultValue: DEFAULT_RATES2 })); this.container = this.shadowRoot.querySelector('slot[name="icon"]'); this.container.innerHTML = `${DEFAULT_RATE2}x`; } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_PLAYBACK_RATE, Attributes15.RATES ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === Attributes15.RATES) { __privateGet26(this, _rates3).value = newValue; } if (attrName === MediaUIAttributes.MEDIA_PLAYBACK_RATE) { const newPlaybackRate = newValue ? +newValue : Number.NaN; const playbackRate = !Number.isNaN(newPlaybackRate) ? newPlaybackRate : DEFAULT_RATE2; this.container.innerHTML = `${playbackRate}x`; this.setAttribute("aria-label", nouns.PLAYBACK_RATE({ playbackRate })); } } /** * Returns the element with the id specified by the `invoketarget` attribute. */ get invokeTargetElement() { if (this.invokeTarget != void 0) return super.invokeTargetElement; return getMediaController(this).querySelector("media-playback-rate-menu"); } /** * Will return a DOMTokenList. * Setting a value will accept an array of numbers. */ get rates() { return __privateGet26(this, _rates3); } set rates(value) { if (!value) { __privateGet26(this, _rates3).value = ""; } else if (Array.isArray(value)) { __privateGet26(this, _rates3).value = value.join(" "); } } /** * The current playback rate */ get mediaPlaybackRate() { return getNumericAttr( this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, DEFAULT_RATE2 ); } set mediaPlaybackRate(value) { setNumericAttr(this, MediaUIAttributes.MEDIA_PLAYBACK_RATE, value); } }; _rates3 = /* @__PURE__ */ new WeakMap(); if (!GlobalThis.customElements.get("media-playback-rate-menu-button")) { GlobalThis.customElements.define( "media-playback-rate-menu-button", MediaPlaybackRateMenuButton ); } // node_modules/media-chrome/dist/menu/media-rendition-menu.js var __accessCheck28 = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet27 = (obj, member, getter) => { __accessCheck28(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd28 = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet25 = (obj, member, value, setter) => { __accessCheck28(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod13 = (obj, member, method) => { __accessCheck28(obj, member, "access private method"); return method; }; var _renditionList; var _prevState3; var _render4; var render_fn4; var _onChange4; var onChange_fn4; var MediaRenditionMenu = class extends MediaChromeMenu { constructor() { super(...arguments); __privateAdd28(this, _render4); __privateAdd28(this, _onChange4); __privateAdd28(this, _renditionList, []); __privateAdd28(this, _prevState3, {}); } static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_RENDITION_LIST, MediaUIAttributes.MEDIA_RENDITION_SELECTED, MediaUIAttributes.MEDIA_RENDITION_UNAVAILABLE, MediaUIAttributes.MEDIA_HEIGHT ]; } attributeChangedCallback(attrName, oldValue, newValue) { super.attributeChangedCallback(attrName, oldValue, newValue); if (attrName === MediaUIAttributes.MEDIA_RENDITION_SELECTED && oldValue !== newValue) { this.value = newValue != null ? newValue : "auto"; } else if (attrName === MediaUIAttributes.MEDIA_RENDITION_LIST && oldValue !== newValue) { __privateSet25(this, _renditionList, parseRenditionList(newValue)); __privateMethod13(this, _render4, render_fn4).call(this); } else if (attrName === MediaUIAttributes.MEDIA_HEIGHT && oldValue !== newValue) { __privateMethod13(this, _render4, render_fn4).call(this); } } connectedCallback() { super.connectedCallback(); this.addEventListener("change", __privateMethod13(this, _onChange4, onChange_fn4)); } disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener("change", __privateMethod13(this, _onChange4, onChange_fn4)); } /** * Returns the anchor element when it is a floating menu. */ get anchorElement() { if (this.anchor !== "auto") return super.anchorElement; return getMediaController(this).querySelector( "media-rendition-menu-button" ); } get mediaRenditionList() { return __privateGet27(this, _renditionList); } set mediaRenditionList(list) { __privateSet25(this, _renditionList, list); __privateMethod13(this, _render4, render_fn4).call(this); } /** * Get selected rendition id. */ get mediaRenditionSelected() { return getStringAttr(this, MediaUIAttributes.MEDIA_RENDITION_SELECTED); } set mediaRenditionSelected(id) { setStringAttr(this, MediaUIAttributes.MEDIA_RENDITION_SELECTED, id); } get mediaHeight() { return getNumericAttr(this, MediaUIAttributes.MEDIA_HEIGHT); } set mediaHeight(height) { setNumericAttr(this, MediaUIAttributes.MEDIA_HEIGHT, height); } }; _renditionList = /* @__PURE__ */ new WeakMap(); _prevState3 = /* @__PURE__ */ new WeakMap(); _render4 = /* @__PURE__ */ new WeakSet(); render_fn4 = function() { if (__privateGet27(this, _prevState3).mediaRenditionList === JSON.stringify(this.mediaRenditionList) && __privateGet27(this, _prevState3).mediaHeight === this.mediaHeight) return; __privateGet27(this, _prevState3).mediaRenditionList = JSON.stringify(this.mediaRenditionList); __privateGet27(this, _prevState3).mediaHeight = this.mediaHeight; const renditionList = this.mediaRenditionList.sort( (a2, b2) => b2.height - a2.height ); for (const rendition of renditionList) { rendition.selected = rendition.id === this.mediaRenditionSelected; } this.defaultSlot.textContent = ""; const isAuto = !this.mediaRenditionSelected; for (const rendition of renditionList) { const text = this.formatMenuItemText( `${Math.min(rendition.width, rendition.height)}p`, rendition ); const item2 = createMenuItem({ type: "radio", text, value: `${rendition.id}`, checked: rendition.selected && !isAuto }); item2.prepend(createIndicator(this, "checked-indicator")); this.defaultSlot.append(item2); } const item = createMenuItem({ type: "radio", text: this.formatMenuItemText("Auto"), value: "auto", checked: isAuto }); const autoDescription = this.mediaHeight > 0 ? `Auto (${this.mediaHeight}p)` : "Auto"; item.dataset.description = autoDescription; item.prepend(createIndicator(this, "checked-indicator")); this.defaultSlot.append(item); }; _onChange4 = /* @__PURE__ */ new WeakSet(); onChange_fn4 = function() { if (this.value == null) return; const event = new GlobalThis.CustomEvent( MediaUIEvents.MEDIA_RENDITION_REQUEST, { composed: true, bubbles: true, detail: this.value } ); this.dispatchEvent(event); }; if (!GlobalThis.customElements.get("media-rendition-menu")) { GlobalThis.customElements.define("media-rendition-menu", MediaRenditionMenu); } // node_modules/media-chrome/dist/menu/media-rendition-menu-button.js var renditionIcon = ( /*html*/ `<svg aria-hidden="true" viewBox="0 0 24 24"> <path d="M13.5 2.5h2v6h-2v-2h-11v-2h11v-2Zm4 2h4v2h-4v-2Zm-12 4h2v6h-2v-2h-3v-2h3v-2Zm4 2h12v2h-12v-2Zm1 4h2v6h-2v-2h-8v-2h8v-2Zm4 2h7v2h-7v-2Z" /> </svg>` ); var slotTemplate16 = Document2.createElement("template"); slotTemplate16.innerHTML = /*html*/ ` <style> :host([aria-expanded="true"]) slot[name=tooltip] { display: none; } </style> <slot name="icon">${renditionIcon}</slot> `; var MediaRenditionMenuButton = class extends MediaChromeMenuButton { static get observedAttributes() { return [ ...super.observedAttributes, MediaUIAttributes.MEDIA_RENDITION_SELECTED, MediaUIAttributes.MEDIA_RENDITION_UNAVAILABLE, MediaUIAttributes.MEDIA_HEIGHT ]; } constructor() { super({ slotTemplate: slotTemplate16, tooltipContent: tooltipLabels.RENDITIONS }); } connectedCallback() { super.connectedCallback(); this.setAttribute("aria-label", nouns.QUALITY()); } /** * Returns the element with the id specified by the `invoketarget` attribute. */ get invokeTargetElement() { if (this.invokeTarget != void 0) return super.invokeTargetElement; return getMediaController(this).querySelector("media-rendition-menu"); } /** * Get selected rendition id. */ get mediaRenditionSelected() { return getStringAttr(this, MediaUIAttributes.MEDIA_RENDITION_SELECTED); } set mediaRenditionSelected(id) { setStringAttr(this, MediaUIAttributes.MEDIA_RENDITION_SELECTED, id); } get mediaHeight() { return getNumericAttr(this, MediaUIAttributes.MEDIA_HEIGHT); } set mediaHeight(height) { setNumericAttr(this, MediaUIAttributes.MEDIA_HEIGHT, height); } }; if (!GlobalThis.customElements.get("media-rendition-menu-button")) { GlobalThis.customElements.define( "media-rendition-menu-button", MediaRenditionMenuButton ); } // node_modules/@mux/mux-player/dist/index.mjs var ke4 = (t2, a2, e) => { if (!a2.has(t2)) throw TypeError("Cannot " + e); }; var u2 = (t2, a2, e) => (ke4(t2, a2, "read from private field"), e ? e.call(t2) : a2.get(t2)); var b = (t2, a2, e) => { if (a2.has(t2)) throw TypeError("Cannot add the same private member more than once"); a2 instanceof WeakSet ? a2.add(t2) : a2.set(t2, e); }; var R3 = (t2, a2, e, i3) => (ke4(t2, a2, "write to private field"), i3 ? i3.call(t2, e) : a2.set(t2, e), e); var h2 = (t2, a2, e) => (ke4(t2, a2, "access private method"), e); var W4 = class { addEventListener() { } removeEventListener() { } dispatchEvent(a2) { return true; } }; if (typeof DocumentFragment == "undefined") { class t2 extends W4 { } globalThis.DocumentFragment = t2; } var X4 = class extends W4 { }; var Re3 = class extends W4 { }; var Gt3 = { get(t2) { }, define(t2, a2, e) { }, getName(t2) { return null; }, upgrade(t2) { }, whenDefined(t2) { return Promise.resolve(X4); } }; var J4; var Oe4 = class { constructor(a2, e = {}) { b(this, J4, void 0); R3(this, J4, e == null ? void 0 : e.detail); } get detail() { return u2(this, J4); } initCustomEvent() { } }; J4 = /* @__PURE__ */ new WeakMap(); function jt3(t2, a2) { return new X4(); } var lt4 = { document: { createElement: jt3 }, DocumentFragment, customElements: Gt3, CustomEvent: Oe4, EventTarget: W4, HTMLElement: X4, HTMLVideoElement: Re3 }; var ut4 = typeof window == "undefined" || typeof globalThis.customElements == "undefined"; var p = ut4 ? lt4 : globalThis; var C3 = ut4 ? lt4.document : globalThis.document; function mt3(t2) { let a2 = ""; return Object.entries(t2).forEach(([e, i3]) => { i3 != null && (a2 += `${le4(e)}: ${i3}; `); }), a2 ? a2.trim() : void 0; } function le4(t2) { return t2.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } function ue3(t2) { return t2.replace(/[-_]([a-z])/g, (a2, e) => e.toUpperCase()); } function T2(t2) { if (t2 == null) return; let a2 = +t2; return Number.isNaN(a2) ? void 0 : a2; } function xe2(t2) { let a2 = qt3(t2).toString(); return a2 ? "?" + a2 : ""; } function qt3(t2) { let a2 = {}; for (let e in t2) t2[e] != null && (a2[e] = t2[e]); return new URLSearchParams(a2); } var _e4 = (t2, a2) => !t2 || !a2 ? false : t2.contains(a2) ? true : _e4(t2, a2.getRootNode().host); var pt3 = "mux.com"; var zt3 = () => { try { return "3.1.0"; } catch { } return "UNKNOWN"; }; var Xt3 = zt3(); var ce3 = () => Xt3; var bt4 = (t2, { token: a2, customDomain: e = pt3, thumbnailTime: i3, programTime: r9 } = {}) => { var l2; let o2 = a2 == null ? i3 : void 0, { aud: d2 } = (l2 = Q2(a2)) != null ? l2 : {}; if (!(a2 && d2 !== "t")) return `https://image.${e}/${t2}/thumbnail.webp${xe2({ token: a2, time: o2, program_time: r9 })}`; }; var ht4 = (t2, { token: a2, customDomain: e = pt3, programStartTime: i3, programEndTime: r9 } = {}) => { var d2; let { aud: o2 } = (d2 = Q2(a2)) != null ? d2 : {}; if (!(a2 && o2 !== "s")) return `https://image.${e}/${t2}/storyboard.vtt${xe2({ token: a2, format: "webp", program_start_time: i3, program_end_time: r9 })}`; }; var Q4 = (t2) => { if (t2) { if ([D2.LIVE, D2.ON_DEMAND].includes(t2)) return t2; if (t2 != null && t2.includes("live")) return D2.LIVE; } }; var Jt3 = { crossorigin: "crossOrigin", playsinline: "playsInline" }; function gt3(t2) { var a2; return (a2 = Jt3[t2]) != null ? a2 : ue3(t2); } var H4; var K3; var v; var me2 = class { constructor(a2, e) { b(this, H4, void 0); b(this, K3, void 0); b(this, v, []); R3(this, H4, a2), R3(this, K3, e); } [Symbol.iterator]() { return u2(this, v).values(); } get length() { return u2(this, v).length; } get value() { var a2; return (a2 = u2(this, v).join(" ")) != null ? a2 : ""; } set value(a2) { var e; a2 !== this.value && (R3(this, v, []), this.add(...(e = a2 == null ? void 0 : a2.split(" ")) != null ? e : [])); } toString() { return this.value; } item(a2) { return u2(this, v)[a2]; } values() { return u2(this, v).values(); } keys() { return u2(this, v).keys(); } forEach(a2) { u2(this, v).forEach(a2); } add(...a2) { var e, i3; a2.forEach((r9) => { this.contains(r9) || u2(this, v).push(r9); }), !(this.value === "" && !((e = u2(this, H4)) != null && e.hasAttribute(`${u2(this, K3)}`))) && ((i3 = u2(this, H4)) == null || i3.setAttribute(`${u2(this, K3)}`, `${this.value}`)); } remove(...a2) { var e; a2.forEach((i3) => { u2(this, v).splice(u2(this, v).indexOf(i3), 1); }), (e = u2(this, H4)) == null || e.setAttribute(`${u2(this, K3)}`, `${this.value}`); } contains(a2) { return u2(this, v).includes(a2); } toggle(a2, e) { return typeof e != "undefined" ? e ? (this.add(a2), true) : (this.remove(a2), false) : this.contains(a2) ? (this.remove(a2), false) : (this.add(a2), true); } replace(a2, e) { this.remove(a2), this.add(e); } }; H4 = /* @__PURE__ */ new WeakMap(), K3 = /* @__PURE__ */ new WeakMap(), v = /* @__PURE__ */ new WeakMap(); var ft4 = `[mux-player ${ce3()}]`; function _2(...t2) { console.warn(ft4, ...t2); } function E3(...t2) { console.error(ft4, ...t2); } function Me4(t2) { var e; let a2 = (e = t2.message) != null ? e : ""; t2.context && (a2 += ` ${t2.context}`), t2.file && (a2 += ` ${E("Read more: ")} https://github.com/muxinc/elements/blob/main/errors/${t2.file}`), _2(a2); } var y2 = { AUTOPLAY: "autoplay", CROSSORIGIN: "crossorigin", LOOP: "loop", MUTED: "muted", PLAYSINLINE: "playsinline", PRELOAD: "preload" }; var U4 = { VOLUME: "volume", PLAYBACKRATE: "playbackrate", MUTED: "muted" }; var vt4 = Object.freeze({ length: 0, start(t2) { let a2 = t2 >>> 0; if (a2 >= this.length) throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${a2}) is greater than or equal to the maximum bound (${this.length}).`); return 0; }, end(t2) { let a2 = t2 >>> 0; if (a2 >= this.length) throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${a2}) is greater than or equal to the maximum bound (${this.length}).`); return 0; } }); var ta2 = ve3.filter((t2) => t2 !== "error"); var aa2 = Object.values(y2).filter((t2) => ![y2.PLAYSINLINE].includes(t2)); var ia2 = Object.values(U4); var Z3; var Se4 = class extends p.HTMLElement { constructor() { super(); b(this, Z3, /* @__PURE__ */ new WeakMap()); let e = (r9) => { for (let o2 of r9) o2.type === "childList" && (o2.removedNodes.forEach((d2) => { var l2; (l2 = u2(this, Z3).get(d2)) == null || l2.remove(); }), o2.addedNodes.forEach((d2) => { var c3; let l2 = d2; l2 != null && l2.slot || (c3 = this.media) == null || c3.append(Tt4(u2(this, Z3), d2)); })); }; new MutationObserver(e).observe(this, { childList: true, subtree: true }); } static get observedAttributes() { return [...aa2, ...ia2]; } init() { this.querySelectorAll(":scope > :not([slot])").forEach((e) => { var i3; (i3 = this.media) == null || i3.append(Tt4(u2(this, Z3), e)); }), ta2.forEach((e) => { var i3; (i3 = this.media) == null || i3.addEventListener(e, (r9) => { this.dispatchEvent(new Event(r9.type)); }); }); } attributeChangedCallback(e, i3, r9) { var o2, d2; switch (e) { case U4.MUTED: { this.media && (this.media.muted = r9 != null, this.media.defaultMuted = r9 != null); return; } case U4.VOLUME: { let l2 = (o2 = T2(r9)) != null ? o2 : 1; this.media && (this.media.volume = l2); return; } case U4.PLAYBACKRATE: { let l2 = (d2 = T2(r9)) != null ? d2 : 1; this.media && (this.media.playbackRate = l2, this.media.defaultPlaybackRate = l2); return; } } } play() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.play()) != null ? i3 : Promise.reject(); } pause() { var e; (e = this.media) == null || e.pause(); } load() { var e; (e = this.media) == null || e.load(); } requestCast(e) { var i3; return (i3 = this.media) == null ? void 0 : i3.requestCast(e); } get media() { var e; return (e = this.shadowRoot) == null ? void 0 : e.querySelector("mux-video"); } get audioTracks() { return this.media.audioTracks; } get videoTracks() { return this.media.videoTracks; } get audioRenditions() { return this.media.audioRenditions; } get videoRenditions() { return this.media.videoRenditions; } get paused() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.paused) != null ? i3 : true; } get duration() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.duration) != null ? i3 : NaN; } get ended() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.ended) != null ? i3 : false; } get buffered() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.buffered) != null ? i3 : vt4; } get seekable() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.seekable) != null ? i3 : vt4; } get readyState() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.readyState) != null ? i3 : 0; } get videoWidth() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.videoWidth) != null ? i3 : 0; } get videoHeight() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.videoHeight) != null ? i3 : 0; } get currentSrc() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.currentSrc) != null ? i3 : ""; } get currentTime() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.currentTime) != null ? i3 : 0; } set currentTime(e) { this.media && (this.media.currentTime = Number(e)); } get volume() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.volume) != null ? i3 : 1; } set volume(e) { this.media && (this.media.volume = Number(e)); } get playbackRate() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.playbackRate) != null ? i3 : 1; } set playbackRate(e) { this.media && (this.media.playbackRate = Number(e)); } get defaultPlaybackRate() { var e; return (e = T2(this.getAttribute(U4.PLAYBACKRATE))) != null ? e : 1; } set defaultPlaybackRate(e) { e != null ? this.setAttribute(U4.PLAYBACKRATE, `${e}`) : this.removeAttribute(U4.PLAYBACKRATE); } get crossOrigin() { return ee4(this, y2.CROSSORIGIN); } set crossOrigin(e) { this.setAttribute(y2.CROSSORIGIN, `${e}`); } get autoplay() { return ee4(this, y2.AUTOPLAY) != null; } set autoplay(e) { e ? this.setAttribute(y2.AUTOPLAY, typeof e == "string" ? e : "") : this.removeAttribute(y2.AUTOPLAY); } get loop() { return ee4(this, y2.LOOP) != null; } set loop(e) { e ? this.setAttribute(y2.LOOP, "") : this.removeAttribute(y2.LOOP); } get muted() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.muted) != null ? i3 : false; } set muted(e) { this.media && (this.media.muted = !!e); } get defaultMuted() { return ee4(this, y2.MUTED) != null; } set defaultMuted(e) { e ? this.setAttribute(y2.MUTED, "") : this.removeAttribute(y2.MUTED); } get playsInline() { return ee4(this, y2.PLAYSINLINE) != null; } set playsInline(e) { E3("playsInline is set to true by default and is not currently supported as a setter."); } get preload() { return this.media ? this.media.preload : this.getAttribute("preload"); } set preload(e) { ["", "none", "metadata", "auto"].includes(e) ? this.setAttribute(y2.PRELOAD, e) : this.removeAttribute(y2.PRELOAD); } }; Z3 = /* @__PURE__ */ new WeakMap(); function ee4(t2, a2) { return t2.media ? t2.media.getAttribute(a2) : t2.getAttribute(a2); } function Tt4(t2, a2) { let e = t2.get(a2); return e || (e = a2.cloneNode(), t2.set(a2, e)), e; } var Ne2 = Se4; var Et4 = `:host { --media-control-display: var(--controls); --media-loading-indicator-display: var(--loading-indicator); --media-dialog-display: var(--dialog); --media-play-button-display: var(--play-button); --media-live-button-display: var(--live-button); --media-seek-backward-button-display: var(--seek-backward-button); --media-seek-forward-button-display: var(--seek-forward-button); --media-mute-button-display: var(--mute-button); --media-captions-button-display: var(--captions-button); --media-captions-menu-button-display: var(--captions-menu-button, var(--media-captions-button-display)); --media-rendition-menu-button-display: var(--rendition-menu-button); --media-audio-track-menu-button-display: var(--audio-track-menu-button); --media-airplay-button-display: var(--airplay-button); --media-pip-button-display: var(--pip-button); --media-fullscreen-button-display: var(--fullscreen-button); --media-cast-button-display: var(--cast-button, var(--_cast-button-drm-display)); --media-playback-rate-button-display: var(--playback-rate-button); --media-playback-rate-menu-button-display: var(--playback-rate-menu-button); --media-volume-range-display: var(--volume-range); --media-time-range-display: var(--time-range); --media-time-display-display: var(--time-display); --media-duration-display-display: var(--duration-display); --media-title-display-display: var(--title-display); display: inline-block; width: 100%; line-height: 0; } /* Hide custom elements that are not defined yet */ :not(:defined) { display: none; } a { color: #fff; font-size: 0.9em; text-decoration: underline; } media-theme { width: 100%; height: 100%; direction: ltr; } media-poster-image { width: 100%; height: 100%; } media-poster-image:not([src]):not([placeholdersrc]) { display: none; } ::part(top), [part~='top'] { --media-control-display: var(--controls, var(--top-controls)); --media-play-button-display: var(--play-button, var(--top-play-button)); --media-live-button-display: var(--live-button, var(--top-live-button)); --media-seek-backward-button-display: var(--seek-backward-button, var(--top-seek-backward-button)); --media-seek-forward-button-display: var(--seek-forward-button, var(--top-seek-forward-button)); --media-mute-button-display: var(--mute-button, var(--top-mute-button)); --media-captions-button-display: var(--captions-button, var(--top-captions-button)); --media-captions-menu-button-display: var( --captions-menu-button, var(--media-captions-button-display, var(--top-captions-menu-button)) ); --media-rendition-menu-button-display: var(--rendition-menu-button, var(--top-rendition-menu-button)); --media-audio-track-menu-button-display: var(--audio-track-menu-button, var(--top-audio-track-menu-button)); --media-airplay-button-display: var(--airplay-button, var(--top-airplay-button)); --media-pip-button-display: var(--pip-button, var(--top-pip-button)); --media-fullscreen-button-display: var(--fullscreen-button, var(--top-fullscreen-button)); --media-cast-button-display: var(--cast-button, var(--top-cast-button, var(--_cast-button-drm-display))); --media-playback-rate-button-display: var(--playback-rate-button, var(--top-playback-rate-button)); --media-playback-rate-menu-button-display: var( --captions-menu-button, var(--media-playback-rate-button-display, var(--top-playback-rate-menu-button)) ); --media-volume-range-display: var(--volume-range, var(--top-volume-range)); --media-time-range-display: var(--time-range, var(--top-time-range)); --media-time-display-display: var(--time-display, var(--top-time-display)); --media-duration-display-display: var(--duration-display, var(--top-duration-display)); --media-title-display-display: var(--title-display, var(--top-title-display)); } ::part(center), [part~='center'] { --media-control-display: var(--controls, var(--center-controls)); --media-play-button-display: var(--play-button, var(--center-play-button)); --media-live-button-display: var(--live-button, var(--center-live-button)); --media-seek-backward-button-display: var(--seek-backward-button, var(--center-seek-backward-button)); --media-seek-forward-button-display: var(--seek-forward-button, var(--center-seek-forward-button)); --media-mute-button-display: var(--mute-button, var(--center-mute-button)); --media-captions-button-display: var(--captions-button, var(--center-captions-button)); --media-captions-menu-button-display: var( --captions-menu-button, var(--media-captions-button-display, var(--center-captions-menu-button)) ); --media-rendition-menu-button-display: var(--rendition-menu-button, var(--center-rendition-menu-button)); --media-audio-track-menu-button-display: var(--audio-track-menu-button, var(--center-audio-track-menu-button)); --media-airplay-button-display: var(--airplay-button, var(--center-airplay-button)); --media-pip-button-display: var(--pip-button, var(--center-pip-button)); --media-fullscreen-button-display: var(--fullscreen-button, var(--center-fullscreen-button)); --media-cast-button-display: var(--cast-button, var(--center-cast-button, var(--_cast-button-drm-display))); --media-playback-rate-button-display: var(--playback-rate-button, var(--center-playback-rate-button)); --media-playback-rate-menu-button-display: var( --playback-rate-menu-button, var(--media-playback-rate-button-display, var(--center-playback-rate-menu-button)) ); --media-volume-range-display: var(--volume-range, var(--center-volume-range)); --media-time-range-display: var(--time-range, var(--center-time-range)); --media-time-display-display: var(--time-display, var(--center-time-display)); --media-duration-display-display: var(--duration-display, var(--center-duration-display)); } ::part(bottom), [part~='bottom'] { --media-control-display: var(--controls, var(--bottom-controls)); --media-play-button-display: var(--play-button, var(--bottom-play-button)); --media-live-button-display: var(--live-button, var(--bottom-live-button)); --media-seek-backward-button-display: var(--seek-backward-button, var(--bottom-seek-backward-button)); --media-seek-forward-button-display: var(--seek-forward-button, var(--bottom-seek-forward-button)); --media-mute-button-display: var(--mute-button, var(--bottom-mute-button)); --media-captions-button-display: var(--captions-button, var(--bottom-captions-button)); --media-captions-menu-button-display: var( --captions-menu-button, var(--media-captions-button-display, var(--bottom-captions-menu-button)) ); --media-rendition-menu-button-display: var(--rendition-menu-button, var(--bottom-rendition-menu-button)); --media-audio-track-menu-button-display: var(--audio-track-menu-button, var(--bottom-audio-track-menu-button)); --media-airplay-button-display: var(--airplay-button, var(--bottom-airplay-button)); --media-pip-button-display: var(--pip-button, var(--bottom-pip-button)); --media-fullscreen-button-display: var(--fullscreen-button, var(--bottom-fullscreen-button)); --media-cast-button-display: var(--cast-button, var(--bottom-cast-button, var(--_cast-button-drm-display))); --media-playback-rate-button-display: var(--playback-rate-button, var(--bottom-playback-rate-button)); --media-playback-rate-menu-button-display: var( --playback-rate-menu-button, var(--media-playback-rate-button-display, var(--bottom-playback-rate-menu-button)) ); --media-volume-range-display: var(--volume-range, var(--bottom-volume-range)); --media-time-range-display: var(--time-range, var(--bottom-time-range)); --media-time-display-display: var(--time-display, var(--bottom-time-display)); --media-duration-display-display: var(--duration-display, var(--bottom-duration-display)); --media-title-display-display: var(--title-display, var(--bottom-title-display)); } :host([no-tooltips]) { --media-tooltip-display: none; } `; var Ct4 = ` :host { z-index: 100; display: var(--media-dialog-display, flex); justify-content: center; align-items: center; width: 100%; height: 100%; position: absolute; top: 0; left: 0; box-sizing: border-box; color: #fff; line-height: 18px; font-family: Arial, sans-serif; padding: var(--media-dialog-backdrop-padding, 0); background: var(--media-dialog-backdrop-background, linear-gradient(to bottom, rgba(20, 20, 30, 0.7) 50%, rgba(20, 20, 30, 0.9)) ); /* Needs to use !important to prevent overwrite of media-chrome */ transition: var(--media-dialog-transition-open, visibility .2s, opacity .2s) !important; transform: var(--media-dialog-transform-open, none) !important; visibility: visible !important; opacity: 1 !important; pointer-events: auto !important; } :host(:not([open])) { /* Needs to use !important to prevent overwrite of media-chrome */ transition: var(--media-dialog-transition-close, visibility .1s, opacity .1s) !important; transform: var(--media-dialog-transform-close, none) !important; visibility: hidden !important; opacity: 0 !important; pointer-events: none !important; } :focus-visible { box-shadow: 0 0 0 2px rgba(27, 127, 204, 0.9); } .dialog { position: relative; box-sizing: border-box; background: var(--media-dialog-background, none); padding: var(--media-dialog-padding, 10px); width: min(320px, 100%); word-wrap: break-word; max-height: 100%; overflow: auto; text-align: center; line-height: 1.4; } `; var kt4 = C3.createElement("template"); kt4.innerHTML = ` <style> ${Ct4} </style> <div class="dialog"> <slot></slot> </div> `; var I3 = class extends p.HTMLElement { constructor() { var a2; super(), this.attachShadow({ mode: "open" }), (a2 = this.shadowRoot) == null || a2.appendChild(this.constructor.template.content.cloneNode(true)); } show() { this.setAttribute("open", ""), this.dispatchEvent(new CustomEvent("open", { composed: true, bubbles: true })), At4(this); } close() { this.hasAttribute("open") && (this.removeAttribute("open"), this.dispatchEvent(new CustomEvent("close", { composed: true, bubbles: true })), oa2(this)); } attributeChangedCallback(a2, e, i3) { a2 === "open" && e !== i3 && (i3 != null ? this.show() : this.close()); } connectedCallback() { this.hasAttribute("role") || this.setAttribute("role", "dialog"), this.hasAttribute("open") && At4(this); } }; I3.styles = Ct4, I3.template = kt4, I3.observedAttributes = ["open"]; function At4(t2) { let a2 = new CustomEvent("initfocus", { composed: true, bubbles: true, cancelable: true }); if (t2.dispatchEvent(a2), a2.defaultPrevented) return; let e = t2.querySelector("[autofocus]:not([disabled])"); !e && t2.tabIndex >= 0 && (e = t2), e || (e = Rt4(t2.shadowRoot)), t2._previouslyFocusedElement = C3.activeElement, C3.activeElement instanceof HTMLElement && C3.activeElement.blur(), t2.addEventListener("transitionend", () => { e instanceof HTMLElement && e.focus({ preventScroll: true }); }, { once: true }); } function Rt4(t2) { let e = ["button", "input", "keygen", "select", "textarea"].map(function(r9) { return r9 + ":not([disabled])"; }); e.push('[tabindex]:not([disabled]):not([tabindex=""])'); let i3 = t2 == null ? void 0 : t2.querySelector(e.join(", ")); if (!i3 && "attachShadow" in Element.prototype) { let r9 = (t2 == null ? void 0 : t2.querySelectorAll("*")) || []; for (let o2 = 0; o2 < r9.length && !(r9[o2].tagName && r9[o2].shadowRoot && (i3 = Rt4(r9[o2].shadowRoot), i3)); o2++) ; } return i3; } function oa2(t2) { t2._previouslyFocusedElement instanceof HTMLElement && t2._previouslyFocusedElement.focus(); } p.customElements.get("media-dialog") || (p.customElements.define("media-dialog", I3), p.MediaDialog = I3); var we3 = I3; var Ot3 = C3.createElement("template"); Ot3.innerHTML = ` <style> ${we3.styles} .close { background: none; color: inherit; border: none; padding: 0; font: inherit; cursor: pointer; outline: inherit; width: 28px; height: 28px; position: absolute; top: 1rem; right: 1rem; } </style> <div class="dialog"> <slot></slot> </div> <slot name="close"> <button class="close" tabindex="0"> <svg fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /> </svg> </button> </slot> `; var te4 = class extends we3 { constructor() { var a2, e; super(), (e = (a2 = this.shadowRoot) == null ? void 0 : a2.querySelector(".close")) == null || e.addEventListener("click", () => { this.close(); }); } }; te4.template = Ot3; p.customElements.get("mxp-dialog") || (p.customElements.define("mxp-dialog", te4), p.MxpDialog = te4); var ae3 = /* @__PURE__ */ new WeakMap(); var Ie4 = class t { constructor(a2, e) { this.element = a2; this.type = e; this.element.addEventListener(this.type, this); let i3 = ae3.get(this.element); i3 && i3.set(this.type, this); } set(a2) { if (typeof a2 == "function") this.handleEvent = a2.bind(this.element); else if (typeof a2 == "object" && typeof a2.handleEvent == "function") this.handleEvent = a2.handleEvent.bind(a2); else { this.element.removeEventListener(this.type, this); let e = ae3.get(this.element); e && e.delete(this.type); } } static for(a2) { ae3.has(a2.element) || ae3.set(a2.element, /* @__PURE__ */ new Map()); let e = a2.attributeName.slice(2), i3 = ae3.get(a2.element); return i3 && i3.has(e) ? i3.get(e) : new t(a2.element, e); } }; function sa2(t2, a2) { return t2 instanceof AttrPart && t2.attributeName.startsWith("on") ? (Ie4.for(t2).set(a2), t2.element.removeAttributeNS(t2.attributeNamespace, t2.attributeName), true) : false; } function da2(t2, a2) { return a2 instanceof pe4 && t2 instanceof ChildNodePart ? (a2.renderInto(t2), true) : false; } function la2(t2, a2) { return a2 instanceof DocumentFragment && t2 instanceof ChildNodePart ? (a2.childNodes.length && t2.replace(...a2.childNodes), true) : false; } function ua2(t2, a2) { if (t2 instanceof AttrPart) { let e = t2.attributeNamespace, i3 = t2.element.getAttributeNS(e, t2.attributeName); return String(a2) !== i3 && (t2.value = String(a2)), true; } return t2.value = String(a2), true; } function ma2(t2, a2) { if (t2 instanceof AttrPart && a2 instanceof Element) { let e = t2.element; return e[t2.attributeName] !== a2 && (t2.element.removeAttributeNS(t2.attributeNamespace, t2.attributeName), e[t2.attributeName] = a2), true; } return false; } function ca2(t2, a2) { if (typeof a2 == "boolean" && t2 instanceof AttrPart) { let e = t2.attributeNamespace, i3 = t2.element.hasAttributeNS(e, t2.attributeName); return a2 !== i3 && (t2.booleanValue = a2), true; } return false; } function pa2(t2, a2) { return a2 === false && t2 instanceof ChildNodePart ? (t2.replace(""), true) : false; } function ba2(t2, a2) { ma2(t2, a2) || ca2(t2, a2) || sa2(t2, a2) || pa2(t2, a2) || da2(t2, a2) || la2(t2, a2) || ua2(t2, a2); } var Pe4 = /* @__PURE__ */ new Map(); var xt4 = /* @__PURE__ */ new WeakMap(); var _t4 = /* @__PURE__ */ new WeakMap(); var pe4 = class { constructor(a2, e, i3) { this.strings = a2; this.values = e; this.processor = i3; this.stringsKey = this.strings.join(""); } get template() { if (Pe4.has(this.stringsKey)) return Pe4.get(this.stringsKey); { let a2 = C3.createElement("template"), e = this.strings.length - 1; return a2.innerHTML = this.strings.reduce((i3, r9, o2) => i3 + r9 + (o2 < e ? `{{ ${o2} }}` : ""), ""), Pe4.set(this.stringsKey, a2), a2; } } renderInto(a2) { var r9; let e = this.template; if (xt4.get(a2) !== e) { xt4.set(a2, e); let o2 = new TemplateInstance(e, this.values, this.processor); _t4.set(a2, o2), a2 instanceof ChildNodePart ? a2.replace(...o2.children) : a2.appendChild(o2); return; } let i3 = _t4.get(a2); (r9 = i3 == null ? void 0 : i3.update) == null || r9.call(i3, this.values); } }; var ha2 = { processCallback(t2, a2, e) { var i3; if (e) { for (let [r9, o2] of a2) if (r9 in e) { let d2 = (i3 = e[r9]) != null ? i3 : ""; ba2(o2, d2); } } } }; function S2(t2, ...a2) { return new pe4(t2, a2, ha2); } function Lt3(t2, a2) { t2.renderInto(a2); } var ya2 = (t2) => { let { tokens: a2 } = t2; return a2.drm ? ":host { --_cast-button-drm-display: none; }" : ""; }; var St3 = (t2) => S2` <style> ${ya2(t2)} ${Et4} </style> ${Aa2(t2)} `; var va2 = (t2) => { let a2 = t2.hotKeys ? `${t2.hotKeys}` : ""; return Q4(t2.streamType) === "live" && (a2 += " noarrowleft noarrowright"), a2; }; var Ta2 = { TOP: "top", CENTER: "center", BOTTOM: "bottom", LAYER: "layer", MEDIA_LAYER: "media-layer", POSTER_LAYER: "poster-layer", VERTICAL_LAYER: "vertical-layer", CENTERED_LAYER: "centered-layer", GESTURE_LAYER: "gesture-layer", CONTROLLER_LAYER: "controller", BUTTON: "button", RANGE: "range", DISPLAY: "display", CONTROL_BAR: "control-bar", MENU_BUTTON: "menu-button", LISTBOX: "listbox", OPTION: "option", POSTER: "poster", LIVE: "live", PLAY: "play", PRE_PLAY: "pre-play", SEEK_BACKWARD: "seek-backward", SEEK_FORWARD: "seek-forward", MUTE: "mute", CAPTIONS: "captions", AIRPLAY: "airplay", PIP: "pip", FULLSCREEN: "fullscreen", CAST: "cast", PLAYBACK_RATE: "playback-rate", VOLUME: "volume", TIME: "time", TITLE: "title", AUDIO_TRACK: "audio-track", RENDITION: "rendition" }; var Ea2 = Object.values(Ta2).join(", "); var Aa2 = (t2) => { var a2, e, i3, r9, o2, d2, l2, c3, O3, j3, k3, A4, x2, Y4, g2, de5, q4, z3, Fe4, Ye4, We3, Ze4, Ge4, je3, qe2, ze3, Xe4, Je4, Qe4, et3, tt3, at3, it3, rt4, ot4, nt4, st3, dt5; return S2` <media-theme template="${t2.themeTemplate || false}" defaultstreamtype="${(a2 = t2.defaultStreamType) != null ? a2 : false}" hotkeys="${va2(t2) || false}" nohotkeys="${t2.noHotKeys || !t2.hasSrc || t2.isDialogOpen || false}" noautoseektolive="${!!((e = t2.streamType) != null && e.includes(D2.LIVE)) && t2.targetLiveWindow !== 0}" novolumepref="${t2.novolumepref || false}" disabled="${!t2.hasSrc || t2.isDialogOpen}" audio="${(i3 = t2.audio) != null ? i3 : false}" style="${(r9 = mt3({ "--media-primary-color": t2.primaryColor, "--media-secondary-color": t2.secondaryColor, "--media-accent-color": t2.accentColor })) != null ? r9 : false}" defaultsubtitles="${!t2.defaultHiddenCaptions}" forwardseekoffset="${(o2 = t2.forwardSeekOffset) != null ? o2 : false}" backwardseekoffset="${(d2 = t2.backwardSeekOffset) != null ? d2 : false}" playbackrates="${(l2 = t2.playbackRates) != null ? l2 : false}" defaultshowremainingtime="${(c3 = t2.defaultShowRemainingTime) != null ? c3 : false}" defaultduration="${(O3 = t2.defaultDuration) != null ? O3 : false}" hideduration="${(j3 = t2.hideDuration) != null ? j3 : false}" title="${(k3 = t2.title) != null ? k3 : false}" exportparts="${Ea2}" > <mux-video slot="media" target-live-window="${(A4 = t2.targetLiveWindow) != null ? A4 : false}" stream-type="${(x2 = Q4(t2.streamType)) != null ? x2 : false}" crossorigin="${(Y4 = t2.crossOrigin) != null ? Y4 : ""}" playsinline autoplay="${(g2 = t2.autoplay) != null ? g2 : false}" muted="${(de5 = t2.muted) != null ? de5 : false}" loop="${(q4 = t2.loop) != null ? q4 : false}" preload="${(z3 = t2.preload) != null ? z3 : false}" debug="${(Fe4 = t2.debug) != null ? Fe4 : false}" prefer-cmcd="${(Ye4 = t2.preferCmcd) != null ? Ye4 : false}" disable-tracking="${(We3 = t2.disableTracking) != null ? We3 : false}" disable-cookies="${(Ze4 = t2.disableCookies) != null ? Ze4 : false}" prefer-playback="${(Ge4 = t2.preferPlayback) != null ? Ge4 : false}" start-time="${t2.startTime != null ? t2.startTime : false}" beacon-collection-domain="${(je3 = t2.beaconCollectionDomain) != null ? je3 : false}" player-software-name="${(qe2 = t2.playerSoftwareName) != null ? qe2 : false}" player-software-version="${(ze3 = t2.playerSoftwareVersion) != null ? ze3 : false}" env-key="${(Xe4 = t2.envKey) != null ? Xe4 : false}" custom-domain="${(Je4 = t2.customDomain) != null ? Je4 : false}" src="${t2.src ? t2.src : t2.playbackId ? Lr2(t2) : false}" cast-src="${t2.src ? t2.src : t2.playbackId ? Lr2(t2) : false}" cast-receiver="${(Qe4 = t2.castReceiver) != null ? Qe4 : false}" drm-token="${(tt3 = (et3 = t2.tokens) == null ? void 0 : et3.drm) != null ? tt3 : false}" exportparts="video" > ${t2.storyboard ? S2`<track label="thumbnails" default kind="metadata" src="${t2.storyboard}" />` : S2``} </mux-video> <slot name="poster" slot="poster"> <media-poster-image part="poster" exportparts="poster, img" src="${t2.poster ? t2.poster : false}" placeholdersrc="${(at3 = t2.placeholder) != null ? at3 : false}" ></media-poster-image> </slot> <mxp-dialog no-auto-hide open="${(it3 = t2.isDialogOpen) != null ? it3 : false}" onclose="${t2.onCloseErrorDialog}" oninitfocus="${t2.onInitFocusDialog}" > ${(rt4 = t2.dialog) != null && rt4.title ? S2`<h3>${t2.dialog.title}</h3>` : S2``} <p> ${(ot4 = t2.dialog) == null ? void 0 : ot4.message} ${(nt4 = t2.dialog) != null && nt4.linkUrl ? S2`<a href="${t2.dialog.linkUrl}" target="_blank" rel="external noopener" aria-label="${(st3 = t2.dialog.linkText) != null ? st3 : ""} ${E("(opens in a new window)")}" >${(dt5 = t2.dialog.linkText) != null ? dt5 : t2.dialog.linkUrl}</a >` : S2``} </p> </mxp-dialog> </media-theme> `; }; var Pt4 = (t2) => t2.charAt(0).toUpperCase() + t2.slice(1); var Ca = (t2, a2 = false) => { var e, i3; if (t2.muxCode) { let r9 = Pt4((e = t2.errorCategory) != null ? e : "video"), o2 = H2((i3 = t2.errorCategory) != null ? i3 : C2.VIDEO); if (t2.muxCode === M.NETWORK_OFFLINE) return E("Your device appears to be offline", a2); if (t2.muxCode === M.NETWORK_TOKEN_EXPIRED) return E("{category} URL has expired", a2).format({ category: r9 }); if ([M.NETWORK_TOKEN_SUB_MISMATCH, M.NETWORK_TOKEN_AUD_MISMATCH, M.NETWORK_TOKEN_AUD_MISSING, M.NETWORK_TOKEN_MALFORMED].includes(t2.muxCode)) return E("{category} URL is formatted incorrectly", a2).format({ category: r9 }); if (t2.muxCode === M.NETWORK_TOKEN_MISSING) return E("Invalid {categoryName} URL", a2).format({ categoryName: o2 }); if (t2.muxCode === M.NETWORK_NOT_FOUND) return E("{category} does not exist", a2).format({ category: r9 }); if (t2.muxCode === M.NETWORK_NOT_READY) return E("{category} is not currently available", a2).format({ category: r9 }); } if (t2.code) { if (t2.code === T.MEDIA_ERR_NETWORK) return E("Network Error", a2); if (t2.code === T.MEDIA_ERR_DECODE) return E("Media Error", a2); if (t2.code === T.MEDIA_ERR_SRC_NOT_SUPPORTED) return E("Source Not Supported", a2); } return E("Error", a2); }; var ka2 = (t2, a2 = false) => { var e, i3; if (t2.muxCode) { let r9 = Pt4((e = t2.errorCategory) != null ? e : "video"), o2 = H2((i3 = t2.errorCategory) != null ? i3 : C2.VIDEO); return t2.muxCode === M.NETWORK_OFFLINE ? E("Check your internet connection and try reloading this video.", a2) : t2.muxCode === M.NETWORK_TOKEN_EXPIRED ? E("The video’s secured {tokenNamePrefix}-token has expired.", a2).format({ tokenNamePrefix: o2 }) : t2.muxCode === M.NETWORK_TOKEN_SUB_MISMATCH ? E("The video’s playback ID does not match the one encoded in the {tokenNamePrefix}-token.", a2).format({ tokenNamePrefix: o2 }) : t2.muxCode === M.NETWORK_TOKEN_MALFORMED ? E("{category} URL is formatted incorrectly", a2).format({ category: r9 }) : [M.NETWORK_TOKEN_AUD_MISMATCH, M.NETWORK_TOKEN_AUD_MISSING].includes(t2.muxCode) ? E("The {tokenNamePrefix}-token is formatted with incorrect information.", a2).format({ tokenNamePrefix: o2 }) : [M.NETWORK_TOKEN_MISSING, M.NETWORK_INVALID_URL].includes(t2.muxCode) ? E("The video URL or {tokenNamePrefix}-token are formatted with incorrect or incomplete information.", a2).format({ tokenNamePrefix: o2 }) : t2.muxCode === M.NETWORK_NOT_FOUND ? "" : t2.muxCode === M.NETWORK_NOT_READY ? E("The live stream or video file are not yet ready.", a2) : t2.message; } return t2.code && (t2.code === T.MEDIA_ERR_NETWORK || t2.code === T.MEDIA_ERR_DECODE || t2.code === T.MEDIA_ERR_SRC_NOT_SUPPORTED), t2.message; }; var Ra2 = (t2, a2 = false) => { let e = Ca(t2, a2), i3 = ka2(t2, a2); return { title: e, message: i3 }; }; var Oa2 = (t2) => { if (t2.muxCode) { if (t2.muxCode === M.NETWORK_TOKEN_EXPIRED) return "403-expired-token.md"; if (t2.muxCode === M.NETWORK_TOKEN_MALFORMED) return "403-malformatted-token.md"; if ([M.NETWORK_TOKEN_AUD_MISMATCH, M.NETWORK_TOKEN_AUD_MISSING].includes(t2.muxCode)) return "403-incorrect-aud-value.md"; if (t2.muxCode === M.NETWORK_TOKEN_SUB_MISMATCH) return "403-playback-id-mismatch.md"; if (t2.muxCode === M.NETWORK_TOKEN_MISSING) return "missing-signed-tokens.md"; if (t2.muxCode === M.NETWORK_NOT_FOUND) return "404-not-found.md"; if (t2.muxCode === M.NETWORK_NOT_READY) return "412-not-playable.md"; } if (t2.code) { if (t2.code === T.MEDIA_ERR_NETWORK) return ""; if (t2.code === T.MEDIA_ERR_DECODE) return "media-decode-error.md"; if (t2.code === T.MEDIA_ERR_SRC_NOT_SUPPORTED) return "media-src-not-supported.md"; } return ""; }; var xa2 = (t2, a2) => { let e = Oa2(t2); return { message: t2.message, context: t2.context, file: e }; }; function De3(t2, a2 = false) { let e = Ra2(t2, a2), i3 = xa2(t2, a2); return { dialog: e, devlog: i3 }; } var It4 = `<template id="media-theme-gerwig"> <style> @keyframes pre-play-hide { 0% { transform: scale(1); opacity: 1; } 30% { transform: scale(0.7); } 100% { transform: scale(1.5); opacity: 0; } } :host { --_primary-color: var(--media-primary-color, #fff); --_secondary-color: var(--media-secondary-color, transparent); --_accent-color: var(--media-accent-color, #fa50b5); --_text-color: var(--media-text-color, #000); --media-icon-color: var(--_primary-color); --media-control-background: var(--_secondary-color); --media-control-hover-background: var(--_accent-color); --media-time-buffered-color: rgba(255, 255, 255, 0.4); --media-preview-time-text-shadow: none; --media-control-height: 14px; --media-control-padding: 6px; --media-tooltip-container-margin: 6px; --media-tooltip-distance: 18px; color: var(--_primary-color); display: inline-block; width: 100%; height: 100%; } :host([audio]) { --_secondary-color: var(--media-secondary-color, black); --media-preview-time-text-shadow: none; } :host([audio]) ::slotted([slot='media']) { height: 0px; } :host([audio]) media-loading-indicator { display: none; } :host([audio]) media-controller { background: transparent; } :host([audio]) media-controller::part(vertical-layer) { background: transparent; } :host([audio]) media-control-bar { width: 100%; background-color: var(--media-control-background); } /* * 0.433s is the transition duration for VTT Regions. * Borrowed here, so the captions don't move too fast. */ media-controller { --media-webkit-text-track-transform: translateY(0) scale(0.98); --media-webkit-text-track-transition: transform 0.433s ease-out 0.3s; } media-controller:is([mediapaused], :not([userinactive])) { --media-webkit-text-track-transform: translateY(-50px) scale(0.98); --media-webkit-text-track-transition: transform 0.15s ease; } /* * CSS specific to iOS devices. * See: https://stackoverflow.com/questions/30102792/css-media-query-to-target-only-ios-devices/60220757#60220757 */ @supports (-webkit-touch-callout: none) { /* Disable subtitle adjusting for iOS Safari */ media-controller[mediaisfullscreen] { --media-webkit-text-track-transform: unset; --media-webkit-text-track-transition: unset; } } media-time-range { --media-box-padding-left: 6px; --media-box-padding-right: 6px; --media-range-bar-color: var(--_accent-color); --media-time-range-buffered-color: var(--_primary-color); --media-range-track-color: transparent; --media-range-track-background: rgba(255, 255, 255, 0.4); --media-range-thumb-background: radial-gradient( circle, #000 0%, #000 25%, var(--_accent-color) 25%, var(--_accent-color) ); --media-range-thumb-width: 12px; --media-range-thumb-height: 12px; --media-range-thumb-transform: scale(0); --media-range-thumb-transition: transform 0.3s; --media-range-thumb-opacity: 1; --media-preview-background: var(--_primary-color); --media-box-arrow-background: var(--_primary-color); --media-preview-thumbnail-border: 5px solid var(--_primary-color); --media-preview-border-radius: 5px; --media-text-color: var(--_text-color); --media-control-hover-background: transparent; --media-preview-chapter-text-shadow: none; color: var(--_accent-color); padding: 0 6px; } :host([audio]) media-time-range { --media-preview-time-padding: 1.5px 6px; --media-preview-box-margin: 0 0 -5px; } media-time-range:hover { --media-range-thumb-transform: scale(1); } media-preview-thumbnail { border-bottom-width: 0; } [part~='menu'] { border-radius: 2px; border: 1px solid rgba(0, 0, 0, 0.1); bottom: 50px; padding: 2.5px 10px; } [part~='menu']::part(indicator) { fill: var(--_accent-color); } [part~='menu']::part(menu-item) { box-sizing: border-box; display: flex; align-items: center; padding: 6px 10px; min-height: 34px; } [part~='menu']::part(checked) { font-weight: 700; } media-captions-menu, media-rendition-menu, media-audio-track-menu, media-playback-rate-menu { position: absolute; /* ensure they don't take up space in DOM on load */ --media-menu-background: var(--_primary-color); --media-menu-item-checked-background: transparent; --media-text-color: var(--_text-color); --media-menu-item-hover-background: transparent; --media-menu-item-hover-outline: var(--_accent-color) solid 1px; } /* The icon is a circle so make it 16px high instead of 14px for more balance. */ media-audio-track-menu-button { --media-control-padding: 5px; --media-control-height: 16px; } media-playback-rate-menu-button { --media-control-padding: 6px 3px; min-width: 4.4ch; } media-playback-rate-menu { --media-menu-flex-direction: row; --media-menu-item-checked-background: var(--_accent-color); --media-menu-item-checked-indicator-display: none; margin-right: 6px; padding: 0; --media-menu-gap: 0.25em; } media-playback-rate-menu[part~='menu']::part(menu-item) { padding: 6px 6px 6px 8px; } media-playback-rate-menu[part~='menu']::part(checked) { color: #fff; } :host(:not([audio])) media-time-range { /* Adding px is required here for calc() */ --media-range-padding: 0px; background: transparent; z-index: 10; height: 10px; bottom: -3px; width: 100%; } media-control-bar :is([role='button'], [role='switch'], button) { line-height: 0; } media-control-bar :is([part*='button'], [part*='range'], [part*='display']) { border-radius: 3px; } .spacer { flex-grow: 1; background-color: var(--media-control-background, rgba(20, 20, 30, 0.7)); } media-control-bar[slot~='top-chrome'] { min-height: 42px; pointer-events: none; } media-control-bar { --gradient-steps: hsl(0 0% 0% / 0) 0%, hsl(0 0% 0% / 0.013) 8.1%, hsl(0 0% 0% / 0.049) 15.5%, hsl(0 0% 0% / 0.104) 22.5%, hsl(0 0% 0% / 0.175) 29%, hsl(0 0% 0% / 0.259) 35.3%, hsl(0 0% 0% / 0.352) 41.2%, hsl(0 0% 0% / 0.45) 47.1%, hsl(0 0% 0% / 0.55) 52.9%, hsl(0 0% 0% / 0.648) 58.8%, hsl(0 0% 0% / 0.741) 64.7%, hsl(0 0% 0% / 0.825) 71%, hsl(0 0% 0% / 0.896) 77.5%, hsl(0 0% 0% / 0.951) 84.5%, hsl(0 0% 0% / 0.987) 91.9%, hsl(0 0% 0%) 100%; } :host([title]:not([audio])) media-control-bar[slot='top-chrome']::before { content: ''; position: absolute; width: 100%; padding-bottom: min(100px, 25%); background: linear-gradient(to top, var(--gradient-steps)); opacity: 0.8; pointer-events: none; } :host(:not([audio])) media-control-bar[part~='bottom']::before { content: ''; position: absolute; width: 100%; bottom: 0; left: 0; padding-bottom: min(100px, 25%); background: linear-gradient(to bottom, var(--gradient-steps)); opacity: 0.8; z-index: 1; pointer-events: none; } media-control-bar[part~='bottom'] > * { z-index: 20; } media-control-bar[part~='bottom'] { padding: 6px 6px; } media-control-bar[slot~='top-chrome'] > * { --media-control-background: transparent; --media-control-hover-background: transparent; position: relative; } media-controller::part(vertical-layer) { transition: background-color 1s; } media-controller:is([mediapaused], :not([userinactive]))::part(vertical-layer) { background-color: var(--controls-backdrop-color, var(--controls, transparent)); transition: background-color 0.25s; } .center-controls { --media-button-icon-width: 100%; --media-button-icon-height: auto; --media-tooltip-display: none; pointer-events: none; width: 100%; display: flex; flex-flow: row; align-items: center; justify-content: center; filter: drop-shadow(0 0 2px rgb(0 0 0 / 0.25)) drop-shadow(0 0 6px rgb(0 0 0 / 0.25)); paint-order: stroke; stroke: rgba(102, 102, 102, 1); stroke-width: 0.3px; text-shadow: 0 0 2px rgb(0 0 0 / 0.25), 0 0 6px rgb(0 0 0 / 0.25); } .center-controls media-play-button { --media-control-background: transparent; --media-control-hover-background: transparent; --media-control-padding: 0; width: 40px; } [breakpointsm] .center-controls media-play-button { width: 90px; height: 90px; border-radius: 50%; transition: background 0.4s; padding: 24px; --media-control-background: #000; --media-control-hover-background: var(--_accent-color); } .center-controls media-seek-backward-button, .center-controls media-seek-forward-button { --media-control-background: transparent; --media-control-hover-background: transparent; padding: 0; margin: 0 20px; width: max(33px, min(8%, 40px)); } [breakpointsm]:not([audio]) .center-controls.pre-playback { display: grid; align-items: initial; justify-content: initial; height: 100%; overflow: hidden; } [breakpointsm]:not([audio]) .center-controls.pre-playback media-play-button { place-self: var(--_pre-playback-place, center); grid-area: 1 / 1; margin: 16px; } /* Show and hide controls or pre-playback state */ [breakpointsm]:is([mediahasplayed], :not([mediapaused])):not([audio]) .center-controls.pre-playback media-play-button { /* Using \`forwards\` would lead to a laggy UI after the animation got in the end state */ animation: 0.3s linear pre-play-hide; opacity: 0; pointer-events: none; } .autoplay-unmute { --media-control-hover-background: transparent; width: 100%; display: flex; align-items: center; justify-content: center; filter: drop-shadow(0 0 2px rgb(0 0 0 / 0.25)) drop-shadow(0 0 6px rgb(0 0 0 / 0.25)); } .autoplay-unmute-btn { --media-control-height: 16px; border-radius: 8px; background: #000; color: var(--_primary-color); display: flex; align-items: center; padding: 8px 16px; font-size: 18px; font-weight: 500; cursor: pointer; } .autoplay-unmute-btn:hover { background: var(--_accent-color); } [breakpointsm] .autoplay-unmute-btn { --media-control-height: 30px; padding: 14px 24px; font-size: 26px; } .autoplay-unmute-btn svg { margin: 0 6px 0 0; } [breakpointsm] .autoplay-unmute-btn svg { margin: 0 10px 0 0; } media-controller:not([audio]):not([mediahasplayed]) *:is(media-control-bar, media-time-range) { display: none; } media-loading-indicator { --media-loading-icon-width: 100%; --media-button-icon-height: auto; display: var(--media-control-display, var(--media-loading-indicator-display, flex)); pointer-events: none; position: absolute; width: min(15%, 150px); flex-flow: row; align-items: center; justify-content: center; } /* Intentionally don't target the div for transition but the children of the div. Prevents messing with media-chrome's autohide feature. */ media-loading-indicator + div * { transition: opacity 0.15s; opacity: 1; } media-loading-indicator[medialoading]:not([mediapaused]) ~ div > * { opacity: 0; transition-delay: 400ms; } media-volume-range { width: min(100%, 100px); --media-range-padding-left: 10px; --media-range-padding-right: 10px; --media-range-thumb-width: 12px; --media-range-thumb-height: 12px; --media-range-thumb-background: radial-gradient( circle, #000 0%, #000 25%, var(--_primary-color) 25%, var(--_primary-color) ); --media-control-hover-background: none; } media-time-display { white-space: nowrap; } /* Generic style for explicitly disabled controls */ media-control-bar[part~='bottom'] [disabled], media-control-bar[part~='bottom'] [aria-disabled='true'] { opacity: 60%; cursor: not-allowed; } media-text-display { --media-font-size: 16px; --media-control-padding: 14px; font-weight: 500; } media-play-button.animated *:is(g, path) { transition: all 0.3s; } media-play-button.animated[mediapaused] .pause-icon-pt1 { opacity: 0; } media-play-button.animated[mediapaused] .pause-icon-pt2 { transform-origin: center center; transform: scaleY(0); } media-play-button.animated[mediapaused] .play-icon { clip-path: inset(0 0 0 0); } media-play-button.animated:not([mediapaused]) .play-icon { clip-path: inset(0 0 0 100%); } media-seek-forward-button, media-seek-backward-button { --media-font-weight: 400; } .mute-icon { display: inline-block; } .mute-icon :is(path, g) { transition: opacity 0.5s; } .muted { opacity: 0; } media-mute-button[mediavolumelevel='low'] :is(.volume-medium, .volume-high), media-mute-button[mediavolumelevel='medium'] :is(.volume-high) { opacity: 0; } media-mute-button[mediavolumelevel='off'] .unmuted { opacity: 0; } media-mute-button[mediavolumelevel='off'] .muted { opacity: 1; } /** * Our defaults for these buttons are to hide them at small sizes * users can override this with CSS */ media-controller:not([breakpointsm]):not([audio]) { --bottom-play-button: none; --bottom-seek-backward-button: none; --bottom-seek-forward-button: none; --bottom-time-display: none; --bottom-playback-rate-menu-button: none; --bottom-pip-button: none; } </style> <template partial="TitleDisplay"> <template if="title"> <media-text-display part="top title display" class="title-display">{{title}}</media-text-display> </template> </template> <template partial="PlayButton"> <media-play-button part="{{section ?? 'bottom'}} play button" disabled="{{disabled}}" aria-disabled="{{disabled}}" class="animated" > <svg aria-hidden="true" viewBox="0 0 18 14" slot="icon"> <g class="play-icon"> <path d="M15.5987 6.2911L3.45577 0.110898C2.83667 -0.204202 2.06287 0.189698 2.06287 0.819798V13.1802C2.06287 13.8103 2.83667 14.2042 3.45577 13.8891L15.5987 7.7089C16.2178 7.3938 16.2178 6.6061 15.5987 6.2911Z" /> </g> <g class="pause-icon"> <path class="pause-icon-pt1" d="M5.90709 0H2.96889C2.46857 0 2.06299 0.405585 2.06299 0.9059V13.0941C2.06299 13.5944 2.46857 14 2.96889 14H5.90709C6.4074 14 6.81299 13.5944 6.81299 13.0941V0.9059C6.81299 0.405585 6.4074 0 5.90709 0Z" /> <path class="pause-icon-pt2" d="M15.1571 0H12.2189C11.7186 0 11.313 0.405585 11.313 0.9059V13.0941C11.313 13.5944 11.7186 14 12.2189 14H15.1571C15.6574 14 16.063 13.5944 16.063 13.0941V0.9059C16.063 0.405585 15.6574 0 15.1571 0Z" /> </g> </svg> </media-play-button> </template> <template partial="PrePlayButton"> <media-play-button part="{{section ?? 'center'}} play button pre-play" disabled="{{disabled}}" aria-disabled="{{disabled}}" > <svg aria-hidden="true" viewBox="0 0 18 14" slot="icon" style="transform: translate(3px, 0)"> <path d="M15.5987 6.2911L3.45577 0.110898C2.83667 -0.204202 2.06287 0.189698 2.06287 0.819798V13.1802C2.06287 13.8103 2.83667 14.2042 3.45577 13.8891L15.5987 7.7089C16.2178 7.3938 16.2178 6.6061 15.5987 6.2911Z" /> </svg> </media-play-button> </template> <template partial="SeekBackwardButton"> <media-seek-backward-button seekoffset="{{backwardseekoffset}}" part="{{section ?? 'bottom'}} seek-backward button" disabled="{{disabled}}" aria-disabled="{{disabled}}" > <svg viewBox="0 0 22 14" aria-hidden="true" slot="icon"> <path d="M3.65 2.07888L0.0864 6.7279C-0.0288 6.87812 -0.0288 7.12188 0.0864 7.2721L3.65 11.9211C3.7792 12.0896 4 11.9703 4 11.7321V2.26787C4 2.02968 3.7792 1.9104 3.65 2.07888Z" /> <text transform="translate(6 12)" style="font-size: 14px; font-family: 'ArialMT', 'Arial'"> {{backwardseekoffset}} </text> </svg> </media-seek-backward-button> </template> <template partial="SeekForwardButton"> <media-seek-forward-button seekoffset="{{forwardseekoffset}}" part="{{section ?? 'bottom'}} seek-forward button" disabled="{{disabled}}" aria-disabled="{{disabled}}" > <svg viewBox="0 0 22 14" aria-hidden="true" slot="icon"> <g> <text transform="translate(-1 12)" style="font-size: 14px; font-family: 'ArialMT', 'Arial'"> {{forwardseekoffset}} </text> <path d="M18.35 11.9211L21.9136 7.2721C22.0288 7.12188 22.0288 6.87812 21.9136 6.7279L18.35 2.07888C18.2208 1.91041 18 2.02968 18 2.26787V11.7321C18 11.9703 18.2208 12.0896 18.35 11.9211Z" /> </g> </svg> </media-seek-forward-button> </template> <template partial="MuteButton"> <media-mute-button part="bottom mute button" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <svg viewBox="0 0 18 14" slot="icon" class="mute-icon" aria-hidden="true"> <g class="unmuted"> <path d="M6.76786 1.21233L3.98606 3.98924H1.19937C0.593146 3.98924 0.101743 4.51375 0.101743 5.1607V6.96412L0 6.99998L0.101743 7.03583V8.83926C0.101743 9.48633 0.593146 10.0108 1.19937 10.0108H3.98606L6.76773 12.7877C7.23561 13.2547 8 12.9007 8 12.2171V1.78301C8 1.09925 7.23574 0.745258 6.76786 1.21233Z" /> <path class="volume-low" d="M10 3.54781C10.7452 4.55141 11.1393 5.74511 11.1393 6.99991C11.1393 8.25471 10.7453 9.44791 10 10.4515L10.7988 11.0496C11.6734 9.87201 12.1356 8.47161 12.1356 6.99991C12.1356 5.52821 11.6735 4.12731 10.7988 2.94971L10 3.54781Z" /> <path class="volume-medium" d="M12.3778 2.40086C13.2709 3.76756 13.7428 5.35806 13.7428 7.00026C13.7428 8.64246 13.2709 10.233 12.3778 11.5992L13.2106 12.1484C14.2107 10.6185 14.739 8.83796 14.739 7.00016C14.739 5.16236 14.2107 3.38236 13.2106 1.85156L12.3778 2.40086Z" /> <path class="volume-high" d="M15.5981 0.75L14.7478 1.2719C15.7937 2.9919 16.3468 4.9723 16.3468 7C16.3468 9.0277 15.7937 11.0082 14.7478 12.7281L15.5981 13.25C16.7398 11.3722 17.343 9.211 17.343 7C17.343 4.789 16.7398 2.6268 15.5981 0.75Z" /> </g> <g class="muted"> <path fill-rule="evenodd" clip-rule="evenodd" d="M4.39976 4.98924H1.19937C1.19429 4.98924 1.17777 4.98961 1.15296 5.01609C1.1271 5.04369 1.10174 5.09245 1.10174 5.1607V8.83926C1.10174 8.90761 1.12714 8.95641 1.15299 8.984C1.17779 9.01047 1.1943 9.01084 1.19937 9.01084H4.39977L7 11.6066V2.39357L4.39976 4.98924ZM7.47434 1.92006C7.4743 1.9201 7.47439 1.92002 7.47434 1.92006V1.92006ZM6.76773 12.7877L3.98606 10.0108H1.19937C0.593146 10.0108 0.101743 9.48633 0.101743 8.83926V7.03583L0 6.99998L0.101743 6.96412V5.1607C0.101743 4.51375 0.593146 3.98924 1.19937 3.98924H3.98606L6.76786 1.21233C7.23574 0.745258 8 1.09925 8 1.78301V12.2171C8 12.9007 7.23561 13.2547 6.76773 12.7877Z" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M15.2677 9.30323C15.463 9.49849 15.7796 9.49849 15.9749 9.30323C16.1701 9.10796 16.1701 8.79138 15.9749 8.59612L14.2071 6.82841L15.9749 5.06066C16.1702 4.8654 16.1702 4.54882 15.9749 4.35355C15.7796 4.15829 15.4631 4.15829 15.2678 4.35355L13.5 6.1213L11.7322 4.35348C11.537 4.15822 11.2204 4.15822 11.0251 4.35348C10.8298 4.54874 10.8298 4.86532 11.0251 5.06058L12.7929 6.82841L11.0251 8.59619C10.8299 8.79146 10.8299 9.10804 11.0251 9.3033C11.2204 9.49856 11.537 9.49856 11.7323 9.3033L13.5 7.53552L15.2677 9.30323Z" /> </g> </svg> </media-mute-button> </template> <template partial="PipButton"> <media-pip-button part="bottom pip button" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <svg viewBox="0 0 18 14" aria-hidden="true" slot="icon"> <path d="M15.9891 0H2.011C0.9004 0 0 0.9003 0 2.0109V11.989C0 13.0996 0.9004 14 2.011 14H15.9891C17.0997 14 18 13.0997 18 11.9891V2.0109C18 0.9003 17.0997 0 15.9891 0ZM17 11.9891C17 12.5465 16.5465 13 15.9891 13H2.011C1.4536 13 1.0001 12.5465 1.0001 11.9891V2.0109C1.0001 1.4535 1.4536 0.9999 2.011 0.9999H15.9891C16.5465 0.9999 17 1.4535 17 2.0109V11.9891Z" /> <path d="M15.356 5.67822H8.19523C8.03253 5.67822 7.90063 5.81012 7.90063 5.97282V11.3836C7.90063 11.5463 8.03253 11.6782 8.19523 11.6782H15.356C15.5187 11.6782 15.6506 11.5463 15.6506 11.3836V5.97282C15.6506 5.81012 15.5187 5.67822 15.356 5.67822Z" /> </svg> </media-pip-button> </template> <template partial="CaptionsMenu"> <media-captions-menu-button part="bottom captions button"> <svg aria-hidden="true" viewBox="0 0 18 14" slot="on"> <path d="M15.989 0H2.011C0.9004 0 0 0.9003 0 2.0109V11.9891C0 13.0997 0.9004 14 2.011 14H15.989C17.0997 14 18 13.0997 18 11.9891V2.0109C18 0.9003 17.0997 0 15.989 0ZM4.2292 8.7639C4.5954 9.1902 5.0935 9.4031 5.7233 9.4031C6.1852 9.4031 6.5544 9.301 6.8302 9.0969C7.1061 8.8933 7.2863 8.614 7.3702 8.26H8.4322C8.3062 8.884 8.0093 9.3733 7.5411 9.7273C7.0733 10.0813 6.4703 10.2581 5.732 10.2581C5.108 10.2581 4.5699 10.1219 4.1168 9.8489C3.6637 9.5759 3.3141 9.1946 3.0685 8.7058C2.8224 8.2165 2.6994 7.6511 2.6994 7.009C2.6994 6.3611 2.8224 5.7927 3.0685 5.3034C3.3141 4.8146 3.6637 4.4323 4.1168 4.1559C4.5699 3.88 5.108 3.7418 5.732 3.7418C6.4703 3.7418 7.0733 3.922 7.5411 4.2818C8.0094 4.6422 8.3062 5.1461 8.4322 5.794H7.3702C7.2862 5.4283 7.106 5.1368 6.8302 4.921C6.5544 4.7052 6.1852 4.5968 5.7233 4.5968C5.0934 4.5968 4.5954 4.8116 4.2292 5.2404C3.8635 5.6696 3.6804 6.259 3.6804 7.009C3.6804 7.7531 3.8635 8.3381 4.2292 8.7639ZM11.0974 8.7639C11.4636 9.1902 11.9617 9.4031 12.5915 9.4031C13.0534 9.4031 13.4226 9.301 13.6984 9.0969C13.9743 8.8933 14.1545 8.614 14.2384 8.26H15.3004C15.1744 8.884 14.8775 9.3733 14.4093 9.7273C13.9415 10.0813 13.3385 10.2581 12.6002 10.2581C11.9762 10.2581 11.4381 10.1219 10.985 9.8489C10.5319 9.5759 10.1823 9.1946 9.9367 8.7058C9.6906 8.2165 9.5676 7.6511 9.5676 7.009C9.5676 6.3611 9.6906 5.7927 9.9367 5.3034C10.1823 4.8146 10.5319 4.4323 10.985 4.1559C11.4381 3.88 11.9762 3.7418 12.6002 3.7418C13.3385 3.7418 13.9415 3.922 14.4093 4.2818C14.8776 4.6422 15.1744 5.1461 15.3004 5.794H14.2384C14.1544 5.4283 13.9742 5.1368 13.6984 4.921C13.4226 4.7052 13.0534 4.5968 12.5915 4.5968C11.9616 4.5968 11.4636 4.8116 11.0974 5.2404C10.7317 5.6696 10.5486 6.259 10.5486 7.009C10.5486 7.7531 10.7317 8.3381 11.0974 8.7639Z" /> </svg> <svg aria-hidden="true" viewBox="0 0 18 14" slot="off"> <path d="M5.73219 10.258C5.10819 10.258 4.57009 10.1218 4.11699 9.8488C3.66389 9.5758 3.31429 9.1945 3.06869 8.7057C2.82259 8.2164 2.69958 7.651 2.69958 7.0089C2.69958 6.361 2.82259 5.7926 3.06869 5.3033C3.31429 4.8145 3.66389 4.4322 4.11699 4.1558C4.57009 3.8799 5.10819 3.7417 5.73219 3.7417C6.47049 3.7417 7.07348 3.9219 7.54128 4.2817C8.00958 4.6421 8.30638 5.146 8.43238 5.7939H7.37039C7.28639 5.4282 7.10618 5.1367 6.83039 4.9209C6.55459 4.7051 6.18538 4.5967 5.72348 4.5967C5.09358 4.5967 4.59559 4.8115 4.22939 5.2403C3.86369 5.6695 3.68058 6.2589 3.68058 7.0089C3.68058 7.753 3.86369 8.338 4.22939 8.7638C4.59559 9.1901 5.09368 9.403 5.72348 9.403C6.18538 9.403 6.55459 9.3009 6.83039 9.0968C7.10629 8.8932 7.28649 8.6139 7.37039 8.2599H8.43238C8.30638 8.8839 8.00948 9.3732 7.54128 9.7272C7.07348 10.0812 6.47049 10.258 5.73219 10.258Z" /> <path d="M12.6003 10.258C11.9763 10.258 11.4382 10.1218 10.9851 9.8488C10.532 9.5758 10.1824 9.1945 9.93685 8.7057C9.69075 8.2164 9.56775 7.651 9.56775 7.0089C9.56775 6.361 9.69075 5.7926 9.93685 5.3033C10.1824 4.8145 10.532 4.4322 10.9851 4.1558C11.4382 3.8799 11.9763 3.7417 12.6003 3.7417C13.3386 3.7417 13.9416 3.9219 14.4094 4.2817C14.8777 4.6421 15.1745 5.146 15.3005 5.7939H14.2385C14.1545 5.4282 13.9743 5.1367 13.6985 4.9209C13.4227 4.7051 13.0535 4.5967 12.5916 4.5967C11.9617 4.5967 11.4637 4.8115 11.0975 5.2403C10.7318 5.6695 10.5487 6.2589 10.5487 7.0089C10.5487 7.753 10.7318 8.338 11.0975 8.7638C11.4637 9.1901 11.9618 9.403 12.5916 9.403C13.0535 9.403 13.4227 9.3009 13.6985 9.0968C13.9744 8.8932 14.1546 8.6139 14.2385 8.2599H15.3005C15.1745 8.8839 14.8776 9.3732 14.4094 9.7272C13.9416 10.0812 13.3386 10.258 12.6003 10.258Z" /> <path d="M15.9891 1C16.5465 1 17 1.4535 17 2.011V11.9891C17 12.5465 16.5465 13 15.9891 13H2.0109C1.4535 13 1 12.5465 1 11.9891V2.0109C1 1.4535 1.4535 0.9999 2.0109 0.9999L15.9891 1ZM15.9891 0H2.0109C0.9003 0 0 0.9003 0 2.0109V11.9891C0 13.0997 0.9003 14 2.0109 14H15.9891C17.0997 14 18 13.0997 18 11.9891V2.0109C18 0.9003 17.0997 0 15.9891 0Z" /> </svg> </media-captions-menu-button> <media-captions-menu hidden anchor="auto" part="bottom captions menu" disabled="{{disabled}}" aria-disabled="{{disabled}}" exportparts="menu-item" > <div slot="checked-indicator"> <style> .indicator { position: relative; top: 1px; width: 0.9em; height: auto; fill: var(--_accent-color); margin-right: 5px; } [aria-checked='false'] .indicator { display: none; } </style> <svg viewBox="0 0 14 18" class="indicator"> <path d="M12.252 3.48c-.115.033-.301.161-.425.291-.059.063-1.407 1.815-2.995 3.894s-2.897 3.79-2.908 3.802c-.013.014-.661-.616-1.672-1.624-.908-.905-1.702-1.681-1.765-1.723-.401-.27-.783-.211-1.176.183a1.285 1.285 0 0 0-.261.342.582.582 0 0 0-.082.35c0 .165.01.205.08.35.075.153.213.296 2.182 2.271 1.156 1.159 2.17 2.159 2.253 2.222.189.143.338.196.539.194.203-.003.412-.104.618-.299.205-.193 6.7-8.693 6.804-8.903a.716.716 0 0 0 .085-.345c.01-.179.005-.203-.062-.339-.124-.252-.45-.531-.746-.639a.784.784 0 0 0-.469-.027" fill-rule="evenodd" /> </svg></div ></media-captions-menu> </template> <template partial="AirplayButton"> <media-airplay-button part="bottom airplay button" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <svg viewBox="0 0 18 14" aria-hidden="true" slot="icon"> <path d="M16.1383 0H1.8618C0.8335 0 0 0.8335 0 1.8617V10.1382C0 11.1664 0.8335 12 1.8618 12H3.076C3.1204 11.9433 3.1503 11.8785 3.2012 11.826L4.004 11H1.8618C1.3866 11 1 10.6134 1 10.1382V1.8617C1 1.3865 1.3866 0.9999 1.8618 0.9999H16.1383C16.6135 0.9999 17.0001 1.3865 17.0001 1.8617V10.1382C17.0001 10.6134 16.6135 11 16.1383 11H13.9961L14.7989 11.826C14.8499 11.8785 14.8798 11.9432 14.9241 12H16.1383C17.1665 12 18.0001 11.1664 18.0001 10.1382V1.8617C18 0.8335 17.1665 0 16.1383 0Z" /> <path d="M9.55061 8.21903C9.39981 8.06383 9.20001 7.98633 9.00011 7.98633C8.80021 7.98633 8.60031 8.06383 8.44951 8.21903L4.09771 12.697C3.62471 13.1838 3.96961 13.9998 4.64831 13.9998H13.3518C14.0304 13.9998 14.3754 13.1838 13.9023 12.697L9.55061 8.21903Z" /> </svg> </media-airplay-button> </template> <template partial="FullscreenButton"> <media-fullscreen-button part="bottom fullscreen button" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <svg viewBox="0 0 18 14" aria-hidden="true" slot="enter"> <path d="M1.00745 4.39539L1.01445 1.98789C1.01605 1.43049 1.47085 0.978289 2.02835 0.979989L6.39375 0.992589L6.39665 -0.007411L2.03125 -0.020011C0.920646 -0.023211 0.0176463 0.874489 0.0144463 1.98509L0.00744629 4.39539H1.00745Z" /> <path d="M17.0144 2.03431L17.0076 4.39541H18.0076L18.0144 2.03721C18.0176 0.926712 17.1199 0.0237125 16.0093 0.0205125L11.6439 0.0078125L11.641 1.00781L16.0064 1.02041C16.5638 1.02201 17.016 1.47681 17.0144 2.03431Z" /> <path d="M16.9925 9.60498L16.9855 12.0124C16.9839 12.5698 16.5291 13.022 15.9717 13.0204L11.6063 13.0078L11.6034 14.0078L15.9688 14.0204C17.0794 14.0236 17.9823 13.1259 17.9855 12.0153L17.9925 9.60498H16.9925Z" /> <path d="M0.985626 11.9661L0.992426 9.60498H-0.0074737L-0.0142737 11.9632C-0.0174737 13.0738 0.880226 13.9767 1.99083 13.98L6.35623 13.9926L6.35913 12.9926L1.99373 12.98C1.43633 12.9784 0.983926 12.5236 0.985626 11.9661Z" /> </svg> <svg viewBox="0 0 18 14" aria-hidden="true" slot="exit"> <path d="M5.39655 -0.0200195L5.38955 2.38748C5.38795 2.94488 4.93315 3.39708 4.37565 3.39538L0.0103463 3.38278L0.00744629 4.38278L4.37285 4.39538C5.48345 4.39858 6.38635 3.50088 6.38965 2.39028L6.39665 -0.0200195H5.39655Z" /> <path d="M12.6411 2.36891L12.6479 0.0078125H11.6479L11.6411 2.36601C11.6379 3.47651 12.5356 4.37951 13.6462 4.38271L18.0116 4.39531L18.0145 3.39531L13.6491 3.38271C13.0917 3.38111 12.6395 2.92641 12.6411 2.36891Z" /> <path d="M12.6034 14.0204L12.6104 11.613C12.612 11.0556 13.0668 10.6034 13.6242 10.605L17.9896 10.6176L17.9925 9.61759L13.6271 9.60499C12.5165 9.60179 11.6136 10.4995 11.6104 11.6101L11.6034 14.0204H12.6034Z" /> <path d="M5.359 11.6315L5.3522 13.9926H6.3522L6.359 11.6344C6.3622 10.5238 5.4645 9.62088 4.3539 9.61758L-0.0115043 9.60498L-0.0144043 10.605L4.351 10.6176C4.9084 10.6192 5.3607 11.074 5.359 11.6315Z" /> </svg> </media-fullscreen-button> </template> <template partial="CastButton"> <media-cast-button part="bottom cast button" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <svg viewBox="0 0 18 14" aria-hidden="true" slot="enter"> <path d="M16.0072 0H2.0291C0.9185 0 0.0181 0.9003 0.0181 2.011V5.5009C0.357 5.5016 0.6895 5.5275 1.0181 5.5669V2.011C1.0181 1.4536 1.4716 1 2.029 1H16.0072C16.5646 1 17.0181 1.4536 17.0181 2.011V11.9891C17.0181 12.5465 16.5646 13 16.0072 13H8.4358C8.4746 13.3286 8.4999 13.6611 8.4999 13.9999H16.0071C17.1177 13.9999 18.018 13.0996 18.018 11.989V2.011C18.0181 0.9003 17.1178 0 16.0072 0ZM0 6.4999V7.4999C3.584 7.4999 6.5 10.4159 6.5 13.9999H7.5C7.5 9.8642 4.1357 6.4999 0 6.4999ZM0 8.7499V9.7499C2.3433 9.7499 4.25 11.6566 4.25 13.9999H5.25C5.25 11.1049 2.895 8.7499 0 8.7499ZM0.0181 11V14H3.0181C3.0181 12.3431 1.675 11 0.0181 11Z" /> </svg> <svg viewBox="0 0 18 14" aria-hidden="true" slot="exit"> <path d="M15.9891 0H2.01103C0.900434 0 3.35947e-05 0.9003 3.35947e-05 2.011V5.5009C0.338934 5.5016 0.671434 5.5275 1.00003 5.5669V2.011C1.00003 1.4536 1.45353 1 2.01093 1H15.9891C16.5465 1 17 1.4536 17 2.011V11.9891C17 12.5465 16.5465 13 15.9891 13H8.41773C8.45653 13.3286 8.48183 13.6611 8.48183 13.9999H15.989C17.0996 13.9999 17.9999 13.0996 17.9999 11.989V2.011C18 0.9003 17.0997 0 15.9891 0ZM-0.0180664 6.4999V7.4999C3.56593 7.4999 6.48193 10.4159 6.48193 13.9999H7.48193C7.48193 9.8642 4.11763 6.4999 -0.0180664 6.4999ZM-0.0180664 8.7499V9.7499C2.32523 9.7499 4.23193 11.6566 4.23193 13.9999H5.23193C5.23193 11.1049 2.87693 8.7499 -0.0180664 8.7499ZM3.35947e-05 11V14H3.00003C3.00003 12.3431 1.65693 11 3.35947e-05 11Z" /> <path d="M2.15002 5.634C5.18352 6.4207 7.57252 8.8151 8.35282 11.8499H15.8501V2.1499H2.15002V5.634Z" /> </svg> </media-cast-button> </template> <template partial="LiveButton"> <media-live-button part="{{section ?? 'top'}} live button" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <span slot="text">Live</span> </media-live-button> </template> <template partial="PlaybackRateMenu"> <media-playback-rate-menu-button part="bottom playback-rate button"></media-playback-rate-menu-button> <media-playback-rate-menu hidden anchor="auto" rates="{{playbackrates}}" exportparts="menu-item" part="bottom playback-rate menu" disabled="{{disabled}}" aria-disabled="{{disabled}}" ></media-playback-rate-menu> </template> <template partial="VolumeRange"> <media-volume-range part="bottom volume range" disabled="{{disabled}}" aria-disabled="{{disabled}}" ></media-volume-range> </template> <template partial="TimeDisplay"> <media-time-display remaining="{{defaultshowremainingtime}}" showduration="{{!hideduration}}" part="bottom time display" disabled="{{disabled}}" aria-disabled="{{disabled}}" ></media-time-display> </template> <template partial="TimeRange"> <media-time-range part="bottom time range" disabled="{{disabled}}" aria-disabled="{{disabled}}"> <media-preview-thumbnail slot="preview"></media-preview-thumbnail> <media-preview-chapter-display slot="preview"></media-preview-chapter-display> <media-preview-time-display slot="preview"></media-preview-time-display> <div slot="preview" part="arrow"></div> </media-time-range> </template> <template partial="AudioTrackMenu"> <media-audio-track-menu-button part="bottom audio-track button"> <svg aria-hidden="true" slot="icon" viewBox="0 0 18 16"> <path d="M9 15A7 7 0 1 1 9 1a7 7 0 0 1 0 14Zm0 1A8 8 0 1 0 9 0a8 8 0 0 0 0 16Z" /> <path d="M5.2 6.3a.5.5 0 0 1 .5.5v2.4a.5.5 0 1 1-1 0V6.8a.5.5 0 0 1 .5-.5Zm2.4-2.4a.5.5 0 0 1 .5.5v7.2a.5.5 0 0 1-1 0V4.4a.5.5 0 0 1 .5-.5ZM10 5.5a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5Zm2.4-.8a.5.5 0 0 1 .5.5v5.6a.5.5 0 0 1-1 0V5.2a.5.5 0 0 1 .5-.5Z" /> </svg> </media-audio-track-menu-button> <media-audio-track-menu hidden anchor="auto" part="bottom audio-track menu" disabled="{{disabled}}" aria-disabled="{{disabled}}" exportparts="menu-item" > <div slot="checked-indicator"> <style> .indicator { position: relative; top: 1px; width: 0.9em; height: auto; fill: var(--_accent-color); margin-right: 5px; } [aria-checked='false'] .indicator { display: none; } </style> <svg viewBox="0 0 14 18" class="indicator"> <path d="M12.252 3.48c-.115.033-.301.161-.425.291-.059.063-1.407 1.815-2.995 3.894s-2.897 3.79-2.908 3.802c-.013.014-.661-.616-1.672-1.624-.908-.905-1.702-1.681-1.765-1.723-.401-.27-.783-.211-1.176.183a1.285 1.285 0 0 0-.261.342.582.582 0 0 0-.082.35c0 .165.01.205.08.35.075.153.213.296 2.182 2.271 1.156 1.159 2.17 2.159 2.253 2.222.189.143.338.196.539.194.203-.003.412-.104.618-.299.205-.193 6.7-8.693 6.804-8.903a.716.716 0 0 0 .085-.345c.01-.179.005-.203-.062-.339-.124-.252-.45-.531-.746-.639a.784.784 0 0 0-.469-.027" fill-rule="evenodd" /> </svg> </div> </media-audio-track-menu> </template> <template partial="RenditionMenu"> <media-rendition-menu-button part="bottom rendition button"> <svg aria-hidden="true" slot="icon" viewBox="0 0 18 14"> <path d="M2.25 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM9 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4Zm6.75 0a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z" /> </svg> </media-rendition-menu-button> <media-rendition-menu hidden anchor="auto" part="bottom rendition menu" disabled="{{disabled}}" aria-disabled="{{disabled}}" > <div slot="checked-indicator"> <style> .indicator { position: relative; top: 1px; width: 0.9em; height: auto; fill: var(--_accent-color); margin-right: 5px; } [aria-checked='false'] .indicator { display: none; } </style> <svg viewBox="0 0 14 18" class="indicator"> <path d="M12.252 3.48c-.115.033-.301.161-.425.291-.059.063-1.407 1.815-2.995 3.894s-2.897 3.79-2.908 3.802c-.013.014-.661-.616-1.672-1.624-.908-.905-1.702-1.681-1.765-1.723-.401-.27-.783-.211-1.176.183a1.285 1.285 0 0 0-.261.342.582.582 0 0 0-.082.35c0 .165.01.205.08.35.075.153.213.296 2.182 2.271 1.156 1.159 2.17 2.159 2.253 2.222.189.143.338.196.539.194.203-.003.412-.104.618-.299.205-.193 6.7-8.693 6.804-8.903a.716.716 0 0 0 .085-.345c.01-.179.005-.203-.062-.339-.124-.252-.45-.531-.746-.639a.784.784 0 0 0-.469-.027" fill-rule="evenodd" /> </svg> </div> </media-rendition-menu> </template> <media-controller part="controller" defaultstreamtype="{{defaultstreamtype ?? 'on-demand'}}" breakpoints="sm:470" gesturesdisabled="{{disabled}}" hotkeys="{{hotkeys}}" nohotkeys="{{nohotkeys}}" novolumepref="{{novolumepref}}" audio="{{audio}}" noautoseektolive="{{noautoseektolive}}" defaultsubtitles="{{defaultsubtitles}}" defaultduration="{{defaultduration ?? false}}" keyboardforwardseekoffset="{{forwardseekoffset}}" keyboardbackwardseekoffset="{{backwardseekoffset}}" exportparts="layer, media-layer, poster-layer, vertical-layer, centered-layer, gesture-layer" style="--_pre-playback-place:{{preplaybackplace ?? 'center'}}" > <slot name="media" slot="media"></slot> <slot name="poster" slot="poster"></slot> <media-loading-indicator slot="centered-chrome" noautohide></media-loading-indicator> <template if="!audio"> <!-- Pre-playback UI --> <!-- same for both on-demand and live --> <div slot="centered-chrome" class="center-controls pre-playback"> <template if="!breakpointsm">{{>PlayButton section="center"}}</template> <template if="breakpointsm">{{>PrePlayButton section="center"}}</template> </div> <!-- Autoplay centered unmute button --> <!-- todo: figure out how show this with available state variables needs to show when: - autoplay is enabled - playback has been successful - audio is muted - in place / instead of the pre-plaback play button - not to show again after user has interacted with this button - OR user has interacted with the mute button in the control bar --> <!-- There should be a >MuteButton to the left of the "Unmute" text, but a templating bug makes it appear even if commented out in the markup, add it back when code is un-commented --> <!-- <div slot="centered-chrome" class="autoplay-unmute"> <div role="button" class="autoplay-unmute-btn">Unmute</div> </div> --> <template if="streamtype == 'on-demand'"> <template if="breakpointsm"> <media-control-bar part="control-bar top" slot="top-chrome">{{>TitleDisplay}} </media-control-bar> </template> {{>TimeRange}} <media-control-bar part="control-bar bottom"> {{>PlayButton}} {{>SeekBackwardButton}} {{>SeekForwardButton}} {{>TimeDisplay}} {{>MuteButton}} {{>VolumeRange}} <div class="spacer"></div> {{>RenditionMenu}} {{>PlaybackRateMenu}} {{>AudioTrackMenu}} {{>CaptionsMenu}} {{>AirplayButton}} {{>CastButton}} {{>PipButton}} {{>FullscreenButton}} </media-control-bar> </template> <template if="streamtype == 'live'"> <media-control-bar part="control-bar top" slot="top-chrome"> {{>LiveButton}} <template if="breakpointsm"> {{>TitleDisplay}} </template> </media-control-bar> <template if="targetlivewindow > 0">{{>TimeRange}}</template> <media-control-bar part="control-bar bottom"> {{>PlayButton}} <template if="targetlivewindow > 0">{{>SeekBackwardButton}} {{>SeekForwardButton}}</template> {{>MuteButton}} {{>VolumeRange}} <div class="spacer"></div> {{>RenditionMenu}} {{>AudioTrackMenu}} {{>CaptionsMenu}} {{>AirplayButton}} {{>CastButton}} {{>PipButton}} {{>FullscreenButton}} </media-control-bar> </template> </template> <template if="audio"> <template if="streamtype == 'on-demand'"> <template if="title"> <media-control-bar part="control-bar top">{{>TitleDisplay}}</media-control-bar> </template> <media-control-bar part="control-bar bottom"> {{>PlayButton}} <template if="breakpointsm"> {{>SeekBackwardButton}} {{>SeekForwardButton}} </template> {{>MuteButton}} <template if="breakpointsm">{{>VolumeRange}}</template> {{>TimeDisplay}} {{>TimeRange}} <template if="breakpointsm">{{>PlaybackRateMenu}}</template> {{>AirplayButton}} {{>CastButton}} </media-control-bar> </template> <template if="streamtype == 'live'"> <template if="title"> <media-control-bar part="control-bar top">{{>TitleDisplay}}</media-control-bar> </template> <media-control-bar part="control-bar bottom"> {{>PlayButton}} {{>LiveButton section="bottom"}} {{>MuteButton}} <template if="breakpointsm"> {{>VolumeRange}} <template if="targetlivewindow > 0"> {{>SeekBackwardButton}} {{>SeekForwardButton}} </template> </template> <template if="targetlivewindow > 0"> {{>TimeDisplay}} {{>TimeRange}} </template> <template if="!targetlivewindow"><div class="spacer"></div></template> {{>AirplayButton}} {{>CastButton}} </media-control-bar> </template> </template> <slot></slot> </media-controller> </template> `; var Ve3 = C3.createElement("template"); "innerHTML" in Ve3 && (Ve3.innerHTML = It4); var Dt4; var Vt4; var ge4 = class extends MediaThemeElement { }; ge4.template = (Vt4 = (Dt4 = Ve3.content) == null ? void 0 : Dt4.children) == null ? void 0 : Vt4[0]; p.customElements.get("media-theme-gerwig") || p.customElements.define("media-theme-gerwig", ge4); var Pa = "gerwig"; var w3 = { SRC: "src", POSTER: "poster" }; var n = { STYLE: "style", DEFAULT_HIDDEN_CAPTIONS: "default-hidden-captions", PRIMARY_COLOR: "primary-color", SECONDARY_COLOR: "secondary-color", ACCENT_COLOR: "accent-color", FORWARD_SEEK_OFFSET: "forward-seek-offset", BACKWARD_SEEK_OFFSET: "backward-seek-offset", PLAYBACK_TOKEN: "playback-token", THUMBNAIL_TOKEN: "thumbnail-token", STORYBOARD_TOKEN: "storyboard-token", DRM_TOKEN: "drm-token", STORYBOARD_SRC: "storyboard-src", THUMBNAIL_TIME: "thumbnail-time", AUDIO: "audio", NOHOTKEYS: "nohotkeys", HOTKEYS: "hotkeys", PLAYBACK_RATES: "playbackrates", DEFAULT_SHOW_REMAINING_TIME: "default-show-remaining-time", DEFAULT_DURATION: "default-duration", TITLE: "title", PLACEHOLDER: "placeholder", THEME: "theme", DEFAULT_STREAM_TYPE: "default-stream-type", TARGET_LIVE_WINDOW: "target-live-window", EXTRA_SOURCE_PARAMS: "extra-source-params", NO_VOLUME_PREF: "no-volume-pref", CAST_RECEIVER: "cast-receiver", NO_TOOLTIPS: "no-tooltips" }; var Be3 = ["audio", "backwardseekoffset", "defaultduration", "defaultshowremainingtime", "defaultsubtitles", "noautoseektolive", "disabled", "exportparts", "forwardseekoffset", "hideduration", "hotkeys", "nohotkeys", "playbackrates", "defaultstreamtype", "streamtype", "style", "targetlivewindow", "template", "title", "novolumepref"]; function Ia(t2, a2) { var i3; return { src: !t2.playbackId && t2.src, playbackId: t2.playbackId, hasSrc: !!t2.playbackId || !!t2.src || !!t2.currentSrc, poster: t2.poster, storyboard: t2.storyboard, storyboardSrc: t2.getAttribute(n.STORYBOARD_SRC), placeholder: t2.getAttribute("placeholder"), themeTemplate: Da2(t2), thumbnailTime: !t2.tokens.thumbnail && t2.thumbnailTime, autoplay: t2.autoplay, crossOrigin: t2.crossOrigin, loop: t2.loop, noHotKeys: t2.hasAttribute(n.NOHOTKEYS), hotKeys: t2.getAttribute(n.HOTKEYS), muted: t2.muted, paused: t2.paused, preload: t2.preload, envKey: t2.envKey, preferCmcd: t2.preferCmcd, debug: t2.debug, disableTracking: t2.disableTracking, disableCookies: t2.disableCookies, tokens: t2.tokens, beaconCollectionDomain: t2.beaconCollectionDomain, maxResolution: t2.maxResolution, minResolution: t2.minResolution, programStartTime: t2.programStartTime, programEndTime: t2.programEndTime, assetStartTime: t2.assetStartTime, assetEndTime: t2.assetEndTime, renditionOrder: t2.renditionOrder, metadata: t2.metadata, playerSoftwareName: t2.playerSoftwareName, playerSoftwareVersion: t2.playerSoftwareVersion, startTime: t2.startTime, preferPlayback: t2.preferPlayback, audio: t2.audio, defaultStreamType: t2.defaultStreamType, targetLiveWindow: t2.getAttribute(o.TARGET_LIVE_WINDOW), streamType: Q4(t2.getAttribute(o.STREAM_TYPE)), primaryColor: t2.getAttribute(n.PRIMARY_COLOR), secondaryColor: t2.getAttribute(n.SECONDARY_COLOR), accentColor: t2.getAttribute(n.ACCENT_COLOR), forwardSeekOffset: t2.forwardSeekOffset, backwardSeekOffset: t2.backwardSeekOffset, defaultHiddenCaptions: t2.defaultHiddenCaptions, defaultDuration: t2.defaultDuration, defaultShowRemainingTime: t2.defaultShowRemainingTime, hideDuration: Va(t2), playbackRates: t2.getAttribute(n.PLAYBACK_RATES), customDomain: (i3 = t2.getAttribute(o.CUSTOM_DOMAIN)) != null ? i3 : void 0, title: t2.getAttribute(n.TITLE), novolumepref: t2.hasAttribute(n.NO_VOLUME_PREF), castReceiver: t2.castReceiver, ...a2, extraSourceParams: t2.extraSourceParams }; } function Da2(t2) { var e, i3; let a2 = t2.theme; if (a2) { let r9 = (i3 = (e = t2.getRootNode()) == null ? void 0 : e.getElementById) == null ? void 0 : i3.call(e, a2); if (r9 && r9 instanceof HTMLTemplateElement) return r9; a2.startsWith("media-theme-") || (a2 = `media-theme-${a2}`); let o2 = p.customElements.get(a2); if (o2 != null && o2.template) return o2.template; } } function Va(t2) { var e; let a2 = (e = t2.mediaController) == null ? void 0 : e.querySelector("media-time-display"); return a2 && getComputedStyle(a2).getPropertyValue("--media-duration-display-display").trim() === "none"; } function Ut4(t2) { let a2 = t2.hasAttribute(n.TITLE) ? { video_title: t2.getAttribute(n.TITLE) } : {}; return t2.getAttributeNames().filter((e) => e.startsWith("metadata-")).reduce((e, i3) => { let r9 = t2.getAttribute(i3); return r9 !== null && (e[i3.replace(/^metadata-/, "").replace(/-/g, "_")] = r9), e; }, a2); } var Ha = Object.values(o); var Ka = Object.values(w3); var Ua = Object.values(n); var Ba = ce3(); var $a = "mux-player"; var Bt3 = { dialog: void 0, isDialogOpen: false }; var Fa = { redundant_streams: true }; var re4; var oe3; var V4; var ne4; var F3; var M3; var D3; var ve4; var $t3; var se3; var $e4; var P; var $4; var Te3; var Ft3; var Ee3; var Yt3; var Ae4; var Wt3; var Ce4; var Zt3; var ie4 = class extends Ne2 { constructor() { super(); b(this, M3); b(this, ve4); b(this, se3); b(this, P); b(this, Te3); b(this, Ee3); b(this, Ae4); b(this, Ce4); b(this, re4, false); b(this, oe3, {}); b(this, V4, true); b(this, ne4, new me2(this, "hotkeys")); b(this, F3, { ...Bt3, onCloseErrorDialog: () => h2(this, se3, $e4).call(this, { dialog: void 0, isDialogOpen: false }), onInitFocusDialog: (e) => { _e4(this, C3.activeElement) || e.preventDefault(); } }); this.attachShadow({ mode: "open" }), h2(this, ve4, $t3).call(this), this.isConnected && h2(this, M3, D3).call(this); } static get observedAttributes() { var e; return [...(e = Ne2.observedAttributes) != null ? e : [], ...Ka, ...Ha, ...Ua]; } get mediaTheme() { var e; return (e = this.shadowRoot) == null ? void 0 : e.querySelector("media-theme"); } get mediaController() { var e, i3; return (i3 = (e = this.mediaTheme) == null ? void 0 : e.shadowRoot) == null ? void 0 : i3.querySelector("media-controller"); } connectedCallback() { var i3; let e = (i3 = this.shadowRoot) == null ? void 0 : i3.querySelector("mux-video"); e && (e.metadata = Ut4(this)); } attributeChangedCallback(e, i3, r9) { switch (h2(this, M3, D3).call(this), super.attributeChangedCallback(e, i3, r9), e) { case n.HOTKEYS: u2(this, ne4).value = r9; break; case n.THUMBNAIL_TIME: { r9 != null && this.tokens.thumbnail && _2(E("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.")); break; } case n.THUMBNAIL_TOKEN: { if (r9) { let d2 = Q2(r9); if (d2) { let { aud: l2 } = d2, c3 = oe.THUMBNAIL; l2 !== c3 && _2(E("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({ aud: l2, expectedAud: c3, tokenNamePrefix: "thumbnail" })); } } break; } case n.STORYBOARD_TOKEN: { if (r9) { let d2 = Q2(r9); if (d2) { let { aud: l2 } = d2, c3 = oe.STORYBOARD; l2 !== c3 && _2(E("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({ aud: l2, expectedAud: c3, tokenNamePrefix: "storyboard" })); } } break; } case n.DRM_TOKEN: { if (r9) { let d2 = Q2(r9); if (d2) { let { aud: l2 } = d2, c3 = oe.DRM; l2 !== c3 && _2(E("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({ aud: l2, expectedAud: c3, tokenNamePrefix: "drm" })); } } break; } case o.PLAYBACK_ID: { r9 != null && r9.includes("?token") && E3(E("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({ playbackId: r9 })); break; } case o.STREAM_TYPE: r9 && ![D2.LIVE, D2.ON_DEMAND, D2.UNKNOWN].includes(r9) ? ["ll-live", "live:dvr", "ll-live:dvr"].includes(this.streamType) ? this.targetLiveWindow = r9.includes("dvr") ? Number.POSITIVE_INFINITY : 0 : Me4({ file: "invalid-stream-type.md", message: E("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({ streamType: this.streamType }) }) : r9 === D2.LIVE ? this.getAttribute(n.TARGET_LIVE_WINDOW) == null && (this.targetLiveWindow = 0) : this.targetLiveWindow = Number.NaN; } [o.PLAYBACK_ID, w3.SRC, n.PLAYBACK_TOKEN].includes(e) && i3 !== r9 && R3(this, F3, { ...u2(this, F3), ...Bt3 }), h2(this, P, $4).call(this, { [gt3(e)]: r9 }); } get preferCmcd() { var e; return (e = this.getAttribute(o.PREFER_CMCD)) != null ? e : void 0; } set preferCmcd(e) { e !== this.preferCmcd && (e ? Ut2.includes(e) ? this.setAttribute(o.PREFER_CMCD, e) : _2(`Invalid value for preferCmcd. Must be one of ${Ut2.join()}`) : this.removeAttribute(o.PREFER_CMCD)); } get hasPlayed() { var e, i3; return (i3 = (e = this.mediaController) == null ? void 0 : e.hasAttribute(MediaUIAttributes.MEDIA_HAS_PLAYED)) != null ? i3 : false; } get inLiveWindow() { var e; return (e = this.mediaController) == null ? void 0 : e.hasAttribute(MediaUIAttributes.MEDIA_TIME_IS_LIVE); } get _hls() { var e; return (e = this.media) == null ? void 0 : e._hls; } get mux() { var e; return (e = this.media) == null ? void 0 : e.mux; } get theme() { var e; return (e = this.getAttribute(n.THEME)) != null ? e : Pa; } set theme(e) { this.setAttribute(n.THEME, `${e}`); } get themeProps() { let e = this.mediaTheme; if (!e) return; let i3 = {}; for (let r9 of e.getAttributeNames()) { if (Be3.includes(r9)) continue; let o2 = e.getAttribute(r9); i3[ue3(r9)] = o2 === "" ? true : o2; } return i3; } set themeProps(e) { var r9, o2; h2(this, M3, D3).call(this); let i3 = { ...this.themeProps, ...e }; for (let d2 in i3) { if (Be3.includes(d2)) continue; let l2 = e == null ? void 0 : e[d2]; typeof l2 == "boolean" || l2 == null ? (r9 = this.mediaTheme) == null || r9.toggleAttribute(le4(d2), !!l2) : (o2 = this.mediaTheme) == null || o2.setAttribute(le4(d2), l2); } } get playbackId() { var e; return (e = this.getAttribute(o.PLAYBACK_ID)) != null ? e : void 0; } set playbackId(e) { e ? this.setAttribute(o.PLAYBACK_ID, e) : this.removeAttribute(o.PLAYBACK_ID); } get src() { var e, i3; return this.playbackId ? (e = B4(this, w3.SRC)) != null ? e : void 0 : (i3 = this.getAttribute(w3.SRC)) != null ? i3 : void 0; } set src(e) { e ? this.setAttribute(w3.SRC, e) : this.removeAttribute(w3.SRC); } get poster() { var r9; let e = this.getAttribute(w3.POSTER); if (e != null) return e; let { tokens: i3 } = this; if (i3.playback && !i3.thumbnail) { _2("Missing expected thumbnail token. No poster image will be shown"); return; } if (this.playbackId && !this.audio) return bt4(this.playbackId, { customDomain: this.customDomain, thumbnailTime: (r9 = this.thumbnailTime) != null ? r9 : this.startTime, programTime: this.programStartTime, token: i3.thumbnail }); } set poster(e) { e || e === "" ? this.setAttribute(w3.POSTER, e) : this.removeAttribute(w3.POSTER); } get storyboardSrc() { var e; return (e = this.getAttribute(n.STORYBOARD_SRC)) != null ? e : void 0; } set storyboardSrc(e) { e ? this.setAttribute(n.STORYBOARD_SRC, e) : this.removeAttribute(n.STORYBOARD_SRC); } get storyboard() { let { tokens: e } = this; if (this.storyboardSrc && !e.storyboard) return this.storyboardSrc; if (!(this.audio || !this.playbackId || !this.streamType || [D2.LIVE, D2.UNKNOWN].includes(this.streamType) || e.playback && !e.storyboard)) return ht4(this.playbackId, { customDomain: this.customDomain, token: e.storyboard, programStartTime: this.programStartTime, programEndTime: this.programEndTime }); } get audio() { return this.hasAttribute(n.AUDIO); } set audio(e) { if (!e) { this.removeAttribute(n.AUDIO); return; } this.setAttribute(n.AUDIO, ""); } get hotkeys() { return u2(this, ne4); } get nohotkeys() { return this.hasAttribute(n.NOHOTKEYS); } set nohotkeys(e) { if (!e) { this.removeAttribute(n.NOHOTKEYS); return; } this.setAttribute(n.NOHOTKEYS, ""); } get thumbnailTime() { return T2(this.getAttribute(n.THUMBNAIL_TIME)); } set thumbnailTime(e) { this.setAttribute(n.THUMBNAIL_TIME, `${e}`); } get title() { var e; return (e = this.getAttribute(n.TITLE)) != null ? e : ""; } set title(e) { e !== this.title && (e ? this.setAttribute(n.TITLE, e) : this.removeAttribute("title"), super.title = e); } get placeholder() { var e; return (e = B4(this, n.PLACEHOLDER)) != null ? e : ""; } set placeholder(e) { this.setAttribute(n.PLACEHOLDER, `${e}`); } get primaryColor() { var i3, r9; let e = this.getAttribute(n.PRIMARY_COLOR); if (e != null || this.mediaTheme && (e = (r9 = (i3 = p.getComputedStyle(this.mediaTheme)) == null ? void 0 : i3.getPropertyValue("--_primary-color")) == null ? void 0 : r9.trim(), e)) return e; } set primaryColor(e) { this.setAttribute(n.PRIMARY_COLOR, `${e}`); } get secondaryColor() { var i3, r9; let e = this.getAttribute(n.SECONDARY_COLOR); if (e != null || this.mediaTheme && (e = (r9 = (i3 = p.getComputedStyle(this.mediaTheme)) == null ? void 0 : i3.getPropertyValue("--_secondary-color")) == null ? void 0 : r9.trim(), e)) return e; } set secondaryColor(e) { this.setAttribute(n.SECONDARY_COLOR, `${e}`); } get accentColor() { var i3, r9; let e = this.getAttribute(n.ACCENT_COLOR); if (e != null || this.mediaTheme && (e = (r9 = (i3 = p.getComputedStyle(this.mediaTheme)) == null ? void 0 : i3.getPropertyValue("--_accent-color")) == null ? void 0 : r9.trim(), e)) return e; } set accentColor(e) { this.setAttribute(n.ACCENT_COLOR, `${e}`); } get defaultShowRemainingTime() { return this.hasAttribute(n.DEFAULT_SHOW_REMAINING_TIME); } set defaultShowRemainingTime(e) { e ? this.setAttribute(n.DEFAULT_SHOW_REMAINING_TIME, "") : this.removeAttribute(n.DEFAULT_SHOW_REMAINING_TIME); } get playbackRates() { if (this.hasAttribute(n.PLAYBACK_RATES)) return this.getAttribute(n.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map((e) => Number(e)).filter((e) => !Number.isNaN(e)).sort((e, i3) => e - i3); } set playbackRates(e) { if (!e) { this.removeAttribute(n.PLAYBACK_RATES); return; } this.setAttribute(n.PLAYBACK_RATES, e.join(" ")); } get forwardSeekOffset() { var e; return (e = T2(this.getAttribute(n.FORWARD_SEEK_OFFSET))) != null ? e : 10; } set forwardSeekOffset(e) { this.setAttribute(n.FORWARD_SEEK_OFFSET, `${e}`); } get backwardSeekOffset() { var e; return (e = T2(this.getAttribute(n.BACKWARD_SEEK_OFFSET))) != null ? e : 10; } set backwardSeekOffset(e) { this.setAttribute(n.BACKWARD_SEEK_OFFSET, `${e}`); } get defaultHiddenCaptions() { return this.hasAttribute(n.DEFAULT_HIDDEN_CAPTIONS); } set defaultHiddenCaptions(e) { e ? this.setAttribute(n.DEFAULT_HIDDEN_CAPTIONS, "") : this.removeAttribute(n.DEFAULT_HIDDEN_CAPTIONS); } get defaultDuration() { return T2(this.getAttribute(n.DEFAULT_DURATION)); } set defaultDuration(e) { e == null ? this.removeAttribute(n.DEFAULT_DURATION) : this.setAttribute(n.DEFAULT_DURATION, `${e}`); } get playerSoftwareName() { var e; return (e = this.getAttribute(o.PLAYER_SOFTWARE_NAME)) != null ? e : $a; } get playerSoftwareVersion() { var e; return (e = this.getAttribute(o.PLAYER_SOFTWARE_VERSION)) != null ? e : Ba; } get beaconCollectionDomain() { var e; return (e = this.getAttribute(o.BEACON_COLLECTION_DOMAIN)) != null ? e : void 0; } set beaconCollectionDomain(e) { e !== this.beaconCollectionDomain && (e ? this.setAttribute(o.BEACON_COLLECTION_DOMAIN, e) : this.removeAttribute(o.BEACON_COLLECTION_DOMAIN)); } get maxResolution() { var e; return (e = this.getAttribute(o.MAX_RESOLUTION)) != null ? e : void 0; } set maxResolution(e) { e !== this.maxResolution && (e ? this.setAttribute(o.MAX_RESOLUTION, e) : this.removeAttribute(o.MAX_RESOLUTION)); } get minResolution() { var e; return (e = this.getAttribute(o.MIN_RESOLUTION)) != null ? e : void 0; } set minResolution(e) { e !== this.minResolution && (e ? this.setAttribute(o.MIN_RESOLUTION, e) : this.removeAttribute(o.MIN_RESOLUTION)); } get renditionOrder() { var e; return (e = this.getAttribute(o.RENDITION_ORDER)) != null ? e : void 0; } set renditionOrder(e) { e !== this.renditionOrder && (e ? this.setAttribute(o.RENDITION_ORDER, e) : this.removeAttribute(o.RENDITION_ORDER)); } get programStartTime() { return T2(this.getAttribute(o.PROGRAM_START_TIME)); } set programStartTime(e) { e == null ? this.removeAttribute(o.PROGRAM_START_TIME) : this.setAttribute(o.PROGRAM_START_TIME, `${e}`); } get programEndTime() { return T2(this.getAttribute(o.PROGRAM_END_TIME)); } set programEndTime(e) { e == null ? this.removeAttribute(o.PROGRAM_END_TIME) : this.setAttribute(o.PROGRAM_END_TIME, `${e}`); } get assetStartTime() { return T2(this.getAttribute(o.ASSET_START_TIME)); } set assetStartTime(e) { e == null ? this.removeAttribute(o.ASSET_START_TIME) : this.setAttribute(o.ASSET_START_TIME, `${e}`); } get assetEndTime() { return T2(this.getAttribute(o.ASSET_END_TIME)); } set assetEndTime(e) { e == null ? this.removeAttribute(o.ASSET_END_TIME) : this.setAttribute(o.ASSET_END_TIME, `${e}`); } get extraSourceParams() { return this.hasAttribute(n.EXTRA_SOURCE_PARAMS) ? [...new URLSearchParams(this.getAttribute(n.EXTRA_SOURCE_PARAMS)).entries()].reduce((e, [i3, r9]) => (e[i3] = r9, e), {}) : Fa; } set extraSourceParams(e) { e == null ? this.removeAttribute(n.EXTRA_SOURCE_PARAMS) : this.setAttribute(n.EXTRA_SOURCE_PARAMS, new URLSearchParams(e).toString()); } get customDomain() { var e; return (e = this.getAttribute(o.CUSTOM_DOMAIN)) != null ? e : void 0; } set customDomain(e) { e !== this.customDomain && (e ? this.setAttribute(o.CUSTOM_DOMAIN, e) : this.removeAttribute(o.CUSTOM_DOMAIN)); } get envKey() { var e; return (e = B4(this, o.ENV_KEY)) != null ? e : void 0; } set envKey(e) { this.setAttribute(o.ENV_KEY, `${e}`); } get noVolumePref() { return this.hasAttribute(n.NO_VOLUME_PREF); } set noVolumePref(e) { e ? this.setAttribute(n.NO_VOLUME_PREF, "") : this.removeAttribute(n.NO_VOLUME_PREF); } get debug() { return B4(this, o.DEBUG) != null; } set debug(e) { e ? this.setAttribute(o.DEBUG, "") : this.removeAttribute(o.DEBUG); } get disableTracking() { return B4(this, o.DISABLE_TRACKING) != null; } set disableTracking(e) { this.toggleAttribute(o.DISABLE_TRACKING, !!e); } get disableCookies() { return B4(this, o.DISABLE_COOKIES) != null; } set disableCookies(e) { e ? this.setAttribute(o.DISABLE_COOKIES, "") : this.removeAttribute(o.DISABLE_COOKIES); } get streamType() { var e, i3, r9; return (r9 = (i3 = this.getAttribute(o.STREAM_TYPE)) != null ? i3 : (e = this.media) == null ? void 0 : e.streamType) != null ? r9 : D2.UNKNOWN; } set streamType(e) { this.setAttribute(o.STREAM_TYPE, `${e}`); } get defaultStreamType() { var e, i3, r9; return (r9 = (i3 = this.getAttribute(n.DEFAULT_STREAM_TYPE)) != null ? i3 : (e = this.mediaController) == null ? void 0 : e.getAttribute(n.DEFAULT_STREAM_TYPE)) != null ? r9 : D2.ON_DEMAND; } set defaultStreamType(e) { e ? this.setAttribute(n.DEFAULT_STREAM_TYPE, e) : this.removeAttribute(n.DEFAULT_STREAM_TYPE); } get targetLiveWindow() { var e, i3; return this.hasAttribute(n.TARGET_LIVE_WINDOW) ? +this.getAttribute(n.TARGET_LIVE_WINDOW) : (i3 = (e = this.media) == null ? void 0 : e.targetLiveWindow) != null ? i3 : Number.NaN; } set targetLiveWindow(e) { e == this.targetLiveWindow || Number.isNaN(e) && Number.isNaN(this.targetLiveWindow) || (e == null ? this.removeAttribute(n.TARGET_LIVE_WINDOW) : this.setAttribute(n.TARGET_LIVE_WINDOW, `${+e}`)); } get liveEdgeStart() { var e; return (e = this.media) == null ? void 0 : e.liveEdgeStart; } get startTime() { return T2(B4(this, o.START_TIME)); } set startTime(e) { this.setAttribute(o.START_TIME, `${e}`); } get preferPlayback() { let e = this.getAttribute(o.PREFER_PLAYBACK); if (e === q2.MSE || e === q2.NATIVE) return e; } set preferPlayback(e) { e !== this.preferPlayback && (e === q2.MSE || e === q2.NATIVE ? this.setAttribute(o.PREFER_PLAYBACK, e) : this.removeAttribute(o.PREFER_PLAYBACK)); } get metadata() { var e; return (e = this.media) == null ? void 0 : e.metadata; } set metadata(e) { if (h2(this, M3, D3).call(this), !this.media) { E3("underlying media element missing when trying to set metadata. metadata will not be set."); return; } this.media.metadata = { ...Ut4(this), ...e }; } get _hlsConfig() { var e; return (e = this.media) == null ? void 0 : e._hlsConfig; } set _hlsConfig(e) { if (h2(this, M3, D3).call(this), !this.media) { E3("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set."); return; } this.media._hlsConfig = e; } async addCuePoints(e) { var i3; if (h2(this, M3, D3).call(this), !this.media) { E3("underlying media element missing when trying to addCuePoints. cuePoints will not be added."); return; } return (i3 = this.media) == null ? void 0 : i3.addCuePoints(e); } get activeCuePoint() { var e; return (e = this.media) == null ? void 0 : e.activeCuePoint; } get cuePoints() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.cuePoints) != null ? i3 : []; } addChapters(e) { var i3; if (h2(this, M3, D3).call(this), !this.media) { E3("underlying media element missing when trying to addChapters. chapters will not be added."); return; } return (i3 = this.media) == null ? void 0 : i3.addChapters(e); } get activeChapter() { var e; return (e = this.media) == null ? void 0 : e.activeChapter; } get chapters() { var e, i3; return (i3 = (e = this.media) == null ? void 0 : e.chapters) != null ? i3 : []; } getStartDate() { var e; return (e = this.media) == null ? void 0 : e.getStartDate(); } get currentPdt() { var e; return (e = this.media) == null ? void 0 : e.currentPdt; } get tokens() { let e = this.getAttribute(n.PLAYBACK_TOKEN), i3 = this.getAttribute(n.DRM_TOKEN), r9 = this.getAttribute(n.THUMBNAIL_TOKEN), o2 = this.getAttribute(n.STORYBOARD_TOKEN); return { ...u2(this, oe3), ...e != null ? { playback: e } : {}, ...i3 != null ? { drm: i3 } : {}, ...r9 != null ? { thumbnail: r9 } : {}, ...o2 != null ? { storyboard: o2 } : {} }; } set tokens(e) { R3(this, oe3, e != null ? e : {}); } get playbackToken() { var e; return (e = this.getAttribute(n.PLAYBACK_TOKEN)) != null ? e : void 0; } set playbackToken(e) { this.setAttribute(n.PLAYBACK_TOKEN, `${e}`); } get drmToken() { var e; return (e = this.getAttribute(n.DRM_TOKEN)) != null ? e : void 0; } set drmToken(e) { this.setAttribute(n.DRM_TOKEN, `${e}`); } get thumbnailToken() { var e; return (e = this.getAttribute(n.THUMBNAIL_TOKEN)) != null ? e : void 0; } set thumbnailToken(e) { this.setAttribute(n.THUMBNAIL_TOKEN, `${e}`); } get storyboardToken() { var e; return (e = this.getAttribute(n.STORYBOARD_TOKEN)) != null ? e : void 0; } set storyboardToken(e) { this.setAttribute(n.STORYBOARD_TOKEN, `${e}`); } addTextTrack(e, i3, r9, o2) { var l2; let d2 = (l2 = this.media) == null ? void 0 : l2.nativeEl; if (d2) return te2(d2, e, i3, r9, o2); } removeTextTrack(e) { var r9; let i3 = (r9 = this.media) == null ? void 0 : r9.nativeEl; if (i3) return Ze2(i3, e); } get textTracks() { var e; return (e = this.media) == null ? void 0 : e.textTracks; } get castReceiver() { var e; return (e = this.getAttribute(n.CAST_RECEIVER)) != null ? e : void 0; } set castReceiver(e) { e !== this.castReceiver && (e ? this.setAttribute(n.CAST_RECEIVER, e) : this.removeAttribute(n.CAST_RECEIVER)); } get castCustomData() { var e; return (e = this.media) == null ? void 0 : e.castCustomData; } set castCustomData(e) { if (!this.media) { E3("underlying media element missing when trying to set castCustomData. castCustomData will not be set."); return; } this.media.castCustomData = e; } get noTooltips() { return this.hasAttribute(n.NO_TOOLTIPS); } set noTooltips(e) { if (!e) { this.removeAttribute(n.NO_TOOLTIPS); return; } this.setAttribute(n.NO_TOOLTIPS, ""); } }; re4 = /* @__PURE__ */ new WeakMap(), oe3 = /* @__PURE__ */ new WeakMap(), V4 = /* @__PURE__ */ new WeakMap(), ne4 = /* @__PURE__ */ new WeakMap(), F3 = /* @__PURE__ */ new WeakMap(), M3 = /* @__PURE__ */ new WeakSet(), D3 = function() { var e, i3, r9, o2; if (!u2(this, re4)) { R3(this, re4, true), h2(this, P, $4).call(this); try { if (customElements.upgrade(this.mediaTheme), !(this.mediaTheme instanceof p.HTMLElement)) throw ""; } catch { E3("<media-theme> failed to upgrade!"); } try { if (customElements.upgrade(this.media), !(this.media instanceof Cs)) throw ""; } catch { E3("<mux-video> failed to upgrade!"); } try { if (customElements.upgrade(this.mediaController), !(this.mediaController instanceof media_controller_default)) throw ""; } catch { E3("<media-controller> failed to upgrade!"); } this.init(), h2(this, Te3, Ft3).call(this), h2(this, Ee3, Yt3).call(this), h2(this, Ae4, Wt3).call(this), R3(this, V4, (i3 = (e = this.mediaController) == null ? void 0 : e.hasAttribute(Attributes.USER_INACTIVE)) != null ? i3 : true), h2(this, Ce4, Zt3).call(this), (r9 = this.media) == null || r9.addEventListener("streamtypechange", () => h2(this, P, $4).call(this)), (o2 = this.media) == null || o2.addEventListener("loadstart", () => h2(this, P, $4).call(this)); } }, ve4 = /* @__PURE__ */ new WeakSet(), $t3 = function() { var e, i3; try { (e = window == null ? void 0 : window.CSS) == null || e.registerProperty({ name: "--media-primary-color", syntax: "<color>", inherits: true }), (i3 = window == null ? void 0 : window.CSS) == null || i3.registerProperty({ name: "--media-secondary-color", syntax: "<color>", inherits: true }); } catch { } }, se3 = /* @__PURE__ */ new WeakSet(), $e4 = function(e) { Object.assign(u2(this, F3), e), h2(this, P, $4).call(this); }, P = /* @__PURE__ */ new WeakSet(), $4 = function(e = {}) { Lt3(St3(Ia(this, { ...u2(this, F3), ...e })), this.shadowRoot); }, Te3 = /* @__PURE__ */ new WeakSet(), Ft3 = function() { let e = (r9) => { var l2, c3; if (!(r9 != null && r9.startsWith("theme-"))) return; let o2 = r9.replace(/^theme-/, ""); if (Be3.includes(o2)) return; let d2 = this.getAttribute(r9); d2 != null ? (l2 = this.mediaTheme) == null || l2.setAttribute(o2, d2) : (c3 = this.mediaTheme) == null || c3.removeAttribute(o2); }; new MutationObserver((r9) => { for (let { attributeName: o2 } of r9) e(o2); }).observe(this, { attributes: true }), this.getAttributeNames().forEach(e); }, Ee3 = /* @__PURE__ */ new WeakSet(), Yt3 = function() { var i3; let e = (r9) => { let { detail: o2 } = r9; if (o2 instanceof T || (o2 = new T(o2.message, o2.code, o2.fatal)), !(o2 != null && o2.fatal)) { _2(o2), o2.data && _2(`${o2.name} data:`, o2.data); return; } let { dialog: d2, devlog: l2 } = De3(o2, false); l2.message && Me4(l2), E3(o2), o2.data && E3(`${o2.name} data:`, o2.data), h2(this, se3, $e4).call(this, { isDialogOpen: true, dialog: d2 }); }; this.addEventListener("error", e), this.media && (this.media.errorTranslator = (r9 = {}) => { var d2, l2, c3; if (!(((d2 = this.media) == null ? void 0 : d2.error) instanceof T)) return r9; let { devlog: o2 } = De3((l2 = this.media) == null ? void 0 : l2.error, false); return { player_error_code: (c3 = this.media) == null ? void 0 : c3.error.code, player_error_message: o2.message ? String(o2.message) : r9.player_error_message, player_error_context: o2.context ? String(o2.context) : r9.player_error_context }; }), (i3 = this.media) == null || i3.addEventListener("error", (r9) => { var d2, l2; let { detail: o2 } = r9; if (!o2) { let { message: c3, code: O3 } = (l2 = (d2 = this.media) == null ? void 0 : d2.error) != null ? l2 : {}; o2 = new T(c3, O3); } o2 != null && o2.fatal && this.dispatchEvent(new CustomEvent("error", { detail: o2 })); }); }, Ae4 = /* @__PURE__ */ new WeakSet(), Wt3 = function() { var i3, r9, o2, d2; let e = () => h2(this, P, $4).call(this); (r9 = (i3 = this.media) == null ? void 0 : i3.textTracks) == null || r9.addEventListener("addtrack", e), (d2 = (o2 = this.media) == null ? void 0 : o2.textTracks) == null || d2.addEventListener("removetrack", e); }, Ce4 = /* @__PURE__ */ new WeakSet(), Zt3 = function() { var O3, j3; if (!/Firefox/i.test(navigator.userAgent)) return; let i3, r9 = /* @__PURE__ */ new WeakMap(), o2 = () => this.streamType === D2.LIVE && !this.secondaryColor && this.offsetWidth >= 800, d2 = (k3, A4, x2 = false) => { if (o2()) return; Array.from(k3 && k3.activeCues || []).forEach((g2) => { if (!(!g2.snapToLines || g2.line < -5 || g2.line >= 0 && g2.line < 10)) if (!A4 || this.paused) { let de5 = g2.text.split(` `).length, q4 = -3; this.streamType === D2.LIVE && (q4 = -2); let z3 = q4 - de5; if (g2.line === z3 && !x2) return; r9.has(g2) || r9.set(g2, g2.line), g2.line = z3; } else setTimeout(() => { g2.line = r9.get(g2) || "auto"; }, 500); }); }, l2 = () => { var k3, A4; d2(i3, (A4 = (k3 = this.mediaController) == null ? void 0 : k3.hasAttribute(Attributes.USER_INACTIVE)) != null ? A4 : false); }, c3 = () => { var x2, Y4; let A4 = Array.from(((Y4 = (x2 = this.mediaController) == null ? void 0 : x2.media) == null ? void 0 : Y4.textTracks) || []).filter((g2) => ["subtitles", "captions"].includes(g2.kind) && g2.mode === "showing")[0]; A4 !== i3 && (i3 == null || i3.removeEventListener("cuechange", l2)), i3 = A4, i3 == null || i3.addEventListener("cuechange", l2), d2(i3, u2(this, V4)); }; c3(), (O3 = this.textTracks) == null || O3.addEventListener("change", c3), (j3 = this.textTracks) == null || j3.addEventListener("addtrack", c3), this.addEventListener("userinactivechange", () => { var A4, x2; let k3 = (x2 = (A4 = this.mediaController) == null ? void 0 : A4.hasAttribute(Attributes.USER_INACTIVE)) != null ? x2 : true; u2(this, V4) !== k3 && (R3(this, V4, k3), d2(i3, u2(this, V4))); }); }; function B4(t2, a2) { return t2.media ? t2.media.getAttribute(a2) : t2.getAttribute(a2); } p.customElements.get("mux-player") || (p.customElements.define("mux-player", ie4), p.MuxPlayerElement = ie4); // node_modules/@mux/mux-player-react/dist/index.mjs var import_react12 = __toESM(require_react(), 1); var import_react13 = __toESM(require_react(), 1); var import_react14 = __toESM(require_react(), 1); var d = { className: "class", classname: "class", htmlFor: "for", crossOrigin: "crossorigin", viewBox: "viewBox", playsInline: "playsinline", autoPlay: "autoplay", playbackRate: "playbackrate" }; var $5 = (e) => e == null; var Q5 = (e, n2) => $5(n2) ? false : e in n2; var X5 = (e) => e.replace(/[A-Z]/g, (n2) => `-${n2.toLowerCase()}`); var B5 = (e, n2) => { if (!(typeof n2 == "boolean" && !n2)) { if (Q5(e, d)) return d[e]; if (typeof n2 != null) return /[A-Z]/.test(e) ? X5(e) : e; } }; var ee5 = (e, n2) => typeof e == "boolean" ? "" : e; var p2 = (e = {}) => Object.entries(e).reduce((n2, [t2, o2]) => { let r9 = B5(t2, o2); if (!r9) return n2; let s = ee5(o2, t2); return n2[r9] = s, n2; }, {}); var m = (...e) => { let n2 = (0, import_react13.useRef)(null); return (0, import_react13.useEffect)(() => { e.forEach((t2) => { t2 && (typeof t2 == "function" ? t2(n2.current) : t2.current = n2.current); }); }, [e]), n2; }; var re5 = Object.prototype.hasOwnProperty; var oe4 = (e, n2) => { if (Object.is(e, n2)) return true; if (typeof e != "object" || e === null || typeof n2 != "object" || n2 === null) return false; if (Array.isArray(e)) return !Array.isArray(n2) || e.length !== n2.length ? false : e.some((r9, s) => n2[s] === r9); let t2 = Object.keys(e), o2 = Object.keys(n2); if (t2.length !== o2.length) return false; for (let r9 = 0; r9 < t2.length; r9++) if (!re5.call(n2, t2[r9]) || !Object.is(e[t2[r9]], n2[t2[r9]])) return false; return true; }; var c2 = (e, n2, t2) => !oe4(n2, e[t2]); var ie5 = (e, n2, t2) => { e[t2] = n2; }; var se4 = (e, n2, t2, o2 = ie5, r9 = c2) => (0, import_react14.useEffect)(() => { let s = t2 == null ? void 0 : t2.current; s && r9(s, n2, e) && o2(s, n2, e); }, [t2 == null ? void 0 : t2.current, n2]); var i2 = se4; var le5 = () => { try { return "3.1.0"; } catch { } return "UNKNOWN"; }; var ue4 = le5(); var E4 = () => ue4; var de4 = import_react11.default.forwardRef(({ children: e, ...n2 }, t2) => import_react11.default.createElement("mux-player", p2({ ...n2, ref: t2 }), e)); var a = (e, n2, t2) => (0, import_react11.useEffect)(() => { let o2 = n2 == null ? void 0 : n2.current; if (!(!o2 || !t2)) return o2.addEventListener(e, t2), () => { o2.removeEventListener(e, t2); }; }, [n2 == null ? void 0 : n2.current, t2]); var pe5 = (e, n2) => { let { onAbort: t2, onCanPlay: o2, onCanPlayThrough: r9, onEmptied: s, onLoadStart: g2, onLoadedData: M4, onLoadedMetadata: f, onProgress: P2, onDurationChange: b2, onVolumeChange: v2, onRateChange: x2, onResize: h3, onWaiting: T3, onPlay: R4, onPlaying: C4, onTimeUpdate: k3, onPause: L2, onSeeking: O3, onSeeked: S3, onStalled: G3, onSuspend: w4, onEnded: V5, onError: A4, onCuePointChange: N2, onCuePointsChange: D4, onChapterChange: I4, metadata: K4, tokens: U5, paused: _3, playbackId: H5, playbackRates: j3, currentTime: z3, themeProps: F4, extraSourceParams: W5, castCustomData: Z4, _hlsConfig: q4, ...J5 } = n2; return i2("playbackRates", j3, e), i2("metadata", K4, e), i2("extraSourceParams", W5, e), i2("_hlsConfig", q4, e), i2("themeProps", F4, e), i2("tokens", U5, e), i2("playbackId", H5, e), i2("castCustomData", Z4, e), i2("paused", _3, e, (l2, u3) => { u3 != null && (u3 ? l2.pause() : l2.play()); }, (l2, u3, Y4) => l2.hasAttribute("autoplay") && !l2.hasPlayed ? false : c2(l2, u3, Y4)), i2("currentTime", z3, e, (l2, u3) => { u3 != null && (l2.currentTime = u3); }), a("abort", e, t2), a("canplay", e, o2), a("canplaythrough", e, r9), a("emptied", e, s), a("loadstart", e, g2), a("loadeddata", e, M4), a("loadedmetadata", e, f), a("progress", e, P2), a("durationchange", e, b2), a("volumechange", e, v2), a("ratechange", e, x2), a("resize", e, h3), a("waiting", e, T3), a("play", e, R4), a("playing", e, C4), a("timeupdate", e, k3), a("pause", e, L2), a("seeking", e, O3), a("seeked", e, S3), a("stalled", e, G3), a("suspend", e, w4), a("ended", e, V5), a("error", e, A4), a("cuepointchange", e, N2), a("cuepointschange", e, D4), a("chapterchange", e, I4), [J5]; }; var me3 = E4(); var Ee4 = "mux-player-react"; var ge5 = import_react11.default.forwardRef((e, n2) => { let t2 = (0, import_react12.useRef)(null), o2 = m(t2, n2), [r9] = pe5(t2, e); return import_react11.default.createElement(de4, { ref: o2, playerSoftwareName: Ee4, playerSoftwareVersion: me3, ...r9 }); }); var Ne3 = ge5; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/AssetPreview.mjs var CardAsset2 = dt(Flex)` min-height: 26.4rem; border-radius: ${({ theme }) => theme.borderRadius} ${({ theme }) => theme.borderRadius} 0 0; background: linear-gradient( 180deg, ${({ theme }) => theme.colors.neutral0} 0%, ${({ theme }) => theme.colors.neutral100} 121.48% ); `; var AssetPreview = React13.forwardRef(({ mime, url, name, ...props }, ref) => { const theme = nt(); const { formatMessage } = useIntl(); if (mime.includes(AssetType.Image)) { return (0, import_jsx_runtime8.jsx)("img", { ref, src: url, alt: name, ...props }); } if (mime.includes(AssetType.Video)) { return (0, import_jsx_runtime8.jsx)(Ne3, { src: url, accentColor: theme.colors.primary500 }); } if (mime.includes(AssetType.Audio)) { return (0, import_jsx_runtime8.jsx)(Box, { margin: "5", children: (0, import_jsx_runtime8.jsx)("audio", { controls: true, src: url, ref, ...props, children: name }) }); } if (mime.includes("pdf")) { return (0, import_jsx_runtime8.jsx)(CardAsset2, { width: "100%", justifyContent: "center", ...props, children: (0, import_jsx_runtime8.jsxs)(Flex, { gap: 2, direction: "column", alignItems: "center", children: [ (0, import_jsx_runtime8.jsx)(ForwardRef$3p, { "aria-label": name, fill: "neutral500", width: 24, height: 24 }), (0, import_jsx_runtime8.jsx)(Typography, { textColor: "neutral500", variant: "pi", children: formatMessage({ id: "noPreview", defaultMessage: "No preview available" }) }) ] }) }); } return (0, import_jsx_runtime8.jsx)(CardAsset2, { width: "100%", justifyContent: "center", ...props, children: (0, import_jsx_runtime8.jsxs)(Flex, { gap: 2, direction: "column", alignItems: "center", children: [ (0, import_jsx_runtime8.jsx)(ForwardRef$3v, { "aria-label": name, fill: "neutral500", width: 24, height: 24 }), (0, import_jsx_runtime8.jsx)(Typography, { textColor: "neutral500", variant: "pi", children: formatMessage({ id: "noPreview", defaultMessage: "No preview available" }) }) ] }) }); }); AssetPreview.displayName = "AssetPreview"; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/CroppingActions.mjs var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1); var import_qs5 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/PreviewComponents.mjs var RelativeBox = dt(Box)` position: relative; `; var Wrapper = dt.div` position: relative; display: flex; justify-content: center; background: repeating-conic-gradient( ${({ theme }) => theme.colors.neutral100} 0% 25%, transparent 0% 50% ) 50% / 20px 20px; svg { height: 26px; } img, mux-player { margin: 0; padding: 0; max-height: 26.4rem; max-width: 100%; } mux-player { --play-button: inline-flex; --mute-button: inline-flex; --pip-button: inline-flex; --fullscreen-button: inline-flex; --playback-rate-button: inline-flex; --volume-range: inline-flex; --time-range: inline-flex; --time-display: inline-flex; --duration-display: inline-flex; } `; var ActionRow = dt(Flex)` height: 5.2rem; background-color: ${({ $blurry }) => $blurry ? `rgba(33, 33, 52, 0.4)` : void 0}; `; var CroppingActionRow = dt(Flex)` z-index: 1; height: 5.2rem; position: absolute; background-color: rgba(33, 33, 52, 0.4); width: 100%; `; var BadgeOverride = dt(Badge)` span { color: inherit; font-weight: ${({ theme }) => theme.fontWeights.regular}; } `; var UploadProgressWrapper = dt.div` position: absolute; z-index: 2; height: 100%; width: 100%; `; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/CroppingActions.mjs var CroppingActions = ({ onCancel, onValidate, onDuplicate }) => { const { formatMessage } = useIntl(); const theme = nt(); return (0, import_jsx_runtime9.jsx)(FocusTrap, { onEscape: onCancel, children: (0, import_jsx_runtime9.jsx)(CroppingActionRow, { justifyContent: "flex-end", paddingLeft: 3, paddingRight: 3, children: (0, import_jsx_runtime9.jsxs)(Flex, { gap: 1, children: [ (0, import_jsx_runtime9.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.stop-crop"), defaultMessage: "Stop cropping" }), onClick: onCancel, children: (0, import_jsx_runtime9.jsx)(ForwardRef$45, {}) }), (0, import_jsx_runtime9.jsxs)(Menu.Root, { children: [ (0, import_jsx_runtime9.jsx)(Trigger, { "aria-label": formatMessage({ id: getTrad("control-card.crop"), defaultMessage: "Crop" }), variant: "tertiary", paddingLeft: 2, paddingRight: 2, endIcon: null, children: (0, import_jsx_runtime9.jsx)(ForwardRef$4F, { "aria-hidden": true, focusable: false, style: { position: "relative", top: 2 }, fill: "#C0C0D0" }) }), (0, import_jsx_runtime9.jsxs)(Menu.Content, { zIndex: theme.zIndices.dialog, children: [ (0, import_jsx_runtime9.jsx)(Menu.Item, { onSelect: onValidate, children: formatMessage({ id: getTrad("checkControl.crop-original"), defaultMessage: "Crop the original asset" }) }), onDuplicate && (0, import_jsx_runtime9.jsx)(Menu.Item, { onSelect: onDuplicate, children: formatMessage({ id: getTrad("checkControl.crop-duplicate"), defaultMessage: "Duplicate & crop the asset" }) }) ] }) ] }) ] }) }) }); }; var Trigger = dt(Menu.Trigger)` svg { > g, path { fill: ${({ theme }) => theme.colors.neutral500}; } } &:hover { svg { > g, path { fill: ${({ theme }) => theme.colors.neutral600}; } } } &:active { svg { > g, path { fill: ${({ theme }) => theme.colors.neutral400}; } } } `; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/PreviewBox/PreviewBox.mjs import "/home/oier/projects/fosil-group/pole-book/server/node_modules/cropperjs/dist/cropper.css"; var PreviewBox = ({ asset, canUpdate, canCopyLink, canDownload, onDelete, onCropFinish, onCropStart, onCropCancel, replacementFile, trackedLocation }) => { var _a3; const { trackUsage } = useTracking(); const previewRef = React14.useRef(null); const [isCropImageReady, setIsCropImageReady] = React14.useState(false); const [hasCropIntent, setHasCropIntent] = React14.useState(null); const [assetUrl, setAssetUrl] = React14.useState(createAssetUrl(asset, false)); const [thumbnailUrl, setThumbnailUrl] = React14.useState(createAssetUrl(asset, true)); const { formatMessage } = useIntl(); const [showConfirmDialog, setShowConfirmDialog] = React14.useState(false); const { crop: crop2, produceFile, stopCropping, isCropping, isCropperReady, width, height } = useCropImg(); const { editAsset, error, isLoading, progress, cancel } = useEditAsset(); const { upload, isLoading: isLoadingUpload, cancel: cancelUpload, error: uploadError, progress: progressUpload } = useUpload(); React14.useEffect(() => { if (replacementFile) { const fileLocalUrl = URL.createObjectURL(replacementFile); if (asset.isLocal) { asset.url = fileLocalUrl; } setAssetUrl(fileLocalUrl); setThumbnailUrl(fileLocalUrl); } }, [ replacementFile, asset ]); React14.useEffect(() => { if (hasCropIntent === false) { stopCropping(); onCropCancel(); } }, [ hasCropIntent, stopCropping, onCropCancel, onCropFinish ]); React14.useEffect(() => { if (hasCropIntent && isCropImageReady) { crop2(previewRef.current); onCropStart(); } }, [ isCropImageReady, hasCropIntent, onCropStart, crop2 ]); const handleCropping = async () => { var _a4; const nextAsset = { ...asset, width, height, folder: (_a4 = asset.folder) == null ? void 0 : _a4.id }; const file = await produceFile(nextAsset.name, nextAsset.mime, nextAsset.updatedAt); let optimizedCachingImage; let optimizedCachingThumbnailImage; if (asset.isLocal) { optimizedCachingImage = URL.createObjectURL(file); optimizedCachingThumbnailImage = optimizedCachingImage; asset.url = optimizedCachingImage; asset.rawFile = file; trackUsage("didCropFile", { duplicatedFile: null, location: trackedLocation }); } else { const updatedAsset = await editAsset(nextAsset, file); optimizedCachingImage = createAssetUrl(updatedAsset, false); optimizedCachingThumbnailImage = createAssetUrl(updatedAsset, true); trackUsage("didCropFile", { duplicatedFile: false, location: trackedLocation }); } setAssetUrl(optimizedCachingImage); setThumbnailUrl(optimizedCachingThumbnailImage); setHasCropIntent(false); }; const isInCroppingMode = isCropping && !isLoading; const handleDuplication = async () => { var _a4; const nextAsset = { ...asset, width, height }; const file = await produceFile(nextAsset.name, nextAsset.mime, nextAsset.updatedAt); await upload({ name: file.name, rawFile: file }, ((_a4 = asset.folder) == null ? void 0 : _a4.id) ? asset.folder.id : null); trackUsage("didCropFile", { duplicatedFile: true, location: trackedLocation }); setHasCropIntent(false); onCropFinish(); }; const handleCropCancel = () => { setHasCropIntent(false); }; const handleCropStart = () => { setHasCropIntent(true); }; return (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [ (0, import_jsx_runtime10.jsxs)(RelativeBox, { hasRadius: true, background: "neutral150", borderColor: "neutral200", children: [ isCropperReady && isInCroppingMode && (0, import_jsx_runtime10.jsx)(CroppingActions, { onValidate: handleCropping, onDuplicate: asset.isLocal ? void 0 : handleDuplication, onCancel: handleCropCancel }), (0, import_jsx_runtime10.jsx)(ActionRow, { paddingLeft: 3, paddingRight: 3, justifyContent: "flex-end", children: (0, import_jsx_runtime10.jsxs)(Flex, { gap: 1, children: [ canUpdate && !asset.isLocal && (0, import_jsx_runtime10.jsx)(IconButton, { label: formatMessage({ id: "global.delete", defaultMessage: "Delete" }), onClick: () => setShowConfirmDialog(true), children: (0, import_jsx_runtime10.jsx)(ForwardRef$j, {}) }), canDownload && (0, import_jsx_runtime10.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.download"), defaultMessage: "Download" }), onClick: () => downloadFile(assetUrl, asset.name), children: (0, import_jsx_runtime10.jsx)(ForwardRef$3V, {}) }), canCopyLink && (0, import_jsx_runtime10.jsx)(CopyLinkButton, { url: assetUrl }), canUpdate && ((_a3 = asset.mime) == null ? void 0 : _a3.includes(AssetType.Image)) && (0, import_jsx_runtime10.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.crop"), defaultMessage: "Crop" }), onClick: handleCropStart, children: (0, import_jsx_runtime10.jsx)(ForwardRef$47, {}) }) ] }) }), (0, import_jsx_runtime10.jsxs)(Wrapper, { children: [ isLoading && (0, import_jsx_runtime10.jsx)(UploadProgressWrapper, { children: (0, import_jsx_runtime10.jsx)(UploadProgress, { error, onCancel: cancel, progress }) }), isLoadingUpload && (0, import_jsx_runtime10.jsx)(UploadProgressWrapper, { children: (0, import_jsx_runtime10.jsx)(UploadProgress, { error: uploadError, onCancel: cancelUpload, progress: progressUpload }) }), (0, import_jsx_runtime10.jsx)(AssetPreview, { ref: previewRef, mime: asset.mime, name: asset.name, url: hasCropIntent ? assetUrl : thumbnailUrl, onLoad: () => { if (asset.isLocal || hasCropIntent) { setIsCropImageReady(true); } } }) ] }), (0, import_jsx_runtime10.jsx)(ActionRow, { paddingLeft: 2, paddingRight: 2, justifyContent: "flex-end", $blurry: isInCroppingMode, children: isInCroppingMode && width && height && (0, import_jsx_runtime10.jsx)(BadgeOverride, { background: "neutral900", color: "neutral0", children: width && height ? `${height}✕${width}` : "N/A" }) }) ] }), (0, import_jsx_runtime10.jsx)(RemoveAssetDialog, { open: showConfirmDialog, onClose: () => { setShowConfirmDialog(false); onDelete(null); }, asset }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/ReplaceMediaButton.mjs var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1); var React15 = __toESM(require_react(), 1); var import_qs7 = __toESM(require_lib(), 1); var ReplaceMediaButton = ({ onSelectMedia, acceptedMime, trackedLocation, ...props }) => { const { formatMessage } = useIntl(); const inputRef = React15.useRef(null); const { trackUsage } = useTracking(); const handleClick = (e) => { var _a3; e.preventDefault(); if (trackedLocation) { trackUsage("didReplaceMedia", { location: trackedLocation }); } (_a3 = inputRef.current) == null ? void 0 : _a3.click(); }; const handleChange = () => { var _a3, _b; const file = (_b = (_a3 = inputRef.current) == null ? void 0 : _a3.files) == null ? void 0 : _b[0]; onSelectMedia(file); }; return (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [ (0, import_jsx_runtime11.jsx)(Button, { variant: "secondary", onClick: handleClick, ...props, children: formatMessage({ id: getTrad("control-card.replace-media"), defaultMessage: "Replace media" }) }), (0, import_jsx_runtime11.jsx)(VisuallyHidden, { children: (0, import_jsx_runtime11.jsx)("input", { accept: acceptedMime, type: "file", name: "file", "data-testid": "file-input", tabIndex: -1, ref: inputRef, onChange: handleChange, "aria-hidden": true }) }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/EditAssetDialog/EditAssetContent.mjs var LoadingBody = dt(Flex)` /* 80px are coming from the Tabs component that is not included in the ModalBody */ min-height: ${() => `calc(60vh + 8rem)`}; `; var fileInfoSchema = create3({ name: create().required(), alternativeText: create(), caption: create(), folder: create2() }); var EditAssetContent = ({ onClose, asset, canUpdate = false, canCopyLink = false, canDownload = false, trackedLocation }) => { var _a3, _b; const { formatMessage, formatDate } = useIntl(); const { trackUsage } = useTracking(); const submitButtonRef = React16.useRef(null); const [isCropping, setIsCropping] = React16.useState(false); const [replacementFile, setReplacementFile] = React16.useState(); const { editAsset, isLoading } = useEditAsset(); const { data: folderStructure, isLoading: folderStructureIsLoading } = useFolderStructure({ enabled: true }); const handleSubmit = async (values) => { var _a4, _b2, _c, _d, _e5; const nextAsset = { ...asset, ...values, folder: (_a4 = values.parent) == null ? void 0 : _a4.value }; if (asset == null ? void 0 : asset.isLocal) { onClose(nextAsset); } else { const editedAsset = await editAsset(nextAsset, replacementFile); const assetType = (_b2 = asset == null ? void 0 : asset.mime) == null ? void 0 : _b2.split("/")[0]; const didChangeLocation = ((_c = asset == null ? void 0 : asset.folder) == null ? void 0 : _c.id) ? asset.folder.id !== ((_d = values.parent) == null ? void 0 : _d.value) : (asset == null ? void 0 : asset.folder) === null && !!((_e5 = values.parent) == null ? void 0 : _e5.value); trackUsage("didEditMediaLibraryElements", { location: trackedLocation, type: assetType, changeLocation: didChangeLocation }); onClose(editedAsset); } }; const handleStartCropping = () => { setIsCropping(true); }; const handleCancelCropping = () => { setIsCropping(false); }; const handleFinishCropping = () => { setIsCropping(false); onClose(); }; const formDisabled = !canUpdate || isCropping; const handleConfirmClose = () => { const confirm = window.confirm(formatMessage({ id: "window.confirm.close-modal.file", defaultMessage: "Are you sure? Your changes will be lost." })); if (confirm) { onClose(); } }; const activeFolderId = (_a3 = asset == null ? void 0 : asset.folder) == null ? void 0 : _a3.id; const initialFormData = !folderStructureIsLoading && { name: asset == null ? void 0 : asset.name, alternativeText: (asset == null ? void 0 : asset.alternativeText) ?? void 0, caption: (asset == null ? void 0 : asset.caption) ?? void 0, parent: { value: activeFolderId ?? void 0, label: ((_b = findRecursiveFolderByValue(folderStructure, activeFolderId)) == null ? void 0 : _b.label) ?? folderStructure[0].label } }; const handleClose = (values) => { if (!(0, import_isEqual.default)(initialFormData, values)) { handleConfirmClose(); } else { onClose(); } }; if (folderStructureIsLoading) { return (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: [ (0, import_jsx_runtime12.jsx)(DialogHeader, {}), (0, import_jsx_runtime12.jsx)(LoadingBody, { minHeight: "60vh", justifyContent: "center", paddingTop: 4, paddingBottom: 4, children: (0, import_jsx_runtime12.jsx)(Loader, { children: formatMessage({ id: getTrad("content.isLoading"), defaultMessage: "Content is loading." }) }) }), (0, import_jsx_runtime12.jsx)(Modal.Footer, { children: (0, import_jsx_runtime12.jsx)(Button, { onClick: () => handleClose(), variant: "tertiary", children: formatMessage({ id: "cancel", defaultMessage: "Cancel" }) }) }) ] }); } return (0, import_jsx_runtime12.jsx)(Formik, { validationSchema: fileInfoSchema, validateOnChange: false, onSubmit: handleSubmit, initialValues: initialFormData, children: ({ values, errors, handleChange, setFieldValue }) => (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: [ (0, import_jsx_runtime12.jsx)(DialogHeader, {}), (0, import_jsx_runtime12.jsx)(Modal.Body, { children: (0, import_jsx_runtime12.jsxs)(Grid.Root, { gap: 4, children: [ (0, import_jsx_runtime12.jsx)(Grid.Item, { xs: 12, col: 6, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime12.jsx)(PreviewBox, { asset, canUpdate, canCopyLink, canDownload, onDelete: onClose, onCropFinish: handleFinishCropping, onCropStart: handleStartCropping, onCropCancel: handleCancelCropping, replacementFile, trackedLocation }) }), (0, import_jsx_runtime12.jsx)(Grid.Item, { xs: 12, col: 6, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime12.jsxs)(Form, { noValidate: true, children: [ (0, import_jsx_runtime12.jsxs)(Flex, { direction: "column", alignItems: "stretch", gap: 3, children: [ (0, import_jsx_runtime12.jsx)(ContextInfo, { blocks: [ { label: formatMessage({ id: getTrad("modal.file-details.size"), defaultMessage: "Size" }), value: formatBytes((asset == null ? void 0 : asset.size) ? asset.size : 0) }, { label: formatMessage({ id: getTrad("modal.file-details.dimensions"), defaultMessage: "Dimensions" }), value: (asset == null ? void 0 : asset.height) && asset.width ? `${asset.width}✕${asset.height}` : null }, { label: formatMessage({ id: getTrad("modal.file-details.date"), defaultMessage: "Date" }), value: formatDate(new Date((asset == null ? void 0 : asset.createdAt) ? asset.createdAt : "")) }, { label: formatMessage({ id: getTrad("modal.file-details.extension"), defaultMessage: "Extension" }), value: getFileExtension(asset == null ? void 0 : asset.ext) }, { label: formatMessage({ id: getTrad("modal.file-details.id"), defaultMessage: "Asset ID" }), value: (asset == null ? void 0 : asset.id) ? asset.id : null } ] }), (0, import_jsx_runtime12.jsxs)(Field.Root, { name: "name", error: errors.name, children: [ (0, import_jsx_runtime12.jsx)(Field.Label, { children: formatMessage({ id: getTrad("form.input.label.file-name"), defaultMessage: "File name" }) }), (0, import_jsx_runtime12.jsx)(TextInput, { value: values.name, onChange: handleChange, disabled: formDisabled }), (0, import_jsx_runtime12.jsx)(Field.Error, {}) ] }), (0, import_jsx_runtime12.jsxs)(Field.Root, { name: "alternativeText", hint: formatMessage({ id: getTrad("form.input.description.file-alt"), defaultMessage: "This text will be displayed if the asset can’t be shown." }), error: errors.alternativeText, children: [ (0, import_jsx_runtime12.jsx)(Field.Label, { children: formatMessage({ id: getTrad("form.input.label.file-alt"), defaultMessage: "Alternative text" }) }), (0, import_jsx_runtime12.jsx)(TextInput, { value: values.alternativeText, onChange: handleChange, disabled: formDisabled }), (0, import_jsx_runtime12.jsx)(Field.Hint, {}), (0, import_jsx_runtime12.jsx)(Field.Error, {}) ] }), (0, import_jsx_runtime12.jsxs)(Field.Root, { name: "caption", error: errors.caption, children: [ (0, import_jsx_runtime12.jsx)(Field.Label, { children: formatMessage({ id: getTrad("form.input.label.file-caption"), defaultMessage: "Caption" }) }), (0, import_jsx_runtime12.jsx)(TextInput, { value: values.caption, onChange: handleChange, disabled: formDisabled }) ] }), (0, import_jsx_runtime12.jsx)(Flex, { direction: "column", alignItems: "stretch", gap: 1, children: (0, import_jsx_runtime12.jsxs)(Field.Root, { name: "parent", id: "asset-folder", children: [ (0, import_jsx_runtime12.jsx)(Field.Label, { children: formatMessage({ id: getTrad("form.input.label.file-location"), defaultMessage: "Location" }) }), (0, import_jsx_runtime12.jsx)(SelectTree, { name: "parent", defaultValue: values.parent, options: folderStructure, onChange: (value) => { setFieldValue("parent", value); }, menuPortalTarget: document.querySelector("body"), inputId: "asset-folder", isDisabled: formDisabled, error: errors == null ? void 0 : errors.parent, ariaErrorMessage: "folder-parent-error" }) ] }) }) ] }), (0, import_jsx_runtime12.jsx)(VisuallyHidden, { children: (0, import_jsx_runtime12.jsx)("button", { type: "submit", tabIndex: -1, ref: submitButtonRef, disabled: formDisabled, children: formatMessage({ id: "submit", defaultMessage: "Submit" }) }) }) ] }) }) ] }) }), (0, import_jsx_runtime12.jsxs)(Modal.Footer, { children: [ (0, import_jsx_runtime12.jsx)(Button, { onClick: () => handleClose({ ...values }), variant: "tertiary", children: formatMessage({ id: "global.cancel", defaultMessage: "Cancel" }) }), (0, import_jsx_runtime12.jsxs)(Flex, { gap: 2, children: [ (0, import_jsx_runtime12.jsx)(ReplaceMediaButton, { onSelectMedia: setReplacementFile, acceptedMime: (asset == null ? void 0 : asset.mime) ?? "", disabled: formDisabled, trackedLocation }), (0, import_jsx_runtime12.jsx)(Button, { onClick: () => { var _a4; return (_a4 = submitButtonRef.current) == null ? void 0 : _a4.click(); }, loading: isLoading, disabled: formDisabled, children: formatMessage({ id: "global.finish", defaultMessage: "Finish" }) }) ] }) ] }) ] }) }); }; var EditAssetDialog = ({ open, onClose, canUpdate = false, canCopyLink = false, canDownload = false, ...restProps }) => { return (0, import_jsx_runtime12.jsx)(Modal.Root, { open, onOpenChange: onClose, children: (0, import_jsx_runtime12.jsx)(Modal.Content, { children: (0, import_jsx_runtime12.jsx)(EditAssetContent, { onClose, canUpdate, canCopyLink, canDownload, ...restProps }) }) }); }; // node_modules/@strapi/upload/dist/admin/components/EditFolderDialog/EditFolderDialog.mjs var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1); var React17 = __toESM(require_react(), 1); var import_isEmpty = __toESM(require_isEmpty(), 1); // node_modules/@strapi/upload/dist/admin/hooks/useBulkRemove.mjs var import_qs9 = __toESM(require_lib(), 1); var useBulkRemove = () => { const { toggleNotification } = useNotification(); const { formatMessage } = useIntl(); const queryClient = useQueryClient(); const { post } = useFetchClient(); const bulkRemoveQuery = (filesAndFolders) => { const payload = filesAndFolders.reduce((acc, selected) => { const { id, type } = selected; const key = type === "asset" ? "fileIds" : "folderIds"; if (!acc[key]) { acc[key] = []; } acc[key].push(id); return acc; }, {}); return post("/upload/actions/bulk-delete", payload); }; const mutation = useMutation(bulkRemoveQuery, { onSuccess(res) { var _a3, _b; const { data: { data } } = res; if (((_a3 = data == null ? void 0 : data.files) == null ? void 0 : _a3.length) > 0) { queryClient.refetchQueries([ pluginId, "assets" ], { active: true }); queryClient.refetchQueries([ pluginId, "asset-count" ], { active: true }); } if (((_b = data == null ? void 0 : data.folders) == null ? void 0 : _b.length) > 0) { queryClient.refetchQueries([ pluginId, "folders" ], { active: true }); } toggleNotification({ type: "success", message: formatMessage({ id: getTrad("modal.remove.success-label"), defaultMessage: "Elements have been successfully deleted." }) }); }, onError(error) { toggleNotification({ type: "danger", message: error == null ? void 0 : error.message }); } }); const remove = (...args) => mutation.mutateAsync(...args); return { ...mutation, remove }; }; // node_modules/@strapi/upload/dist/admin/hooks/useEditFolder.mjs var editFolderRequest = (put, post, { attrs, id }) => { const isEditing = !!id; const method = isEditing ? put : post; return method(`/upload/folders/${id ?? ""}`, attrs).then((res) => res.data); }; var useEditFolder = () => { const queryClient = useQueryClient(); const { put, post } = useFetchClient(); const mutation = useMutation((...args) => editFolderRequest(put, post, ...args), { async onSuccess() { await queryClient.refetchQueries([ pluginId, "folders" ], { active: true }); await queryClient.refetchQueries([ pluginId, "folder", "structure" ], { active: true }); } }); const editFolder = (attrs, id) => mutation.mutateAsync({ attrs, id }); return { ...mutation, editFolder, status: mutation.status }; }; // node_modules/@strapi/upload/dist/admin/utils/normalizeAPIError.mjs function getPrefixedId(message, callback) { const prefixedMessage = `apiError.${message}`; if (typeof callback === "function") { return callback(prefixedMessage); } return prefixedMessage; } function normalizeError(error, { name, intlMessagePrefixCallback }) { const { message } = error; const normalizedError = { id: getPrefixedId(message, intlMessagePrefixCallback), defaultMessage: message, name: error.name ?? name, values: {} }; if ("path" in error) { normalizedError.values = { path: error.path.join(".") }; } return normalizedError; } var validateErrorIsYupValidationError = (err) => typeof err.details === "object" && err.details !== null && "errors" in err.details; function normalizeAPIError(apiError, intlMessagePrefixCallback) { var _a3; const error = (_a3 = apiError.response) == null ? void 0 : _a3.data.error; if (error) { if (validateErrorIsYupValidationError(error)) { return { name: error.name, message: (error == null ? void 0 : error.message) || null, errors: error.details.errors.map((err) => normalizeError(err, { name: error.name, intlMessagePrefixCallback })) }; } return normalizeError(error, { intlMessagePrefixCallback }); } return null; } // node_modules/@strapi/upload/dist/admin/utils/getAPIInnerErrors.mjs function getAPIInnerErrors(error, { getTrad: getTrad2 }) { const normalizedError = normalizeAPIError(error, getTrad2); if (normalizedError && "errors" in normalizedError) { return normalizedError.errors.reduce((acc, error2) => { if ("path" in error2.values) { acc[error2.values.path] = { id: error2.id, defaultMessage: error2.defaultMessage }; } return acc; }, {}); } return normalizedError == null ? void 0 : normalizedError.defaultMessage; } // node_modules/@strapi/upload/dist/admin/components/EditFolderDialog/EditFolderDialog.mjs var import_qs11 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/EditFolderDialog/ModalHeader/ModalHeader.mjs var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1); var import_qs10 = __toESM(require_lib(), 1); var EditFolderModalHeader = ({ isEditing = false }) => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime13.jsx)(Modal.Header, { children: (0, import_jsx_runtime13.jsx)(Modal.Title, { children: formatMessage(isEditing ? { id: getTrad("modal.folder.edit.title"), defaultMessage: "Edit folder" } : { id: getTrad("modal.folder.create.title"), defaultMessage: "Add new folder" }) }) }); }; // node_modules/@strapi/upload/dist/admin/components/EditFolderDialog/RemoveFolderDialog.mjs var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1); var RemoveFolderDialog = ({ onClose, onConfirm, open }) => { return (0, import_jsx_runtime14.jsx)(Dialog.Root, { open, onOpenChange: onClose, children: (0, import_jsx_runtime14.jsx)(ConfirmDialog, { onConfirm }) }); }; // node_modules/@strapi/upload/dist/admin/components/EditFolderDialog/EditFolderDialog.mjs var folderSchema = create3({ name: create().required(), parent: create3({ label: create(), value: create2().nullable(true) }).nullable(true) }); var EditFolderContent = ({ onClose, folder, location: location3, parentFolderId }) => { var _a3; const { data: folderStructure, isLoading: folderStructureIsLoading } = useFolderStructure({ enabled: true }); const { canCreate, isLoading: isLoadingPermissions, canUpdate } = useMediaLibraryPermissions(); const [showConfirmDialog, setShowConfirmDialog] = React17.useState(false); const { formatMessage, formatDate } = useIntl(); const { trackUsage } = useTracking(); const { editFolder, isLoading: isEditFolderLoading } = useEditFolder(); const { remove } = useBulkRemove(); const { toggleNotification } = useNotification(); const isLoading = isLoadingPermissions || folderStructureIsLoading; const isEditing = !!folder; const formDisabled = folder && !canUpdate || !folder && !canCreate; const initialFormData = !folderStructureIsLoading ? { name: (folder == null ? void 0 : folder.name) ?? "", parent: { /* ideally we would use folderStructure[0].value, but since it is null react complains about rendering null as field value */ value: parentFolderId ? parseInt(parentFolderId.toString(), 10) : void 0, label: parentFolderId ? folderStructure && ((_a3 = findRecursiveFolderByValue(folderStructure, parseInt(parentFolderId.toString(), 10))) == null ? void 0 : _a3.label) : folderStructure == null ? void 0 : folderStructure[0].label } } : { name: "", parent: null }; const handleSubmit = async (values, { setErrors }) => { var _a4, _b, _c; try { await editFolder({ ...values, parent: ((_a4 = values.parent) == null ? void 0 : _a4.value) ?? null }, folder == null ? void 0 : folder.id); toggleNotification({ type: "success", message: isEditing ? formatMessage({ id: getTrad("modal.folder-notification-edited-success"), defaultMessage: "Folder successfully edited" }) : formatMessage({ id: getTrad("modal.folder-notification-created-success"), defaultMessage: "Folder successfully created" }) }); if (isEditing) { const didChangeLocation = parentFolderId ? parseInt(parentFolderId.toString(), 10) !== ((_b = values.parent) == null ? void 0 : _b.value) : parentFolderId === null && !!((_c = values.parent) == null ? void 0 : _c.value); trackUsage("didEditMediaLibraryElements", { location: location3, type: "folder", changeLocation: didChangeLocation }); } else { trackUsage("didAddMediaLibraryFolders", { location: location3 }); } onClose({ created: true }); } catch (err) { const errors = getAPIInnerErrors(err, { getTrad }); const formikErrors = Object.entries(errors).reduce((acc, [key, error]) => { acc[key] = error.defaultMessage; return acc; }, {}); if (!(0, import_isEmpty.default)(formikErrors)) { setErrors(formikErrors); } } }; const handleDelete = async () => { if (folder) { await remove([ folder ]); } setShowConfirmDialog(false); onClose(); }; if (isLoading) { return (0, import_jsx_runtime15.jsxs)(import_jsx_runtime15.Fragment, { children: [ (0, import_jsx_runtime15.jsx)(EditFolderModalHeader, { isEditing }), (0, import_jsx_runtime15.jsx)(Modal.Body, { children: (0, import_jsx_runtime15.jsx)(Flex, { justifyContent: "center", paddingTop: 4, paddingBottom: 4, children: (0, import_jsx_runtime15.jsx)(Loader, { children: formatMessage({ id: getTrad("content.isLoading"), defaultMessage: "Content is loading." }) }) }) }) ] }); } return (0, import_jsx_runtime15.jsxs)(import_jsx_runtime15.Fragment, { children: [ (0, import_jsx_runtime15.jsx)(Formik, { validationSchema: folderSchema, validateOnChange: false, onSubmit: handleSubmit, initialValues: initialFormData, children: ({ values, errors, handleChange, setFieldValue }) => { var _a4, _b; return (0, import_jsx_runtime15.jsxs)(Form, { noValidate: true, children: [ (0, import_jsx_runtime15.jsx)(EditFolderModalHeader, { isEditing }), (0, import_jsx_runtime15.jsx)(Modal.Body, { children: (0, import_jsx_runtime15.jsxs)(Grid.Root, { gap: 4, children: [ isEditing && (0, import_jsx_runtime15.jsx)(Grid.Item, { xs: 12, col: 12, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime15.jsx)(ContextInfo, { blocks: [ { label: formatMessage({ id: getTrad("modal.folder.create.elements"), defaultMessage: "Elements" }), value: formatMessage({ id: getTrad("modal.folder.elements.count"), defaultMessage: "{folderCount} folders, {assetCount} assets" }, { assetCount: ((_a4 = folder == null ? void 0 : folder.files) == null ? void 0 : _a4.count) ?? 0, folderCount: ((_b = folder == null ? void 0 : folder.children) == null ? void 0 : _b.count) ?? 0 }) }, { label: formatMessage({ id: getTrad("modal.folder.create.creation-date"), defaultMessage: "Creation Date" }), value: formatDate(new Date(folder.createdAt)) } ] }) }), (0, import_jsx_runtime15.jsx)(Grid.Item, { xs: 12, col: 6, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime15.jsxs)(Field.Root, { name: "name", error: typeof errors.name === "string" ? errors.name : void 0, children: [ (0, import_jsx_runtime15.jsx)(Field.Label, { children: formatMessage({ id: getTrad("form.input.label.folder-name"), defaultMessage: "Name" }) }), (0, import_jsx_runtime15.jsx)(TextInput, { value: values.name, onChange: handleChange, disabled: formDisabled }), (0, import_jsx_runtime15.jsx)(Field.Error, {}) ] }) }), (0, import_jsx_runtime15.jsx)(Grid.Item, { xs: 12, col: 6, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime15.jsxs)(Field.Root, { id: "folder-parent", children: [ (0, import_jsx_runtime15.jsx)(Field.Label, { children: formatMessage({ id: getTrad("form.input.label.folder-location"), defaultMessage: "Location" }) }), (0, import_jsx_runtime15.jsx)(SelectTree, { options: folderStructure, onChange: (value) => { setFieldValue("parent", value); }, isDisabled: formDisabled, defaultValue: values.parent, name: "parent", menuPortalTarget: document.querySelector("body"), inputId: "folder-parent", disabled: formDisabled, error: typeof errors.parent === "string" ? errors.parent : void 0, ariaErrorMessage: "folder-parent-error" }), errors.parent && (0, import_jsx_runtime15.jsx)(Typography, { variant: "pi", tag: "p", id: "folder-parent-error", textColor: "danger600", children: typeof errors.parent === "string" ? errors.parent : void 0 }) ] }) }) ] }) }), (0, import_jsx_runtime15.jsxs)(Modal.Footer, { children: [ (0, import_jsx_runtime15.jsx)(Button, { onClick: () => onClose(), variant: "tertiary", name: "cancel", children: formatMessage({ id: "cancel", defaultMessage: "Cancel" }) }), (0, import_jsx_runtime15.jsxs)(Flex, { gap: 2, children: [ isEditing && canUpdate && (0, import_jsx_runtime15.jsx)(Button, { type: "button", variant: "danger-light", onClick: () => setShowConfirmDialog(true), name: "delete", disabled: !canUpdate || isEditFolderLoading, children: formatMessage({ id: getTrad("modal.folder.create.delete"), defaultMessage: "Delete folder" }) }), (0, import_jsx_runtime15.jsx)(Button, { name: "submit", loading: isEditFolderLoading, disabled: formDisabled, type: "submit", children: formatMessage(isEditing ? { id: getTrad("modal.folder.edit.submit"), defaultMessage: "Save" } : { id: getTrad("modal.folder.create.submit"), defaultMessage: "Create" }) }) ] }) ] }) ] }); } }), (0, import_jsx_runtime15.jsx)(RemoveFolderDialog, { open: showConfirmDialog, onClose: () => setShowConfirmDialog(false), onConfirm: handleDelete }) ] }); }; var EditFolderDialog = ({ open, onClose, ...restProps }) => { return (0, import_jsx_runtime15.jsx)(Modal.Root, { open, onOpenChange: onClose, children: (0, import_jsx_runtime15.jsx)(Modal.Content, { children: (0, import_jsx_runtime15.jsx)(EditFolderContent, { ...restProps, onClose, open }) }) }); }; // node_modules/@strapi/upload/dist/admin/hooks/useFolder.mjs var import_qs12 = __toESM(require_lib(), 1); var useFolder = (id, { enabled = true } = {}) => { const { toggleNotification } = useNotification(); const { get } = useFetchClient(); const { formatMessage } = useIntl(); const { data, error, isLoading } = useQuery([ pluginId, "folder", id ], async () => { const { data: { data: data2 } } = await get(`/upload/folders/${id}`, { params: { populate: { parent: { populate: { parent: "*" } } } } }); return data2; }, { retry: false, enabled, staleTime: 0, cacheTime: 0, onError() { toggleNotification({ type: "danger", message: formatMessage({ id: getTrad("notification.warning.404"), defaultMessage: "Not found" }) }); } }); return { data, error, isLoading }; }; // node_modules/@strapi/upload/dist/admin/hooks/usePersistentState.mjs var import_react15 = __toESM(require_react(), 1); var usePersistentState = (key, defaultValue) => { const [value, setValue] = (0, import_react15.useState)(() => { const stickyValue = window.localStorage.getItem(key); if (stickyValue !== null) { try { return JSON.parse(stickyValue); } catch { return stickyValue; } } return defaultValue; }); (0, import_react15.useEffect)(() => { window.localStorage.setItem(key, JSON.stringify(value)); }, [ key, value ]); return [ value, setValue ]; }; // node_modules/@strapi/upload/dist/admin/components/AssetGridList/AssetGridList.mjs var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/components/AssetCard/AssetCard.mjs var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1); var import_qs16 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/AssetCard/AudioAssetCard.mjs var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/components/AssetCard/AssetCardBase.mjs var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1); var import_react16 = __toESM(require_react(), 1); var import_qs13 = __toESM(require_lib(), 1); var Extension = dt.span` text-transform: uppercase; `; var CardActionsContainer = dt(CardActionImpl)` opacity: 0; &:focus-within { opacity: 1; } `; var CardContainer = dt(Card)` cursor: pointer; &:hover { ${CardActionsContainer} { opacity: 1; } } `; var AssetCardBase = ({ children, extension, isSelectable = false, name, onSelect, onRemove, onEdit, selected = false, subtitle = "", variant = "Image" }) => { const { formatMessage } = useIntl(); const handleClick = (e) => { if (onEdit) { onEdit(e); } }; const handlePropagationClick = (e) => { e.stopPropagation(); }; return (0, import_jsx_runtime16.jsxs)(CardContainer, { role: "button", height: "100%", tabIndex: -1, onClick: handleClick, children: [ (0, import_jsx_runtime16.jsxs)(CardHeader, { children: [ isSelectable && (0, import_jsx_runtime16.jsx)("div", { onClick: handlePropagationClick, children: (0, import_jsx_runtime16.jsx)(CardCheckbox, { checked: selected, onCheckedChange: onSelect }) }), (onRemove || onEdit) && (0, import_jsx_runtime16.jsxs)(CardActionsContainer, { onClick: handlePropagationClick, position: "end", children: [ onRemove && (0, import_jsx_runtime16.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.remove-selection"), defaultMessage: "Remove from selection" }), onClick: onRemove, children: (0, import_jsx_runtime16.jsx)(ForwardRef$j, {}) }), onEdit && (0, import_jsx_runtime16.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.edit"), defaultMessage: "Edit" }), onClick: onEdit, children: (0, import_jsx_runtime16.jsx)(ForwardRef$1v, {}) }) ] }), children ] }), (0, import_jsx_runtime16.jsxs)(CardBody, { children: [ (0, import_jsx_runtime16.jsxs)(CardContent, { children: [ (0, import_jsx_runtime16.jsx)(Box, { paddingTop: 1, children: (0, import_jsx_runtime16.jsx)(Typography, { tag: "h2", children: (0, import_jsx_runtime16.jsx)(CardTitle, { tag: "span", children: name }) }) }), (0, import_jsx_runtime16.jsxs)(CardSubtitle, { children: [ (0, import_jsx_runtime16.jsx)(Extension, { children: extension }), subtitle ] }) ] }), (0, import_jsx_runtime16.jsx)(Flex, { paddingTop: 1, grow: 1, children: (0, import_jsx_runtime16.jsx)(CardBadge, { children: formatMessage({ id: getTrad(`settings.section.${variant.toLowerCase()}.label`), defaultMessage: variant }) }) }) ] }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/AudioPreview.mjs var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1); var AudioPreview = ({ url, alt }) => { return (0, import_jsx_runtime17.jsx)(Box, { children: (0, import_jsx_runtime17.jsx)("audio", { controls: true, src: url, children: alt }) }); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/AudioAssetCard.mjs var AudioPreviewWrapper = dt(Box)` canvas, audio { display: block; max-width: 100%; max-height: ${({ size }) => size === "M" ? 16.4 : 8.8}rem; } `; var AudioAssetCard = ({ name, url, size = "M", selected = false, ...restProps }) => { return (0, import_jsx_runtime18.jsx)(AssetCardBase, { name, selected, ...restProps, variant: "Audio", children: (0, import_jsx_runtime18.jsx)(CardAsset, { size, children: (0, import_jsx_runtime18.jsx)(Flex, { alignItems: "center", children: (0, import_jsx_runtime18.jsx)(AudioPreviewWrapper, { size, children: (0, import_jsx_runtime18.jsx)(AudioPreview, { url, alt: name }) }) }) }) }); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/DocAssetCard.mjs var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1); var CardAsset3 = dt(Flex)` border-radius: ${({ theme }) => theme.borderRadius} ${({ theme }) => theme.borderRadius} 0 0; background: linear-gradient( 180deg, ${({ theme }) => theme.colors.neutral0} 0%, ${({ theme }) => theme.colors.neutral100} 121.48% ); `; var DocAssetCard = ({ name, extension, size = "M", selected = false, ...restProps }) => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime19.jsx)(AssetCardBase, { name, extension, selected, ...restProps, variant: "Doc", children: (0, import_jsx_runtime19.jsx)(CardAsset3, { width: "100%", height: size === "S" ? `8.8rem` : `16.4rem`, justifyContent: "center", children: (0, import_jsx_runtime19.jsxs)(Flex, { gap: 2, direction: "column", alignItems: "center", children: [ extension === "pdf" ? (0, import_jsx_runtime19.jsx)(ForwardRef$3p, { "aria-label": name, fill: "neutral500", width: 24, height: 24 }) : (0, import_jsx_runtime19.jsx)(ForwardRef$3v, { "aria-label": name, fill: "neutral500", width: 24, height: 24 }), (0, import_jsx_runtime19.jsx)(Typography, { textColor: "neutral500", variant: "pi", children: formatMessage({ id: "noPreview", defaultMessage: "No preview available" }) }) ] }) }) }); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/ImageAssetCard.mjs var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/utils/appendSearchParamsToUrl.mjs var appendSearchParamsToUrl = ({ url, params }) => { if (url === void 0 || typeof params !== "object") { return url; } const urlObj = new URL(url, window.strapi.backendURL); Object.entries(params).forEach(([key, value]) => { if (value !== void 0 && value !== null) { urlObj.searchParams.append(key, value); } }); return urlObj.toString(); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/ImageAssetCard.mjs var import_qs14 = __toESM(require_lib(), 1); var ImageAssetCard = ({ height, width, thumbnail, size = "M", alt, isUrlSigned, selected = false, ...props }) => { const thumbnailUrl = isUrlSigned ? thumbnail : appendSearchParamsToUrl({ url: thumbnail, params: { updatedAt: props.updatedAt } }); const subtitle = height && width ? ` - ${width}✕${height}` : void 0; return (0, import_jsx_runtime20.jsx)(AssetCardBase, { ...props, selected, subtitle, variant: "Image", children: (0, import_jsx_runtime20.jsx)(CardAsset, { src: thumbnailUrl, size, alt }) }); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/VideoAssetCard.mjs var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1); var React18 = __toESM(require_react(), 1); // node_modules/@strapi/upload/dist/admin/utils/formatDuration.mjs var zeroPad = (num) => String(num).padStart(2, "0"); var formatDuration = (durationInSecond) => { const duration = intervalToDuration({ start: 0, end: durationInSecond * 1e3 }); return `${zeroPad(duration.hours)}:${zeroPad(duration.minutes)}:${zeroPad(duration.seconds)}`; }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/VideoAssetCard.mjs var import_qs15 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/AssetCard/VideoPreview.mjs var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1); var import_react17 = __toESM(require_react(), 1); var HAVE_FUTURE_DATA = 3; var VideoPreview = ({ url, mime, onLoadDuration = () => { }, alt, ...props }) => { const handleTimeUpdate = (e) => { var _a3; if (e.currentTarget.currentTime > 0) { const video = e.currentTarget; const canvas = document.createElement("canvas"); canvas.height = video.videoHeight; canvas.width = video.videoWidth; (_a3 = canvas.getContext("2d")) == null ? void 0 : _a3.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); video.replaceWith(canvas); onLoadDuration && onLoadDuration(video.duration); } }; const handleThumbnailVisibility = (e) => { const video = e.currentTarget; if (video.readyState < HAVE_FUTURE_DATA) return; video.play(); }; return (0, import_jsx_runtime21.jsxs)(Box, { tag: "figure", ...props, children: [ (0, import_jsx_runtime21.jsx)("video", { muted: true, onLoadedData: handleThumbnailVisibility, src: url, crossOrigin: "anonymous", onTimeUpdate: handleTimeUpdate, children: (0, import_jsx_runtime21.jsx)("source", { type: mime }) }), (0, import_jsx_runtime21.jsx)(VisuallyHidden, { tag: "figcaption", children: alt }) ] }, url); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/VideoAssetCard.mjs var VideoPreviewWrapper = dt(Box)` canvas, video { display: block; pointer-events: none; max-width: 100%; max-height: ${({ size }) => size === "M" ? 16.4 : 8.8}rem; } `; var VideoAssetCard = ({ name, url, mime, size = "M", selected = false, ...props }) => { const [duration, setDuration] = React18.useState(); const formattedDuration = duration && formatDuration(duration); return (0, import_jsx_runtime22.jsxs)(AssetCardBase, { selected, name, ...props, variant: "Video", children: [ (0, import_jsx_runtime22.jsx)(CardAsset, { size, children: (0, import_jsx_runtime22.jsx)(VideoPreviewWrapper, { size, children: (0, import_jsx_runtime22.jsx)(VideoPreview, { url, mime, onLoadDuration: setDuration, alt: name }) }) }), (0, import_jsx_runtime22.jsx)(CardTimer, { children: formattedDuration || "..." }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/AssetCard/AssetCard.mjs var AssetCard = ({ asset, isSelected = false, onSelect, onEdit, onRemove, size = "M", local = false }) => { var _a3, _b, _c, _d, _e5; const handleSelect = onSelect ? () => onSelect(asset) : void 0; const commonAssetCardProps = { id: asset.id, isSelectable: asset.isSelectable, extension: getFileExtension(asset.ext), name: asset.name, url: local ? asset.url : createAssetUrl(asset, true), mime: asset.mime, onEdit: onEdit ? () => onEdit(asset) : void 0, onSelect: handleSelect, onRemove: onRemove ? () => onRemove(asset) : void 0, selected: isSelected, size }; if ((_a3 = asset.mime) == null ? void 0 : _a3.includes(AssetType.Video)) { return (0, import_jsx_runtime23.jsx)(VideoAssetCard, { ...commonAssetCardProps }); } if ((_b = asset.mime) == null ? void 0 : _b.includes(AssetType.Image)) { return (0, import_jsx_runtime23.jsx)(ImageAssetCard, { alt: asset.alternativeText || asset.name, height: asset.height, thumbnail: prefixFileUrlWithBackendUrl(((_d = (_c = asset == null ? void 0 : asset.formats) == null ? void 0 : _c.thumbnail) == null ? void 0 : _d.url) || asset.url), width: asset.width, updatedAt: asset.updatedAt, isUrlSigned: (asset == null ? void 0 : asset.isUrlSigned) || false, ...commonAssetCardProps }); } if ((_e5 = asset.mime) == null ? void 0 : _e5.includes(AssetType.Audio)) { return (0, import_jsx_runtime23.jsx)(AudioAssetCard, { ...commonAssetCardProps }); } return (0, import_jsx_runtime23.jsx)(DocAssetCard, { ...commonAssetCardProps }); }; // node_modules/@strapi/upload/dist/admin/components/AssetGridList/Draggable.mjs var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1); var React19 = __toESM(require_react(), 1); var Draggable = ({ children, id, index: index2, moveItem }) => { const ref = React19.useRef(null); const [, drop] = useDrop({ accept: "draggable", hover(hoveredOverItem) { if (!ref.current) { return; } if (hoveredOverItem.id !== id) { moveItem(hoveredOverItem.index, index2); hoveredOverItem.index = index2; } } }); const [{ isDragging }, drag] = useDrag({ type: "draggable", item() { return { index: index2, id }; }, collect: (monitor) => ({ isDragging: monitor.isDragging() }) }); const opacity = isDragging ? 0.2 : 1; drag(drop(ref)); return (0, import_jsx_runtime24.jsx)("div", { ref, style: { opacity, cursor: "move" }, children }); }; // node_modules/@strapi/upload/dist/admin/components/AssetGridList/AssetGridList.mjs var AssetGridList = ({ allowedTypes = [ "files", "images", "videos", "audios" ], assets, onEditAsset, onSelectAsset, selectedAssets, size = "M", onReorderAsset, title = null }) => { return (0, import_jsx_runtime25.jsxs)(KeyboardNavigable, { tagName: "article", children: [ title && (0, import_jsx_runtime25.jsx)(Box, { paddingTop: 2, paddingBottom: 2, children: (0, import_jsx_runtime25.jsx)(Typography, { tag: "h2", variant: "delta", fontWeight: "semiBold", children: title }) }), (0, import_jsx_runtime25.jsx)(Grid.Root, { gap: 4, children: assets.map((asset, index2) => { const isSelected = !!selectedAssets.find((currentAsset) => currentAsset.id === asset.id); if (onReorderAsset) { return (0, import_jsx_runtime25.jsx)(Grid.Item, { col: 3, height: "100%", children: (0, import_jsx_runtime25.jsx)(Draggable, { index: index2, moveItem: onReorderAsset, id: asset.id, children: (0, import_jsx_runtime25.jsx)(AssetCard, { allowedTypes, asset, isSelected, onEdit: onEditAsset ? () => onEditAsset(asset) : void 0, onSelect: () => onSelectAsset(asset), size }) }) }, asset.id); } return (0, import_jsx_runtime25.jsx)(Grid.Item, { col: 3, height: "100%", direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime25.jsx)(AssetCard, { allowedTypes, asset, isSelected, onEdit: onEditAsset ? () => onEditAsset(asset) : void 0, onSelect: () => onSelectAsset(asset), size }, asset.id) }, asset.id); }) }) ] }); }; // node_modules/@strapi/upload/dist/admin/utils/getFolderURL.mjs var import_qs17 = __toESM(require_lib(), 1); var getFolderURL = (pathname, currentQuery, { folder, folderPath } = {}) => { const { _q, ...queryParamsWithoutQ } = currentQuery; const queryParamsString = (0, import_qs17.stringify)({ ...queryParamsWithoutQ, folder, folderPath }, { encode: false }); return `${pathname}${queryParamsString ? `?${queryParamsString}` : ""}`; }; // node_modules/@strapi/upload/dist/admin/components/FolderCard/FolderCard/FolderCard.mjs var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1); var React20 = __toESM(require_react(), 1); // node_modules/@strapi/upload/dist/admin/components/FolderCard/contexts/FolderCard.mjs var import_react18 = __toESM(require_react(), 1); var FolderCardContext = (0, import_react18.createContext)({}); function useFolderCard() { return (0, import_react18.useContext)(FolderCardContext); } // node_modules/@strapi/upload/dist/admin/components/FolderCard/FolderCard/FolderCard.mjs var FauxClickWrapper = dt.button` height: 100%; left: 0; position: absolute; opacity: 0; top: 0; width: 100%; &:hover, &:focus { text-decoration: none; } `; var StyledFolder = dt(ForwardRef$3h)` path { fill: currentColor; } `; var CardActionDisplay = dt(Box)` display: none; `; var Card2 = dt(Box)` &:hover, &:focus-within { ${CardActionDisplay} { display: ${({ $isCardActions }) => $isCardActions ? "block" : ""}; } } `; var FolderCard = React20.forwardRef(({ children, startAction = null, cardActions = null, ariaLabel, onClick, to, ...props }, ref) => { const generatedId = React20.useId(); const fodlerCtxValue = React20.useMemo(() => ({ id: generatedId }), [ generatedId ]); return (0, import_jsx_runtime26.jsx)(FolderCardContext.Provider, { value: fodlerCtxValue, children: (0, import_jsx_runtime26.jsxs)(Card2, { position: "relative", tabIndex: 0, $isCardActions: !!cardActions, ref, ...props, children: [ (0, import_jsx_runtime26.jsx)(FauxClickWrapper, { to: to || void 0, as: to ? NavLink : "button", type: to ? void 0 : "button", onClick, tabIndex: -1, "aria-label": ariaLabel, "aria-hidden": true }), (0, import_jsx_runtime26.jsxs)(Flex, { hasRadius: true, borderStyle: "solid", borderWidth: "1px", borderColor: "neutral150", background: "neutral0", shadow: "tableShadow", padding: 3, gap: 2, cursor: "pointer", children: [ startAction, (0, import_jsx_runtime26.jsx)(Box, { hasRadius: true, background: "secondary100", color: "secondary500", paddingBottom: 2, paddingLeft: 3, paddingRight: 3, paddingTop: 2, children: (0, import_jsx_runtime26.jsx)(StyledFolder, { width: "2.4rem", height: "2.4rem" }) }), children, (0, import_jsx_runtime26.jsx)(CardActionDisplay, { children: (0, import_jsx_runtime26.jsx)(CardActionImpl, { right: 4, position: "end", children: cardActions }) }) ] }) ] }) }); }); // node_modules/@strapi/upload/dist/admin/components/FolderCard/FolderCardBody/FolderCardBody.mjs var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1); var StyledBox = dt(Flex)` user-select: none; `; var FolderCardBody = (props) => { const { id } = useFolderCard(); return (0, import_jsx_runtime27.jsx)(StyledBox, { ...props, id: `${id}-title`, "data-testid": `${id}-title`, alignItems: "flex-start", direction: "column", maxWidth: "100%", overflow: "hidden", position: "relative" }); }; // node_modules/@strapi/upload/dist/admin/components/FolderCard/FolderCardBodyAction/FolderCardBodyAction.mjs var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1); var BoxOutline = dt(Box)` &:focus { outline: 2px solid ${({ theme }) => theme.colors.primary600}; outline-offset: -2px; } `; var BoxTextDecoration = dt(BoxOutline)` text-decoration: none; `; var FolderCardBodyAction = ({ to, ...props }) => { if (to) { return (0, import_jsx_runtime28.jsx)(BoxTextDecoration, { // padding needed to give outline space to appear // since FolderCardBody needs overflow hidden property padding: 1, tag: NavLink, maxWidth: "100%", to, ...props }); } return (0, import_jsx_runtime28.jsx)(BoxOutline, { padding: 1, tag: "button", type: "button", maxWidth: "100%", ...props }); }; // node_modules/@strapi/upload/dist/admin/components/FolderGridList/FolderGridList.mjs var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1); var import_react19 = __toESM(require_react(), 1); var FolderGridList = ({ title = null, children }) => { return (0, import_jsx_runtime29.jsxs)(KeyboardNavigable, { tagName: "article", children: [ title && (0, import_jsx_runtime29.jsx)(Box, { paddingBottom: 2, children: (0, import_jsx_runtime29.jsx)(Typography, { tag: "h2", variant: "delta", fontWeight: "semiBold", children: title }) }), (0, import_jsx_runtime29.jsx)(Grid.Root, { gap: 4, children }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/SortPicker/SortPicker.mjs var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1); var import_qs18 = __toESM(require_lib(), 1); var SortPicker = ({ onChangeSort, value }) => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime30.jsx)(SingleSelect, { size: "S", value, onChange: (value2) => onChangeSort(value2.toString()), "aria-label": formatMessage({ id: getTrad("sort.label"), defaultMessage: "Sort by" }), placeholder: formatMessage({ id: getTrad("sort.label"), defaultMessage: "Sort by" }), children: sortOptions.map((filter) => (0, import_jsx_runtime30.jsx)(SingleSelectOption, { value: filter.value, children: formatMessage({ id: getTrad(filter.key), defaultMessage: `${filter.value}` }) }, filter.key)) }); }; // node_modules/@strapi/upload/dist/admin/components/TableList/TableList.mjs var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1); var import_qs22 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/TableList/TableRows.mjs var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1); var import_qs21 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/TableList/CellContent.mjs var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1); var import_qs20 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/TableList/PreviewCell.mjs var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1); var import_qs19 = __toESM(require_lib(), 1); var VideoPreviewWrapper2 = dt(Box)` figure { width: ${({ theme }) => theme.spaces[7]}; height: ${({ theme }) => theme.spaces[7]}; } canvas, video { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; } `; var PreviewCell = ({ type, content }) => { var _a3; const { formatMessage } = useIntl(); if (type === "folder") { return (0, import_jsx_runtime31.jsx)(Flex, { justifyContent: "center", background: "secondary100", width: "3.2rem", height: "3.2rem", borderRadius: "50%", children: (0, import_jsx_runtime31.jsx)(ForwardRef$3h, { "aria-label": formatMessage({ id: getTrad("header.actions.add-assets.folder"), defaultMessage: "folder" }), fill: "secondary500", width: "1.6rem", height: "1.6rem" }) }); } const { alternativeText, ext, formats, mime, name, url } = content; if (mime == null ? void 0 : mime.includes(AssetType.Image)) { const mediaURL = prefixFileUrlWithBackendUrl((_a3 = formats == null ? void 0 : formats.thumbnail) == null ? void 0 : _a3.url) ?? prefixFileUrlWithBackendUrl(url); return (0, import_jsx_runtime31.jsx)(Avatar.Item, { src: mediaURL, alt: alternativeText || void 0, preview: true, fallback: alternativeText }); } if (mime == null ? void 0 : mime.includes(AssetType.Video)) { return (0, import_jsx_runtime31.jsx)(VideoPreviewWrapper2, { children: (0, import_jsx_runtime31.jsx)(VideoPreview, { url: createAssetUrl(content, true) || "", mime, alt: alternativeText ?? name }) }); } return (0, import_jsx_runtime31.jsx)(Box, { background: "secondary100", color: "secondary600", width: "3.2rem", height: "3.2rem", children: getFileExtension(ext) }); }; // node_modules/@strapi/upload/dist/admin/components/TableList/CellContent.mjs var CellContent = ({ cellType, contentType, content, name }) => { var _a3; const { formatDate, formatMessage } = useIntl(); const contentValue = content[name]; switch (cellType) { case "image": return (0, import_jsx_runtime32.jsx)(PreviewCell, { type: contentType, content }); case "date": if (typeof contentValue === "string") { return (0, import_jsx_runtime32.jsx)(Typography, { children: formatDate(parseISO(contentValue), { dateStyle: "full" }) }); } case "size": if (contentType === "folder") return (0, import_jsx_runtime32.jsx)(Typography, { "aria-label": formatMessage({ id: "list.table.content.empty-label", defaultMessage: "This field is empty" }), children: "-" }); if (typeof contentValue === "string" || typeof contentValue === "number") { return (0, import_jsx_runtime32.jsx)(Typography, { children: formatBytes(contentValue) }); } case "ext": if (contentType === "folder") return (0, import_jsx_runtime32.jsx)(Typography, { "aria-label": formatMessage({ id: "list.table.content.empty-label", defaultMessage: "This field is empty" }), children: "-" }); if (typeof contentValue === "string") { return (0, import_jsx_runtime32.jsx)(Typography, { children: (_a3 = getFileExtension(contentValue)) == null ? void 0 : _a3.toUpperCase() }); } case "text": if (typeof contentValue === "string") { return (0, import_jsx_runtime32.jsx)(Typography, { children: contentValue }); } default: return (0, import_jsx_runtime32.jsx)(Typography, { "aria-label": formatMessage({ id: "list.table.content.empty-label", defaultMessage: "This field is empty" }), children: "-" }); } }; // node_modules/@strapi/upload/dist/admin/components/TableList/TableRows.mjs var TableRows = ({ onChangeFolder = null, onEditAsset, onEditFolder, onSelectOne, rows = [], selected = [] }) => { const { formatMessage } = useIntl(); const handleRowClickFn = (element, id, path, elementType) => { if (elementType === "asset") { onEditAsset(element); } else { if (onChangeFolder) { onChangeFolder(id, path); } } }; return (0, import_jsx_runtime33.jsx)(Tbody, { children: rows.map((element) => { const { path, id, isSelectable, name, folderURL, type: contentType } = element; const isSelected = !!selected.find((currentRow) => currentRow.id === id && currentRow.type === contentType); return (0, import_jsx_runtime33.jsxs)(Tr, { onClick: () => handleRowClickFn(element, id, path || void 0, contentType), children: [ (0, import_jsx_runtime33.jsx)(Td, { onClick: (e) => e.stopPropagation(), children: (0, import_jsx_runtime33.jsx)(CheckboxImpl, { "aria-label": formatMessage({ id: contentType === "asset" ? "list-assets-select" : "list.folder.select", defaultMessage: contentType === "asset" ? "Select {name} asset" : "Select {name} folder" }, { name }), disabled: !isSelectable, onCheckedChange: () => onSelectOne(element), checked: isSelected }) }), tableHeaders.map(({ name: name2, type: cellType }) => { return (0, import_jsx_runtime33.jsx)(Td, { children: (0, import_jsx_runtime33.jsx)(CellContent, { content: element, cellType, contentType, name: name2 }) }, name2); }), (0, import_jsx_runtime33.jsx)(Td, { onClick: (e) => e.stopPropagation(), children: (0, import_jsx_runtime33.jsxs)(Flex, { justifyContent: "flex-end", children: [ contentType === "folder" && (folderURL ? (0, import_jsx_runtime33.jsx)(IconButton, { tag: Link, label: formatMessage({ id: getTrad("list.folders.link-label"), defaultMessage: "Access folder" }), to: folderURL, variant: "ghost", children: (0, import_jsx_runtime33.jsx)(ForwardRef$3D, {}) }) : (0, import_jsx_runtime33.jsx)(IconButton, { tag: "button", label: formatMessage({ id: getTrad("list.folders.link-label"), defaultMessage: "Access folder" }), onClick: () => onChangeFolder && onChangeFolder(id), variant: "ghost", children: (0, import_jsx_runtime33.jsx)(ForwardRef$3D, {}) })), (0, import_jsx_runtime33.jsx)(IconButton, { label: formatMessage({ id: getTrad("control-card.edit"), defaultMessage: "Edit" }), onClick: () => contentType === "asset" ? onEditAsset(element) : onEditFolder(element), variant: "ghost", children: (0, import_jsx_runtime33.jsx)(ForwardRef$1v, {}) }) ] }) }) ] }, id); }) }); }; // node_modules/@strapi/upload/dist/admin/components/TableList/TableList.mjs var TableList = ({ assetCount = 0, folderCount = 0, indeterminate = false, onChangeSort = null, onChangeFolder = null, onEditAsset = null, onEditFolder = null, onSelectAll, onSelectOne, rows = [], selected = [], shouldDisableBulkSelect = false, sortQuery = "" }) => { const { formatMessage } = useIntl(); const [sortBy, sortOrder] = sortQuery.split(":"); const handleClickSort = (isSorted, name) => { const nextSortOrder = isSorted && sortOrder === "ASC" ? "DESC" : "ASC"; const nextSort = `${name}:${nextSortOrder}`; onChangeSort && onChangeSort(nextSort); }; return (0, import_jsx_runtime34.jsxs)(Table, { colCount: tableHeaders.length + 2, rowCount: assetCount + folderCount + 1, children: [ (0, import_jsx_runtime34.jsx)(Thead, { children: (0, import_jsx_runtime34.jsxs)(Tr, { children: [ (0, import_jsx_runtime34.jsx)(Th, { children: (0, import_jsx_runtime34.jsx)(CheckboxImpl, { "aria-label": formatMessage({ id: getTrad("bulk.select.label"), defaultMessage: "Select all folders & assets" }), disabled: shouldDisableBulkSelect, onCheckedChange: (checked) => onSelectAll(checked, rows), checked: indeterminate && !shouldDisableBulkSelect ? "indeterminate" : (assetCount > 0 || folderCount > 0) && selected.length === assetCount + folderCount }) }), tableHeaders.map(({ metadatas: { label, isSortable }, name, key }) => { const isSorted = sortBy === name; const isUp = sortOrder === "ASC"; const tableHeaderLabel = formatMessage(label); const sortLabel = formatMessage({ id: "list.table.header.sort", defaultMessage: "Sort on {label}" }, { label: tableHeaderLabel }); return (0, import_jsx_runtime34.jsx)(Th, { action: isSorted && (0, import_jsx_runtime34.jsx)(IconButton, { label: sortLabel, onClick: () => handleClickSort(isSorted, name), variant: "ghost", children: isUp ? (0, import_jsx_runtime34.jsx)(ForwardRef$4R, {}) : (0, import_jsx_runtime34.jsx)(ForwardRef$4T, {}) }), children: (0, import_jsx_runtime34.jsx)(TooltipImpl, { label: isSortable ? sortLabel : tableHeaderLabel, children: isSortable ? (0, import_jsx_runtime34.jsx)(Typography, { onClick: () => handleClickSort(isSorted, name), tag: isSorted ? "span" : "button", textColor: "neutral600", variant: "sigma", children: tableHeaderLabel }) : (0, import_jsx_runtime34.jsx)(Typography, { textColor: "neutral600", variant: "sigma", children: tableHeaderLabel }) }) }, key); }), (0, import_jsx_runtime34.jsx)(Th, { children: (0, import_jsx_runtime34.jsx)(VisuallyHidden, { children: formatMessage({ id: getTrad("list.table.header.actions"), defaultMessage: "actions" }) }) }) ] }) }), (0, import_jsx_runtime34.jsx)(TableRows, { onChangeFolder, onEditAsset, onEditFolder, rows, onSelectOne, selected }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/UploadAssetDialog.mjs var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1); var React25 = __toESM(require_react(), 1); // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/AddAssetStep/AddAssetStep.mjs var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1); var import_qs25 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/AddAssetStep/FromComputerForm.mjs var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1); var React21 = __toESM(require_react(), 1); var import_qs23 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/utils/typeFromMime.mjs var typeFromMime = (mime) => { if (mime.includes(AssetType.Image)) { return AssetType.Image; } if (mime.includes(AssetType.Video)) { return AssetType.Video; } if (mime.includes(AssetType.Audio)) { return AssetType.Audio; } return AssetType.Document; }; // node_modules/@strapi/upload/dist/admin/utils/rawFileToAsset.mjs var rawFileToAsset = (rawFile, assetSource) => { return { size: rawFile.size / 1e3, createdAt: new Date(rawFile.lastModified).toISOString(), name: rawFile.name, source: assetSource, type: typeFromMime(rawFile.type), url: URL.createObjectURL(rawFile), ext: rawFile.name.split(".").pop(), mime: rawFile.type, rawFile, isLocal: true }; }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/AddAssetStep/FromComputerForm.mjs var Wrapper2 = dt(Flex)` flex-direction: column; `; var IconWrapper = dt.div` font-size: 6rem; svg path { fill: ${({ theme }) => theme.colors.primary600}; } `; var MediaBox = dt(Box)` border-style: dashed; `; var OpaqueBox = dt(Box)` opacity: 0; cursor: pointer; `; var FromComputerForm = ({ onClose, onAddAssets, trackedLocation }) => { const { formatMessage } = useIntl(); const [dragOver, setDragOver] = React21.useState(false); const inputRef = React21.useRef(null); const { trackUsage } = useTracking(); const handleDragOver = (event) => { event.preventDefault(); }; const handleDragEnter = (event) => { event.preventDefault(); setDragOver(true); }; const handleDragLeave = () => setDragOver(false); const handleClick = (e) => { var _a3; e.preventDefault(); (_a3 = inputRef.current) == null ? void 0 : _a3.click(); }; const handleChange = () => { var _a3; const files = (_a3 = inputRef.current) == null ? void 0 : _a3.files; const assets = []; if (files) { for (let i3 = 0; i3 < files.length; i3++) { const file = files.item(i3); if (file) { const asset = rawFileToAsset(file, AssetSource.Computer); assets.push(asset); } } } if (trackedLocation) { trackUsage("didSelectFile", { source: "computer", location: trackedLocation }); } onAddAssets(assets); }; const handleDrop = (e) => { var _a3; e.preventDefault(); if ((_a3 = e == null ? void 0 : e.dataTransfer) == null ? void 0 : _a3.files) { const files = e.dataTransfer.files; const assets = []; for (let i3 = 0; i3 < files.length; i3++) { const file = files.item(i3); if (file) { const asset = rawFileToAsset(file, AssetSource.Computer); assets.push(asset); } } onAddAssets(assets); } setDragOver(false); }; return (0, import_jsx_runtime35.jsxs)("form", { children: [ (0, import_jsx_runtime35.jsx)(Box, { paddingLeft: 8, paddingRight: 8, paddingTop: 6, paddingBottom: 6, children: (0, import_jsx_runtime35.jsx)("label", { children: (0, import_jsx_runtime35.jsx)(MediaBox, { paddingTop: 11, paddingBottom: 11, hasRadius: true, justifyContent: "center", borderColor: dragOver ? "primary500" : "neutral300", background: dragOver ? "primary100" : "neutral100", position: "relative", onDragEnter: handleDragEnter, onDragLeave: handleDragLeave, onDragOver: handleDragOver, onDrop: handleDrop, children: (0, import_jsx_runtime35.jsx)(Flex, { justifyContent: "center", children: (0, import_jsx_runtime35.jsxs)(Wrapper2, { children: [ (0, import_jsx_runtime35.jsx)(IconWrapper, { children: (0, import_jsx_runtime35.jsx)(ForwardRef$1f, { "aria-hidden": true, width: "3.2rem", height: "3.2rem" }) }), (0, import_jsx_runtime35.jsx)(Box, { paddingTop: 3, paddingBottom: 5, children: (0, import_jsx_runtime35.jsx)(Typography, { variant: "delta", textColor: "neutral600", tag: "span", children: formatMessage({ id: getTrad("input.label"), defaultMessage: "Drag & Drop here or" }) }) }), (0, import_jsx_runtime35.jsx)(OpaqueBox, { tag: "input", position: "absolute", left: 0, right: 0, bottom: 0, top: 0, width: "100%", type: "file", multiple: true, name: "files", "aria-label": formatMessage({ id: getTrad("input.label"), defaultMessage: "Drag & Drop here or" }), tabIndex: -1, ref: inputRef, zIndex: 1, onChange: handleChange }), (0, import_jsx_runtime35.jsx)(Box, { position: "relative", children: (0, import_jsx_runtime35.jsx)(Button, { type: "button", onClick: handleClick, children: formatMessage({ id: getTrad("input.button.label"), defaultMessage: "Browse files" }) }) }) ] }) }) }) }) }), (0, import_jsx_runtime35.jsx)(Modal.Footer, { children: (0, import_jsx_runtime35.jsx)(Button, { onClick: onClose, variant: "tertiary", children: formatMessage({ id: "app.components.Button.cancel", defaultMessage: "cancel" }) }) }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/AddAssetStep/FromUrlForm.mjs var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1); var React22 = __toESM(require_react(), 1); var import_qs24 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/utils/urlsToAssets.mjs function getFilenameFromURL(url) { return new URL(url).pathname.split("/").pop(); } var urlsToAssets = async (urls) => { const assetPromises = urls.map((url) => fetch(url).then(async (res) => { const blob = await res.blob(); const loadedFile = new File([ blob ], getFilenameFromURL(res.url), { type: res.headers.get("content-type") || void 0 }); return { name: loadedFile.name, url: res.url, mime: res.headers.get("content-type"), rawFile: loadedFile }; })); const assetsResults = await Promise.all(assetPromises); const assets = assetsResults.map((fullFilledAsset) => ({ source: AssetSource.Url, name: fullFilledAsset.name, type: typeFromMime(fullFilledAsset.mime), url: fullFilledAsset.url, ext: fullFilledAsset.url.split(".").pop(), mime: fullFilledAsset.mime ? fullFilledAsset.mime : void 0, rawFile: fullFilledAsset.rawFile })); return assets; }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/AddAssetStep/FromUrlForm.mjs var FromUrlForm = ({ onClose, onAddAsset, trackedLocation }) => { const [loading, setLoading] = React22.useState(false); const [error, setError] = React22.useState(void 0); const { formatMessage } = useIntl(); const { trackUsage } = useTracking(); const handleSubmit = async ({ urls }) => { setLoading(true); const urlArray = urls.split(/\r?\n/); try { const assets = await urlsToAssets(urlArray); if (trackedLocation) { trackUsage("didSelectFile", { source: "url", location: trackedLocation }); } onAddAsset(assets); } catch (e) { setError(e); setLoading(false); } }; return (0, import_jsx_runtime36.jsx)(Formik, { enableReinitialize: true, initialValues: { urls: "" }, onSubmit: handleSubmit, validationSchema: urlSchema, validateOnChange: false, children: ({ values, errors, handleChange }) => (0, import_jsx_runtime36.jsxs)(Form, { noValidate: true, children: [ (0, import_jsx_runtime36.jsx)(Box, { paddingLeft: 8, paddingRight: 8, paddingBottom: 6, paddingTop: 6, children: (0, import_jsx_runtime36.jsxs)(Field.Root, { hint: formatMessage({ id: getTrad("input.url.description"), defaultMessage: "Separate your URL links by a carriage return." }), error: (error == null ? void 0 : error.message) || (errors.urls ? formatMessage({ id: errors.urls, defaultMessage: "An error occured" }) : void 0), children: [ (0, import_jsx_runtime36.jsx)(Field.Label, { children: formatMessage({ id: getTrad("input.url.label"), defaultMessage: "URL" }) }), (0, import_jsx_runtime36.jsx)(Textarea, { name: "urls", onChange: handleChange, value: values.urls }), (0, import_jsx_runtime36.jsx)(Field.Hint, {}), (0, import_jsx_runtime36.jsx)(Field.Error, {}) ] }) }), (0, import_jsx_runtime36.jsxs)(Modal.Footer, { children: [ (0, import_jsx_runtime36.jsx)(Button, { onClick: onClose, variant: "tertiary", children: formatMessage({ id: "app.components.Button.cancel", defaultMessage: "cancel" }) }), (0, import_jsx_runtime36.jsx)(Button, { type: "submit", loading, children: formatMessage({ id: getTrad("button.next"), defaultMessage: "Next" }) }) ] }) ] }) }); }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/AddAssetStep/AddAssetStep.mjs var AddAssetStep = ({ onClose, onAddAsset, trackedLocation }) => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime37.jsxs)(import_jsx_runtime37.Fragment, { children: [ (0, import_jsx_runtime37.jsx)(Modal.Header, { children: (0, import_jsx_runtime37.jsx)(Modal.Title, { children: formatMessage({ id: getTrad("header.actions.add-assets"), defaultMessage: "Add new assets" }) }) }), (0, import_jsx_runtime37.jsxs)(Tabs.Root, { variant: "simple", defaultValue: "computer", children: [ (0, import_jsx_runtime37.jsxs)(Box, { paddingLeft: 8, paddingRight: 8, paddingTop: 6, children: [ (0, import_jsx_runtime37.jsxs)(Tabs.List, { "aria-label": formatMessage({ id: getTrad("tabs.title"), defaultMessage: "How do you want to upload your assets?" }), children: [ (0, import_jsx_runtime37.jsx)(Tabs.Trigger, { value: "computer", children: formatMessage({ id: getTrad("modal.nav.computer"), defaultMessage: "From computer" }) }), (0, import_jsx_runtime37.jsx)(Tabs.Trigger, { value: "url", children: formatMessage({ id: getTrad("modal.nav.url"), defaultMessage: "From URL" }) }) ] }), (0, import_jsx_runtime37.jsx)(Divider, {}) ] }), (0, import_jsx_runtime37.jsx)(Tabs.Content, { value: "computer", children: (0, import_jsx_runtime37.jsx)(FromComputerForm, { onClose, onAddAssets: onAddAsset, trackedLocation }) }), (0, import_jsx_runtime37.jsx)(Tabs.Content, { value: "url", children: (0, import_jsx_runtime37.jsx)(FromUrlForm, { onClose, onAddAsset, trackedLocation }) }) ] }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/PendingAssetStep/PendingAssetStep.mjs var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1); var React24 = __toESM(require_react(), 1); var import_qs27 = __toESM(require_lib(), 1); // node_modules/@strapi/upload/dist/admin/components/AssetCard/UploadingAssetCard.mjs var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1); var React23 = __toESM(require_react(), 1); var import_qs26 = __toESM(require_lib(), 1); var UploadProgressWrapper2 = dt.div` height: 8.8rem; width: 100%; `; var Extension2 = dt.span` text-transform: uppercase; `; var UploadingAssetCard = ({ asset, onCancel, onStatusChange, addUploadedFiles, folderId = null }) => { const { upload, cancel, error, progress, status: status2 } = useUpload(); const { formatMessage } = useIntl(); let badgeContent = formatMessage({ id: getTrad("settings.section.doc.label"), defaultMessage: "Doc" }); if (asset.type === AssetType.Image) { badgeContent = formatMessage({ id: getTrad("settings.section.image.label"), defaultMessage: "Image" }); } else if (asset.type === AssetType.Video) { badgeContent = formatMessage({ id: getTrad("settings.section.video.label"), defaultMessage: "Video" }); } else if (asset.type === AssetType.Audio) { badgeContent = formatMessage({ id: getTrad("settings.section.audio.label"), defaultMessage: "Audio" }); } React23.useEffect(() => { const uploadFile = async () => { const files = await upload(asset, folderId ? Number(folderId) : null); if (addUploadedFiles) { addUploadedFiles(files); } }; uploadFile(); }, []); React23.useEffect(() => { onStatusChange(status2); }, [ status2, onStatusChange ]); const handleCancel = () => { cancel(); onCancel(asset.rawFile); }; return (0, import_jsx_runtime38.jsxs)(Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [ (0, import_jsx_runtime38.jsxs)(Card, { borderColor: error ? "danger600" : "neutral150", children: [ (0, import_jsx_runtime38.jsx)(CardHeader, { children: (0, import_jsx_runtime38.jsx)(UploadProgressWrapper2, { children: (0, import_jsx_runtime38.jsx)(UploadProgress, { error: error || void 0, onCancel: handleCancel, progress }) }) }), (0, import_jsx_runtime38.jsxs)(CardBody, { children: [ (0, import_jsx_runtime38.jsxs)(CardContent, { children: [ (0, import_jsx_runtime38.jsx)(Box, { paddingTop: 1, children: (0, import_jsx_runtime38.jsx)(Typography, { tag: "h2", children: (0, import_jsx_runtime38.jsx)(CardTitle, { tag: "span", children: asset.name }) }) }), (0, import_jsx_runtime38.jsx)(CardSubtitle, { children: (0, import_jsx_runtime38.jsx)(Extension2, { children: asset.ext }) }) ] }), (0, import_jsx_runtime38.jsx)(Flex, { paddingTop: 1, grow: 1, children: (0, import_jsx_runtime38.jsx)(CardBadge, { children: badgeContent }) }) ] }) ] }), error ? (0, import_jsx_runtime38.jsx)(Typography, { variant: "pi", fontWeight: "bold", textColor: "danger600", children: formatMessage((error == null ? void 0 : error.message) ? { id: getTrad(`apiError.${error.message}`), defaultMessage: error.message } : { id: getTrad("upload.generic-error"), defaultMessage: "An error occured while uploading the file." }) }) : void 0 ] }); }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/PendingAssetStep/PendingAssetStep.mjs var Status = { Idle: "IDLE", Uploading: "UPLOADING", Intermediate: "INTERMEDIATE" }; var PendingAssetStep = ({ addUploadedFiles, folderId, onClose, onEditAsset, onRemoveAsset, assets, onClickAddAsset, onCancelUpload, onUploadSucceed, trackedLocation }) => { const assetCountRef = React24.useRef(0); const { formatMessage } = useIntl(); const { trackUsage } = useTracking(); const [uploadStatus, setUploadStatus] = React24.useState(Status.Idle); const handleSubmit = async (e) => { e.preventDefault(); e.stopPropagation(); const assetsCountByType = assets.reduce((acc, asset) => { const { type } = asset; if (type !== void 0 && !acc[type]) { acc[type] = 0; } if (type !== void 0) { const accType = acc[type]; const currentCount = typeof accType === "string" ? accType : accType.toString(); acc[type] = `${parseInt(currentCount, 10) + 1}`; } return acc; }, {}); trackUsage("willAddMediaLibraryAssets", { location: trackedLocation, ...assetsCountByType }); setUploadStatus(Status.Uploading); }; const handleStatusChange = (status2, file) => { if (status2 === "success" || status2 === "error") { assetCountRef.current++; if (assetCountRef.current === assets.length) { assetCountRef.current = 0; setUploadStatus(Status.Intermediate); } } if (status2 === "success") { onUploadSucceed(file); } }; return (0, import_jsx_runtime39.jsxs)(import_jsx_runtime39.Fragment, { children: [ (0, import_jsx_runtime39.jsx)(Modal.Header, { children: (0, import_jsx_runtime39.jsx)(Modal.Title, { children: formatMessage({ id: getTrad("header.actions.add-assets"), defaultMessage: "Add new assets" }) }) }), (0, import_jsx_runtime39.jsx)(Modal.Body, { children: (0, import_jsx_runtime39.jsxs)(Flex, { direction: "column", alignItems: "stretch", gap: 7, children: [ (0, import_jsx_runtime39.jsxs)(Flex, { justifyContent: "space-between", children: [ (0, import_jsx_runtime39.jsxs)(Flex, { direction: "column", alignItems: "stretch", gap: 0, children: [ (0, import_jsx_runtime39.jsx)(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", children: formatMessage({ id: getTrad("list.assets.to-upload"), defaultMessage: "{number, plural, =0 {No asset} one {1 asset} other {# assets}} ready to upload" }, { number: assets.length }) }), (0, import_jsx_runtime39.jsx)(Typography, { variant: "pi", textColor: "neutral600", children: formatMessage({ id: getTrad("modal.upload-list.sub-header-subtitle"), defaultMessage: "Manage the assets before adding them to the Media Library" }) }) ] }), (0, import_jsx_runtime39.jsx)(Button, { size: "S", onClick: onClickAddAsset, children: formatMessage({ id: getTrad("header.actions.add-assets"), defaultMessage: "Add new assets" }) }) ] }), (0, import_jsx_runtime39.jsx)(KeyboardNavigable, { tagName: "article", children: (0, import_jsx_runtime39.jsx)(Grid.Root, { gap: 4, children: assets.map((asset) => { const assetKey = asset.url; if (uploadStatus === Status.Uploading || uploadStatus === Status.Intermediate) { return (0, import_jsx_runtime39.jsx)(Grid.Item, { col: 4, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime39.jsx)(UploadingAssetCard, { // Props used to store the newly uploaded files addUploadedFiles, asset, id: assetKey, onCancel: onCancelUpload, onStatusChange: (status2) => handleStatusChange(status2, asset.rawFile), size: "S", folderId }) }, assetKey); } return (0, import_jsx_runtime39.jsx)(Grid.Item, { col: 4, direction: "column", alignItems: "stretch", children: (0, import_jsx_runtime39.jsx)(AssetCard, { asset, size: "S", local: true, alt: asset.name, onEdit: onEditAsset, onRemove: onRemoveAsset }, assetKey) }, assetKey); }) }) }) ] }) }), (0, import_jsx_runtime39.jsxs)(Modal.Footer, { children: [ (0, import_jsx_runtime39.jsx)(Button, { onClick: onClose, variant: "tertiary", children: formatMessage({ id: "app.components.Button.cancel", defaultMessage: "cancel" }) }), (0, import_jsx_runtime39.jsx)(Button, { onClick: handleSubmit, loading: uploadStatus === Status.Uploading, children: formatMessage({ id: getTrad("modal.upload-list.footer.button"), defaultMessage: "Upload {number, plural, one {# asset} other {# assets}} to the library" }, { number: assets.length }) }) ] }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/UploadAssetDialog/UploadAssetDialog.mjs var Steps = { AddAsset: "AddAsset", PendingAsset: "PendingAsset" }; var UploadAssetDialog = ({ initialAssetsToAdd, folderId = null, onClose = () => { }, addUploadedFiles, trackedLocation, open, validateAssetsTypes = (_3, cb) => cb() }) => { const { formatMessage } = useIntl(); const [step, setStep] = React25.useState(initialAssetsToAdd ? Steps.PendingAsset : Steps.AddAsset); const [assets, setAssets] = React25.useState(initialAssetsToAdd || []); const [assetToEdit, setAssetToEdit] = React25.useState(void 0); const handleAddToPendingAssets = (nextAssets) => { validateAssetsTypes(nextAssets, () => { setAssets((prevAssets) => prevAssets.concat(nextAssets)); setStep(Steps.PendingAsset); }); }; const moveToAddAsset = () => { setStep(Steps.AddAsset); }; const handleCancelUpload = (file) => { const nextAssets = assets.filter((asset) => asset.rawFile !== file); setAssets(nextAssets); if (nextAssets.length === 0) { moveToAddAsset(); } }; const handleUploadSuccess = (file) => { const nextAssets = assets.filter((asset) => asset.rawFile !== file); setAssets(nextAssets); if (nextAssets.length === 0) { onClose(); } }; const handleAssetEditValidation = (nextAsset) => { if (nextAsset && typeof nextAsset !== "boolean") { const nextAssets = assets.map((asset) => asset === assetToEdit ? nextAsset : asset); setAssets(nextAssets); } setAssetToEdit(void 0); }; const handleClose = () => { if (step === Steps.PendingAsset && assets.length > 0) { const confirm = window.confirm(formatMessage({ id: "window.confirm.close-modal.files", defaultMessage: "Are you sure? You have some files that have not been uploaded yet." })); if (confirm) { onClose(); } } else { onClose(); } }; const handleRemoveAsset = (assetToRemove) => { const nextAssets = assets.filter((asset) => asset !== assetToRemove); setAssets(nextAssets); }; return (0, import_jsx_runtime40.jsxs)(Modal.Root, { open, onOpenChange: handleClose, children: [ step === Steps.AddAsset && (0, import_jsx_runtime40.jsx)(Modal.Content, { children: (0, import_jsx_runtime40.jsx)(AddAssetStep, { onClose, onAddAsset: (assets2) => handleAddToPendingAssets(assets2), trackedLocation }) }), step === Steps.PendingAsset && (0, import_jsx_runtime40.jsx)(Modal.Content, { children: (0, import_jsx_runtime40.jsx)(PendingAssetStep, { onClose: handleClose, assets, onEditAsset: setAssetToEdit, onRemoveAsset: handleRemoveAsset, onClickAddAsset: moveToAddAsset, onCancelUpload: handleCancelUpload, onUploadSucceed: handleUploadSuccess, initialAssetsToAdd, addUploadedFiles, folderId, trackedLocation }) }), assetToEdit && (0, import_jsx_runtime40.jsx)(Modal.Content, { children: (0, import_jsx_runtime40.jsx)(EditAssetContent, { onClose: handleAssetEditValidation, asset: assetToEdit, canUpdate: true, canCopyLink: false, canDownload: false, trackedLocation }) }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/Breadcrumbs/Breadcrumbs.mjs var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/components/Breadcrumbs/CrumbSimpleMenuAsync.mjs var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1); var React26 = __toESM(require_react(), 1); // node_modules/@strapi/upload/dist/admin/utils/getFolderParents.mjs var getFolderParents = (folders, currentFolderId) => { const parents = []; const flatFolders = flattenTree(folders); const currentFolder = flatFolders.find((folder) => folder.value === currentFolderId); if (!currentFolder) { return []; } let { parent } = currentFolder; while (parent !== void 0) { const parentToStore = flatFolders.find(({ value }) => value === parent); parents.push({ id: parentToStore == null ? void 0 : parentToStore.value, label: parentToStore == null ? void 0 : parentToStore.label }); parent = parentToStore == null ? void 0 : parentToStore.parent; } return parents.reverse(); }; // node_modules/@strapi/upload/dist/admin/components/Breadcrumbs/CrumbSimpleMenuAsync.mjs var CrumbSimpleMenuAsync = ({ parentsToOmit = [], currentFolderId, onChangeFolder }) => { const [shouldFetch, setShouldFetch] = React26.useState(false); const { data, isLoading } = useFolderStructure({ enabled: shouldFetch }); const { pathname } = useLocation(); const [{ query }] = useQueryParams(); const { formatMessage } = useIntl(); const allAscendants = data && getFolderParents(data, currentFolderId); const filteredAscendants = allAscendants && allAscendants.filter((ascendant) => typeof ascendant.id === "number" && !parentsToOmit.includes(ascendant.id) && ascendant.id !== null); return (0, import_jsx_runtime41.jsxs)(CrumbSimpleMenu, { onOpen: () => setShouldFetch(true), onClose: () => setShouldFetch(false), "aria-label": formatMessage({ id: getTrad("header.breadcrumbs.menu.label"), defaultMessage: "Get more ascendants folders" }), label: "...", children: [ isLoading && (0, import_jsx_runtime41.jsx)(MenuItem, { children: (0, import_jsx_runtime41.jsx)(Loader, { small: true, children: formatMessage({ id: getTrad("content.isLoading"), defaultMessage: "Content is loading." }) }) }), filteredAscendants && filteredAscendants.map((ascendant) => { if (onChangeFolder) { return (0, import_jsx_runtime41.jsx)(MenuItem, { tag: "button", type: "button", onClick: () => onChangeFolder(Number(ascendant.id), ascendant.path), children: ascendant.label }, ascendant.id); } const url = getFolderURL(pathname, query, { folder: typeof (ascendant == null ? void 0 : ascendant.id) === "string" ? ascendant.id : void 0, folderPath: ascendant == null ? void 0 : ascendant.path }); return (0, import_jsx_runtime41.jsx)(MenuItem, { isLink: true, href: url, children: ascendant.label }, ascendant.id); }) ] }); }; // node_modules/@strapi/upload/dist/admin/components/Breadcrumbs/Breadcrumbs.mjs var Breadcrumbs2 = ({ breadcrumbs, onChangeFolder, currentFolderId, ...props }) => { const { formatMessage } = useIntl(); return (0, import_jsx_runtime42.jsx)(Breadcrumbs, { ...props, children: breadcrumbs.map((crumb, index2) => { var _a3, _b, _c; if (Array.isArray(crumb)) { return (0, import_jsx_runtime42.jsx)(CrumbSimpleMenuAsync, { parentsToOmit: [ ...breadcrumbs ].splice(index2 + 1, breadcrumbs.length - 1).map((parent) => parent.id), currentFolderId, onChangeFolder }, `breadcrumb-${(crumb == null ? void 0 : crumb.id) ?? "menu"}`); } const isCurrentFolderMediaLibrary = crumb.id === null && currentFolderId === void 0; if (currentFolderId !== crumb.id && !isCurrentFolderMediaLibrary) { if (onChangeFolder) { return (0, import_jsx_runtime42.jsx)(CrumbLink, { type: "button", onClick: () => onChangeFolder(crumb.id, crumb.path), children: typeof crumb.label !== "string" && ((_a3 = crumb.label) == null ? void 0 : _a3.id) ? formatMessage(crumb.label) : crumb.label }, `breadcrumb-${(crumb == null ? void 0 : crumb.id) ?? "root"}`); } return (0, import_jsx_runtime42.jsx)(CrumbLink, { to: crumb.href, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - `tag` prop is not defined in the `BaseLinkProps` type tag: Link, children: typeof crumb.label !== "string" && ((_b = crumb.label) == null ? void 0 : _b.id) ? formatMessage(crumb.label) : crumb.label }, `breadcrumb-${(crumb == null ? void 0 : crumb.id) ?? "root"}`); } return (0, import_jsx_runtime42.jsx)(Crumb, { isCurrent: index2 + 1 === breadcrumbs.length, children: typeof crumb.label !== "string" && ((_c = crumb.label) == null ? void 0 : _c.id) ? formatMessage(crumb.label) : crumb.label }, `breadcrumb-${(crumb == null ? void 0 : crumb.id) ?? "root"}`); }) }); }; // node_modules/@strapi/upload/dist/admin/components/EmptyAssets/EmptyAssets.mjs var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/components/EmptyAssets/EmptyAssetGrid.mjs var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1); var EmptyAssetCard = dt(Box)` background: linear-gradient( 180deg, rgba(234, 234, 239, 0) 0%, ${({ theme }) => theme.colors.neutral200} 100% ); opacity: 0.33; `; var PlaceholderSize = { S: 138, M: 234 }; var EmptyAssetGrid = ({ count, size }) => { return (0, import_jsx_runtime43.jsx)(Layouts.Grid, { size, children: Array(count).fill(null).map((_3, idx) => (0, import_jsx_runtime43.jsx)(EmptyAssetCard, { height: `${PlaceholderSize[size]}px`, hasRadius: true }, `empty-asset-card-${idx}`)) }); }; // node_modules/@strapi/upload/dist/admin/components/EmptyAssets/EmptyAssets.mjs var EmptyAssets = ({ icon: Icon = ForwardRef$J, content, action, size = "M", count = 12 }) => { return (0, import_jsx_runtime44.jsxs)(Box, { position: "relative", children: [ (0, import_jsx_runtime44.jsx)(EmptyAssetGrid, { size, count }), (0, import_jsx_runtime44.jsx)(Box, { position: "absolute", top: 11, width: "100%", children: (0, import_jsx_runtime44.jsxs)(Flex, { direction: "column", alignItems: "center", gap: 4, textAlign: "center", children: [ (0, import_jsx_runtime44.jsxs)(Flex, { direction: "column", alignItems: "center", gap: 6, children: [ (0, import_jsx_runtime44.jsx)(Icon, { width: "160px", height: "88px" }), (0, import_jsx_runtime44.jsx)(Typography, { variant: "delta", tag: "p", textColor: "neutral600", children: content }) ] }), action ] }) }) ] }); }; // node_modules/@strapi/upload/dist/admin/utils/displayedFilters.mjs var displayedFilters = [ { name: "createdAt", fieldSchema: { type: "date" }, metadatas: { label: "createdAt" } }, { name: "updatedAt", fieldSchema: { type: "date" }, metadatas: { label: "updatedAt" } }, { name: "mime", fieldSchema: { type: "enumeration", options: [ { label: "audio", value: "audio" }, { label: "file", value: "file" }, { label: "image", value: "image" }, { label: "video", value: "video" } ] }, metadatas: { label: "type" } } ]; // node_modules/@strapi/upload/dist/admin/components/FilterList/FilterList.mjs var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1); // node_modules/@strapi/upload/dist/admin/components/FilterList/FilterTag.mjs var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1); var FilterTag = ({ attribute, filter, onClick, operator, value }) => { var _a3; const { formatMessage, formatDate, formatTime: formatTime2 } = useIntl(); const handleClick = () => { onClick(filter); }; const { fieldSchema } = attribute; const type = fieldSchema == null ? void 0 : fieldSchema.type; let formattedValue = value; if (type === "date") { formattedValue = formatDate(value, { dateStyle: "full" }); } if (type === "datetime") { formattedValue = formatDate(value, { dateStyle: "full", timeStyle: "short" }); } if (type === "time") { const [hour, minute] = value.split(":"); const date = /* @__PURE__ */ new Date(); date.setHours(Number(hour)); date.setMinutes(Number(minute)); formattedValue = formatTime2(date, { hour: "numeric", minute: "numeric" }); } const content = `${(_a3 = attribute.metadatas) == null ? void 0 : _a3.label} ${formatMessage({ id: `components.FilterOptions.FILTER_TYPES.${operator}`, defaultMessage: operator })} ${formattedValue}`; return (0, import_jsx_runtime45.jsx)(Tag, { onClick: handleClick, icon: (0, import_jsx_runtime45.jsx)(ForwardRef$45, {}), padding: 1, children: content }); }; // node_modules/@strapi/upload/dist/admin/components/FilterList/FilterList.mjs var FilterList = ({ appliedFilters, filtersSchema, onRemoveFilter }) => { const handleClick = (filter) => { const nextFilters = appliedFilters.filter((prevFilter) => { var _a3; const name = Object.keys(filter)[0]; const filterName = filter[name]; if (filterName !== void 0) { const filterType = Object.keys(filterName)[0]; const filterValue = filterName[filterType]; if (typeof filterValue === "string") { const decodedValue = decodeURIComponent(filterValue); return ((_a3 = prevFilter[name]) == null ? void 0 : _a3[filterType]) !== decodedValue; } } return true; }); onRemoveFilter(nextFilters); }; return appliedFilters.map((filter, i3) => { const attributeName = Object.keys(filter)[0]; const attribute = filtersSchema.find(({ name }) => name === attributeName); if (!attribute) { return null; } const filterObj = filter[attributeName]; const operator = Object.keys(filterObj)[0]; let value = filterObj[operator]; if (Array.isArray(value)) { value = value.join(", "); } else if (typeof value === "object") { value = Object.values(value).join(", "); } else { value = Array.isArray(value) || typeof value === "object" ? Object.values(value).join(", ") : decodeURIComponent(value); } let displayedOperator = operator; if ((attribute == null ? void 0 : attribute.name) === "mime") { displayedOperator = operator === "$contains" ? "$eq" : "$ne"; if (operator === "$not") { value = "file"; displayedOperator = "$eq"; } if ([ "image", "video" ].includes(value[0]) && [ "image", "video" ].includes(value[1])) { value = "file"; displayedOperator = "$ne"; } } return (0, import_jsx_runtime46.jsx)(FilterTag, { attribute, filter, onClick: handleClick, operator: displayedOperator, value }, `${attributeName}-${i3}`); }); }; // node_modules/@strapi/upload/dist/admin/components/FilterPopover/FilterPopover.mjs var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1); var React27 = __toESM(require_react(), 1); // node_modules/@strapi/upload/dist/admin/components/FilterPopover/FilterValueInput.mjs var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1); var FilterValueInput = ({ label = "", onChange: onChange2, options: options2 = [], type, value = "" }) => { const { formatMessage } = useIntl(); if (type === "date") { return (0, import_jsx_runtime47.jsx)(DateTimePicker, { clearLabel: formatMessage({ id: "clearLabel", defaultMessage: "Clear" }), "aria-label": label, name: "datetimepicker", onChange: (date) => { const formattedDate = date ? new Date(date).toISOString() : ""; onChange2(formattedDate); }, onClear: () => onChange2(""), value: value ? new Date(value) : void 0 }); } return (0, import_jsx_runtime47.jsx)(SingleSelect, { "aria-label": label, onChange: (value2) => onChange2(value2.toString()), value, children: options2 == null ? void 0 : options2.map((option) => { return (0, import_jsx_runtime47.jsx)(SingleSelectOption, { value: option.value, children: option.label }, option.value); }) }); }; // node_modules/@strapi/upload/dist/admin/components/FilterPopover/utils/getFilterList.mjs var getFilterList = ({ fieldSchema: { type: fieldType, mainField } }) => { const type = (mainField == null ? void 0 : mainField.schema.type) ? mainField.schema.type : fieldType; switch (type) { case "enumeration": { return [ { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$eq", defaultMessage: "is" }, value: "$contains" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$ne", defaultMessage: "is not" }, value: "$notContains" } ]; } case "date": { return [ { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$eq", defaultMessage: "is" }, value: "$eq" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$ne", defaultMessage: "is not" }, value: "$ne" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$gt", defaultMessage: "is greater than" }, value: "$gt" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$gte", defaultMessage: "is greater than or equal to" }, value: "$gte" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$lt", defaultMessage: "is less than" }, value: "$lt" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$lte", defaultMessage: "is less than or equal to" }, value: "$lte" } ]; } default: return [ { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$eq", defaultMessage: "is" }, value: "$eq" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$eqi", defaultMessage: "is (case insensitive)" }, value: "$eqi" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$ne", defaultMessage: "is not" }, value: "$ne" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$null", defaultMessage: "is null" }, value: "$null" }, { intlLabel: { id: "components.FilterOptions.FILTER_TYPES.$notNull", defaultMessage: "is not null" }, value: "$notNull" } ]; } }; // node_modules/@strapi/upload/dist/admin/components/FilterPopover/FilterPopover.mjs var FilterPopover = ({ displayedFilters: displayedFilters2, filters, onSubmit, onToggle }) => { const { formatMessage } = useIntl(); const [modifiedData, setModifiedData] = React27.useState({ name: "createdAt", filter: "$eq", value: "" }); const handleChangeFilterField = (value) => { const nextField = displayedFilters2.find((f) => f.name === value); if (!nextField) { return; } const { fieldSchema: { type, options: options2 } } = nextField; let filterValue = ""; if (type === "enumeration") { filterValue = (options2 == null ? void 0 : options2[0].value) || ""; } const filter = getFilterList(nextField)[0].value; setModifiedData({ name: value.toString(), filter, value: filterValue }); }; const handleChangeOperator = (operator) => { if (modifiedData.name === "mime") { setModifiedData((prev2) => ({ ...prev2, filter: operator.toString(), value: "image" })); } else { setModifiedData((prev2) => ({ ...prev2, filter: operator.toString(), value: "" })); } }; const handleSubmit = (e) => { e.preventDefault(); e.stopPropagation(); const encodedValue = encodeURIComponent(modifiedData.value); if (encodedValue) { if (modifiedData.name === "mime") { const alreadyAppliedFilters = filters.filter((filter) => { return Object.keys(filter)[0] === "mime"; }); if (modifiedData.value === "file") { const filtersWithoutMimeType = filters.filter((filter) => { return Object.keys(filter)[0] !== "mime"; }); let hasCurrentFilter = false; let filterToAdd2; if (modifiedData.filter === "$contains") { hasCurrentFilter = alreadyAppliedFilters.find((filter) => { var _a3, _b, _c, _d; if (typeof ((_a3 = filter.mime) == null ? void 0 : _a3.$not) !== "string" && !Array.isArray((_b = filter.mime) == null ? void 0 : _b.$not)) { return ((_d = (_c = filter.mime) == null ? void 0 : _c.$not) == null ? void 0 : _d.$contains) !== void 0; } }) !== void 0; filterToAdd2 = { mime: { $not: { $contains: [ "image", "video" ] } } }; } else { hasCurrentFilter = alreadyAppliedFilters.find((filter) => { var _a3; return Array.isArray((_a3 = filter.mime) == null ? void 0 : _a3.$contains); }) !== void 0; filterToAdd2 = { mime: { $contains: [ "image", "video" ] } }; } if (hasCurrentFilter) { onToggle(); return; } const nextFilters = [ ...filtersWithoutMimeType, filterToAdd2 ]; onSubmit(nextFilters); onToggle(); return; } const hasFilter2 = alreadyAppliedFilters.find((filter) => { const modifiedDataFilter = modifiedData.filter; return filter.mime && filter.mime[modifiedDataFilter] === modifiedData.value; }) !== void 0; if (hasFilter2) { onToggle(); return; } const filtersWithoutFile = filters.filter((filter) => { var _a3, _b, _c, _d, _e5; const filterType = Object.keys(filter)[0]; if (filterType !== "mime") { return true; } if (typeof ((_a3 = filter.mime) == null ? void 0 : _a3.$not) !== "string" && !Array.isArray((_b = filter.mime) == null ? void 0 : _b.$not) && ((_d = (_c = filter.mime) == null ? void 0 : _c.$not) == null ? void 0 : _d.$contains) !== void 0) { return false; } if (Array.isArray((_e5 = filter == null ? void 0 : filter.mime) == null ? void 0 : _e5.$contains)) { return false; } return true; }); const oppositeFilter = modifiedData.filter === "$contains" ? "$notContains" : "$contains"; const oppositeFilterIndex = filtersWithoutFile.findIndex((filter) => { var _a3; return ((_a3 = filter.mime) == null ? void 0 : _a3[oppositeFilter]) === modifiedData.value; }); const hasOppositeFilter = oppositeFilterIndex !== -1; const filterToAdd = { [modifiedData.name]: { [modifiedData.filter]: modifiedData.value } }; if (!hasOppositeFilter) { const nextFilters = [ ...filtersWithoutFile, filterToAdd ]; onSubmit(nextFilters); onToggle(); return; } if (hasOppositeFilter) { const nextFilters = filtersWithoutFile.slice(); nextFilters.splice(oppositeFilterIndex, 1, filterToAdd); onSubmit(nextFilters); onToggle(); } return; } const hasFilter = filters.find((filter) => { var _a3; const modifiedDataName = modifiedData.name; return filter[modifiedDataName] && ((_a3 = filter[modifiedDataName]) == null ? void 0 : _a3[modifiedDataName]) === encodedValue; }) !== void 0; if (!hasFilter) { const filterToAdd = { [modifiedData.name]: { [modifiedData.filter]: encodedValue } }; const nextFilters = [ ...filters, filterToAdd ]; onSubmit(nextFilters); } } onToggle(); }; const appliedFilter = displayedFilters2.find((filter) => filter.name === modifiedData.name); return (0, import_jsx_runtime48.jsx)(Popover.Content, { sideOffset: 4, children: (0, import_jsx_runtime48.jsx)("form", { onSubmit: handleSubmit, children: (0, import_jsx_runtime48.jsxs)(Flex, { padding: 3, direction: "column", alignItems: "stretch", gap: 1, style: { minWidth: 184 }, children: [ (0, import_jsx_runtime48.jsx)(Box, { children: (0, import_jsx_runtime48.jsx)(SingleSelect, { "aria-label": formatMessage({ id: "app.utils.select-field", defaultMessage: "Select field" }), name: "name", size: "M", onChange: handleChangeFilterField, value: modifiedData.name, children: displayedFilters2.map((filter) => { var _a3; return (0, import_jsx_runtime48.jsx)(SingleSelectOption, { value: filter.name, children: (_a3 = filter.metadatas) == null ? void 0 : _a3.label }, filter.name); }) }) }), (0, import_jsx_runtime48.jsx)(Box, { children: (0, import_jsx_runtime48.jsx)(SingleSelect, { "aria-label": formatMessage({ id: "app.utils.select-filter", defaultMessage: "Select filter" }), name: "filter", size: "M", value: modifiedData.filter, onChange: handleChangeOperator, children: getFilterList(appliedFilter).map((option) => { return (0, import_jsx_runtime48.jsx)(SingleSelectOption, { value: option.value, children: formatMessage(option.intlLabel) }, option.value); }) }) }), (0, import_jsx_runtime48.jsx)(Box, { children: (0, import_jsx_runtime48.jsx)(FilterValueInput, { ...appliedFilter == null ? void 0 : appliedFilter.metadatas, ...appliedFilter == null ? void 0 : appliedFilter.fieldSchema, value: modifiedData.value, onChange: (value) => setModifiedData((prev2) => ({ ...prev2, value })) }) }), (0, import_jsx_runtime48.jsx)(Box, { children: (0, import_jsx_runtime48.jsx)(Button, { size: "L", variant: "secondary", startIcon: (0, import_jsx_runtime48.jsx)(ForwardRef$1h, {}), type: "submit", fullWidth: true, children: formatMessage({ id: "app.utils.add-filter", defaultMessage: "Add filter" }) }) }) ] }) }) }); }; export { useAssets, useFolders, useMediaLibraryPermissions, useSelectionState, containsAssetFilter, useFolderStructure, SelectTree, prefixFileUrlWithBackendUrl, createAssetUrl, CopyLinkButton, EditAssetContent, EditAssetDialog, useBulkRemove, normalizeAPIError, EditFolderContent, EditFolderDialog, useFolder, usePersistentState, AudioPreview, VideoPreview, AssetGridList, getFolderURL, Breadcrumbs2 as Breadcrumbs, EmptyAssets, useFolderCard, FolderCard, FolderCardBody, FolderCardBodyAction, FolderGridList, SortPicker, TableList, displayedFilters, FilterList, FilterPopover, rawFileToAsset, UploadAssetDialog }; /*! Bundled license information: cropperjs/dist/cropper.esm.js: (*! * Cropper.js v1.6.1 * https://fengyuanchen.github.io/cropperjs * * Copyright 2015-present Chen Fengyuan * Released under the MIT license * * Date: 2023-09-17T03:44:19.860Z *) mux-embed/dist/mux.mjs: (*! * JavaScript Cookie v2.1.3 * https://github.com/js-cookie/js-cookie * * Copyright 2006, 2015 Klaus Hartl & Fagner Brack * Released under the MIT license *) */ //# sourceMappingURL=chunk-7KYK3FTC.js.map