YouTube JS Engine Tamer

修改 YouTube 的 JS 引擎以提升性能

当前为 2025-05-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube JS Engine Tamer
  3. // @name:ja YouTube JS Engine Tamer
  4. // @name:zh-TW YouTube JS Engine Tamer
  5. // @name:zh-CN YouTube JS Engine Tamer
  6. // @namespace UserScripts
  7. // @version 0.41.0
  8. // @match https://www.youtube.com/*
  9. // @match https://www.youtube-nocookie.com/embed/*
  10. // @match https://studio.youtube.com/live_chat*
  11. // @license MIT
  12. // @author CY Fung
  13. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/yt-engine.png
  14. // @grant none
  15. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@c2b707e4977f77792042d4a5015fb188aae4772e/library/nextBrowserTick.min.js
  16. // @run-at document-start
  17. // @unwrap
  18. // @inject-into page
  19. // @allFrames true
  20. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  21. //
  22. // @description To enhance YouTube performance by modifying YouTube JS Engine
  23. // @description:ja YouTubeのJSエンジンを変更してパフォーマンスを向上させる
  24. // @description:zh-TW 修改 YouTube 的 JS 引擎以提升效能
  25. // @description:zh-CN 修改 YouTube 的 JS 引擎以提升性能
  26. //
  27. // ==/UserScript==
  28.  
  29. (() => {
  30.  
  31. /** @type {WeakMapConstructor} */
  32. const WeakMap = window.WeakMapOriginal || window.WeakMap;
  33.  
  34. const HOOK_ACTIVE_MODULES = true; // added in 0.37.0
  35. const HOOK_ACTIVE_MODULES_fetchUpdatedMetadata = true; // added in 0.37.0 (make likeCount update)
  36. const NATIVE_CANVAS_ANIMATION = false; // for #cinematics
  37. const FIX_schedulerInstanceInstance = 2 | 4;
  38. const FIX_yt_player = true; // DONT CHANGE
  39. const FIX_Animation_n_timeline = true;
  40. const FIX_Animation_n_timeline_cinematic = true;
  41. const FIX_ytScheduler = true;
  42. const NO_PRELOAD_GENERATE_204 = false;
  43. const ENABLE_COMPUTEDSTYLE_CACHE = true;
  44. const NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE = true;
  45. const CHANGE_appendChild = true; // discussions#236759
  46. const FIX_bind_self_this = false; // EXPERIMENTAL !!!!! this affect page switch after live ends
  47.  
  48. const FIX_error_many_stack = true; // should be a bug caused by uBlock Origin
  49.  
  50. const IGNORE_bindAnimationForCustomEffect = true; // prevent `v.bindAnimationForCustomEffect(this);` being executed
  51.  
  52. const FIX_ytdExpander_childrenChanged = true;
  53. const FIX_paper_ripple_animate = true;
  54. const FIX_avoid_incorrect_video_meta = true; // [legacy feature for rolling number fixing] 2025.05.10 - obsoleted -> y.fetchUpdatedMetadata(t, e.continuation)
  55. const FIX_avoid_incorrect_video_meta_emitterBehavior = true; // [legacy feature for rolling number fixing] 2025.05.10 - obsoleted -> y.fetchUpdatedMetadata(t, e.continuation)
  56.  
  57. const FIX_doIdomRender = true;
  58.  
  59. const FIX_Shady = true;
  60.  
  61. // [[ 2024.04.24 ]]
  62. const MODIFY_ShadyDOM_OBJ = true;
  63. // << if MODIFY_ShadyDOM_OBJ >>
  64. const WEAKREF_ShadyDOM = true;
  65. const OMIT_ShadyDOM_EXPERIMENTAL = 1 | 0; // 1 => enable; 2 => composedPath
  66. const OMIT_ShadyDOM_settings = 0 | 0 | 0; // 1: inUse; 2: handlesDynamicScoping; 4: force // {{ PRELIM TESTING PURPOSE }}
  67. // << end >>
  68.  
  69. const WEAK_REF_BINDING_CONTROL = 1 | 2; // 2 - conflict control with ShadyDOM weakref
  70.  
  71. const FIX_ytAction_ = true; // ytd-app
  72. const FIX_onVideoDataChange = false;
  73. // const FIX_onClick = true;
  74. const FIX_onStateChange = true;
  75. const FIX_onLoopRangeChange = true;
  76. // const FIX_maybeUpdateFlexibleMenu = true; // ytd-menu-renderer
  77. const FIX_VideoEVENTS_v2 = true; // true might cause bug in switching page
  78.  
  79. const FIX_stampDomArray_ = true; // v0.30.0
  80. const FIX_stampDomArray = FIX_stampDomArray_ && typeof WeakRef === "function" && typeof FinalizationRegistry === "function";
  81. // const stampDomArray_MemoryFix_Flag001 = false;
  82. const XFlag = true; // root issue tbc
  83. const MemoryFix_Flag002 = 1 | 2 | 4 | 8 | 0 | 32 | 64 | 0 | 256;
  84. // 32 required for new stampDomArray
  85. // 128 to be tested
  86.  
  87. const FIX_perfNow = true; // history state issue; see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  88. const ENABLE_ASYNC_DISPATCHEVENT = false; // problematic
  89.  
  90. const FIX_Polymer_dom = true;
  91. const FIX_Polymer_AF = true;
  92.  
  93. const SCRIPTLET_REMOVE_PRUNE_propNeedles = true; // brave scriptlet related
  94. const DEBUG_removePrune = false; // true for DEBUG
  95.  
  96. const FIX_XHR_REQUESTING = true;
  97.  
  98. const LOG_FETCHMETA_UPDATE = false; // for DEBUG
  99.  
  100. const IGNORE_bufferhealth_CHECK = false; // experimental; true will make "Stats for nerds" no info.
  101.  
  102. const DENY_requestStorageAccess = true; // remove document.requestStorageAccess
  103. const DISABLE_IFRAME_requestStorageAccess = true; // no effect if DENY_requestStorageAccess is true
  104.  
  105. const DISABLE_COOLDOWN_SCROLLING = true; // YT cause scroll hang in MacOS
  106.  
  107. const FIX_removeChild = true;
  108. const FIX_fix_requestIdleCallback_timing = true;
  109.  
  110. const HOOK_CSSPD_LEFT = true; // global css hack for style.left
  111. const FORCE_NO_REUSEABLE_ELEMENT_POOL = true;
  112.  
  113. const FIX_TRANSCRIPT_SEGMENTS = true; // Based on Tabview Youtube's implementation
  114.  
  115. const FIX_POPUP_UNIQUE_ID = true; // currently only for channel about popup;
  116.  
  117. // ------------------------------------------------------------------
  118.  
  119. const MEMORY_RELEASE_NF00 = true;
  120. const MEMORY_RELEASE_NF00_SHOW_MESSAGE = false;
  121. const MEMORY_RELEASE_MAP_SET_REMOVE_NODE = true;
  122. const FULLY_REMOVE_ALL_EVENT_LISTENERS = true; // require MEMORY_RELEASE_NF00
  123.  
  124. const FIX_TEMPLATE_BINDING = true;
  125. const FIX_TEMPLATE_BINDING_SHOW_MESSAGE = false;
  126.  
  127. const USE_fastDomIf = 2; // fastDomIf is seem to be experimental 0 = no change, 1 = enable, 2 = disable
  128. const ENHANCE_DOMIF_createAndInsertInstance = true; // root does not need to store in the instance
  129. const ENHANCE_DOMIF_TEARDOWN = true; // require MEMORY_RELEASE_NF00
  130.  
  131. const FIX_DOM_IF_DETACH = true;
  132. const FIX_DOM_IF_REPEAT = true; // semi-experimental (added in 0.17.0)
  133. const FIX_DOM_IF_TEMPLATE = true;
  134. // const FIX_DOM_REPEAT_TEMPLATE = true; // to be implemented
  135.  
  136. const DEBUG_DBR847 = false;
  137. const FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME = true; // default true. false might be required for future change
  138.  
  139. const FIX_ICON_RENDER = true;
  140. const FIX_GUIDE_ICON = true;
  141. const FIX_ACTIONS_TOOLTIPS = true;
  142.  
  143. const FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS = true; // avoid unnecessary reflows due to cursor moves on the web player.
  144.  
  145. const DISABLE_isLowLatencyLiveStream = false; // TBC
  146.  
  147. const FIX_FlexibleItemSizing = true;
  148. const FIX_ROLLING_NUMBER_UPDATE = true;
  149.  
  150.  
  151. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  152. // example. https://www.youtube.com/channel/UCgPev1KKSCMbnNRsvN83Hag/about
  153. // first tp-yt-paper-dialog: show once the page is loaded.
  154. // second tp-yt-paper-dialog: click "...more"
  155. // third tp-yt-paper-dialog: click "... and 3 more links"
  156. // check with document.querySelectorAll('ytd-popup-container tp-yt-paper-dialog').length
  157. // currently, uniqueId is preassigned by the network resolveCommand.
  158. // so don't modify the source side, just modify the display side (popup display) via handleOpenPopupAction
  159. // other related functions e.g. handleClosePopupCommand_, getAndMaybeCreatePopup_, handleClosePopupAction_, getAndMaybeCreatePopup_
  160.  
  161. // handleOpenPopupAction -> createCacheKey
  162. // handleClosePopupAction_ -> createCacheKey
  163. // handleGetPopupOpenedAction_ -> createCacheKey
  164. // getAndMaybeCreatePopup_ -> createCacheKey
  165. // closePopup -> createCacheKey
  166.  
  167. // yt-close-popup-command -> handleClosePopupCommand_
  168.  
  169. // ensurePopup_ -> getAndMaybeCreatePopup_
  170.  
  171. // yt-close-popup-action -> handleClosePopupAction_
  172. // closePopup -> handleClosePopupAction_
  173. // handleOpenPopupAction -> handleClosePopupAction_
  174. // handleClosePopupCommand_ -> handleClosePopupAction_
  175. // closeSheet -> handleClosePopupAction_("yt-sheet-view-model")
  176.  
  177. // yt-open-popup-action -> handleOpenPopupAction
  178.  
  179.  
  180. // yt-close-popup-action -> handleClosePopupAction_ -> createCacheKey
  181. // yt-close-popup-command -> handleClosePopupCommand_ -> handleClosePopupAction_ -> createCacheKey
  182.  
  183. // Experimental flag "ytpopup_disable_default_html_caching" is disabled by default.
  184. // Not sure enabling it can make GC or not (Yt Components are usually not GC-able)
  185. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  186.  
  187.  
  188. // ----------------------------- Shortkey Keyboard Control -----------------------------
  189. // dependency: FIX_yt_player
  190.  
  191. const FIX_SHORTCUTKEYS = 2; // 0 - no fix; 1 - basic fix; 2 - advanced fix
  192. // [0] no fix - not recommended
  193. // [1] basic fix - just fix the global focus detection variable
  194. // [2] advanced fix - call the shortcut actions directly, auto foucs change, direct control of spacebar behavior, etc
  195. // (note) 0 or 1 if you find conflict with other userscripts/plugin
  196.  
  197. const CHANGE_SPEEDMASTER_SPACEBAR_CONTROL = 0; // 0 - disable; 1 - force true; 2 - force false
  198. const USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER = true; // only for SPEEDMASTER = false & FIX_SHORTCUTKEYS = 2
  199.  
  200. const PROP_OverReInclusion_AVOID = true;
  201. const PROP_OverReInclusion_DEBUGLOG = false;
  202. const PROP_OverReInclusion_LIST = new Set([
  203. 'hostElement72',
  204. 'parentComponent72',
  205. 'localVisibilityObserver_72',
  206. 'cachedProviderNode_72',
  207. '__template72',
  208. '__templatizeOwner72',
  209. '__templateInfo72',
  210. '__dataHost72',
  211. '__CE_shadowRoot72',
  212. 'elements_72',
  213.  
  214. 'ky36',
  215. 'kz62',
  216. 'm822',
  217.  
  218.  
  219.  
  220. // To be reviewed.
  221.  
  222. // chat messages
  223. 'disabled', 'allowedProps',
  224. 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons', 'allowedProps',
  225.  
  226. 'dimension', 'loadTime', 'pendingPaint',
  227.  
  228. 'countdownDurationMs', 'countdownMs', 'lastCountdownTimeMs', 'rafId', 'playerProgressSec', 'detlaSincePausedSecs', 'behaviorActionMap', 'selected', 'maxLikeCount', 'maxReplyCount', 'isMouseOver',
  229.  
  230. 'respectLangDir', 'noEndpoints',
  231.  
  232.  
  233. 'objectURL',
  234. 'buttonOverrides', 'queuedMessages',
  235. 'STEP', 'BLOCK_ON', 'MIN_PROGESS', 'MAX_PROGESS',
  236. 'DISMISSED_CONTENT_KEYSPACE', 'followUpDialogPromise', 'followUpDialogPromiseResolve', 'followUpDialogPromiseReject',
  237. 'hoverJobId', 'JSC$14573_touched',
  238.  
  239.  
  240. // tbc
  241. 'toggleable', 'isConnected',
  242. 'scrollDistance', 'dragging', 'dragMouseStart', 'dragOffsetStart', 'containerWidthDiff',
  243. 'disableDeselectEvent',
  244. 'emojiSize',
  245.  
  246. 'buttonOverride',
  247. 'shouldUseStickyPreferences', 'longPressTimeoutId',
  248.  
  249. // others
  250. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  251. // 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons',
  252. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  253. // 'dimension', 'loadTime', 'pendingPaint',
  254. // 'disabled', 'allowedProps',
  255.  
  256.  
  257. // 'enableMssLazyLoad', 'popupContainerConfig', 'actionRouterNode', 'actionRouterIsRoot', 'actionMap', 'dynamicActionMap',
  258. // 'actionMap',
  259.  
  260. // 'sharedTooltipPosition', 'sharedTooltipAnimationDelay', 'disableEmojiPickerIncrementalLoading', 'useResolveCommand', 'activeRequest', 'popoutWindowCheckIntervalId', 'supportedTooltipTargets', 'closeActionPanelTimerId', 'delayCloseActionPanelTimerId', 'tooltipTimerIds', 'queuedTooltips', 'isPopupConfigReady', 'popoutWindow', 'actionMap',
  261.  
  262. 'clearTimeout',
  263. 'switchTemplateAtRegistration', 'hasUnmounted',
  264. 'switchTemplateAtRegistration', 'stopKeyboardEventPropagation',
  265. 'tangoConfiguration',
  266. 'itemIdToDockDurationMap',
  267. 'actionMap',
  268.  
  269. 'emojiManager', 'inputMethodEditorActive', 'suggestionIndex', 'JSC$10745_lastSuggestionRange',
  270. 'actionMap', 'asyncHandle', 'shouldAnimateIn', 'lastFrameTimestamp', 'scrollClampRaf',
  271. 'scrollRatePixelsPerSecond', 'scrollStartTime', 'scrollStopHandle'
  272.  
  273. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  274. // 'stopKeyboardEventPropagation', 'emojiSize',
  275. // 'switchTemplateAtRegistration', 'hasUnmounted',
  276. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  277. // 'isReusable', 'tangoConfiguration',
  278. // 'itemIdToDockDurationMap', 'bottomAlignMessages', 'actionMap',
  279. // */
  280.  
  281. ]);
  282.  
  283.  
  284. // const CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE = false; // NO USE; TO BE REVIEWED
  285.  
  286. // ----------------------------- Shortkey Keyboard Control -----------------------------
  287.  
  288. /*
  289. window.addEventListener('edm',()=>{
  290. let p = [...this.onerror.errorTokens][0].token; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  291. });
  292.  
  293. window.addEventListener('edn',()=>{
  294. let p = [...this.onerror.errorTokens][0].token+"X"; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  295. });
  296. window.addEventListener('edr',()=>{
  297. let p = '123'; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  298. });
  299. */
  300.  
  301. // only for macOS with Chrome/Firefox 100+
  302. const advanceLogging = typeof AbortSignal !== 'undefined' && typeof (AbortSignal || 0).timeout === 'function' && typeof navigator !== 'undefined' && /\b(Macintosh|Mac\s*OS)\b/i.test((navigator || 0).userAgent || '');
  303.  
  304. const win = this instanceof Window ? this : window;
  305.  
  306. // Create a unique key for the script and check if it is already running
  307. const hkey_script = 'jswylcojvzts';
  308. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  309. win[hkey_script] = true;
  310.  
  311.  
  312.  
  313. const wk = Symbol();
  314.  
  315. // const [setTimeoutX0, clearTimeoutX0] = [setTimeout, clearTimeout];
  316.  
  317. let BY_PASS_KEYBOARD_CONTROL = false;
  318.  
  319.  
  320. // const setImmediate = ((self || 0).jmt || 0).setImmediate;
  321. /** @type {(f: ()=>{})=>{}} */
  322. const nextBrowserTick_ = nextBrowserTick;
  323. if (typeof nextBrowserTick_ !== "function" || (nextBrowserTick_.version || 0) < 2) {
  324. console.log('nextBrowserTick is not found.');
  325. return;
  326. }
  327.  
  328. let p59 = 0;
  329.  
  330. const Promise = (async () => { })().constructor;
  331.  
  332. const PromiseExternal = ((resolve_, reject_) => {
  333. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  334. return class PromiseExternal extends Promise {
  335. constructor(cb = h) {
  336. super(cb);
  337. if (cb === h) {
  338. /** @type {(value: any) => void} */
  339. this.resolve = resolve_;
  340. /** @type {(reason?: any) => void} */
  341. this.reject = reject_;
  342. }
  343. }
  344. };
  345. })();
  346.  
  347. const FinalizationRegistry_ = typeof FinalizationRegistry !== "undefined" ? FinalizationRegistry : class FinalizationRegistry__ {
  348. constructor(callback = undefined) {
  349.  
  350. }
  351. register(target, heldValue, unregisterToken = undefined) {
  352.  
  353. }
  354. unregister(unregisterToken) {
  355.  
  356. }
  357. }
  358.  
  359. let ttpHTML = (s) => {
  360. ttpHTML = s => s;
  361. if (typeof trustedTypes !== 'undefined' && trustedTypes.defaultPolicy === null) {
  362. let s = s => s;
  363. trustedTypes.createPolicy('default', { createHTML: s, createScriptURL: s, createScript: s });
  364. }
  365. return s;
  366. }
  367.  
  368.  
  369. /** @type { typeof HTMLElement } */
  370. const HTMLElement_ = Reflect.getPrototypeOf(HTMLTitleElement);
  371. const nativeAppendE = HTMLElement_.prototype.append;
  372. const nativeRemoveE = HTMLElement_.prototype.remove;
  373. const DocumentFragment_ = DocumentFragment;
  374. const nativeAppendD = DocumentFragment_.prototype.append;
  375. const Node_ = Node;
  376.  
  377. /**
  378. @param {number} x
  379. @param {number} d */
  380. const toFixed2 = (x, d) => {
  381. let t = x.toFixed(d);
  382. let y = `${+t}`;
  383. return y.length > t.length ? t : y;
  384. }
  385.  
  386.  
  387. const isChatRoomURL = location.pathname.startsWith('/live_chat');
  388.  
  389.  
  390. const TRANSLATE_DEBUG = false;
  391.  
  392.  
  393. let xdeadc00 = null; // a deteched node with __domApi
  394. let xlivec00 = null; // a deteched node with __domApi
  395.  
  396. let removeTNodeRM = null;
  397. let removeTNodeBP = false;
  398.  
  399.  
  400. if (Node.isConnectedOverrided === undefined) {
  401. const pdConnected = Object.getOwnPropertyDescriptor(Node.prototype, 'isConnected');
  402. if (pdConnected && pdConnected.get && pdConnected.configurable) {
  403. Node.isConnectedOverrided = null;
  404. const get_ = pdConnected.get;
  405. const get = function () {
  406. const overrided = Node.isConnectedOverrided;
  407. if (typeof overrided === 'boolean') return overrided;
  408. return get_.call(this);
  409. }
  410. Object.defineProperty(Node.prototype, 'isConnected', {
  411. ...pdConnected,
  412. get
  413. });
  414. }
  415. }
  416.  
  417. const _nmSet = new Set();
  418. _nmSet.add = _nmSet.addOriginal || _nmSet.add;
  419. const _nmMap = new Set();
  420. _nmMap.add = _nmMap.addOriginal || _nmMap.add;
  421. const _nmMapV = new Set();
  422. _nmMapV.add = _nmMapV.addOriginal || _nmMapV.add;
  423. if (MEMORY_RELEASE_MAP_SET_REMOVE_NODE && !Set.prototype.addOriginal && !Map.prototype.setOriginal) {
  424. const Node_ = Node;
  425. Set.prototype.addOriginal = Set.prototype.add;
  426. Set.prototype.add = function (n) {
  427. if (n instanceof Node_) {
  428. if (!this[wk]) this[wk] = mWeakRef(this);
  429. _nmSet.add(this[wk]);
  430. }
  431. return this.addOriginal(n);
  432. };
  433. Map.prototype.setOriginal = Map.prototype.set;
  434. Map.prototype.set = function (n, v) {
  435. if (n instanceof Node_) {
  436. if (!this[wk]) this[wk] = mWeakRef(this);
  437. _nmMap.add(this[wk]);
  438. }
  439. if (v instanceof Node_) {
  440. if (!this[wk]) this[wk] = mWeakRef(this);
  441. _nmMapV.add(this[wk]);
  442. }
  443. return this.setOriginal(n, v);
  444. };
  445. }
  446.  
  447. window.showNM00 = () => {
  448. const nmSet = [..._nmSet].map(e => kRef(e)).filter(e => !!e);
  449. const nmMap = [..._nmMap].map(e => kRef(e)).filter(e => !!e);
  450. const nmMapV = [..._nmMapV].map(e => kRef(e)).filter(e => !!e);
  451. return { nmSet, nmMap, nmMapV };
  452. };
  453.  
  454. window.testNM00 = (x) => {
  455. const nmSet = [..._nmSet].map(e => kRef(e)).filter(e => !!e);
  456. const nmMap = [..._nmMap].map(e => kRef(e)).filter(e => !!e);
  457. const nmMapV = [..._nmMapV].map(e => kRef(e)).filter(e => !!e);
  458. for (const s of nmSet) if (s.has(x)) return 1;
  459. for (const m of nmMap) if (m.has(x)) return 2;
  460. for (const m of nmMapV) {
  461. for (const [u, v] of m.entries()) {
  462. if (v === x) return 4;
  463. }
  464. }
  465. return 0;
  466. };
  467.  
  468. let FORCE_NO_REUSEABLE_ELEMENT_POOL_fired = false;
  469.  
  470. const FORCE_NO_REUSEABLE_ELEMENT_POOL_fn = (mainCnt) => {
  471.  
  472. if (FORCE_NO_REUSEABLE_ELEMENT_POOL_fired) return;
  473.  
  474. FORCE_NO_REUSEABLE_ELEMENT_POOL_fired = true;
  475.  
  476. if (typeof mainCnt.createComponent_ !== 'function' || mainCnt.createComponent_.length != 3) {
  477. console.warn('FORCE_NO_REUSEABLE_ELEMENT_POOL_fn failed.')
  478. return;
  479. }
  480.  
  481. const mapGet = Map.prototype.get;
  482. const setHas = Set.prototype.has;
  483.  
  484. /** @type {Map | null} */
  485. let qcMap = null;
  486.  
  487. Set.prototype.has = function (a) {
  488. if (a === 'dummy-4718') return false; // false to allow re-use?
  489. return setHas.call(this, a);
  490. }
  491.  
  492. Map.prototype.get = function (a) {
  493. if (a === 'dummy-4718') qcMap = this;
  494. return mapGet.call(this, a);
  495. };
  496. let r;
  497. try {
  498. r = mainCnt.createComponent_('dummy-4718', {}, true);
  499. } catch (e) {
  500.  
  501. }
  502.  
  503. Map.prototype.get = mapGet;
  504. Set.prototype.has = setHas;
  505.  
  506. if (r && (r.nodeName || '').toLowerCase() === 'dummy-4718') {
  507.  
  508.  
  509. // clearInterval(ckId);
  510. // ckId = 0;
  511.  
  512. if (qcMap !== null && qcMap instanceof Map) {
  513.  
  514. console.log('[yt-js-engine-tamer] qcMap', qcMap);
  515. qcMap.__qcMap8781__ = true;
  516.  
  517. const setArrayC = (c) => {
  518. if (c instanceof Array) {
  519. c.length = 0;
  520. c.push = function () { };
  521. c.pop = function () { };
  522. c.shift = function () { };
  523. c.unshift = function () { };
  524. c.splice = function () { };
  525. c.sort = function () { };
  526. c.reverse = function () { };
  527. }
  528. }
  529.  
  530. const cleaning = function (m) {
  531. m.forEach(setArrayC);
  532. m.clear();
  533. }
  534.  
  535. qcMap.set = function (b, c) {
  536. if (!this.__qcMap8781__) return Map.prototype.set.call(this, b, c);
  537.  
  538. setArrayC(c);
  539.  
  540. // console.log('qcMap.set', b, c);
  541.  
  542. if (this.size > 0) {
  543. // play safe
  544.  
  545. console.log('[yt-js-engine-tamer] qcMap', 'clear 01')
  546. cleaning(this);
  547. }
  548.  
  549. }
  550. qcMap.get = function (b) {
  551. if (!this.__qcMap8781__) return Map.prototype.get.call(this, b);
  552.  
  553. // console.log('qcMap.get', b);
  554.  
  555. if (this.size > 0) {
  556. // play safe
  557.  
  558. console.log('[yt-js-engine-tamer] qcMap', 'clear 02')
  559. cleaning(this);
  560. }
  561.  
  562. }
  563.  
  564.  
  565. if (qcMap.size > 0) {
  566.  
  567. console.log('[yt-js-engine-tamer] qcMap', 'clear 03')
  568. cleaning(qcMap);
  569. }
  570.  
  571. }
  572.  
  573. }
  574.  
  575. r = null;
  576. qcMap = null;
  577.  
  578. }
  579.  
  580.  
  581. const dispatchYtEvent = function (a, b, c, d) {
  582. d || (d = {
  583. bubbles: !0,
  584. cancelable: !1,
  585. composed: !0
  586. });
  587. c !== null && c !== void 0 && (d.detail = c);
  588. b = new CustomEvent(b, d);
  589. a.dispatchEvent(b);
  590. return b
  591. };
  592.  
  593. if (DISABLE_isLowLatencyLiveStream) {
  594. const sm = Symbol();
  595. const f = () => {
  596. try {
  597. const videoDetails = ytInitialPlayerResponse.videoDetails;
  598. if (videoDetails && videoDetails.isLowLatencyLiveStream) {
  599. videoDetails.isLowLatencyLiveStream = false;
  600. }
  601. if (videoDetails && videoDetails.latencyClass === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_LOW') {
  602. videoDetails.latencyClass = 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_NORMAL';
  603. }
  604. if (videoDetails && videoDetails.latencyClass === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_ULTRA_LOW') {
  605. videoDetails.latencyClass = 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_NORMAL';
  606. }
  607. } catch (e) { }
  608. }
  609. Object.defineProperty(Object.prototype, 'isLowLatencyLiveStream', {
  610. get() {
  611. const v = this[sm];
  612. if (typeof v === 'undefined') return v;
  613. f();
  614. return v;
  615. },
  616. set(nv) {
  617. f();
  618. if (nv === true) nv = false;
  619. this[sm] = nv;
  620. },
  621. enumerable: false,
  622. configurable: true
  623. });
  624.  
  625. const sm3 = Symbol();
  626. Object.defineProperty(Object.prototype, 'latencyClass', {
  627. get() {
  628. const v = this[sm3];
  629. if (typeof v === 'undefined') return v;
  630. f();
  631. return v;
  632. },
  633. set(nv) {
  634. f();
  635. if (nv === 'ULTRALOW' || nv === 'LOW') {
  636. nv = 'NORMAL';
  637. } else if (nv === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_LOW' || nv === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_ULTRA_LOW') {
  638. nv = 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_NORMAL';
  639. }
  640. this[sm3] = nv;
  641. },
  642. enumerable: false,
  643. configurable: true
  644. });
  645.  
  646. }
  647.  
  648. class PlainHTMLElement extends HTMLTitleElement {
  649.  
  650. }
  651.  
  652. const removeShady = function (shady) {
  653. if (!shady || typeof shady !== 'object') return;
  654. const props = [...Object.getOwnPropertyNames(shady), ...Object.getOwnPropertySymbols(shady)];
  655. for (const prop of props) {
  656. const node = shady[prop];
  657. if (typeof (node || 0) !== 'object') continue;
  658. if (node.nodeType >= 1 && node.isConnected === false) _removedElements.addNode(node);
  659. }
  660. }
  661.  
  662. const _removedElements = new Set();
  663. _removedElements.add = _removedElements.addOriginal || _removedElements.add;
  664. _removedElements.addNode_ = MEMORY_RELEASE_NF00 ? function (node) {
  665. if (!node || node.__keepInstance038__ || node.t792 || node instanceof HTMLTitleElement || node.nodeName === 'defs' || node.nodeName === 'TITLE') return;
  666. if (node && node.nodeType >= 1 && node.nodeType !== 9) {
  667. if (!node[wk]) node[wk] = mWeakRef(node);
  668. return this.add(node[wk]);
  669. }
  670. } : () => { };
  671.  
  672. _removedElements.addNode = MEMORY_RELEASE_NF00 ? (node) => {
  673. if (!node || node.__keepInstance038__ || node.t792 || node instanceof HTMLTitleElement || node.nodeName === 'defs' || node.nodeName === 'TITLE') return;
  674. if (node && node.nodeType >= 1 && node.nodeType !== 9) {
  675. const rootNode = node.getRootNode();
  676. if (rootNode && rootNode !== node) {
  677. if (rootNode.nodeType >= 1 && rootNode.nodeType !== 9) _removedElements.addNode_(rootNode);
  678. }
  679. _removedElements.addNode_(node);
  680. }
  681. } : () => { };
  682.  
  683. const _emptyElement = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  684. const _emptyTipsElement = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  685. const _emptyVisibilityElement = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  686.  
  687. const nf00 = new FinalizationRegistry_((x) => {
  688. if (MEMORY_RELEASE_NF00_SHOW_MESSAGE) console.log(`NF00: node[${x}] fully removed`);
  689. });
  690. let ud00 = 0;
  691. const ng00 = new Set();
  692. nf00.registerNode = function (node) {
  693. if (node && node.nodeType >= 1) {
  694. if (!node.t792) {
  695. node.t792 = (ud00 = (ud00 & 1073741823) + 1);
  696. const x = `${node.nodeName.toLowerCase()}#${node.t792}`;
  697. this.register(node, x);
  698. if (MEMORY_RELEASE_NF00_SHOW_MESSAGE) console.log(`NF00: try remove node[${x}]`);
  699. ng00.add(mWeakRef(node));
  700. }
  701. }
  702. }
  703. window.showNg00 = () => {
  704. const ng01 = new Set();
  705. ng01.add = ng01.addOriginal || ng01.add;
  706. for (const e of ng00) {
  707. const f = kRef(e);
  708. if (!f) continue;
  709. ng01.add(f);
  710. }
  711. const ng02 = [...ng01];
  712. ng01.clear();
  713. console.log(ng02);
  714. window.showNg01 = [...ng02];
  715. }
  716. window.showTemplates00 = () => {
  717. const result = {};
  718. const elements = document.querySelectorAll('*');
  719. for (const element of elements) {
  720. const tag = element.nodeName.toLocaleLowerCase();
  721. const r = result[tag] || [];
  722. const cnt = insp(element);
  723. if (cnt !== element) {
  724. if (cnt.templateInfo) {
  725. r.push(['cnt0', cnt.templateInfo, element]);
  726. }
  727. if (element._templateInfo) {
  728. r.push(['cnt1', cnt._templateInfo, element]);
  729. }
  730. if (element.__templateInfo) {
  731. r.push(['cnt2', cnt.__templateInfo, element]);
  732. }
  733. }
  734. if (element.templateInfo) {
  735. r.push(['elm0', element.templateInfo, element]);
  736. }
  737. if (element._templateInfo) {
  738. r.push(['elm1', element._templateInfo, element]);
  739. }
  740. if (element.__templateInfo) {
  741. r.push(['elm2', element.__templateInfo, element]);
  742. }
  743. if (r.length >= 1) result[tag] = r;
  744. }
  745. const strCmp = (a, b) => {
  746. if (a === b) return 0;
  747. let u = [a, b].sort();
  748. return u[0] === a ? -1 : 1;
  749. }
  750. const counting1 = Object.entries(result).map(e => [e[0], [...new Set(e[1].map(t => t[0]))].join('|')]).sort((a, b) => {
  751. return strCmp(`${a[1]}.${a[0]}`, `${b[1]}.${b[0]}`);
  752. });
  753.  
  754. const counting2 = Object.entries(result).map(e => [e[0], [...new Set(e[1].map(t => t[1]))]]);
  755.  
  756. const counting3 = Object.entries(result).map(e => {
  757. const a = [...new Set(e[1].map(t => t[1]))];
  758. const b = [...new Set(a.map(e => e.nodeList || e))];
  759.  
  760. const r = [e[0], b];
  761. return r;
  762. });
  763.  
  764. return {result, counting1, counting2, counting3};
  765. };
  766.  
  767. window.showFrag00 = function(){
  768.  
  769. const result = {};
  770. const elements = document.querySelectorAll('*');
  771. for (const element of elements) {
  772. const tag = element.nodeName.toLocaleLowerCase();
  773. const r = result[tag] || [];
  774. const cnt = insp(element);
  775. if (cnt !== element) {
  776. if (cnt.templateInfo) {
  777. r.push(['cnt0', cnt.templateInfo, element]);
  778. }
  779. if (element._templateInfo) {
  780. r.push(['cnt1', cnt._templateInfo, element]);
  781. }
  782. if (element.__templateInfo) {
  783. r.push(['cnt2', cnt.__templateInfo, element]);
  784. }
  785. }
  786. if (element.templateInfo) {
  787. r.push(['elm0', element.templateInfo, element]);
  788. }
  789. if (element._templateInfo) {
  790. r.push(['elm1', element._templateInfo, element]);
  791. }
  792. if (element.__templateInfo) {
  793. r.push(['elm2', element.__templateInfo, element]);
  794. }
  795. if (r.length >= 1) result[tag] = r;
  796. }
  797. return result;
  798.  
  799. }
  800.  
  801. if (MEMORY_RELEASE_NF00) {
  802.  
  803. const __removedElements = new Set();
  804. __removedElements.add = __removedElements.addOriginal || __removedElements.add;
  805.  
  806. setInterval(() => {
  807. const nodesSet = new Set();
  808. nodesSet.add = nodesSet.addOriginal || nodesSet.add;
  809.  
  810. for (const nodeWr of __removedElements) {
  811. __removedElements.delete(nodeWr);
  812. const node = kRef(nodeWr);
  813. if (node && node.nodeType >= 1 && node.isConnected === false) {
  814. const rootNode = node.getRootNode();
  815. if (rootNode && rootNode.nodeType >= 1 && rootNode.nodeType !== 9 && rootNode.isConnected === true) {
  816. // do nothing
  817. } else {
  818. nodesSet.add(node);
  819. if (node.querySelectorAll) {
  820. for (const p of node.querySelectorAll('*')) {
  821. nodesSet.add(p);
  822. }
  823. }
  824. }
  825. }
  826. }
  827. for (const nodeWr of _removedElements) {
  828. _removedElements.delete(nodeWr);
  829. const node = kRef(nodeWr);
  830. if (node && node.isConnected === false) {
  831. __removedElements.add(nodeWr);
  832. }
  833. }
  834.  
  835. if(nodesSet.size === 0) return;
  836.  
  837. const nmSet = [..._nmSet].map(e => kRef(e)).filter(e => !!e);
  838. const nmMap = [..._nmMap].map(e => kRef(e)).filter(e => !!e);
  839. const nmMapV = [..._nmMapV].map(e => kRef(e)).filter(e => !!e);
  840.  
  841. for (const node of nodesSet) {
  842. if (node === _emptyElement || node.__keepInstance038__ || node.t792) continue;
  843. const hasToolTips = !!((insp(node).$ || 0).tooltip);
  844.  
  845. if (node && node.__shady_getRootNode) {
  846. const k = node.__shady_getRootNode();
  847. if (k && k.__keepInstance038__) k.__keepInstance038__ = false;
  848. if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k);
  849. }
  850. if (node && node.getRootNode) {
  851. const k = node.getRootNode();
  852. if (k && k.__keepInstance038__) k.__keepInstance038__ = false;
  853. if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k);
  854. }
  855.  
  856. if (node.__instances) {
  857. for (const k of node.__instances) {
  858. if (k && k.__keepInstance038__) k.__keepInstance038__ = false;
  859. if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k);
  860. }
  861. // node.__instances.length = 0;
  862. }
  863. if (node && node.nodeType === 1) {
  864. if (typeof insp(node).__teardownInstance === 'function') {
  865. try {
  866. insp(node).__teardownInstance();
  867. } catch (e) { }
  868. } else if (typeof node.__teardownInstance === 'function') {
  869. try {
  870. node.__teardownInstance();
  871. } catch (e) { }
  872. }
  873. }
  874. if (node && node.nodeType === 1 && node.__detachAndRemoveInstance && (node.__instances || 0).length >= 1) {
  875. for (let i = node.__instances.length - 1; i >= 0; i--) {
  876. node.__detachAndRemoveInstance(i)
  877. }
  878. }
  879.  
  880. if (node && node.nodeType === 1 && node.is === void 0) {
  881. if (typeof insp(node).dispose === 'function') {
  882. insp(node).dispose();
  883. } else if (typeof node.dispose === 'function') {
  884. node.dispose();
  885. }
  886. }
  887.  
  888. if (node && node.nodeType === 1) {
  889. if (typeof insp(node).unobserve_ === 'function') {
  890. insp(node).unobserve_();
  891. } else if (typeof node.unobserve_ === 'function') {
  892. node.unobserve_();
  893. }
  894. }
  895.  
  896. if (node) {
  897. if (typeof insp(node).unobserveNodes === 'function') {
  898. insp(node).unobserveNodes();
  899. } else if (typeof node.unobserveNodes === 'function') {
  900. node.unobserveNodes();
  901. }
  902. }
  903.  
  904. // if (node && node.nodeType === 1) {
  905. // const cnt = insp(node);
  906. // const paths = cnt.__dataLinkedPaths;
  907. // if (paths && paths.length >= 1 && typeof cnt.unlinkPaths === 'function') {
  908. // for (let k in paths) {
  909. // cnt.unlinkPaths(k);
  910. // }
  911. // }
  912. // }
  913.  
  914. const visibilityMonitorKeys = insp(node).visibilityMonitorKeys || node.visibilityMonitorKeys;
  915. if (visibilityMonitorKeys) {
  916. for (const entry of visibilityMonitorKeys) {
  917. if (entry.element) { entry.element = null }
  918. }
  919. visibilityMonitorKeys.length = 0;
  920. }
  921. const __instances = node.__instances;
  922. if (__instances) {
  923. for (const k of __instances) {
  924. if (k && k.__keepInstance038__) k.__keepInstance038__ = false;
  925. if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k);
  926. }
  927. __instances.length = 0;
  928. }
  929. const sp = node.__shady_parentNode;
  930. if (sp && sp.nodeType >= 1 && sp.isConnected === false) _removedElements.addNode(sp);
  931. FULLY_REMOVE_ALL_EVENT_LISTENERS && node.removeAllEventListener001();
  932. if (node && node.remove) node.remove();
  933.  
  934. /*
  935. if (node._templateInfo && node._templateInfo.content) {
  936. const templateInfoContent = node._templateInfo.content;
  937. if (templateInfoContent.nodeType >= 1 && templateInfoContent.isConnected === false) {
  938. _removedElements.addNode(templateInfoContent);
  939. }
  940. try{
  941. node._templateInfo.content = null;
  942. }catch(e){}
  943. }
  944. */
  945. if (node.__domApi) {
  946. node.__domApi = null;
  947. }
  948. const __shady = node.__shady;
  949. if (__shady) {
  950. node.__shady = null;
  951. removeShady(__shady);
  952. }
  953.  
  954.  
  955. const ceRoot = node.__CE_shadowRoot;
  956. if (ceRoot) {
  957. node.__CE_shadowRoot = null;
  958. if (ceRoot.nodeType >= 1 && ceRoot.isConnected === false) {
  959. _removedElements.addNode(ceRoot);
  960. }
  961.  
  962. }
  963.  
  964. // xTeardownTemplateInfo
  965. const snChildNodes = node.__shady_native_childNodes;
  966. if (snChildNodes.length > 0) {
  967. for (const node of snChildNodes) {
  968. if (node && node.nodeType >= 1 && node.isConnected === false) {
  969. _removedElements.addNode(node);
  970. }
  971. }
  972. snChildNodes.length = 0;
  973. }
  974. node.__shady_native_childNodes = null;
  975.  
  976.  
  977. const __templateInfo = node.__templateInfo;
  978. if (__templateInfo) {
  979. node.__templateInfo = null;
  980. // xTeardownTemplateInfo(__templateInfo);
  981. }
  982.  
  983. if (hasToolTips && insp(node).$) {
  984. insp(node).$.tooltip = _emptyTipsElement;
  985. }
  986.  
  987. if (node && node.nodeType >= 1) {
  988. const pd = Object.getOwnPropertyDescriptor(node, 'visibilityMonitorKeys');
  989. if (pd && pd.value && pd.value.length >= 1) {
  990. const arr = pd.value;
  991. for (let i = 0; i < arr.length; i++) {
  992. arr[i].element = _emptyVisibilityElement;
  993. arr[i] = null;
  994. }
  995. }
  996. }
  997.  
  998. if (node.__dataHost) {
  999. try {
  1000. delete node.__dataHost
  1001. } catch (e) { }
  1002. try {
  1003. node.__dataHost = null;
  1004. } catch (e) { }
  1005. }
  1006.  
  1007. if (node.root) {
  1008. try {
  1009. delete node.root
  1010. } catch (e) { }
  1011. try {
  1012. node.root = null;
  1013. } catch (e) { }
  1014. }
  1015.  
  1016. if (node.children && node.children.splice) {
  1017. try {
  1018. delete node.children
  1019. } catch (e) { }
  1020. try {
  1021. node.children = null;
  1022. } catch (e) { }
  1023. }
  1024.  
  1025. if (node.__shady && typeof node.__shady === 'object') {
  1026. try {
  1027. node.__shady = null;
  1028. } catch (e) { }
  1029. }
  1030.  
  1031. if (node.nodeType === 1) Reflect.setPrototypeOf(node, PlainHTMLElement.prototype);
  1032.  
  1033. for (const prop of Object.getOwnPropertyNames(node)) {
  1034. if (prop === 'host' && typeof (node.host || 0) === 'object') {
  1035. if (node.nodeType === 11) {
  1036. const nodeHost = node.host;
  1037. if (nodeHost && nodeHost.nodeType >= 1) {
  1038. node.host = _emptyElement;
  1039. if (nodeHost.isConnected === false && nodeHost !== _emptyElement) {
  1040. _removedElements.addNode(nodeHost);
  1041. }
  1042. } else {
  1043. node.host = null;
  1044. }
  1045. } else {
  1046. node.host = null;
  1047. }
  1048. continue;
  1049. }
  1050. const pd = Object.getOwnPropertyDescriptor(node, prop);
  1051. if (pd.value) {
  1052. const v = pd.value;
  1053. if (typeof (v || 0) === 'object') node[prop] = null;
  1054. else if (typeof (v || 0) === 'function') delete node[prop];
  1055. }
  1056. }
  1057.  
  1058. for (const prop of Object.getOwnPropertySymbols(node)) {
  1059. const v = node[prop];
  1060. if (typeof (v || 0) === 'object' && !v.deref) node[prop] = null;
  1061. }
  1062.  
  1063. if (node.__shady_native_childNodes) {
  1064. node.__shady_native_childNodes = _emptyElement.childNodes;
  1065. }
  1066. if (node.__shady_children) {
  1067. node.__shady_children = _emptyElement.children;
  1068. }
  1069.  
  1070. for (const s of nmSet) s.delete(node);
  1071. for (const m of nmMap) m.delete(node);
  1072.  
  1073. mightTeardownShadyDomWrap(node);
  1074.  
  1075. nf00.registerNode(node);
  1076.  
  1077.  
  1078.  
  1079. // console.log(1883001, node)
  1080. // console.log(3772001, node, node.countEvent767())
  1081. }
  1082.  
  1083. nodesSet.clear();
  1084.  
  1085. }, 400);
  1086.  
  1087. }
  1088.  
  1089.  
  1090. if (FULLY_REMOVE_ALL_EVENT_LISTENERS && !EventTarget.prototype.addEventListener828 && !EventTarget.prototype.removeAllEventListener001) {
  1091. const handlerMap = new WeakMap();
  1092. EventTarget.prototype.addEventListener828 = EventTarget.prototype.addEventListener;
  1093. EventTarget.prototype.addEventListener = function (type, handler, option = void 0) {
  1094. let hds = handlerMap.get(this);
  1095. if (!hds) handlerMap.set(this, (hds = new Set()));
  1096. hds.add([type, handler, option]);
  1097. return this.addEventListener828(type, handler, option);
  1098. }
  1099. EventTarget.prototype.removeEventListener828 = EventTarget.prototype.removeEventListener;
  1100. EventTarget.prototype.removeEventListener = function (type, handler, option = void 0) {
  1101. let hds = handlerMap.get(this);
  1102. if (hds) {
  1103. for (const entry of hds) {
  1104. if (entry[0] === type && entry[1] === handler && entry[2] === option) {
  1105. hds.delete(entry);
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. return this.removeEventListener828(type, handler, option);
  1111. }
  1112. EventTarget.prototype.countEvent767 = function(){
  1113. return handlerMap.get(this);
  1114. }
  1115. EventTarget.prototype.removeAllEventListener001 = function(){
  1116. let hds = handlerMap.get(this);
  1117. if (hds) {
  1118. handlerMap.delete(this);
  1119. for (const [type, handler, option] of hds) {
  1120. this.removeEventListener828(type, handler, option);
  1121. }
  1122. hds.clear();
  1123. }
  1124. }
  1125. }
  1126.  
  1127. const globalSetup = (key, setup)=>{
  1128. let symb = Symbol();
  1129. Object.defineProperty(Object.prototype, key, {
  1130. get() {
  1131. return this[symb];
  1132. },
  1133. set(nv) {
  1134. if (typeof nv !== 'function') {
  1135. this[symb] = nv;
  1136. return true;
  1137. }
  1138. if (!(symb in this)) {
  1139. setup(this);
  1140. }
  1141. this[symb] = nv;
  1142. return true;
  1143. },
  1144. configurable: true,
  1145. enumerable: false
  1146. });
  1147. }
  1148.  
  1149. const toActualNode = (e) => {
  1150. return e && e.getNode592177 ? e.getNode592177() : e;
  1151. }
  1152.  
  1153. const removeAllChildNodes = (o)=>{
  1154. if ((o instanceof Node) && o.nodeType >= 1) {
  1155. let t, q = null;
  1156. while ((t = o.firstChild) && t !== q) {
  1157. try {
  1158. t.__keepInstance038__ = false;
  1159. t.remove();
  1160. _removedElements.addNode(t);
  1161. q = t;
  1162. } catch (e) { }
  1163. }
  1164. try {
  1165. o.__keepInstance038__ = false;
  1166. o.remove();
  1167. _removedElements.addNode(o);
  1168. } catch (e) { }
  1169. }
  1170. }
  1171.  
  1172. const stampedNodes = new Map(); /* !!!!!! CAUTION FOR MEMORY LEAKAGE !!!!!!! */
  1173. stampedNodes.set = stampedNodes.setOriginal || stampedNodes.set;
  1174. const stampedFragment = new Map(); /* !!!!!! CAUTION FOR MEMORY LEAKAGE !!!!!!! */
  1175. stampedFragment.set = stampedFragment.setOriginal || stampedFragment.set;
  1176.  
  1177. if (FIX_TEMPLATE_BINDING) {
  1178. const templateMap = new Map(); /* !!!!!! CAUTION FOR MEMORY LEAKAGE !!!!!!! */
  1179. templateMap.set = templateMap.setOriginal || templateMap.set;
  1180. // const parsedTemplate = new Map();
  1181.  
  1182.  
  1183. const it0 = Date.now() - 80000000000;
  1184. const genId = () => `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${(Date.now() - it0).toString(36)}`;
  1185.  
  1186.  
  1187. /*
  1188.  
  1189. M.prototype._bindTemplate = function(N, R) {
  1190. var X = this.constructor._parseTemplate(N)
  1191. , A = this.__preBoundTemplateInfo == X;
  1192. if (!A)
  1193. for (var l in X.propertyEffects)
  1194. this._createPropertyAccessor(l);
  1195. R ? (X = Object.create(X),
  1196. X.wasPreBound = A,
  1197. this.__templateInfo ? (N = N._parentTemplateInfo || this.__templateInfo,
  1198. R = N.lastChild,
  1199. X.parent = N,
  1200. N.lastChild = X,
  1201. (X.previousSibling = R) ? R.nextSibling = X : N.firstChild = X) : this.__templateInfo = X) : this.__preBoundTemplateInfo = X;
  1202. return X
  1203. }
  1204. ;
  1205. */
  1206.  
  1207. /*
  1208. ** this.constructor._parseTemplate **
  1209. d._parseTemplate = function(N, R) {
  1210. if (!N._templateInfo) {
  1211. var X = N._templateInfo = {};
  1212. X.nodeInfoList = [];
  1213. X.nestedTemplate = !!R;
  1214. X.stripWhiteSpace = R && R.stripWhiteSpace || N.hasAttribute && N.hasAttribute("strip-whitespace");
  1215. this._parseTemplateContent(N, X, {
  1216. parent: null
  1217. })
  1218. }
  1219. return N._templateInfo
  1220. }
  1221.  
  1222. */
  1223.  
  1224. // let initied1 = false;
  1225. // let _parseTemplateByPass = false;
  1226. const setup1 = (qxx) => {
  1227. // if(initied1) return;
  1228. // initied1 = true;
  1229. const proto = qxx;
  1230. const constructor = proto.constructor;
  1231. const _bindTemplate = proto._bindTemplate;
  1232. // console.log(12883, proto, constructor)
  1233.  
  1234.  
  1235. const _parseTemplate = constructor._parseTemplate;
  1236. if (typeof _parseTemplate === 'function' && _parseTemplate.length === 2 && !constructor._parseTemplate322) {
  1237.  
  1238. FIX_TEMPLATE_BINDING_SHOW_MESSAGE && console.log('Hack00: _parseTemplate', _parseTemplate);
  1239. constructor._parseTemplate322 = _parseTemplate;
  1240. const parsedResults = new WeakMap();
  1241.  
  1242. const _templateInfoPd = {
  1243. get() {
  1244. if (!this || !this[wk]) return undefined;
  1245. const r = parsedResults.get(this[wk]);
  1246. return r;
  1247. },
  1248. set(nv) {
  1249. delete this._templateInfo;
  1250. this._templateInfo = nv;
  1251. console.warn('_templateInfoPd set');
  1252. return true;
  1253. },
  1254. enumerable: true,
  1255. configurable: true
  1256. };
  1257. constructor._parseTemplate = function (N, R) {
  1258. if (!N) return _parseTemplate.call(this, N, R);
  1259. if (!N[wk]) N[wk] = mWeakRef(N);
  1260. let r = parsedResults.get(N[wk]);
  1261. if (r) return r;
  1262. r = _parseTemplate.call(this, N, R);
  1263. if (r && !parsedResults.has(N[wk])) {
  1264. parsedResults.set(N[wk], r);
  1265. r.iAm68 = '_templateInfo';
  1266. N.iHave68 = '_templateInfo';
  1267. if (N._templateInfo && N._templateInfo === r) {
  1268. delete N._templateInfo;
  1269. if (!N._templateInfo) {
  1270. Object.defineProperty(N, '_templateInfo', _templateInfoPd);
  1271. }
  1272. }
  1273. }
  1274. return r;
  1275. }
  1276. }
  1277. if (typeof _bindTemplate === 'function' && _bindTemplate.length === 2 && !proto._bindTemplate322) {
  1278.  
  1279. FIX_TEMPLATE_BINDING_SHOW_MESSAGE && console.log('Hack00: _bindTemplate', _bindTemplate);
  1280. proto._bindTemplate322 = _bindTemplate;
  1281. proto._bindTemplate = function (N, R) {
  1282. // R = boolean true or undefined
  1283. // N = template elemenet
  1284. let M = N;
  1285. if (typeof (N || 0) === 'object' && N instanceof HTMLTemplateElement && (N.content || 0).nodeType === 11) {
  1286. let componentIs = '';
  1287. try {
  1288. componentIs = this ? this.is : '';
  1289. } catch (e) { }
  1290. if (typeof (componentIs || 0) === 'string') {
  1291. if (!templateMap.has(componentIs)) {
  1292. templateMap.set(componentIs, N);
  1293. // const parser = this.constructor;
  1294. // console.log(3882, parser._parseTemplate)
  1295. /*
  1296. if (parser._parseTemplate && !parser._parseTemplate477 && parser._parseTemplate.length === 2) {
  1297. parser._parseTemplate477 = parser._parseTemplate;
  1298. const _parseTemplate477 = parser._parseTemplate477;
  1299. parser._parseTemplate = function (N, R) {
  1300. if (!_parseTemplateByPass && N && N[wk]) {
  1301. const u = parsedTemplate.get(N[wk]);
  1302. if (u) {
  1303. console.log(1838, u)
  1304. return u;
  1305. }
  1306. }
  1307. return _parseTemplate477.call(this, N, R);
  1308. };
  1309. }
  1310. if (parser._parseTemplate && parser._parseTemplate477) {
  1311. if (N && !N[wk]) N[wk] = mWeakRef(N);
  1312. if (!parsedTemplate.has(N[wk])) {
  1313. _parseTemplateByPass = true;
  1314. parsedTemplate.set(N[wk], parser._parseTemplate477(N));
  1315. _parseTemplateByPass = false;
  1316. }
  1317. }
  1318. */
  1319. } else {
  1320. M = templateMap.get(componentIs);
  1321. }
  1322. }
  1323. }
  1324. let r_ = null;
  1325. // Promise.resolve(N).then((N) => {
  1326. // console.log(3488,N.templateInfo, N.templateInfo === r_);
  1327. // })
  1328. const r = _bindTemplate.call(this, M, R);
  1329. r_ = r;
  1330. return r;
  1331. }
  1332. }
  1333.  
  1334. const _runEffectsForTemplate = proto._runEffectsForTemplate;
  1335. const gxx = (window.gxxC572 || (window.gxxC572 = new Set()));
  1336. if (typeof _runEffectsForTemplate === 'function' && _runEffectsForTemplate.length === 4 && !proto._runEffectsForTemplate322) {
  1337. proto._runEffectsForTemplate322 = _runEffectsForTemplate;
  1338.  
  1339. // note: fastDomIf does not work well with runEffects ...
  1340. // so no runEffects actaully?
  1341. const runner = (Tw, Nw, Rw, Xw, Aw) => {
  1342.  
  1343. try {
  1344.  
  1345.  
  1346. // console.log(988003)
  1347. const T = kRef(Tw); // this
  1348. const N = kRef(Nw); // __templateInfo
  1349. if (!T || !N) return;
  1350.  
  1351. // console.log(988004)
  1352. const R = kRef(Rw); // __data
  1353. const X = kRef(Xw); // temp Data ?
  1354. const A = kRef(Aw); // boolean ?
  1355. if (typeof (X || 0) === 'object') gxx.delete(X);
  1356. if (typeof (A || 0) === 'object') gxx.delete(A);
  1357.  
  1358. // console.log(988005)
  1359. const nodeList_ = N.nodeList;
  1360.  
  1361. // console.log(988006, nodeList_)
  1362. const nodeList = nodeList_ ? nodeList_.map(e => toActualNode(e)) : nodeList_;
  1363.  
  1364. // console.log(988007, nodeList)
  1365.  
  1366. const Nx = {
  1367. propertyEffects: N.propertyEffects,
  1368. nodeList: nodeList,
  1369. firstChild: kRef(N.firstChild)
  1370. };
  1371.  
  1372. // if (kRef(N.firstChild)) {
  1373. // console.log(977001, Nx)
  1374. // }
  1375.  
  1376. // console.log(988009, Nx, R, X, A)
  1377.  
  1378.  
  1379. {
  1380.  
  1381.  
  1382. const o = Nx;
  1383. const { propertyEffects, nodeList, firstChild } = o;
  1384. if (propertyEffects && nodeList && nodeList.length >= 0) {
  1385. for (const [effectKey, propertyEffectArr] of Object.entries(propertyEffects)) {
  1386. for (let i = propertyEffectArr.length - 1; i >= 0; i--) {
  1387. const propertyEffect = propertyEffectArr[i];
  1388. const info = (propertyEffect || 0).info;
  1389. if (info && typeof info.index === 'number' && !nodeList[info.index]) {
  1390. propertyEffectArr.splice(i, 1);
  1391. }
  1392. }
  1393. }
  1394. }
  1395.  
  1396. }
  1397.  
  1398.  
  1399. // console.log({T, Nx, R, X , A })
  1400.  
  1401. // console.log(1737001, T)
  1402. // console.log(1737002, Nx)
  1403.  
  1404. // console.log(1737003, R)
  1405. // console.log(1737004, X)
  1406. // console.log(1737005, A)
  1407.  
  1408. const hostElement = T.hostElement;
  1409. const pChildren = (hostElement instanceof Node) ? [...hostElement.childNodes] : null;
  1410.  
  1411. _runEffectsForTemplate.call(T, Nx, R, X, A);
  1412.  
  1413. (pChildren || 0).length >= 1 && Promise.resolve(pChildren).then((pChildren) => {
  1414. for (const node of pChildren) {
  1415. if (node.isConnected === false) {
  1416. let tNode = node;
  1417. let pNode;
  1418. while ((pNode = tNode.parentNode) && pNode.nodeType >= 1) {
  1419. tNode = pNode;
  1420. }
  1421. _removedElements.addNode(tNode);
  1422. }
  1423. }
  1424. pChildren.length = 0;
  1425. pChildren = null;
  1426. });
  1427.  
  1428.  
  1429. } catch (err) {
  1430. debugger;
  1431. console.warn(err);
  1432. }
  1433.  
  1434. };
  1435.  
  1436.  
  1437. proto._runEffectsForTemplate = function (N, R, X, A) {
  1438.  
  1439. // console.log(988001)
  1440. /*
  1441. N {wasPreBound: true, nodeList: Array(23)}
  1442.  
  1443. R {showInput: false, narrow: false, menuStrings: {…}, pageDarkTheme: true, theater: false, …}
  1444. X {showInput: undefined, narrow: undefined, menuStrings: undefined, pageDarkTheme: undefined, theater: undefined, …}
  1445. A false
  1446. */
  1447.  
  1448. const Nw = (!N || typeof N !== 'object') ? N : (N[wk] || (N[wk] = mWeakRef(N))); // __templateInfo
  1449. const Xw = (!X || typeof X !== 'object') ? X : (X[wk] || (X[wk] = mWeakRef(X)));
  1450.  
  1451. const Rw = (!R || typeof R !== 'object') ? R : (R[wk] || (R[wk] = mWeakRef(R))); // __data
  1452. const Aw = (!A || typeof A !== 'object') ? A : (A[wk] || (A[wk] = mWeakRef(A)));
  1453.  
  1454. if (typeof (X || 0) === 'object') gxx.add(X);
  1455. if (typeof (A || 0) === 'object') gxx.add(A);
  1456.  
  1457. const Tw = (!this || typeof this !== 'object') ? this : (this[wk] || (this[wk] = mWeakRef(this)));
  1458.  
  1459.  
  1460. if (N.runEffects) {
  1461. N.runEffects(() => {
  1462. runner(Tw, Nw, Rw, Xw, Aw);
  1463. }, R, A);
  1464. } else {
  1465. runner(Tw, Nw, Rw, Xw, Aw);
  1466. }
  1467.  
  1468. // console.log(988002)
  1469.  
  1470. // const N_ =
  1471.  
  1472. // var l = this
  1473. // , k = function (T, W) {
  1474. // XK(l, N.propertyEffects, T, X, W, N.nodeList);
  1475. // for (var w = N.firstChild; w; w = w.nextSibling)
  1476. // l._runEffectsForTemplate(w, T, X, W)
  1477. // };
  1478. // N.runEffects ? N.runEffects(k, R, A) : k(R, A)
  1479. }
  1480.  
  1481. }
  1482.  
  1483.  
  1484. const _registerHost = proto._registerHost;
  1485. if (_registerHost && !proto._registerHost322 && _registerHost.length === 0) {
  1486. proto._registerHost322 = _registerHost;
  1487. const map = new WeakMap();
  1488. map.set = map.setOriginal || map.set;
  1489. proto._registerHost = function () {
  1490. if (!map.has(this)) {
  1491. map.set(this, (this.__dataHost || null));
  1492. Object.defineProperty(this, '__dataHost', {
  1493. get() {
  1494. return kRef(map.get(this)) || null
  1495. },
  1496. set(nv) {
  1497. const w = kRef(nv);
  1498. if (!w) {
  1499. map.set(this, null);
  1500. } else {
  1501. if (!w[wk]) w[wk] = mWeakRef(w);
  1502. let byPass = false;
  1503. if (this.is === 'ytd-masthead') byPass = true;
  1504. if (byPass) {
  1505. map.set(this, w);
  1506. } else {
  1507. map.set(this, w[wk]);
  1508. }
  1509. }
  1510. return true;
  1511. },
  1512. enumerable: true,
  1513. configurable: true
  1514. });
  1515. }
  1516. let previousDataHost = this.__dataHost;
  1517. let r = _registerHost.call(this);
  1518. let currentDataHost = this.__dataHost;
  1519. if (currentDataHost !== previousDataHost) { // future use only
  1520. if (previousDataHost && previousDataHost.nodeType >= 1 && previousDataHost.isConnected === false) {
  1521. _removedElements.addNode(previousDataHost);
  1522. }
  1523. }
  1524. return r;
  1525. }
  1526. }
  1527.  
  1528. }
  1529. globalSetup('_removeBoundDom', setup1);
  1530.  
  1531.  
  1532. /*
  1533.  
  1534. M.prototype._stampTemplate = function(N, R) {
  1535. R = R || this._bindTemplate(N, !0);
  1536. aU.push(this);
  1537. N = d.prototype._stampTemplate.call(this, N, R);
  1538. aU.pop();
  1539. R.nodeList = N.nodeList;
  1540. if (!R.wasPreBound)
  1541. for (var X = R.childNodes = [], A = N.firstChild; A; A = A.nextSibling)
  1542. X.push(A);
  1543. N.templateInfo = R;
  1544. X = R.nodeList;
  1545. A = R.nodeInfoList;
  1546. if (A.length)
  1547. for (var l = 0; l < A.length; l++) {
  1548. var k = X[l]
  1549. , T = A[l].bindings;
  1550. if (T)
  1551. for (var W = 0; W < T.length; W++) {
  1552. var w = T[W]
  1553. , p = k
  1554. , h = w;
  1555. if (h.isCompound) {
  1556. for (var I = p.__dataCompoundStorage || (p.__dataCompoundStorage = {}), O = h.parts, y = Array(O.length), c = 0; c < O.length; c++)
  1557. y[c] = O[c].literal;
  1558. O = h.target;
  1559. I[O] = y;
  1560. h.literal && h.kind == "property" && (O === "className" && (p = (0,
  1561. _.FK)(p)),
  1562. p[O] = h.literal)
  1563. }
  1564. gM2(k, this, w)
  1565. }
  1566. k.__dataHost = this
  1567. }
  1568. this.__dataClientsReady && (this._runEffectsForTemplate(R, this.__data, null, !1),
  1569. this._flushClients());
  1570. return N
  1571. }
  1572. ;
  1573.  
  1574. */
  1575.  
  1576.  
  1577.  
  1578. class WeakNodeC {
  1579. constructor(eid) {
  1580. this.eid = eid;
  1581. }
  1582. addEventListener(type, listener, option = void 0) {
  1583. const nodeWr = stampedNodes.get(this.eid);
  1584. const node = kRef(nodeWr);
  1585. if (!node) return;
  1586. return node.addEventListener(type, listener, option);
  1587. }
  1588. removeEventListener(type, listener, option = void 0) {
  1589. const nodeWr = stampedNodes.get(this.eid);
  1590. const node = kRef(nodeWr);
  1591. if (!node) return;
  1592. return node.removeEventListener(type, listener, option);
  1593. }
  1594. getNode592177() {
  1595. const nodeWr = stampedNodes.get(this.eid);
  1596. const node = kRef(nodeWr);
  1597. return node;
  1598. }
  1599. set __dataHost(nv) {
  1600. const nodeWr = stampedNodes.get(this.eid);
  1601. const node = kRef(nodeWr);
  1602. if (!node) return;
  1603. node.__dataHost = nv;
  1604. return true;
  1605. }
  1606. get __dataHost() {
  1607. const nodeWr = stampedNodes.get(this.eid);
  1608. const node = kRef(nodeWr);
  1609. if (!node) return;
  1610. return node.__dataHost;
  1611. }
  1612.  
  1613. set __dataCompoundStorage(nv) {
  1614. const nodeWr = stampedNodes.get(this.eid);
  1615. const node = kRef(nodeWr);
  1616. if (!node) return;
  1617. node.__dataCompoundStorage = nv;
  1618. return true;
  1619.  
  1620. }
  1621. get __dataCompoundStorage() {
  1622. const nodeWr = stampedNodes.get(this.eid);
  1623. const node = kRef(nodeWr);
  1624. if (!node) return;
  1625. return node.__dataCompoundStorage;
  1626.  
  1627. }
  1628. }
  1629.  
  1630. // let initied2 = false;
  1631. const setup2 = (qxx) => {
  1632. // if(initied2) return;
  1633. // initied2 = true;
  1634. const proto = qxx;
  1635. const constructor = proto.constructor;
  1636. const _stampTemplate = proto._stampTemplate;
  1637. // console.log(12883, proto, constructor)
  1638. if (typeof _stampTemplate === 'function' && _stampTemplate.length === 2 && !proto._stampTemplate374) {
  1639. proto._stampTemplate374 = _stampTemplate;
  1640. proto._stampTemplate = function (N, R) {
  1641. // R = boolean true or binded template
  1642. // N = template elemenet
  1643. let M = N;
  1644. let r_ = null;
  1645. const r = _stampTemplate.call(this, M, R); // return the fragment created with nodeList
  1646. r_ = r;
  1647.  
  1648. if (r && r.nodeType === 11) {
  1649.  
  1650. const fid = genId();
  1651.  
  1652. r.__fragId57__ = fid;
  1653. if (!r[wk]) r[wk] = mWeakRef(r);
  1654. stampedFragment.set(fid, r[wk]);
  1655.  
  1656. if (r.nodeList) {
  1657. const nl = r.nodeList;
  1658. nl.__belongFragId57__ = fid;
  1659. for (let i = 0, l = nl.length; i < l; i++) {
  1660. const t = nl[i];
  1661. if (t && t.nodeType >= 1) {
  1662. if (!t[wk]) t[wk] = mWeakRef(t);
  1663. const eid = `${fid}::${i}`;
  1664. nl[i] = new WeakNodeC(eid);
  1665. stampedNodes.set(eid, t[wk]);
  1666. t.__weakNodeCId57__ = eid;
  1667. }
  1668. }
  1669. }
  1670.  
  1671. }
  1672.  
  1673. return r;
  1674. }
  1675. }
  1676. }
  1677.  
  1678. globalSetup('_addMethodEventListenerToNode', setup2);
  1679.  
  1680. }
  1681.  
  1682. if (XFlag) {
  1683.  
  1684. const cMap = new Set();
  1685. cMap.add = cMap.addOriginal || cMap.add;
  1686. const yMap = new Set();
  1687. yMap.add = yMap.addOriginal || yMap.add;
  1688.  
  1689.  
  1690. const ydMap = new Set();
  1691. ydMap.add = ydMap.addOriginal || ydMap.add;
  1692.  
  1693. window.yMap = yMap;
  1694. window.cMap = cMap;
  1695. window.ydMap = ydMap;
  1696.  
  1697. const constructAts = new Set();
  1698. constructAts.add = constructAts.addOriginal || constructAts.add;
  1699. window.constructAts = constructAts;
  1700.  
  1701. const kMap = new WeakMap();
  1702.  
  1703. const kRefProp = (wr, prop)=>{
  1704. let o = kRef(wr);
  1705. return o ? o[prop] : null;
  1706. }
  1707.  
  1708. const wrObj = (objRef, props) => {
  1709. let wr = mWeakRef(objRef);
  1710. if (wr === objRef || !props || !props.length) return wr;
  1711. let properties = {};
  1712. props.forEach(k => {
  1713. properties[k] = {
  1714. get() {
  1715. return kRefProp(this, k)
  1716. },
  1717. enumerable: false,
  1718. configurable: true
  1719. };
  1720. });
  1721. Object.defineProperties(wr, properties);
  1722. return wr;
  1723. }
  1724.  
  1725. const sProtos = {};
  1726.  
  1727. const setupCProto = function (cProto) {
  1728.  
  1729. if(cProto === Object.prototype) return;
  1730.  
  1731. if (!kMap.get(cProto)) kMap.set(cProto, `protoKey0_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`);
  1732. cProto[kMap.get(cProto)] = true;
  1733. // debugger;
  1734.  
  1735. const constructAt = `\n\n${new Error().stack}\n\n`.replace(/[\r\n]([^\r\n]*?\.user\.js[^\r\n]*?[\r\n]+)+/g, '\n').replace(/[\r\n]([^\r\n.]+[\r\n]+)+/g, '\n').trim().split(/[\r\n]+/)[0];
  1736. constructAts.add(constructAt)
  1737.  
  1738. if (MemoryFix_Flag002 & 32) {
  1739. if (!cProto.dk322 && (cProto.__attachInstance || cProto.__detachInstance)) {
  1740. fixDetachFn(cProto);
  1741. }
  1742. }
  1743.  
  1744. if (MemoryFix_Flag002 & 2) {
  1745. if (cProto._setPendingProperty && !cProto.__setPropDX38__) {
  1746. cProto.__setPropDX38__ = true;
  1747.  
  1748. if (cProto._setPendingProperty.length === 3) {
  1749. cProto._setPendingProperty.bind = sProtos._setPendingProperty$bind || (sProtos._setPendingProperty$bind = function (obj, ...args) {
  1750. let wobj = obj[wk] || (obj[wk] = mWeakRef(obj));
  1751. return () => {
  1752. const obj = kRef(wobj);
  1753. let u = Reflect.apply(this, obj, args);
  1754. args.length = 0;
  1755. wobj = null;
  1756. return u;
  1757. };
  1758. });
  1759. }
  1760.  
  1761. }
  1762. }
  1763.  
  1764.  
  1765. const cProtoConstructor = cProto.constructor;
  1766.  
  1767. if (MemoryFix_Flag002 & 8) {
  1768. if (cProtoConstructor._parseBindings && !cProtoConstructor.__parseBindingsDX38__) {
  1769. cProtoConstructor.__parseBindingsDX38__ = true;
  1770.  
  1771. ydMap.add(cProtoConstructor);
  1772.  
  1773. if (cProtoConstructor._parseBindings.length === 2) {
  1774.  
  1775. cProtoConstructor._parseBindings3858 = cProtoConstructor._parseBindings;
  1776.  
  1777. cProtoConstructor._parseBindings = sProtos._parseBindings || (sProtos._parseBindings = function (c, d) {
  1778. let p = this._parseBindings3858(c, d);
  1779. this.__bindingsArrs__ = this.__bindingsArrs__ || [];
  1780. if (p) this.__bindingsArrs__.push(p);
  1781. return p;
  1782. });
  1783.  
  1784. }
  1785. }
  1786. }
  1787.  
  1788. /*
  1789. a.prototype._initializeProperties = function() {
  1790. if (Em && this.hasAttribute("disable-upgrade"))
  1791. this.__isUpgradeDisabled = !0;
  1792. else {
  1793. var e = Object.getPrototypeOf(this);
  1794. e.hasOwnProperty("__hasRegisterFinished") || (this._registered(),
  1795. e.__hasRegisterFinished = !0);
  1796. b.prototype._initializeProperties.call(this);
  1797. this.root = this;
  1798. this.created();
  1799. fpb && !this._legacyForceObservedAttributes && (this.hasAttributes() ? this._takeAttributes() : this.parentNode || (this.__needsAttributesAtConnected = !0));
  1800. this._applyListeners()
  1801. }
  1802. }
  1803. */
  1804. /*
  1805. bOa = function(a, b, c) {
  1806. var d = bya(a.prototype, $Na, a.prototype.behaviors);
  1807. d.prototype.is = b;
  1808. d.prototype.localName = b;
  1809. c && aOa(d, c);
  1810. return function(e) {
  1811. e && (d.prototype.hostElement = e);
  1812. var g = new d;
  1813. g.root = g;
  1814. g.hostElement = e;
  1815. return g
  1816. }
  1817. }
  1818. */
  1819.  
  1820.  
  1821. }
  1822. const symDH = Symbol();
  1823.  
  1824. const wfStore = new WeakMap();
  1825.  
  1826. const wrapF = function (f, key) {
  1827. if (wfStore.get(f)) return wfStore.get(f);
  1828.  
  1829. let g = function () {
  1830. const o = kRef(this);
  1831. if (!o) return;
  1832. const cnt = insp(o);
  1833. // if (cnt === o) return;
  1834. // if (!('ready' in cnt)) return;
  1835. return f.apply(o, arguments);
  1836. };
  1837. g.key38 = key;
  1838. g.originalFunc38 = f;
  1839. g.__wrapF84__ = true;
  1840. wfStore.set(f, g);
  1841. wfStore.set(g, g);
  1842. return g;
  1843. };
  1844.  
  1845. if (MemoryFix_Flag002 & 16) {
  1846. ['_createPropertyAccessor', '_addPropertyToAttributeMap', '_definePropertyAccessor', 'ready', '_initializeProperties', '_initializeInstanceProperties', '_setProperty', '_getProperty', '_setPendingProperty', '_isPropertyPending', '_invalidateProperties', '_enableProperties', '_flushProperties', '_shouldPropertiesChange', '_propertiesChanged', '_shouldPropertyChange', 'attributeChangedCallback', '_attributeToProperty', '_propertyToAttribute', '_valueToNodeAttribute', '_serializeValue', '_deserializeValue'].forEach(key => {
  1847.  
  1848. Object.defineProperty(Node.prototype, key, {
  1849. get() {
  1850. return this[`__a0939${key}__`];
  1851. },
  1852. set(nv) {
  1853. if (typeof nv !== 'function') return;
  1854. const g = (nv.__wrapF84__) ? nv : wrapF(nv, key);
  1855. this[`__a0939${key}__`] = g;
  1856. return true;
  1857. }
  1858. });
  1859.  
  1860.  
  1861. });
  1862. }
  1863.  
  1864.  
  1865.  
  1866. // const wm = new WeakMap();
  1867.  
  1868. const fixDetachFn = (tpProto) => { // & 32
  1869.  
  1870. if (tpProto.dk322) return;
  1871. tpProto.dk322 = true;
  1872.  
  1873. window.__fixTemplateReuse1058__ = true;
  1874.  
  1875.  
  1876. tpProto.__ensureTemplatized994 = tpProto.__ensureTemplatized;
  1877. if (typeof tpProto.__ensureTemplatized994 === 'function' && tpProto.__ensureTemplatized994.length === 0) {
  1878. tpProto.__ensureTemplatized = function () {
  1879. // console.log(18470001)
  1880. return this.__ensureTemplatized994();
  1881. }
  1882. }
  1883.  
  1884.  
  1885. tpProto.__updateInstances994 = tpProto.__updateInstances;
  1886. if (typeof tpProto.__updateInstances994 === 'function' && tpProto.__updateInstances994.length === 3) {
  1887. let bypass= false;
  1888. tpProto.__updateInstances = function (a, b, c) {
  1889.  
  1890. // const a_ = [...a];
  1891. if(!bypass && a === this.items && (a||0).length >=1 ){
  1892.  
  1893. bypass = true;
  1894. // console.log(18470002, a, b,c)
  1895. let e;
  1896. for (e = 0; e < b; e++) {
  1897. let g = this.__instances[e]
  1898. , k = c[e]
  1899. , m = a[k];
  1900. if(g && typeof (m||0) === 'object'){
  1901. // const q = g._shouldPropertyChange;
  1902. // g._shouldPropertyChange = ()=>true;
  1903. // g[this.as] = {};
  1904. // a_[k]=a[k] = m;
  1905. // g[this.as] = m;
  1906.  
  1907. // use public interface notifyPath instead of internal interface _setPendingProperty
  1908. const m_ = a[k] = Object.assign({}, a[k]);
  1909. try {
  1910. g.notifyPath(this.as, {});
  1911. } catch (e) { }
  1912. try {
  1913. g.notifyPath(this.as, m_);
  1914. } catch (e) { }
  1915.  
  1916. // g._setPendingProperty(this.as, {});
  1917. // g._setPendingProperty(this.as, m);
  1918. // g._setPendingProperty(this.indexAs, e);
  1919. // g._setPendingProperty(this.itemsIndexAs, k);
  1920. // delete g._shouldPropertyChange;
  1921. // if(g._shouldPropertyChange !== q) g._shouldPropertyChange = q;
  1922. }
  1923. }
  1924. bypass = false;
  1925.  
  1926. }
  1927. const r = this.__updateInstances994(a,b,c);
  1928.  
  1929. // for (e = 0; e < b; e++) {
  1930. // let g = this.__instances[e]
  1931. // , k = c[e]
  1932. // , m = a_[k];
  1933. // if(g){
  1934. // // const q = g._shouldPropertyChange;
  1935. // // g._shouldPropertyChange = ()=>true;
  1936. // // g[this.as] = m;
  1937. // // g._setPendingProperty(this.as, {});
  1938. // // g._setPendingProperty(this.as, m);
  1939. // // g._setPendingProperty(this.indexAs, e);
  1940. // // g._setPendingProperty(this.itemsIndexAs, k);
  1941. // // delete g._shouldPropertyChange;
  1942. // // if(g._shouldPropertyChange !== q) g._shouldPropertyChange = q;
  1943. // }
  1944. // }
  1945.  
  1946. return r;
  1947. }
  1948. }
  1949.  
  1950. tpProto.__detachInstance994 = tpProto.__detachInstance;
  1951. if (typeof tpProto.__detachInstance994 === 'function' && tpProto.__detachInstance994.length === 1) {
  1952. tpProto.__detachInstance = function (a) {
  1953. const u = this.__instances[a];
  1954. if (u && !u.__keepInstance038__) u.__keepInstance038__ = true;
  1955. const children = (u || 0).children;
  1956. if (children && children.length >= 1) {
  1957. const pp = document.createDocumentFragment();
  1958. for (const s of [...children]) {
  1959. pp.appendChild(s);
  1960. }
  1961. }
  1962. try {
  1963. return this.__detachInstance994(a);
  1964. } catch (e) { }
  1965. return u;
  1966. }
  1967. }
  1968.  
  1969. tpProto.__attachInstance994 = tpProto.__attachInstance;
  1970. if (typeof tpProto.__attachInstance994 === 'function' && tpProto.__attachInstance994.length === 2) {
  1971. tpProto.__attachInstance = function (a, b) {
  1972. const u = this.__instances[a];
  1973. if (u && !u.__keepInstance038__) u.__keepInstance038__ = true;
  1974. if (u && u.root && b) {
  1975. const root = u.root;
  1976. const pp = document.createDocumentFragment();
  1977. pp.appendChild(root);
  1978. root.appendChild(pp);
  1979. const r = this.__attachInstance994(a, b);
  1980. if (!this.__chunkingId) this.__chunkingId = 0.25;
  1981. return r;
  1982. }
  1983. }
  1984. }
  1985.  
  1986. }
  1987.  
  1988. const ytTemplateDomEntry = (tpProto) => {
  1989.  
  1990. console.log('ytTemplateDomEntry triggered')
  1991.  
  1992.  
  1993. const convertToWeakArr = (arr) => {
  1994.  
  1995. if (arr.isWeak) return;
  1996.  
  1997. for (let i = 0, l = arr.length; i < l; i++) {
  1998. const o = arr[i]
  1999. if (o) {
  2000. let p = kRef(o)
  2001. if (!p) arr[i] = null;
  2002. else {
  2003. if (!o[wk]) o[wk] = mWeakRef(o);
  2004. arr[i] = o[wk];
  2005. }
  2006. }
  2007. }
  2008. arr.isWeak = true;
  2009.  
  2010. }
  2011.  
  2012. const convertToNormalArr = (arr) => {
  2013.  
  2014. if (!arr.isWeak) return;
  2015.  
  2016. for (let i = 0, l = arr.length; i < l; i++) {
  2017. const o = arr[i]
  2018. if (o) {
  2019. let p = kRef(o)
  2020. arr[i] = p;
  2021. }
  2022. }
  2023. arr.isWeak = false;
  2024.  
  2025. }
  2026.  
  2027. if (MemoryFix_Flag002 & 256) {
  2028. Object.defineProperty(tpProto, '__instances', {
  2029. get() {
  2030. this.dk322 || fixDetachFn(Reflect.getPrototypeOf(this));
  2031. let arr = this.__instances_actual471__;
  2032. if (arr && arr.isWeak) {
  2033. convertToNormalArr(arr);
  2034. for (let i = arr.length - 1; i >= 0; i--) {
  2035. const t = arr[i];
  2036. if (!t) arr.splice(i, 1);
  2037. else if (!t.__keepInstance038__) t.__keepInstance038__ = true;
  2038. }
  2039. Promise.resolve(arr).then(convertToWeakArr);
  2040. }
  2041. return arr;
  2042. },
  2043. set(nv) {
  2044. this.dk322 || fixDetachFn(Reflect.getPrototypeOf(this));
  2045. this.__instances_actual471__ = nv;
  2046. if (nv && !nv.isWeak) {
  2047. Promise.resolve(nv).then(convertToWeakArr);
  2048. }
  2049. return true;
  2050. },
  2051. enumerable: false,
  2052. configurable: true
  2053. });
  2054. }
  2055.  
  2056. // console.log(91901, tpProto.__detachInstance)
  2057. if (MemoryFix_Flag002 & 32) {
  2058. if (tpProto.__detachInstance) {
  2059. fixDetachFn(tpProto);
  2060. } else {
  2061. Promise.resolve(tpProto).then((tpProto) => {
  2062. // console.log(91902, tpProto.__detachInstance)
  2063. fixDetachFn(tpProto);
  2064. })
  2065. }
  2066. }
  2067.  
  2068. }
  2069.  
  2070. if (MemoryFix_Flag002 & 32) {
  2071. Object.defineProperty(Object.prototype, '__ensureTemplatized', {
  2072. set(nv) {
  2073. if (nv === true) return false;
  2074. tpProto = this;
  2075. if ('connectedCallback' in tpProto && tpProto !== Node.prototype && !tpProto.__domDX37__) {
  2076. tpProto.__domDX37__ = true;
  2077. ytTemplateDomEntry(tpProto);
  2078. }
  2079. this.__ensureTemplatized949__ = nv;
  2080. return true;
  2081. },
  2082. get() {
  2083. return this.__ensureTemplatized949__;
  2084. }
  2085. });
  2086. }
  2087.  
  2088.  
  2089. if (MemoryFix_Flag002 & 64) {
  2090. HTMLElement_.prototype.__dataHostBinding374 = true;
  2091. Object.defineProperty(HTMLElement_.prototype, '__dataHost', {
  2092. get() {
  2093. return kRef(this.__dataHostWr413__);
  2094. },
  2095. set(nv) {
  2096. if (nv && typeof nv === 'object' && !nv.deref) {
  2097. if (!nv[wk]) nv[wk] = mWeakRef(nv);
  2098. nv = nv[wk];
  2099. }
  2100. this.__dataHostWr413__ = nv;
  2101. return true;
  2102. }
  2103. });
  2104. }
  2105.  
  2106.  
  2107. const setupYProto = function (yProto) {
  2108.  
  2109. if(yProto === Object.prototype) return;
  2110.  
  2111. if (!kMap.get(yProto)) kMap.set(yProto, `protoKey1_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`);
  2112. yProto[kMap.get(yProto)] = true;
  2113.  
  2114. if (FIX_DOM_IF_DETACH && !yProto.disconnectedCallback277 && yProto.disconnectedCallback && typeof yProto._readyClients === 'function' && typeof yProto._canApplyPropertyDefault === 'function' && typeof yProto._attachDom === 'function' && !yProto.is && typeof yProto.constructor._finalizeTemplate === 'function') {
  2115. const disconnectedCallback277 = yProto.disconnectedCallback;
  2116. yProto.disconnectedCallback277 = true;
  2117. yProto.disconnectedCallback = function () {
  2118. disconnectedCallback277.call(this);
  2119. if (this.nodeName === 'DOM-IF' && this.__instance && typeof this.__teardownInstance === 'function') {
  2120. const shadyParent = (this.__shady_parentNode || 0);
  2121. const actualParent = (this.parentNode || 0);
  2122. if (shadyParent !== actualParent && shadyParent.nodeType === 11 && actualParent.nodeType === 11) {
  2123. // && (shadyParent.compareDocumentPosition(actualParent) & (1|8|16) === 1)
  2124. // if (!this.restamp && !this.id && this.__ctor && this.isConnected === false) {
  2125. const children = (this.__instance.children || 0).length;
  2126. if (children >= 1) {
  2127. try {
  2128. this.__teardownInstance();
  2129. } catch (e) { }
  2130. }
  2131. // }
  2132. }
  2133. }
  2134. }
  2135. }
  2136.  
  2137.  
  2138. if (MemoryFix_Flag002 & 32) {
  2139. if (!yProto.dk322 && (yProto.__attachInstance || yProto.__detachInstance)) {
  2140. fixDetachFn(yProto);
  2141. }
  2142. }
  2143.  
  2144. if (MemoryFix_Flag002 & 128) {
  2145. if (!yProto.__dataHostBinding374) {
  2146. yProto.__dataHostBinding374 = true;
  2147. Object.defineProperty(yProto, '__dataHost', {
  2148. set(nv) {
  2149. let dh = nv;
  2150. if (dh && typeof dh === 'object' && !dh.deref) {
  2151. const wr = dh[wk] || (dh[wk] = mWeakRef(dh));
  2152. dh = wr;
  2153. }
  2154. this[symDH] = dh;
  2155. return true;
  2156. },
  2157. get() {
  2158. let wr = this[symDH];
  2159. let obj = typeof wr === 'object' ? kRef(wr) : wr;
  2160. return obj;
  2161. },
  2162. enumerable: false,
  2163. configurable: true
  2164. });
  2165. }
  2166.  
  2167.  
  2168.  
  2169. if (yProto._registerHost && yProto._enqueueClient && yProto.__enableOrFlushClients && !yProto._registerHostDX38__) {
  2170. yProto._registerHostDX38__ = true;
  2171.  
  2172. // yProto._registerHost7133 = yProto._registerHost;
  2173.  
  2174. yProto.__enableOrFlushClients = function () {
  2175. const c_ = this.__dataPendingClients;
  2176. if (c_) {
  2177. const c = c_.slice();
  2178. c_.length = 0;
  2179. for (let d = 0, l = c.length; d < l; d++) {
  2180. let e = kRef(c[d]);
  2181. if (e) {
  2182. e.__dataEnabled ? e.__dataPending && e._flushProperties() : e._enableProperties()
  2183. }
  2184. }
  2185. }
  2186. }
  2187.  
  2188. yProto._enqueueClient = function (c) {
  2189. if (c === this || !c || typeof c !== 'object') return;
  2190. if (c.deref) c = kRef(c);
  2191. const m = this.__dataPendingClients || (this.__dataPendingClients = []);
  2192. if (!c[wk]) c[wk] = mWeakRef(c);
  2193. m.push(c[wk]);
  2194. }
  2195.  
  2196. }
  2197. }
  2198.  
  2199.  
  2200.  
  2201. }
  2202. const setupRendering = function () {
  2203.  
  2204. const cnt = this;
  2205. const cProto = Reflect.getPrototypeOf(cnt);
  2206. let yProto = Reflect.getPrototypeOf(cProto);
  2207.  
  2208. const yProtos = new Set();
  2209.  
  2210. if (!yMap.has(yProto)) {
  2211. // capture all ancenstor constructors of a and b (non-specific component type)
  2212.  
  2213. do {
  2214. if (yProto === Object.prototype || yProto === null) break;
  2215. if (yProto === Element.prototype || yProto === Node.prototype || yProto === EventTarget.prototype || yProto === HTMLElement_.prototype) break;
  2216. yProtos.add(yProto);
  2217. yProto = Reflect.getPrototypeOf(yProto);
  2218. } while (!yProtos.has(yProto));
  2219.  
  2220. for (const yProto of yProtos) {
  2221. yMap.add(yProto);
  2222. setupYProto(yProto)
  2223. }
  2224.  
  2225. }
  2226.  
  2227.  
  2228. if (!cMap.has(cProto)) {
  2229. cMap.add(cProto); // cProto constrcutor is either a or b? (specific component type)
  2230. setupCProto(cProto);
  2231. }
  2232.  
  2233. }
  2234.  
  2235. /*
  2236.  
  2237. jF = function(M) {
  2238. var d = YNV.call(this) || this;
  2239. d._configureProperties(M);
  2240. d.root = d._stampTemplate(d.__dataHost);
  2241. var N = [];
  2242. d.children = N;
  2243. for (var R = d.root.firstChild; R; R = R.nextSibling)
  2244. N.push(R),
  2245. R.__templatizeInstance = d;
  2246. d.__templatizeOwner && d.__templatizeOwner.__hideTemplateChildren__ && d._showHideChildren(!0);
  2247. N = d.__templatizeOptions;
  2248. (M && N.instanceProps || !N.instanceProps) && d._enableProperties();
  2249. return d
  2250. };
  2251. */
  2252.  
  2253. const sb1 = Symbol();
  2254. Object.defineProperty(Object.prototype, 'root', {
  2255. get() {
  2256. return this[sb1];
  2257. },
  2258. set(nv){
  2259. const p = this ? kRef(this) : null;
  2260. const mv = nv ? kRef(nv) : null;
  2261.  
  2262. if (mv && (mv instanceof Node) && !p.__setupRendered399__) {
  2263. p.__setupRendered399__ = true;
  2264. setupRendering.call(p);
  2265. }
  2266. if (mv && mv.is && !mv.__setupRendered399__) {
  2267. mv.__setupRendered399__ = true;
  2268. setupRendering.call(mv);
  2269. }
  2270.  
  2271. this[sb1] = nv;
  2272. return true;
  2273. }
  2274. });
  2275.  
  2276.  
  2277. }
  2278.  
  2279. let _cssSheet = null;
  2280. const addNewCSS = typeof CSSStyleSheet !== 'undefined' && document.adoptedStyleSheets ? (css) => {
  2281. if (!_cssSheet) {
  2282. _cssSheet = new CSSStyleSheet();
  2283. document.adoptedStyleSheets.push(_cssSheet);
  2284. }
  2285. _cssSheet.insertRule(`${css}`);
  2286. } : (css) => {
  2287. let nonce = document.querySelector('style[nonce]');
  2288. nonce = nonce ? nonce.getAttribute('nonce') : null;
  2289. const st = document.createElement('style');
  2290. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  2291. st.textContent = `${css}`;
  2292. let parent;
  2293. if (parent = document.head) parent.appendChild(st);
  2294. else if (parent = (document.body || document.documentElement)) parent.insertBefore(st, parent.firstChild);
  2295. }
  2296.  
  2297. function getTranslate() {
  2298.  
  2299. pLoad.then(() => {
  2300. addNewCSS(".yt-formatted-string-block-line{display:block;}");
  2301. });
  2302.  
  2303. const snCache = new Map();
  2304.  
  2305. if (TRANSLATE_DEBUG) {
  2306. console.log(11)
  2307. }
  2308.  
  2309. /** @type {(str: string?) => string} */
  2310. function _snippetText(str) {
  2311. // str can be underfinded
  2312. if (!str || typeof str !== 'string') return '';
  2313. let res = snCache.get(str);
  2314. if (res === undefined) {
  2315. let b = false;
  2316. res = str.replace(/[\s\u3000\u200b]*[\u200b\xA0\x20\n]+[\s\u3000\u200b]*/g, (m) => {
  2317. b = true;
  2318. return m.includes('\n') ? '\n' : m.replace(/\u200b/g, '').replace(/[\xA0\x20]+/g, ' ');
  2319. });
  2320. res = res.replace(/^[\s\u3000]+|[\u3000\s]+$/g, () => {
  2321. b = true;
  2322. return '';
  2323. });
  2324. if (b) {
  2325. snCache.set(str, res);
  2326. snCache.set(res, null);
  2327. } else {
  2328. res = null;
  2329. snCache.set(str, null);
  2330. }
  2331. }
  2332. return res === null ? str : res;
  2333. }
  2334.  
  2335. /** @type {(snippet: Object) => string} */
  2336. function snippetText(snippet) {
  2337. let runs = snippet.runs;
  2338. const n = runs.length;
  2339. if (n === 1) return _snippetText(runs[0].text);
  2340. let res = new Array(n);
  2341. let ci = 0;
  2342. for (const s of runs) {
  2343. res[ci++] = _snippetText(s.text);
  2344. }
  2345. return res.join('\n');
  2346. }
  2347.  
  2348. const _DEBUG_szz = (t) => t.map(x => {
  2349. const tsr = x.transcriptSegmentRenderer;
  2350. return ({
  2351. t: tsr.snippet.runs.map(x => x.text).join('//'),
  2352. a: tsr.startMs,
  2353. b: tsr.endMs
  2354. });
  2355. });
  2356.  
  2357. const fixRuns = (runs) => {
  2358. if (runs.length === 1 && runs[0]?.text?.includes('\n')) {
  2359. // https://www.youtube.com/watch?v=dmHJJ5k_G-A
  2360. const text = runs[0].text;
  2361. const nlc = text.includes('\r\n') ? '\r\n' : text.includes('\n\r') ? '\n\r' : text.includes('\r') ? '\r' : '\n';
  2362. const s = text.split(nlc);
  2363. let bi = 0;
  2364. runs.length = s.length;
  2365. for (const text of s) {
  2366. runs[bi++] = { ...runs[0], text, ...{blockLine: true} };
  2367. }
  2368. }
  2369. for (const s of runs) {
  2370. s.text = _snippetText(s.text);
  2371. }
  2372. }
  2373.  
  2374. function translate(initialSegments) {
  2375. // 2023.07.13 - fix initialSegments with transcriptSectionHeaderRenderer
  2376.  
  2377. if (!initialSegments) return initialSegments;
  2378.  
  2379. if (TRANSLATE_DEBUG) {
  2380. console.log(12);
  2381. Promise.resolve(JSON.stringify(initialSegments)).then((r) => {
  2382. let obj = JSON.parse(r);
  2383. console.log(7558, 1, obj)
  2384. return obj;
  2385. }).then(p => {
  2386. let obj = _DEBUG_szz(p)
  2387. console.log(7558, 2, obj)
  2388. })
  2389. }
  2390.  
  2391.  
  2392. //let mapRej = new WeakSet();
  2393.  
  2394. const n1 = initialSegments.length;
  2395. if (!n1) return fRes;
  2396. let n2 = 0;
  2397.  
  2398.  
  2399. const fRes = new Array(n1);
  2400. // -----------------------------------------------------------------------------------------
  2401.  
  2402. const s8 = Symbol();
  2403.  
  2404. {
  2405.  
  2406. /** @type {Map<String, Object>} */
  2407. let cacheTexts = new Map(); // avoid duplicate with javascript object properties
  2408.  
  2409. // /-* * @type {Map<String, number>} *-/
  2410. // let mh1 = new Map(); // avoid duplicate with javascript object properties
  2411. // 1: ok
  2412. // 2: abandoned effect text
  2413.  
  2414. for (const initialSegment of initialSegments) {
  2415. const transcript = (initialSegment || 0).transcriptSegmentRenderer;
  2416. if (!transcript) {
  2417. // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer
  2418. fRes[n2++] = initialSegment;
  2419. continue;
  2420. }
  2421. const runs = transcript.snippet.runs
  2422. if (!runs || runs.length === 0) {
  2423. initialSegment[s8] = true;
  2424. continue;
  2425. }
  2426. let startMs = (+transcript.startMs || 0); //integer
  2427. let endMs = (+transcript.endMs || 0); //integer
  2428. if (startMs === endMs) {
  2429. // effect text
  2430. // https://www.youtube.com/watch?v=Ud73fm4Uoq0
  2431. //mapRej.add(initialSegment)
  2432. continue;
  2433. }
  2434. if (endMs - startMs < 30) {
  2435. continue;
  2436. }
  2437. const text = snippetText(transcript.snippet);
  2438. const hEntry = cacheTexts.get(text);
  2439. const mh1e = hEntry === undefined ? 0 : hEntry === null ? 2 : 1;
  2440. if (mh1e === 2) continue;
  2441. const entry = {
  2442. startMs,
  2443. endMs,
  2444. initialSegment,
  2445. text
  2446. };
  2447. if (mh1e === 0) {
  2448. if (/^[,.\x60\x27\x22\u200b\xA0\x20;-]*$/.test(text)) {
  2449. initialSegment[s8] = true;
  2450. cacheTexts.set(text, null);
  2451. //effect only
  2452. // https://www.youtube.com/watch?v=zLak0dxBKpM
  2453. //mapRej.add(initialSegment)
  2454. continue;
  2455. }
  2456. } else if (hEntry) {
  2457.  
  2458. const timeDiff = entry.startMs - hEntry.endMs;
  2459. let shouldMerge = false;
  2460.  
  2461. if (timeDiff >= 0) {
  2462.  
  2463. if (timeDiff < 25) {
  2464. shouldMerge = true;
  2465. } else if (timeDiff < 450 && entry.endMs - entry.startMs < 900) {
  2466. shouldMerge = true;
  2467. } else if (timeDiff < 150 && entry.endMs - entry.startMs > 800) {
  2468. shouldMerge = true;
  2469. }
  2470.  
  2471. if (shouldMerge && hEntry.endMs <= endMs && startMs <= endMs) {
  2472. // abandon the current entry.
  2473. // absorbed by previous entry
  2474. hEntry.endMs = entry.endMs;
  2475. hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference
  2476. //mapRej.add(entry.initialSegment);
  2477. continue;
  2478. }
  2479.  
  2480. } else if (entry.startMs < hEntry.startMs && hEntry.startMs < entry.endMs) {
  2481.  
  2482. // abandon the current entry.
  2483. // absorbed by previous entry
  2484. if (entry.endMs > hEntry.endMs) {
  2485. hEntry.endMs = entry.endMs;
  2486. hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference
  2487. }
  2488. //mapRej.add(entry.initialSegment);
  2489. continue;
  2490.  
  2491. }
  2492.  
  2493. }
  2494. //if not abandoned
  2495. cacheTexts.set(text, entry); //replace the previous valid entry object if any
  2496. // for (const s of runs) {
  2497. // s.text = _snippetText(s.text);
  2498. // }
  2499. fixRuns(runs);
  2500. fRes[n2++] = initialSegment;
  2501. }
  2502.  
  2503. // cacheTexts.clear(); // let GC do it.
  2504. cacheTexts = null;
  2505. // mh1.clear(); // let GC do it.
  2506. // mh1 = null;
  2507.  
  2508. }
  2509.  
  2510. const si_length = fRes.length = n2;
  2511. const sj_length = n1;
  2512.  
  2513. if (si_length !== sj_length) { // for equal length, no fix is required & ignore spacing fix
  2514. // collect the abandon text to become second subtitle
  2515.  
  2516. let sj_start = 0;
  2517. let invalid_sj = -1;
  2518. for (let si = 0; si < si_length; si++) {
  2519. const segment = fRes[si];
  2520. let transcript = segment.transcriptSegmentRenderer;
  2521. if (!transcript) continue; // e.g. transcriptSectionHeaderRenderer
  2522. const runs = transcript.snippet.runs;
  2523. // fixRuns(runs);
  2524. if (runs.length > 1 || runs[0].text.includes('\n')) continue; // skip multi lines
  2525. const main_startMs = (+transcript.startMs || 0);
  2526. const main_endMs = (+transcript.endMs || 0);
  2527. transcript = null;
  2528.  
  2529. /** @type {Map<string, number>} */
  2530. let tMap = new Map(); // avoid duplicate with javascript object properties
  2531.  
  2532. // assume that it is asc-ordered array of key startMs;
  2533. for (let sj = sj_start; sj < sj_length; sj++) {
  2534. const initialSegment = initialSegments[sj];
  2535.  
  2536. if (!initialSegment || initialSegment[s8]) continue; // should invalid_sj be set ?
  2537.  
  2538. const tSegment = initialSegment.transcriptSegmentRenderer;
  2539.  
  2540. if (!tSegment) {
  2541. // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer
  2542. invalid_sj = sj; // should invalid_sj be set ?
  2543. continue;
  2544. }
  2545.  
  2546. const startMs = (+tSegment.startMs || 0)
  2547. const isStartValid = startMs >= main_startMs;
  2548. if (!isStartValid) {
  2549. invalid_sj = sj;
  2550. continue;
  2551. }
  2552. // isStartValid must be true
  2553. if (startMs > main_endMs) {
  2554. sj_start = invalid_sj + 1;
  2555. break;
  2556. }
  2557.  
  2558. const endMs = (+tSegment.endMs || 0)
  2559. if (endMs <= main_endMs) {
  2560. const mt = snippetText(tSegment.snippet);
  2561. const prev = tMap.get(mt);
  2562. if (endMs >= startMs) {
  2563. tMap.set(mt, (prev || 0) + 1 + (endMs - startMs));
  2564. }
  2565. }
  2566.  
  2567. }
  2568.  
  2569. if (tMap.size <= 1) continue; // no second line
  2570. let rg = [...tMap.entries()]; // N x 2 2D-array [string,number][]
  2571. tMap = null;
  2572.  
  2573. // https://www.youtube.com/watch?v=Ud73fm4Uoq0
  2574.  
  2575. rg.sort((a, b) => b[1] - a[1]); //descending order of number
  2576.  
  2577. let targetZ = rg[1][1];
  2578. if (targetZ > 4) {
  2579. let az = 0;
  2580. let fail = false;
  2581. for (let idx = 2, rgl = rg.length; idx < rgl; idx++) {
  2582. az += rg[idx][1];
  2583. if (az >= targetZ) {
  2584. fail = true;
  2585. break;
  2586. }
  2587. }
  2588. if (!fail) {
  2589. const rgA = rg[0][0];
  2590. const rgB = rg[1][0];
  2591. const isDiff = rgB.replace(/\s/g, '') !== rgA.replace(/\s/g, '');
  2592. if (isDiff && rgA === _snippetText(runs[0].text)) {
  2593. if (runs[0] && runs[0].text) runs[0].blockLine = true;
  2594. runs.push({ text: rgB, blockLine: true });
  2595. }
  2596. }
  2597. }
  2598. rg = null;
  2599. }
  2600.  
  2601. TRANSLATE_DEBUG && Promise.resolve(fRes).then((r) => {
  2602.  
  2603. let obj = r;
  2604. console.log(7559, 1, obj)
  2605. return obj;
  2606. }).then(p => {
  2607. let obj = _DEBUG_szz(p)
  2608. console.log(7559, 2, obj)
  2609.  
  2610. });
  2611. }
  2612.  
  2613. // -----------------------------------------------------------------------------------------
  2614. snCache.clear();
  2615. return fRes;
  2616.  
  2617. }
  2618.  
  2619.  
  2620. return translate
  2621.  
  2622. }
  2623.  
  2624.  
  2625. let translateFn = null;
  2626.  
  2627. FIX_TRANSCRIPT_SEGMENTS && !isChatRoomURL && (() => {
  2628.  
  2629. const wmx = new WeakMap();
  2630.  
  2631. function fixSegments(ytObj) {
  2632. let a, b;
  2633. let seg = ((a = ytObj.data) == null ? void 0 : a[b = 'searchResultSegments']) || ((a = ytObj.data) == null ? void 0 : a[b = 'initialSegments']) || [];
  2634. if (!seg || !a || !b || typeof (seg || 0) !== 'object' || !Number.isFinite(seg.length * 1)) return;
  2635. translateFn = translateFn || getTranslate();
  2636. let cSeg;
  2637. cSeg = wmx.get(seg);
  2638. if (!cSeg) {
  2639. let vSeg = null;
  2640. try {
  2641. vSeg = translateFn(seg);
  2642. } catch (e) {
  2643. }
  2644. if (seg && typeof seg === 'object' && seg.length >= 1 && vSeg && typeof vSeg === 'object' && vSeg.length >= 1) {
  2645. // console.log('translated', vSeg);
  2646. cSeg = vSeg;
  2647. wmx.set(seg, cSeg);
  2648. wmx.set(cSeg, cSeg);
  2649. }
  2650. }
  2651. if (cSeg && cSeg !== seg) {
  2652. a[b] = cSeg;
  2653. }
  2654. }
  2655.  
  2656. const dfn = Symbol();
  2657. const Object_ = Object;
  2658. Object_[dfn] = Object_.defineProperties;
  2659. let activation = true;
  2660. Object_.defineProperties = function (obj, pds) {
  2661. let segments, get_;
  2662. if (activation && pds && (segments = pds.segments) && (get_ = segments.get)) {
  2663. activation = false;
  2664. segments.get = function () {
  2665. fixSegments(this);
  2666. return get_.call(this);
  2667. };
  2668. }
  2669. return Object_[dfn](obj, pds);
  2670. };
  2671.  
  2672. })();
  2673.  
  2674.  
  2675. let pf31 = new PromiseExternal();
  2676.  
  2677. // native RAF
  2678. let __requestAnimationFrame__ = typeof webkitRequestAnimationFrame === 'function' ? window.webkitRequestAnimationFrame.bind(window) : window.requestAnimationFrame.bind(window);
  2679.  
  2680. // 1st wrapped RAF
  2681. const baseRAF = (callback) => {
  2682. return p59 ? __requestAnimationFrame__(callback) : __requestAnimationFrame__((hRes) => {
  2683. pf31.then(() => {
  2684. callback(hRes);
  2685. });
  2686. });
  2687. };
  2688.  
  2689. // 2nd wrapped RAF
  2690. window.requestAnimationFrame = baseRAF;
  2691.  
  2692. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  2693. const indr = o => insp(o).$ || o.$ || 0;
  2694.  
  2695. const prototypeInherit = (d, b) => {
  2696. const m = Object.getOwnPropertyDescriptors(b);
  2697. for (const p in m) {
  2698. if (!Object.getOwnPropertyDescriptor(d, p)) {
  2699. Object.defineProperty(d, p, m[p]);
  2700. }
  2701. }
  2702. };
  2703.  
  2704.  
  2705. const firstObjectKey = (obj) => {
  2706. for (const key in obj) {
  2707. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  2708. }
  2709. return null;
  2710. };
  2711.  
  2712. function searchNestedObject(obj, predicate, maxDepth = 64) {
  2713. // normal case: depth until 36
  2714. const result = [];
  2715. const visited = new WeakSet();
  2716.  
  2717. function search(obj, depth) {
  2718. visited.add(obj);
  2719. for (const [key, value] of Object.entries(obj)) {
  2720. // Recursively search nested objects and arrays
  2721. if (value !== null && typeof value === 'object') {
  2722. // Prevent infinite loops by checking if the object is already visited or depth exceeded
  2723. if (depth + 1 <= maxDepth && !visited.has(value)) {
  2724. search(value, depth + 1);
  2725. }
  2726. } else if (predicate(value)) {
  2727. result.push([obj, key]);
  2728. }
  2729. }
  2730. }
  2731.  
  2732. typeof (obj || 0) === 'object' && search(obj, 0);
  2733. return result;
  2734. }
  2735.  
  2736. /** @type {(o: Object | null) => WeakRef | null} */
  2737. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  2738.  
  2739. /** @type {(wr: Object | null) => Object | null} */
  2740. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  2741.  
  2742. const isIterable = (obj) => (Symbol.iterator in Object_(obj));
  2743.  
  2744. if (typeof Document.prototype.requestStorageAccessFor === 'function') {
  2745. if (DENY_requestStorageAccess) {
  2746. // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccessFor
  2747. Document.prototype.requestStorageAccessFor = undefined;
  2748. console.log('[yt-js-engine-tamer]', 'requestStorageAccessFor is removed.');
  2749. } else if (DISABLE_IFRAME_requestStorageAccess && window !== top) {
  2750. Document.prototype.requestStorageAccessFor = function () {
  2751. return new Promise((resolve, reject) => {
  2752. reject();
  2753. });
  2754. };
  2755. }
  2756. }
  2757.  
  2758. const traceStack = (stack) => {
  2759. let result = new Set();
  2760. let p = new Set();
  2761. let u = ''
  2762. for (const s of stack.split('\n')) {
  2763. if (s.split(':').length < 3) continue;
  2764. let m = /(([\w-_\.]+):\d+:\d+)[^:\r\n]*/.exec(s);
  2765. if (!m) continue;
  2766. p.add(m[2]);
  2767. if (p.size >= 3) break;
  2768. if(!u) u = m[2];
  2769. else if(p.size === 2 && u && u=== m[2]) break;
  2770. result.add(s);
  2771. }
  2772. return [...result].join('\n');
  2773. }
  2774.  
  2775. if (FIX_bind_self_this && !Function.prototype.bind488 && !Function.prototype.bind588) {
  2776. // window.m3bb = new Set();
  2777.  
  2778. // const smb = Symbol();
  2779. const vmb = 'dtz02' // Symbol(); // return kThis for thisArg
  2780. const vmc = 'dtz04' // Symbol(); // whether it is proxied fn
  2781. const vmd = 'dtz08' // Symbol(); // self fn proxy (fn--fn)
  2782.  
  2783. const thisConversionFn = (thisArg) => {
  2784. if (!thisArg) return null;
  2785. const kThis = thisArg[vmb];
  2786. if (kThis) {
  2787. const ref = kThis.ref;
  2788. return (ref ? kRef(ref) : null) || null;
  2789. }
  2790. return thisArg;
  2791. }
  2792.  
  2793. const pFnHandler2 = {
  2794. get(target, prop) {
  2795. if (prop === vmc) return target;
  2796. return Reflect.get(target, prop);
  2797. },
  2798. apply(target, thisArg, argumentsList) {
  2799. thisArg = thisConversionFn(thisArg);
  2800. if (thisArg) return Reflect.apply(target, thisArg, argumentsList);
  2801. }
  2802. }
  2803.  
  2804.  
  2805. const proxySelfHandler = {
  2806. get(target, prop) {
  2807. if(prop === vmb) return target;
  2808. const ref = target.ref;
  2809. const cnt = kRef(ref);
  2810. if (!cnt) return;
  2811. if (typeof cnt[prop] === 'function' && !cnt[prop][vmc] && !cnt[prop][vmb]) {
  2812. if (!cnt[prop][vmd]) cnt[prop][vmd] = new Proxy(cnt[prop], pFnHandler2);
  2813. return cnt[prop][vmd];
  2814. }
  2815. return cnt[prop];
  2816. },
  2817. set(target, prop, value) {
  2818. const cnt = kRef(target.ref);
  2819. if (!cnt) return true;
  2820. if(value && (value[vmc] || value[vmb])){
  2821. cnt[prop] = value[vmc] || thisConversionFn(value);
  2822. return true;
  2823. }
  2824. cnt[prop] = value;
  2825. return true;
  2826. }
  2827. };
  2828.  
  2829. const weakWrap = (thisArg) => {
  2830. thisArg = thisConversionFn(thisArg);
  2831. if (!thisArg) {
  2832. console.error('thisArg is not found');
  2833. return null;
  2834. }
  2835. return new Proxy({ ref: mWeakRef(thisArg) }, proxySelfHandler);
  2836. }
  2837.  
  2838. if (!window.getComputedStyle533 && typeof window.getComputedStyle === 'function') {
  2839. window.getComputedStyle533 = window.getComputedStyle;
  2840. window.getComputedStyle = function (a, ...args) {
  2841. a = thisConversionFn(a);
  2842. if (a) {
  2843. return getComputedStyle533(a, ...args);
  2844. }
  2845. return null;
  2846. }
  2847. }
  2848.  
  2849. Function._count_bind_00 = 0;
  2850. // Function._count_bind_01 = 0;
  2851.  
  2852. // let matchNativeCode = (Object+"");
  2853. // let matchNativeCode1 = matchNativeCode.includes("[native code]");
  2854. // let matchNativeLen = matchNativeCode.length - Object.name.length;
  2855.  
  2856. // const matchConstructor = (thisArg) => {
  2857. // const f = `${(thisArg || 0).constructor}`;
  2858. // if (f.length > 45) return true;
  2859. // if (matchNativeCode1 && f.length - thisArg.constructor.name.length === matchNativeLen) {
  2860. // if (f.includes('[native code]')){
  2861. // return false;
  2862. // }
  2863. // return true;
  2864. // }
  2865. // return false;
  2866. // }
  2867.  
  2868. // const acceptThis = (thisArg)=>{
  2869. // // if(!thisArg || typeof thisArg !=='object') return false;
  2870. // // // if((((thisArg||0).constructor||0).name || 'XXXXXXXX').length < 3) return true;
  2871. // // if(typeof thisArg.path === 'string') return true;
  2872. // // if(typeof thisArg.fn === 'function') return true;
  2873. // // if(typeof thisArg.id === 'string') return true;
  2874. // // if(typeof thisArg.isLoaded === 'boolean') return true;
  2875. // return false;
  2876. // }
  2877.  
  2878. const patchFn = (fn) => {
  2879.  
  2880. let s = `${fn}`;
  2881. if (s.length < 11 || s.includes('\n')) return false;
  2882. if(s.includes('bind(this')) return true;
  2883. if(s.includes('=this') && /[,\s][a-zA-Z_][a-zA-Z0-9_]*=this[;,]/.test(s) ) return true;
  2884. // var a=this;
  2885. // f.bind(this)
  2886.  
  2887.  
  2888. return false;
  2889. }
  2890.  
  2891. Function.prototype.bind488 = Function.prototype.bind;
  2892. Function.prototype.bind = function(thisArg, ...args){
  2893.  
  2894. if (thisConversionFn(thisArg) !== thisArg) {
  2895. return this.bind488(thisArg, ...args);
  2896. }
  2897. if( thisArg && patchFn(this) ){
  2898.  
  2899. // console.log(599,`${this}`)
  2900.  
  2901. try {
  2902. // let b1 = thisArg && typeof thisArg === 'object' && typeof thisArg.isAttached === 'boolean' && !thisArg.dtz06; // ready cnt
  2903. // let b2 = !b1 && thisArg && (thisArg instanceof Node) && typeof thisArg.nodeName === 'string' && !thisArg.dtz06; // dom
  2904. // let b3 = !b1 && !b2 && thisArg && typeof thisArg === 'object' && typeof thisArg.is === 'string' && !thisArg.dtz06; // init stage ?
  2905. // // let b4 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && matchConstructor(thisArg);
  2906. // // let b5 = !b1 && !b2 && !b3 && !b4 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && acceptThis(thisArg);
  2907. // // let b5 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && !(thisArg instanceof Window);
  2908. // // let b4 = false;
  2909. // let b4 = !b1 && !b2 && !b3 && thisArg && !thisArg.dtz06;
  2910.  
  2911. // // b3 = false;
  2912. // // b4 = false;
  2913. // // b5 = false;
  2914.  
  2915. // if (b1 || b2 || b3 ||b4 ) {
  2916. const f = this;
  2917. const ps = thisArg.__proxySelf0__ || (thisArg.__proxySelf0__ = weakWrap(thisArg));
  2918. if (ps && ps[vmb]) {
  2919. Function._count_bind_00++;
  2920. return f.bind488(ps, ...args)
  2921. }
  2922. // }
  2923. } catch (e) {
  2924. console.warn(e)
  2925. }
  2926. }
  2927. return this.bind488(thisArg, ...args);
  2928. }
  2929. Function.prototype.bind588 = 1;
  2930. }
  2931.  
  2932. const ytSchedulerMethods = {
  2933. addJob(a, b, c) {
  2934. const instance = typeof yt !== 'undefined' ? ((yt || 0).scheduler || 0).instance : null;
  2935. if (instance) {
  2936. return instance.addJob(a, b, c);
  2937. } else {
  2938. return setTimeout(a, c);
  2939. }
  2940. },
  2941. addImmediateJob(a) {
  2942. const instance = typeof yt !== 'undefined' ? ((yt || 0).scheduler || 0).instance : null;
  2943. if (instance) {
  2944. return instance.addImmediateJob(a);
  2945. } else {
  2946. a();
  2947. }
  2948. },
  2949. cancelJob(id) {
  2950. const instance = typeof yt !== 'undefined' ? ((yt || 0).scheduler || 0).instance : null;
  2951. if (instance) {
  2952. return instance.cancelJob(id);
  2953. } else {
  2954. return clearTimeout(id);
  2955. }
  2956. }
  2957. };
  2958.  
  2959. if (FIX_ytScheduler) {
  2960.  
  2961. let ytSchedulerFixed = 0;
  2962. // let ytActioned = false;
  2963. // let pr = new PromiseExternal();
  2964.  
  2965. // const hn = function () {
  2966.  
  2967. // document.removeEventListener('yt-action', hn, true);
  2968. // nextBrowserTick_(() => {
  2969. // ytActioned = true;
  2970. // pr.resolve();
  2971. // });
  2972.  
  2973. // }
  2974. // document.addEventListener('yt-action', hn, true);
  2975.  
  2976. // let cancelStore = {}; // tbc
  2977.  
  2978. // yt.scheduler.instance.addJob
  2979. const fixAddJob = (nv) => {
  2980.  
  2981. /*
  2982. function Z() {
  2983. var a = w("ytglobal.schedulerInstanceInstance_");
  2984. if (!a || a.s)
  2985. a = new M(I("scheduler") || {}),
  2986. x("ytglobal.schedulerInstanceInstance_", a);
  2987. return a
  2988. }
  2989. */
  2990.  
  2991. /*
  2992. function R(a, b, c, d) {
  2993. ++a.D;
  2994. if (c === 10)
  2995. return P(a, b),
  2996. a.D;
  2997. var e = a.D;
  2998. a.h[e] = b;
  2999. a.l && !d ? a.u.push({
  3000. id: e,
  3001. priority: c
  3002. }) : (a.i[c].push(e),
  3003. a.C || a.l || (a.g !== 0 && S(a) !== a.m && T(a),
  3004. a.start()));
  3005. return e
  3006. }
  3007. */
  3008.  
  3009. /*
  3010. function sa(a, b, c) {
  3011. if (!c)
  3012. return c = c === void 0,
  3013. -R(Z(), a, b, c);
  3014. var d = window.setTimeout(function() {
  3015. var e = R(Z(), a, b);
  3016. W[d] = e
  3017. }, c);
  3018. return d
  3019. }
  3020. */
  3021. window.originalAddJob = nv;
  3022. // const q1 = new PromiseExternal();
  3023. // const q2 = new PromiseExternal();
  3024. // let uu = 0;
  3025. // let q3 = 0;
  3026. // let mof = null;
  3027. // const mo = new MutationObserver((mutation, observer) => {
  3028. // if (mof) {
  3029. // if (mof() === true) {
  3030. // observer.disconnect();
  3031. // mof = null;
  3032. // }
  3033. // }
  3034. // });
  3035.  
  3036. let lenSkip = -1;
  3037. let lastLen = null;
  3038. let fetchCommentJobTimerId = 0;
  3039. let requestFinish = false;
  3040.  
  3041. const fetchCommentJobDone = ()=>{
  3042. clearInterval(fetchCommentJobTimerId);
  3043. fetchCommentJobTimerId = 0;
  3044. console.log('[yt-js-engine-tamer] fetchCommentJob done');
  3045. }
  3046.  
  3047. const fetchCommentJob = (a, cid) => {
  3048.  
  3049. // if (cid && cancelStore[cid]) return; // tbc
  3050.  
  3051. if(fetchCommentJobTimerId > 0){
  3052. fetchCommentJobDone();
  3053. }
  3054.  
  3055. // if (mof) {
  3056. // console.log('[yt-js-engine-tamer] fetchCommentJob done');
  3057. // mof = null;
  3058. // }
  3059.  
  3060. let f = a;
  3061.  
  3062. const selector = 'ytd-comments, ytd-comments > *, ytd-comments [id] > *, ytd-comments ytd-continuation-item-renderer';
  3063.  
  3064. console.log('[yt-js-engine-tamer] fetchCommentJob start');
  3065.  
  3066. lastLen = -1;
  3067. let u = 0;
  3068. let g = () => {
  3069. if (requestFinish) lastLen = -1;
  3070. const lastLen_ = lastLen;
  3071. const len1 = lastLen = document.querySelectorAll(selector).length;
  3072. let mm = true;
  3073. let ff = false;
  3074. if (len1 !== lastLen_) {
  3075. u = 0;
  3076. f();
  3077. const len2 = lastLen = document.querySelectorAll(selector).length;
  3078. if (len2 !== len1) {
  3079. ff = true;
  3080. mm = false;
  3081. }
  3082. }
  3083. if (mm) {
  3084. ++u;
  3085. if (u > 10 || document.querySelector('ytd-comments:not([hidden]) [id]')) {
  3086. ff = true;
  3087. }
  3088. }
  3089.  
  3090. if (requestFinish) {
  3091. requestFinish = false;
  3092. fetchCommentJobDone();
  3093. } else if (ff){
  3094. fetchCommentJobDone();
  3095. }
  3096.  
  3097. }
  3098.  
  3099.  
  3100. fetchCommentJobTimerId = setInterval(g, 80);
  3101. // g(9);
  3102. // if (lastLen === lenSkip) {
  3103. // console.log('[yt-js-engine-tamer] fetchCommentJob done');
  3104. // g = f = null;
  3105. // return;
  3106. // }
  3107. // console.log('[yt-js-engine-tamer] fetchCommentJob done');
  3108. // const q1 = lastLen;
  3109. // mof = () => {
  3110. // const q2 = document.querySelectorAll(selector).length;
  3111. // if (q1 === q2) return;
  3112. // fetchCommentJobTimerId = setTimeout(g, 80);
  3113. // g = null;
  3114. // return true;
  3115. // }
  3116. // mo.observe(document, { childList: true, subtree: true });
  3117.  
  3118. }
  3119.  
  3120. // let pr72 = Promise.resolve();
  3121.  
  3122.  
  3123. let qa = null;
  3124. let qasf = '';
  3125.  
  3126.  
  3127. document.addEventListener("fullscreenchange", (evt) => {
  3128. if (evt.isTrusted !== true) return;
  3129. if (qa) {
  3130. // qa();
  3131. nextBrowserTick_(qa);
  3132. }
  3133. // const pr = new Promise(resolve => { setTimeout(resolve, 94.25) });
  3134. // pr72 = pr72.then(() => {
  3135. // return pr
  3136. // });
  3137. }, true);
  3138.  
  3139. window.addEventListener("resize", (evt) => {
  3140. if (evt.isTrusted !== true) return;
  3141. if (qa) {
  3142. // qa();
  3143. nextBrowserTick_(qa);
  3144. }
  3145. // const pr = new Promise(resolve => { setTimeout(resolve, 94.25) });
  3146. // pr72 = pr72.then(() => {
  3147. // return pr
  3148. // });
  3149. }, true);
  3150.  
  3151.  
  3152. setInterval(() => {
  3153. const f = qa;
  3154. if (typeof f !== 'function') return;
  3155. qa = null;
  3156. // pr72 = pr72.then(() => {
  3157. // f();
  3158. // });
  3159. // nextBrowserTick_(()=>{
  3160. f();
  3161. // });
  3162. }, 475.25);
  3163.  
  3164.  
  3165.  
  3166. return function (a, b, c) {
  3167.  
  3168.  
  3169. const f = a;
  3170. // const g = ()=>{
  3171. // pr72 = pr72.then(()=>{
  3172. // f();
  3173. // });
  3174. // }
  3175.  
  3176. if (!c) return arguments.length < 3 ? nv(f, b) : nv(f, b, c);
  3177.  
  3178. const c_ = c;
  3179.  
  3180. if (c > 0.25 && (c % 1) === 0) c -= 0.125;
  3181.  
  3182. if (b === 1 && c_ === 500) {
  3183. const sf = `${a}`;
  3184. if (qasf ? (sf === qasf) : (sf.includes('.mediaElement') && sf.includes('.getCurrentTime') && sf.includes('.seekTo'))) {
  3185. qasf = sf;
  3186. qa = a;
  3187. // console.log(12883, a)
  3188. return nv(() => {
  3189. if (qa === a) {
  3190. qa = null;
  3191. a();
  3192. }
  3193. }, b, c);
  3194. }
  3195. }
  3196.  
  3197.  
  3198. if (!b && c_ === 5000 && `${a}`.includes('.cleanupJob=0')) {
  3199. // console.log('[yt-js-engine-tamer] cleanupJob 01');
  3200. // const pr = new Promise(resolve => { setTimeout(resolve, 94.25) });
  3201. // pr72 = pr72.then(() => {
  3202. // return pr
  3203. // });
  3204. // try {
  3205. // yt.scheduler.instance.cancelAllJobs();
  3206. // yt.scheduler.instance.dispose();
  3207. // if(ytglobal.schedulerInstanceInstance_) ytglobal.schedulerInstanceInstance_.dispose();
  3208. // console.log('[yt-js-engine-tamer] cleanupJob 02');
  3209. // } catch (e) { }
  3210. return nv(f, b, c);
  3211. }
  3212.  
  3213. // if(!b && c > 50) c = 50;
  3214. // console.log(58372,a,b,c)
  3215. // function(){xxx(xxx)}
  3216. if (!b && c_ === 1000 && `${a}`.length <= 20 && a.name === '' && /function\(\)\{\w{1,3}\(\w{1,3}\)\}/.test(`${a}`)) {
  3217.  
  3218. /*
  3219.  
  3220. V.setCommentsJobId = _.et(_.r0, function() {
  3221. F5V(V)
  3222. }, 1E3)
  3223.  
  3224. */
  3225.  
  3226. requestFinish = false;
  3227. const cid = nv(() => { if(fetchCommentJobTimerId > 0) requestFinish = true;}, b, 1000);
  3228.  
  3229. // lastLen = null;
  3230. fetchCommentJob(a, cid);
  3231.  
  3232. // queueMicrotask_(a);
  3233. // nextBrowserTick_(a);
  3234. // a(); // no need to delay
  3235. return cid
  3236.  
  3237. // return nv(a, b, 1.125);
  3238. // const cid = window.setTimeout(() => {
  3239. // nextBrowserTick_(() => {
  3240. // if (cancelStore[cid]) {
  3241. // console.log('task cancelled');
  3242. // return;
  3243. // }
  3244. // a();
  3245.  
  3246. // });
  3247. // }, 0.125);
  3248. // return cid;
  3249. } else {
  3250.  
  3251.  
  3252.  
  3253. return nv(f,b,c);
  3254.  
  3255.  
  3256. // if (c > 2400) c = 2400;
  3257. // else if (c > 800) c = 800;
  3258. // if (c > 0.2 && (c % 1) === c) c -= 0.125;
  3259. // if (0 && ytActioned && !b) {
  3260. // const cid = window.setTimeout(() => {
  3261. // nextBrowserTick_(() => {
  3262. // if (cancelStore[cid]) {
  3263. // console.log('task cancelled');
  3264. // return;
  3265. // }
  3266. // a();
  3267. // });
  3268. // }, c);
  3269. // return cid;
  3270. // } else {
  3271. // return nv(a, b, c);
  3272. // }
  3273.  
  3274. }
  3275. }
  3276. }
  3277.  
  3278. const fixCancelJob = (nv) => {
  3279.  
  3280.  
  3281. window.originalCancelJob = nv;
  3282. return function (a) {
  3283. if (a < 0) return nv(a);
  3284. // cancelStore[a] = true; // tbc
  3285. nv(a);
  3286. }
  3287. }
  3288.  
  3289. const sk44 = Symbol();
  3290. Object.defineProperty(Object.prototype, 'addJob', {
  3291. get() {
  3292. return this[sk44];
  3293. },
  3294. set(nv) {
  3295. if (typeof nv === 'function' && !(ytSchedulerFixed & 1) && typeof yt !== 'undefined' && this === ((yt || 0).scheduler || 0).instance) {
  3296. ytSchedulerFixed |= 1;
  3297. nv = fixAddJob(nv);
  3298. }
  3299. this[sk44] = nv;
  3300. return true;
  3301. },
  3302. enumerable: false,
  3303. configurable: true
  3304. });
  3305.  
  3306.  
  3307.  
  3308. const sk45 = Symbol();
  3309. Object.defineProperty(Object.prototype, 'cancelJob', {
  3310. get() {
  3311. return this[sk45];
  3312. },
  3313. set(nv) {
  3314. if (typeof nv === 'function' && !(ytSchedulerFixed & 2) && typeof yt !== 'undefined' && this === ((yt || 0).scheduler || 0).instance) {
  3315. ytSchedulerFixed |= 2;
  3316. nv = fixCancelJob(nv);
  3317. }
  3318. this[sk45] = nv;
  3319. return true;
  3320. },
  3321. enumerable: false,
  3322. configurable: true
  3323. });
  3324.  
  3325.  
  3326.  
  3327. if (typeof yt !== 'undefined' && this === ((yt || 0).scheduler || 0).instance) {
  3328. const { addJob, cancelJob } = yt.scheduler.instance;
  3329. if (addJob) {
  3330. yt.scheduler.instance.addJob = null;
  3331. yt.scheduler.instance.addJob = addJob;
  3332. }
  3333. if (cancelJob) {
  3334. yt.scheduler.instance.cancelJob = null;
  3335. yt.scheduler.instance.cancelJob = cancelJob;
  3336. }
  3337. }
  3338.  
  3339.  
  3340. }
  3341.  
  3342. const isWatchPageURL = (url) => {
  3343. url = url || location;
  3344. return location.pathname === '/watch' || location.pathname.startsWith('/live/')
  3345. };
  3346.  
  3347. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  3348.  
  3349. const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
  3350. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  3351. if (typeof customElements === 'undefined') {
  3352. if (!('__CE_registry' in document)) {
  3353. // https://github.com/webcomponents/polyfills/
  3354. Object.defineProperty(document, '__CE_registry', {
  3355. get() {
  3356. // return undefined
  3357. },
  3358. set(nv) {
  3359. if (typeof nv == 'object') {
  3360. delete this.__CE_registry;
  3361. this.__CE_registry = nv;
  3362. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  3363. }
  3364. return true;
  3365. },
  3366. enumerable: false,
  3367. configurable: true
  3368. })
  3369. }
  3370. let eventHandler = (evt) => {
  3371. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  3372. const f = callback;
  3373. callback = null;
  3374. eventHandler = null;
  3375. f();
  3376. };
  3377. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  3378. } else {
  3379. callback();
  3380. }
  3381. });
  3382.  
  3383. const whenCEDefined = isCustomElementsProvided
  3384. ? (nodeName) => customElements.whenDefined(nodeName)
  3385. : (nodeName) => promiseForCustomYtElementsReady.then(() => customElements.whenDefined(nodeName));
  3386.  
  3387. FIX_perfNow && performance.timeOrigin > 9 && (() => {
  3388. if (performance.now23 || performance.now16 || typeof Performance.prototype.now !== 'function') return;
  3389. const f = performance.now23 = Performance.prototype.now;
  3390.  
  3391. let k = 0; // 0 <= k < 9998m
  3392. let u = 0;
  3393. let s = ((performance.timeOrigin % 7) + 1) / 7 - 1e-2 / 7; // s > 0.14
  3394.  
  3395. // By definition, performance.now() is mono increasing.
  3396. // Fixing in YouTube.com is required to ensure performance.now() is strictly increasing.
  3397. performance.now = performance.now16 = function () {
  3398. /**
  3399. * Bug 1842437 - When attempting to go back on youtube.com, the content remains the same
  3400. *
  3401. * If consecutive session history entries had history.state.entryTime set to same value,
  3402. * back button doesn't work as expected. The entryTime value is coming from performance.now()
  3403. * and modifying its return value slightly to make sure two close consecutive calls don't
  3404. * get the same result helped with resolving the issue.
  3405. */
  3406. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  3407. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1842437
  3408.  
  3409. const v = typeof (this || 0).now23 === 'function' ? this.now23() + s : f.call(performance) + s; // v > 0.14
  3410. if (u + 0.0015 < (u = v)) k = 0; // note: hRes should be accurate to 5 µs in isolated contexts
  3411. else if (k < 0.001428) k += 1e-6 / 7; // M = 10000 * m; m * 9996 = 0.001428
  3412. else { // more than 9998 consecutive calls
  3413. /**
  3414. *
  3415. * max no. of consecutive calls
  3416. *
  3417. * Sample Size: 4800
  3418. * Sample Avg = 1565.375
  3419. * Sample Median = 1469.5
  3420. * Sample Max = 5660 << 7500 << 9999
  3421. *
  3422. *
  3423. * */
  3424. k = 0;
  3425. s += 1 / 7;
  3426. }
  3427. return v + k; // 0 < v - M < v - M + k < v
  3428. }
  3429.  
  3430. let loggerMsg = '';
  3431. if (`${performance.now()}` === `${performance.now()}`) {
  3432. const msg1 = 'performance.now is modified but performance.now() is not strictly increasing.';
  3433. const msg2 = 'performance.now cannot be modified and performance.now() is not strictly increasing.';
  3434. loggerMsg = performance.now !== performance.now16 ? msg1 : msg2; // might not able to set in Firefox
  3435. }
  3436. loggerMsg && console.warn(loggerMsg);
  3437. })();
  3438.  
  3439. // let __forceRemoveMode__ = false;
  3440. FIX_removeChild && (() => {
  3441. if (typeof Node.prototype.removeChild === 'function' && typeof Node.prototype.removeChild062 !== 'function') {
  3442. let internalByPass = false;
  3443. const fragD = document.createDocumentFragment();
  3444. fragD.appendChild4201 = fragD.appendChild;
  3445. fragD.removeChild4201 = fragD.removeChild;
  3446. Node.prototype.removeChild062 = Node.prototype.removeChild;
  3447. Node.prototype.removeChild = function (child) {
  3448. try {
  3449. return this.removeChild062(child);
  3450. } catch (e) { }
  3451. if (internalByPass) return child;
  3452. if (this instanceof Node && child instanceof Node && this.nodeType === 11 && child.parentNode !== this && this.contains(child)) { // eg. child = DOM-IF
  3453. let idx = (this.childNodes || 0).length >= 1 ? this.childNodes.indexOf(child) : -1;
  3454. if (idx >= 0) {
  3455. internalByPass = true;
  3456. child.parentNode !== fragD && fragD.appendChild4201(child);
  3457. this.childNodes[idx] === child && typeof this.childNodes.splice === 'function' && this.childNodes.splice(idx, 1);
  3458. fragD.removeChild4201(child);
  3459. internalByPass = false;
  3460. return child;
  3461. }
  3462. }
  3463. // if (this instanceof Node && child instanceof Node && child.parentNode && child.parentNode.nodeType === 11 && child.parentNode !== this && !this.contains(child)) {
  3464. // // force removal
  3465. // internalByPass = true;
  3466. // child.parentNode !== fragD && fragD.appendChild4201(child);
  3467. // fragD.removeChild4201(child);
  3468. // internalByPass = false;
  3469. // return child;
  3470. // }
  3471. if (this && child) {
  3472. if (this.childNodes && this.childNodes.splice) { // tbc
  3473. let idx = (this.childNodes || 0).length >= 1 ? this.childNodes.indexOf(child) : -1;
  3474. if (idx >= 0) {
  3475. internalByPass = true;
  3476. child.parentNode !== fragD && fragD.appendChild4201(child);
  3477. this.childNodes[idx] === child && typeof this.childNodes.splice === 'function' && this.childNodes.splice(idx, 1);
  3478. fragD.removeChild4201(child);
  3479. internalByPass = false;
  3480. return child;
  3481. }
  3482. }
  3483.  
  3484. if (child.parentNode !== this && child.parentNode && child.parentNode === child.__shady_parentNode && child.parentNode.nodeType === 11) {
  3485. if (child.isConnected === false && (this.compareDocumentPosition(child) & (1 | 8 | 16)) === 1) {
  3486. // just ignore (!e.root && a.localName !== "slot" || f === a.__shady_native_parentNode) && f.__shady_native_removeChild(a));
  3487. return child;
  3488. }
  3489. }
  3490.  
  3491. if (child && child.is === 'tp-yt-paper-tooltip' && !child.parentNode && !child.__shady_parentNode) {
  3492. // skip
  3493. return child;
  3494. }
  3495.  
  3496. console.warn('[yt-js-engine-tamer] Node is not removed from parent', {
  3497. parent: this, child: child,
  3498. isParent: child.parentNode === this,
  3499. isParentParent: (child.parentNode || 0).parentNode === this,
  3500. parentNode: child.parentNode,
  3501. shadyParent: child.__shady_parentNode,
  3502. isShadyParent: child.__shady_parentNode === this,
  3503. isAncestor: this instanceof Node && child instanceof Node && this.contains(child)
  3504. });
  3505.  
  3506. }
  3507. return child;
  3508. }
  3509. }
  3510. })();
  3511.  
  3512.  
  3513. FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS && !isChatRoomURL && (() => {
  3514.  
  3515. const [setIntervalX0, clearIntervalX0] = [setInterval, clearInterval];
  3516.  
  3517. // let cid = 0;
  3518.  
  3519. let mousemoveFn = null;
  3520. let mousemoveDT = 0;
  3521. let mousemoveCount = 0;
  3522. // let qv = false;
  3523. const cif = () => {
  3524. if (!mousemoveFn) return;
  3525. const ct = Date.now();
  3526. if (mousemoveDT + 1200 > ct) { // avoid setTimeout delay too long without execution
  3527. mousemoveFn && mousemoveFn();
  3528. }
  3529. mousemoveFn = null;
  3530. };
  3531. let mousemoveCId = 0;
  3532. let mouseoverFn = null;
  3533. HTMLElement_.prototype.addEventListener4882 = HTMLElement_.prototype.addEventListener;
  3534. HTMLElement_.prototype.addEventListener = function (a, b, c) {
  3535. if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) {
  3536. const bt = `${b}`;
  3537. if (bt.length >= 61 && bt.length <= 71 && bt.startsWith('function(){try{return ') && bt.includes('.apply(this,arguments)}catch(')) {
  3538. b[`__$$${a}$$1926__`] = true;
  3539. this[`__$$${a}$$1937__`] = (this[`__$$${a}$$1937__`] || 0) + 1;
  3540. if (this[`__$$${a}$$1937__`] > 1073741823) this[`__$$${a}$$1937__`] -= 536870911;
  3541. // console.log(3928, a, this[`__$$${a}$$1937__`])
  3542. if (!this[`__$$${a}$$1938__`]) {
  3543. this[`__$$${a}$$1938__`] = b;
  3544. if (a === 'mousemove') {
  3545. this.addEventListener4882('mouseenter', (evt) => {
  3546. if (mousemoveCId) return;
  3547. mousemoveCId = setIntervalX0(cif, 380);
  3548. });
  3549. this.addEventListener4882('mouseleave', (evt) => {
  3550. clearIntervalX0(mousemoveCId);
  3551. mousemoveCId = 0;
  3552. });
  3553. }
  3554. this.addEventListener4882(a, (evt) => {
  3555. const evt_ = evt;
  3556. if (!this[`__$$${a}$$1937__`]) return;
  3557. if (!this[`__$$${a}$$1938__`]) return;
  3558. if (a === 'mousemove') {
  3559. mouseoverFn && mouseoverFn();
  3560. if (mousemoveDT + 350 > (mousemoveDT = Date.now())) {
  3561. (++mousemoveCount > 1e9) && (mousemoveCount = 9);
  3562. } else {
  3563. mousemoveCount = 0;
  3564. }
  3565. const f = mousemoveFn = () => {
  3566. if (f !== mousemoveFn) return;
  3567. mousemoveFn = null;
  3568. this[`__$$${a}$$1938__`](evt_);
  3569. };
  3570. if (mousemoveCount <= 1) mousemoveFn();
  3571. } else {
  3572. if (a === 'mouseout' || a === 'mouseleave') {
  3573. mousemoveFn = null;
  3574. mousemoveDT = 0;
  3575. mousemoveCount = 0;
  3576. this[`__$$${a}$$1938__`](evt_);
  3577. mouseoverFn && mouseoverFn();
  3578. } else { // mouseover, mouseenter
  3579. mousemoveFn = null;
  3580. mousemoveDT = 0;
  3581. mousemoveCount = 0;
  3582. mouseoverFn && mouseoverFn(); // just in case
  3583. const f = mouseoverFn = () => {
  3584. if (f !== mouseoverFn) return;
  3585. mouseoverFn = null;
  3586. this[`__$$${a}$$1938__`](evt_);
  3587. }
  3588. nextBrowserTick_(mouseoverFn);
  3589. }
  3590. }
  3591. }, c);
  3592.  
  3593.  
  3594. return;
  3595. } else {
  3596.  
  3597. return;
  3598. }
  3599. }
  3600.  
  3601. }
  3602. return this.addEventListener4882(a, b, c)
  3603. }
  3604.  
  3605.  
  3606.  
  3607.  
  3608. HTMLElement_.prototype.removeEventListener4882 = HTMLElement_.prototype.removeEventListener;
  3609. HTMLElement_.prototype.removeEventListener = function (a, b, c) {
  3610. if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) {
  3611.  
  3612. if (b[`__$$${a}$$1926__`]) {
  3613. b[`__$$${a}$$1926__`] = false;
  3614.  
  3615. if (this[`__$$${a}$$1937__`]) this[`__$$${a}$$1937__`] -= 1;
  3616.  
  3617. // console.log(3929, a, this[`__$$${a}$$1937__`], b[`__$$${a}$$1926__`])
  3618.  
  3619. return;
  3620.  
  3621. }
  3622.  
  3623. }
  3624. return this.removeEventListener4882(a, b, c)
  3625. }
  3626.  
  3627.  
  3628. })();
  3629.  
  3630.  
  3631. FIX_DOM_IF_REPEAT && (() => {
  3632. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  3633. // DOM-IF is still a core class of Polymer, so no polymerController is available.
  3634. // Be careful of the mixture of polymer functions and native Element functions
  3635. // Be careful of the coding design is different with the modern Yt elements
  3636.  
  3637.  
  3638. /*
  3639.  
  3640.  
  3641. function Ks(a, b, c) {
  3642. if (kj && !BOa(a))
  3643. throw Error("strictTemplatePolicy: template owner not trusted");
  3644. c = c || {};
  3645. if (a.__templatizeOwner)
  3646. throw Error("A <template> can only be templatized once");
  3647. a.__templatizeOwner = b;
  3648. var d = (b ? b.constructor : Js)._parseTemplate(a)
  3649. , e = d.templatizeInstanceClass;
  3650. e || (e = COa(a, d, c),
  3651. d.templatizeInstanceClass = e);
  3652. var g = BOa(a);
  3653. EOa(a, d, c, g);
  3654. c = function() {
  3655. return e.apply(this, arguments) || this
  3656. }
  3657. ;
  3658. h(c, e);
  3659. c.prototype._methodHost = g;
  3660. c.prototype.__dataHost = a;
  3661. c.prototype.__templatizeOwner = b;
  3662. c.prototype.__hostProps = d.hostProps;
  3663. return c
  3664. }
  3665.  
  3666. */
  3667.  
  3668. // Polymer.enqueueDebouncer
  3669.  
  3670. const s81 = Symbol();
  3671. const s83 = Symbol();
  3672. const s84 = Symbol();
  3673. const s85 = Symbol();
  3674. const s85b = Symbol();
  3675. const s85c = Symbol();
  3676.  
  3677. let renderDebounceTs = null;
  3678.  
  3679. let renderDebouncePromise = null;
  3680. let qp;
  3681.  
  3682. const shadyFlushMO = new MutationObserver(() => {
  3683.  
  3684. if (!renderDebounceTs) return;
  3685.  
  3686. if (renderDebounceTs.size > 0) {
  3687. console.warn('renderDebounceTs.size is incorect', renderDebounceTs.size);
  3688. try {
  3689. Polymer.flush();
  3690. return;
  3691. } catch (e) { }
  3692. }
  3693.  
  3694. renderDebouncePromise && Promise.resolve().then(() => {
  3695.  
  3696. if (renderDebouncePromise) {
  3697. renderDebouncePromise && renderDebouncePromise.resolve();
  3698. renderDebouncePromise = null;
  3699. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by MutationObserver')
  3700. }
  3701.  
  3702. });
  3703.  
  3704. // Polymer.flush
  3705.  
  3706. window.ShadyDOM && ShadyDOM.flush();
  3707. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  3708.  
  3709.  
  3710. });
  3711.  
  3712. const setupPolymerAdv = () => {
  3713. // here we can obtain the Polymer faster.
  3714. // reserved for future use.
  3715. }
  3716.  
  3717.  
  3718. if (USE_fastDomIf) {
  3719. // 0 = no effect. 1 = enable. 2 = disable
  3720. // fastDomIf because it delayed the rendering process?
  3721. Object.defineProperty(Object.prototype, 'fastDomIf', {
  3722. get() {
  3723. if (this === window.Polymer) {
  3724. const v = USE_fastDomIf === 1 ? true : false;
  3725. this.fastDomIf = v;
  3726. delete Object.prototype.fastDomIf;
  3727. setupPolymerAdv(this);
  3728. return v;
  3729. }
  3730. },
  3731. set(nv) {
  3732. return false;
  3733. }
  3734. });
  3735. }
  3736.  
  3737. let setupDomIfDone = false;
  3738. const setupDomIf = (DomIf)=>{
  3739. setupDomIfDone = true;
  3740. if(setupDomIfDone) return;
  3741.  
  3742. const fProto = DomIf.prototype;
  3743.  
  3744.  
  3745. // Polymer.DomIf
  3746. // Polymer.DomIf = Polymer.fastDomIf ? ZbL : ESz
  3747. // Assume ESz by default
  3748.  
  3749. // We don't need to store "root" in DOM-IF
  3750. if (ENHANCE_DOMIF_createAndInsertInstance && fProto.__createAndInsertInstance && !fProto.__createAndInsertInstance239 && fProto.__createAndInsertInstance.length === 1) {
  3751. fProto.__createAndInsertInstance239 = fProto.__createAndInsertInstance;
  3752. fProto.__createAndInsertInstance = function (M) {
  3753. const r = this.__createAndInsertInstance239(M);
  3754. const __instance = this.__instance;
  3755. const __ctor = this.__ctor;
  3756. if (__instance && __ctor && __instance instanceof __ctor) {
  3757. for (const sym of Object.getOwnPropertySymbols(__instance)) {
  3758. const o = __instance[sym];
  3759. if (o && o.nodeType === 11) {
  3760. __instance[sym] = null;
  3761. }
  3762. }
  3763. }
  3764. return r;
  3765. }
  3766.  
  3767. /*
  3768.  
  3769.  
  3770. sX = function(M, d, N) {
  3771. if (o_ && !vDv(M))
  3772. throw Error("Jd");
  3773. N = N || {};
  3774. if (M.__templatizeOwner)
  3775. throw Error("Kd");
  3776. M.__templatizeOwner = d;
  3777. var R = (d ? d.constructor : jF)._parseTemplate(M)
  3778. , X = R.templatizeInstanceClass;
  3779. X || (X = sfi(M, R, N),
  3780. R.templatizeInstanceClass = X);
  3781. var A = vDv(M);
  3782. y9Z(M, R, N, A);
  3783. N = function() {
  3784. return X.apply(this, arguments) || this
  3785. }
  3786. ;
  3787. _.v(N, X);
  3788. N.prototype._methodHost = A;
  3789. N.prototype.__dataHost = M;
  3790. N.prototype.__templatizeOwner = d;
  3791. N.prototype.__hostProps = R.hostProps;
  3792. return N
  3793. }
  3794.  
  3795. */
  3796. }
  3797.  
  3798. // Polymer.DomIf
  3799. // We can fully teardown the entire instance (including stampFrag and stampNodes), just keep ctor stamper
  3800. if (ENHANCE_DOMIF_TEARDOWN && fProto.__teardownInstance && !fProto.__teardownInstance239 && fProto.__teardownInstance.length === 0) {
  3801. fProto.__teardownInstance239 = fProto.__teardownInstance;
  3802. fProto.__teardownInstance = function () {
  3803. const { __instance, __invalidProps } = this;
  3804. let r, e_;
  3805. try {
  3806. r = this.__teardownInstance239();
  3807. } catch (e) { e_ = e }
  3808. if (!__instance) return r;
  3809.  
  3810. try {
  3811.  
  3812. //console.log(599901,this.countEvent767());
  3813. //console.log('__teardownInstance F', __instance, __invalidProps, this._removeEventListenerFromNode, __instance._removeEventListenerFromNode);
  3814. __instance.__data = null;
  3815. __instance.__dataClientsReady = __instance.__dataEnabled = __instance.__dataReady = false;
  3816. __instance.__dataInvalid = true;
  3817. __instance.__dataHost = __instance.__dataTemp = null;
  3818. __instance.__isPropertyEffectsClient = false;
  3819. __instance.__keepInstance038__ = false;
  3820.  
  3821.  
  3822. const __templateInfo = __instance.__templateInfo;
  3823.  
  3824. let stampFragId = null;
  3825. if (__templateInfo && __templateInfo.nodeList) {
  3826. stampFragId = __templateInfo.nodeList.__belongFragId57__;
  3827. for (const weakNodeC of __templateInfo.nodeList) {
  3828. const node = toActualNode(weakNodeC);
  3829. if (node && node.nodeType >= 1) {
  3830. node.__keepInstance038__ = false;
  3831. node.remove();
  3832. _removedElements.addNode(node);
  3833. }
  3834. }
  3835. __templateInfo.nodeList.length = 0;
  3836. __templateInfo.nodeList = null;
  3837. }
  3838.  
  3839. const stampFrag = stampFragId ? kRef(stampedFragment.get(stampFragId)) : null;
  3840.  
  3841. if (stampFrag && stampFrag.nodeType === 11) {
  3842. stampFrag.__keepInstance038__ = false;
  3843. _removedElements.addNode(stampFrag);
  3844. removeAllChildNodes(stampFrag);
  3845. try {
  3846. stampFrag.remove();
  3847. } catch (e) { }
  3848. stampFrag.__shady = null;
  3849. stampFrag.$ = null;
  3850. stampFrag.__fragTeardowned57__ = true;
  3851. stampFrag.nodeList = null;
  3852. stampFrag.templateInfo = null;
  3853.  
  3854. }
  3855.  
  3856. for (const sym of Object.getOwnPropertySymbols(__instance)) {
  3857. const o = __instance[sym];
  3858. if (o && o.nodeType === 11) {
  3859. __instance[sym] = null;
  3860. }
  3861. }
  3862.  
  3863. const children = (__instance || 0).children;
  3864. if (children && children.splice) {
  3865. __instance.children = null;
  3866. for (const n of children) {
  3867. if (n && n.nodeType >= 1) {
  3868. n.__keepInstance038__ = false;
  3869. _removedElements.addNode(n);
  3870. }
  3871. }
  3872. children.length = 0;
  3873. }
  3874.  
  3875. if (__instance.__templateInfo) __instance.__templateInfo = null;
  3876.  
  3877. if (__instance.root) __instance.root = null;
  3878.  
  3879. } catch (e) {
  3880. console.error(e);
  3881. }
  3882.  
  3883. // console.log(3882)
  3884. if (e_) throw e_;
  3885. return r;
  3886. }
  3887. }
  3888.  
  3889. }
  3890.  
  3891. if (ENHANCE_DOMIF_createAndInsertInstance || ENHANCE_DOMIF_TEARDOWN) {
  3892.  
  3893. Object.defineProperty(Object.prototype, 'DomIf', {
  3894. get() {
  3895. return undefined;
  3896. },
  3897. set(nv) {
  3898. if (typeof (nv || 0) !== 'function') return false;
  3899. delete Object.prototype.DomIf;
  3900. this.DomIf = nv;
  3901. setupDomIf(nv);
  3902. return true;
  3903. },
  3904. enumerable: false,
  3905. configurable: true
  3906. });
  3907.  
  3908. }
  3909.  
  3910. Object.defineProperty(Object.prototype, '_lastIf', {
  3911. get() {
  3912. return this[s81];
  3913. },
  3914. set(nv) {
  3915. if (nv === false && this.nodeName === "DOM-IF" && this.__renderDebouncer === null && this[s81] === undefined) {
  3916. // DOM-IF initialization
  3917. nv = null; // avoid (this.if == this._lastIf) primitive type conversion (object vs false)
  3918.  
  3919. this.__xiWB8__ = 2;
  3920. // this.restamp = true;
  3921.  
  3922. const cProto = this.__proto__;
  3923. if (cProto && !cProto.__xiWB7__) {
  3924. cProto.__xiWB7__ = 1;
  3925.  
  3926. // dom-if __template
  3927. // dom-repeat template
  3928. if (FIX_DOM_IF_TEMPLATE && !cProto.__template && !cProto.__template847) {
  3929. cProto.__template847 = true;
  3930. try {
  3931. // note: this is not "_template" in Polymer ( see POLYMER_COMPONENT_DEFINITION )
  3932. Object.defineProperty(cProto, '__template', {
  3933. get() {
  3934. const v = this[s84];
  3935. return (typeof (v || 0) === 'object' && v.deref) ? kRef(v) : v;
  3936. },
  3937. set(nv) {
  3938. if (typeof (nv || 0) === 'object' && !nv.deref) nv = mWeakRef(nv);
  3939. this[s84] = nv;
  3940. return true;
  3941. }
  3942. });
  3943. } catch (e) {
  3944. console.warn(e);
  3945. }
  3946.  
  3947. console.log('FIX_DOM_IF - __template')
  3948. }
  3949.  
  3950. // dom-if __ensureTemplate
  3951. // dom-repeat __ensureTemplatized
  3952. if (FIX_DOM_IF_TEMPLATE && !cProto.__ensureTemplate847 && typeof cProto.__ensureTemplate === 'function' && cProto.__ensureTemplate.length === 0 && this instanceof HTMLElement_ && `${cProto.__ensureTemplate}`.length > 20) {
  3953. // note that "_templateInfo" diffs the different version of DOM-IF
  3954.  
  3955. cProto.__ensureTemplate847 = cProto.__ensureTemplate;
  3956. cProto.__ensureTemplate = function () {
  3957. if (!(this instanceof HTMLElement_) || arguments.length > 0) return this.__ensureTemplate847(...arguments);
  3958. if (!this.__template) {
  3959. let b;
  3960. if (this._templateInfo) {
  3961. b = this;
  3962. } else {
  3963. if (!this.__templateCollection011__) this.__templateCollection011__ = this.getElementsByTagName('template');
  3964. b = this.__templateCollection011__[0];
  3965. if (!b) {
  3966. if (!this[wk]) this[wk] = mWeakRef(this);
  3967. let a = this[wk];
  3968. let c = new MutationObserver(function () {
  3969. if (!this.__templateCollection011__[0]) throw Error("dom-if requires a <template> child"); // to be reviewed
  3970. if (c && a) {
  3971. c.disconnect();
  3972. a = kRef(a);
  3973. a && a.__render();
  3974. a && (a.__templateCollection011__ = null);
  3975. }
  3976. c = null;
  3977. a = null;
  3978. });
  3979. c && c.observe(this, {
  3980. childList: !0
  3981. });
  3982. return !1
  3983. } else {
  3984. this.__templateCollection011__ = null;
  3985. }
  3986. }
  3987. this.__template = b
  3988. }
  3989. return !0
  3990. }
  3991.  
  3992. console.log('FIX_DOM_IF - __ensureTemplate')
  3993.  
  3994. }
  3995.  
  3996.  
  3997. console.log('FIX_DOM_IF OK', Object.keys(cProto))
  3998. }
  3999.  
  4000.  
  4001. // need to fix __observeEffects
  4002. // this.__observeEffects.if[0].info.method === this.__debounceRender
  4003. const f = () => {
  4004.  
  4005. const __observeEffects = this.__observeEffects;
  4006.  
  4007. if (__observeEffects && __observeEffects.if && isIterable(__observeEffects.if)) {
  4008. for (const effect of __observeEffects.if) {
  4009. const info = effect.info;
  4010. if (info && typeof info.method === 'function') {
  4011.  
  4012. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  4013. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  4014. }
  4015.  
  4016. }
  4017. }
  4018. }
  4019.  
  4020.  
  4021. if (__observeEffects && __observeEffects.restamp && isIterable(__observeEffects.restamp)) {
  4022. for (const effect of __observeEffects.restamp) {
  4023. const info = effect.info;
  4024. if (info && typeof info.method === 'function') {
  4025.  
  4026. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  4027. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  4028. }
  4029.  
  4030. }
  4031. }
  4032. }
  4033.  
  4034. // console.log(5881, this.__observeEffects)
  4035. }
  4036.  
  4037. }
  4038. this[s81] = nv;
  4039. return true;
  4040. }
  4041. });
  4042.  
  4043.  
  4044. Object.defineProperty(Object.prototype, '__renderDebouncer', {
  4045. get() {
  4046. return this[s85];
  4047. },
  4048. set(nv) {
  4049. if (nv === null && this[s85] === undefined) {
  4050. // DOM-IF / DOM-REPEAT initialization
  4051.  
  4052.  
  4053. const cProto = this.__proto__;
  4054. if (qp) {
  4055. qp.obtain();
  4056. qp = null;
  4057. shadyFlushMO.observe(document.documentElement, { attributes: ['nw3a24np'] });
  4058. }
  4059.  
  4060. }
  4061. this[s85] = nv;
  4062. return true;
  4063. }
  4064. });
  4065.  
  4066. // PS-DOM-REPEAT
  4067.  
  4068. Object.defineProperty(Object.prototype, 'JSC$10034_renderDebouncer', {
  4069. get() {
  4070. return this[s85b];
  4071. },
  4072. set(nv) {
  4073.  
  4074. this[s85b] = nv;
  4075. return true;
  4076. }
  4077. })
  4078.  
  4079. Object.defineProperty(Object.prototype, 'JSC$10027_renderDebouncer', {
  4080. get() {
  4081. return this[s85c];
  4082. },
  4083. set(nv) {
  4084.  
  4085. this[s85c] = nv;
  4086. return true;
  4087. }
  4088. })
  4089.  
  4090.  
  4091. })();
  4092.  
  4093. const setupXdeadC = (cnt)=>{
  4094.  
  4095. let xdeadc = xdeadc00;
  4096. if(!xdeadc){
  4097. setupSDomWrapper(); // just in case
  4098. const hostElement = cnt.hostElement;
  4099. const el = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  4100. hostElement.insertAdjacentHTML('beforeend', ttpHTML('<!---->'));
  4101. hostElement.lastChild.replaceWith(el);
  4102. el.insertAdjacentHTML('afterbegin', ttpHTML(`<div></div>`));
  4103. const rid = `xdead_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  4104. el.firstElementChild.id = rid;
  4105. cnt.$[rid] = el.firstElementChild;
  4106. cnt.stampDomArray9682_(null, rid, null, false, false, false);
  4107.  
  4108. xdeadc = cnt.getStampContainer_(rid);
  4109. el.remove();
  4110. xdeadc00 = xdeadc;
  4111. // console.log(xdeadc.__domApi)
  4112. // debugger;
  4113. // const xdeadv = xdeadc.__domApi;
  4114. }
  4115.  
  4116. let xlivec = xlivec00;
  4117. if(!xlivec){
  4118. setupSDomWrapper(); // just in case
  4119. const hostElement = cnt.hostElement;
  4120. const el = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  4121. hostElement.insertAdjacentHTML('beforeend', ttpHTML('<!---->'));
  4122. hostElement.lastChild.replaceWith(el);
  4123. el.insertAdjacentHTML('afterbegin', ttpHTML(`<div></div>`));
  4124. const rid = `xlive_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  4125. el.firstElementChild.id = rid;
  4126. cnt.$[rid] = el.firstElementChild;
  4127. cnt.stampDomArray9682_(null, rid, null, false, false, false);
  4128.  
  4129. xlivec = cnt.getStampContainer_(rid);
  4130. xlivec00 = xlivec;
  4131. // console.log(xdeadc.__domApi)
  4132. // debugger;
  4133. // const xdeadv = xdeadc.__domApi;
  4134. }
  4135.  
  4136. return xdeadc00;
  4137. }
  4138.  
  4139. let standardWrap_ = null;
  4140.  
  4141. const setupSDomWrapper = () => {
  4142.  
  4143. const sdwProto = ShadyDOM.Wrapper.prototype;
  4144.  
  4145. if (sdwProto.__pseudo__isConnected__ !== null) {
  4146. sdwProto.__pseudo__isConnected__ = null;
  4147. const isConnectedPd = Object.getOwnPropertyDescriptor(sdwProto, 'isConnected');
  4148. if (isConnectedPd && isConnectedPd.get && isConnectedPd.configurable === true) {
  4149. const get = isConnectedPd.get;
  4150. isConnectedPd.get = function () {
  4151. const pseudoVal = this.__pseudo__isConnected__;
  4152. return typeof pseudoVal === 'boolean' ? pseudoVal : get.call(this);
  4153. }
  4154. Object.defineProperty(sdwProto, 'isConnected', { ...isConnectedPd });
  4155. }
  4156.  
  4157. // debugger;
  4158. // new xdeadc.__domApi.constructor(document.createElement('div'));
  4159. }
  4160.  
  4161. }
  4162.  
  4163. let domApiConstructor = null;
  4164. const setupDomApi = (daProto) => {
  4165.  
  4166. daProto.__daHook377__ = true;
  4167.  
  4168. domApiConstructor = daProto.constructor; // TBC
  4169.  
  4170. // TBC
  4171.  
  4172. }
  4173.  
  4174.  
  4175. // WEAKREF_ShadyDOM
  4176.  
  4177. let mightTeardownShadyDomWrap = () => { };
  4178.  
  4179. MODIFY_ShadyDOM_OBJ && ((WeakRef) => {
  4180.  
  4181. const setupPlainShadyDOM = (b) => {
  4182. (OMIT_ShadyDOM_settings & 1) && (b.inUse === true) && (b.inUse = false);
  4183. (OMIT_ShadyDOM_settings & 2) && (b.handlesDynamicScoping === true) && (b.handlesDynamicScoping = false);
  4184. (OMIT_ShadyDOM_settings & 4) && (b.force === true) && (b.force = false);
  4185. b.patchOnDemand = true;
  4186. b.preferPerformance = true;
  4187. b.noPatch = true;
  4188. }
  4189.  
  4190. const isPlainObject = (b, m) => {
  4191. if (!b || typeof b !== 'object') return false;
  4192. const e = Object.getOwnPropertyDescriptors(b);
  4193. if (e.length <= m) return false;
  4194. let pr = 0;
  4195. for (const k in e) {
  4196. const d = e[k];
  4197. if (!d || d.get || d.set || !d.enumerable || !d.configurable) return false;
  4198. if (!('value' in d) || typeof d.value === 'function') return false;
  4199. pr++;
  4200. }
  4201. return pr > m;
  4202. }
  4203.  
  4204. let b;
  4205.  
  4206. let lz = 0;
  4207.  
  4208. const sdp = Object.getOwnPropertyDescriptor(window, 'ShadyDOM');
  4209. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable) {
  4210.  
  4211. // Brave - ShadyDOM exists before userscripting
  4212. b = sdp.value;
  4213.  
  4214. if (b && typeof b === 'object' && isPlainObject(b, 0)) {
  4215. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(b);
  4216. lz = 1;
  4217. }
  4218.  
  4219. }
  4220.  
  4221.  
  4222. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable && !sdp.get && !sdp.set) {
  4223. } else if (!sdp) {
  4224. } else {
  4225. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [ PropertyDescriptor issue ]', sdp);
  4226. return;
  4227. }
  4228.  
  4229. const shadyDOMNodeWRM = new WeakMap();
  4230.  
  4231. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 01 >>', b);
  4232.  
  4233. const weakWrapperNodeHandlerFn = () => ({
  4234. get() {
  4235. const wv = this[wk];
  4236. if (typeof wv === 'undefined') return undefined;
  4237. let node = kRef(wv);
  4238. if (!node) this[wk] = undefined;
  4239. return node || undefined;
  4240. },
  4241. set(nv) {
  4242. const wv = nv ? (nv[wk] || (nv[wk] = mWeakRef(nv))) : nv;
  4243. this[wk] = wv;
  4244. return true;
  4245. },
  4246. enumerable: true,
  4247. configurable: true
  4248. });
  4249.  
  4250.  
  4251. function weakWrapper(_ShadyDOM) {
  4252. const ShadyDOM = _ShadyDOM;
  4253. if (WEAKREF_ShadyDOM && lz < 3 && typeof WeakRef === 'function' && typeof ShadyDOM.Wrapper === 'function' && ShadyDOM.Wrapper.length === 1 && typeof (ShadyDOM.Wrapper.prototype || 0) === 'object') {
  4254. let nullElement = { node: null };
  4255. Object.setPrototypeOf(nullElement, Element.prototype);
  4256. let p = new ShadyDOM.Wrapper(nullElement);
  4257. let d = Object.getOwnPropertyDescriptor(p, 'node');
  4258. if (d.configurable && d.enumerable && !d.get && !d.set && d.writable && d.value === nullElement && !Object.getOwnPropertyDescriptor(ShadyDOM.Wrapper.prototype, 'node')) {
  4259. Object.defineProperty(ShadyDOM.Wrapper.prototype, 'node', weakWrapperNodeHandlerFn());
  4260. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << WEAKREF_ShadyDOM >>')
  4261. }
  4262.  
  4263. }
  4264. if (typeof (((ShadyDOM || 0).Wrapper || 0).prototype || 0) === 'object') {
  4265. try {
  4266. setupSDomWrapper();
  4267. } catch (e) { }
  4268. }
  4269.  
  4270. }
  4271.  
  4272. let previousWrapStore = null;
  4273.  
  4274. mightTeardownShadyDomWrap = (node) => {
  4275. if (previousWrapStore) previousWrapStore.delete(node);
  4276. if (shadyDOMNodeWRM) shadyDOMNodeWRM.delete(node);
  4277. };
  4278.  
  4279. const standardWrap = function (a) {
  4280. // if(a && a.deref) a= a.deref();
  4281. if(!a) return a;
  4282. if (a instanceof ShadowRoot || a instanceof ShadyDOM.Wrapper) return a;
  4283. if (previousWrapStore) {
  4284. const s = kRef(previousWrapStore.get(a)); // kRef for play safe only
  4285. if (s) {
  4286. previousWrapStore.delete(a);
  4287. shadyDOMNodeWRM.set(a, mWeakRef(s));
  4288. }
  4289. }
  4290. let u = kRef(shadyDOMNodeWRM.get(a));
  4291. if (!u) {
  4292. u = new ShadyDOM.Wrapper(a);
  4293. shadyDOMNodeWRM.set(a, mWeakRef(u));
  4294. }
  4295. return u;
  4296. }
  4297.  
  4298. standardWrap_ = standardWrap;
  4299.  
  4300.  
  4301. function setupWrapFunc(_ShadyDOM) {
  4302. const ShadyDOM = _ShadyDOM;
  4303.  
  4304.  
  4305. const wmPD = Object.getOwnPropertyDescriptor(WeakMap.prototype, 'get');
  4306. if (!(wmPD && wmPD.writable && !wmPD.enumerable && wmPD.configurable && wmPD.value && !wmPD.get && !wmPD.set)) {
  4307. return;
  4308. }
  4309. let mm = new Set();
  4310. const pget = wmPD.value;
  4311. WeakMap.prototype.get = function (a) {
  4312. mm.add(this);
  4313. return a;
  4314. }
  4315. try {
  4316. let nullElement = { node: null };
  4317. Object.setPrototypeOf(nullElement, Element.prototype);
  4318. ShadyDOM.wrapIfNeeded(nullElement)
  4319. ShadyDOM.wrap(nullElement)
  4320. } catch (e) { }
  4321. WeakMap.prototype.get = pget;
  4322. if (mm.size !== 1) {
  4323. mm.clear();
  4324. return;
  4325. }
  4326. const p = mm.values().next().value;
  4327. if (!(p instanceof WeakMap)) return;
  4328. // p.clear();
  4329. // p.get = function (a) { return a }
  4330. // p.set = function (a, b) { return this }
  4331. // console.log(188, window.n2n = mm, window.n2p = p)
  4332.  
  4333. // console.log(34929,p.size)
  4334. previousWrapStore = p;
  4335.  
  4336. if (typeof ShadyDOM.wrap === 'function' && ShadyDOM.wrap.length === 1) {
  4337. ShadyDOM.wrap = function (a) { 0 && console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrap'); return standardWrap(a) }
  4338. }
  4339. if (typeof ShadyDOM.wrapIfNeeded === 'function' && ShadyDOM.wrapIfNeeded.length === 1) {
  4340. ShadyDOM.wrapIfNeeded = function (a) { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrapIfNeeded'); return standardWrap(a) }
  4341. }
  4342.  
  4343. }
  4344.  
  4345. function setupLZ3(nv) {
  4346.  
  4347. const ShadyDOM = nv;
  4348.  
  4349. const ShadyDOMSettings = ShadyDOM.settings;
  4350. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  4351. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  4352. return false;
  4353. }
  4354.  
  4355. weakWrapper(ShadyDOM);
  4356.  
  4357. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  4358.  
  4359. setupPlainShadyDOM(ShadyDOMSettings);
  4360. setupPlainShadyDOM(ShadyDOM);
  4361.  
  4362. ShadyDOM.isShadyRoot = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - isShadyRoot'); return false; }
  4363.  
  4364. setupWrapFunc(ShadyDOM);
  4365. ShadyDOM.patchElementProto = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patchElementProto') }
  4366. ShadyDOM.patch = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patch') }
  4367.  
  4368. // To be confirmed
  4369. if (OMIT_ShadyDOM_EXPERIMENTAL & 2) {
  4370. ShadyDOM.composedPath = function (e) {
  4371. const t = (e || 0).target || null;
  4372. if (!(t instanceof HTMLElement_)) {
  4373. console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM&2) composedPath', t)
  4374. }
  4375. return t instanceof HTMLElement_ ? [t] : [];
  4376. };
  4377. }
  4378.  
  4379. }
  4380.  
  4381. }
  4382.  
  4383.  
  4384. function setupLZ6(nv) {
  4385.  
  4386. const ShadyDOM = nv;
  4387.  
  4388. const ShadyDOMSettings = ShadyDOM.settings;
  4389.  
  4390. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  4391. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  4392. return false;
  4393. }
  4394.  
  4395. weakWrapper(ShadyDOM);
  4396.  
  4397. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  4398.  
  4399. setupPlainShadyDOM(ShadyDOMSettings);
  4400. setupPlainShadyDOM(ShadyDOM);
  4401.  
  4402. setupWrapFunc(ShadyDOM);
  4403.  
  4404. }
  4405.  
  4406. }
  4407.  
  4408. if (b && typeof b.Wrapper === 'function' && typeof b.settings === 'object' && typeof b.wrap === 'function') {
  4409.  
  4410. const nv = b;
  4411.  
  4412. if (setupLZ6(nv) === false) return;
  4413.  
  4414. lz = 6;
  4415.  
  4416. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02b >>', nv)
  4417.  
  4418. return;
  4419. }
  4420.  
  4421. delete window.ShadyDOM;
  4422.  
  4423. Object.defineProperty(window, 'ShadyDOM', {
  4424. get() {
  4425. return b;
  4426. },
  4427. set(nv) {
  4428. let ret = 0;
  4429. try {
  4430. do {
  4431. if (!nv || !nv.settings) {
  4432. if (lz < 1 && nv && typeof nv === 'object' && isPlainObject(nv, 0)) {
  4433. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(nv);
  4434. lz = 1;
  4435. break;
  4436. } else {
  4437. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [nv:null]', nv);
  4438. break;
  4439. }
  4440. }
  4441.  
  4442. const sdp = Object.getOwnPropertyDescriptor(this || {}, 'ShadyDOM');
  4443. if (!(sdp && sdp.configurable && sdp.get && sdp.set)) {
  4444. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [ incorrect PropertyDescriptor ]', nv);
  4445. break;
  4446. }
  4447.  
  4448. if (setupLZ3(nv) === false) break;
  4449.  
  4450. lz = 3;
  4451.  
  4452. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02a >>', nv)
  4453.  
  4454. ret = 1;
  4455.  
  4456. } while (0);
  4457. } catch (e) {
  4458. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << ERROR >>', e)
  4459. }
  4460.  
  4461. if (!ret) b = nv;
  4462. else {
  4463. delete this.ShadyDOM;
  4464. this.ShadyDOM = nv;
  4465. }
  4466. return true;
  4467. },
  4468. enumerable: false,
  4469. configurable: true
  4470. });
  4471.  
  4472. })(typeof WeakRef !== 'undefined' ? WeakRef : function () { });
  4473.  
  4474. if (ENABLE_ASYNC_DISPATCHEVENT) {
  4475. const filter = new Set([
  4476. 'yt-action',
  4477. // 'iframe-src-replaced',
  4478. 'shown-items-changed',
  4479. 'can-show-more-changed', 'collapsed-changed',
  4480.  
  4481. 'yt-navigate', 'yt-navigate-start', 'yt-navigate-cache',
  4482. 'yt-player-updated', 'yt-page-data-fetched', 'yt-page-type-changed', 'yt-page-data-updated',
  4483. 'yt-navigate-finish',
  4484.  
  4485. // 'data-changed','yt-watch-comments-ready'
  4486. ])
  4487. EventTarget.prototype.dispatchEvent938 = EventTarget.prototype.dispatchEvent;
  4488. EventTarget.prototype.dispatchEvent = function (event) {
  4489. const type = (event || 0).type;
  4490. if (typeof type === 'string' && event.isTrusted === false && (event instanceof CustomEvent) && event.cancelable === false) {
  4491. if (!filter.has(type) && !type.endsWith('-changed')) {
  4492. if (this instanceof Node || this instanceof Window) {
  4493. nextBrowserTick_(() => this.dispatchEvent938(event));
  4494. return true;
  4495. }
  4496. }
  4497. }
  4498. return this.dispatchEvent938(event);
  4499. }
  4500. }
  4501.  
  4502. // avoid REGEXP testPattern execution in Brave's scriptlet for performance boost
  4503. SCRIPTLET_REMOVE_PRUNE_propNeedles && (() => {
  4504. // const xhr = new XMLHttpRequest;
  4505. const pdOri = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
  4506. if (!pdOri || pdOri.configurable !== true) return;
  4507. let propNeedles = null;
  4508. const pdNew = {
  4509. configurable: true,
  4510. enumerable: true,
  4511. get: function () {
  4512. propNeedles = this;
  4513. if (DEBUG_removePrune) debugger; // to locate Brave scriptlets
  4514. throw new Error();
  4515. }
  4516. }
  4517. Object.defineProperty(Map.prototype, 'size', pdNew);
  4518. try {
  4519. XMLHttpRequest.prototype.open.call(0);
  4520. // xhr.open.call(null)
  4521. } catch (e) { }
  4522. Object.defineProperty(Map.prototype, 'size', pdOri);
  4523. if (!propNeedles) return;
  4524. const entries = [...propNeedles.entries()];
  4525. propNeedles.clear();
  4526. console.log('[yt-js-engine-tamer] propNeedles is cleared from scriptlet', entries, propNeedles);
  4527. })();
  4528.  
  4529. if (FIX_XHR_REQUESTING) {
  4530.  
  4531. const URL = window.URL || new Function('return URL')();
  4532. const createObjectURL = URL.createObjectURL.bind(URL);
  4533.  
  4534. XMLHttpRequest = (() => {
  4535. const XMLHttpRequest_ = XMLHttpRequest;
  4536. if ('__xmMc8__' in XMLHttpRequest_.prototype) return XMLHttpRequest_;
  4537. const url0 = createObjectURL(new Blob([], { type: 'text/plain' }));
  4538. const c = class XMLHttpRequest extends XMLHttpRequest_ {
  4539. constructor(...args) {
  4540. super(...args);
  4541. }
  4542. open(method, url, ...args) {
  4543. let skip = false;
  4544. if (!url || typeof url !== 'string') skip = true;
  4545. else if (typeof url === 'string') {
  4546. let turl = url[0] === '/' ? `.youtube.com${url}` : `${url}`;
  4547. if (turl.includes('googleads') || turl.includes('doubleclick.net')) {
  4548. skip = true;
  4549. } else if (turl.includes('.youtube.com/pagead/')) {
  4550. skip = true;
  4551. } else if (turl.includes('.youtube.com/ptracking')) {
  4552. skip = true;
  4553. } else if (turl.includes('.youtube.com/youtubei/v1/log_event?')) {
  4554. skip = true;
  4555. } else if (turl.includes('.youtube.com/api/stats/')) { // /api/stats/
  4556. if (turl.includes('.youtube.com/api/stats/qoe?')) {
  4557. skip = true;
  4558. } else if (turl.includes('.youtube.com/api/stats/ads?')) {
  4559. skip = true;
  4560. } else {
  4561. // skip = true; // for user activity logging e.g. watched videos
  4562. }
  4563. } else if (turl.includes('play.google.com/log')) {
  4564. skip = true;
  4565. } else if (turl.includes('.youtube.com//?')) { // //?cpn=
  4566. skip = true;
  4567. }
  4568. }
  4569. if (!skip) {
  4570. this.__xmMc8__ = 1;
  4571. return super.open(method, url, ...args);
  4572. } else {
  4573. this.__xmMc8__ = 2;
  4574. return super.open('GET', url0);
  4575. }
  4576. }
  4577. send(...args) {
  4578. if (this.__xmMc8__ === 1) {
  4579. return super.send(...args);
  4580. } else if (this.__xmMc8__ === 2) {
  4581. return super.send();
  4582. } else {
  4583. console.log('[yt-js-engine-tamer]', 'xhr warning');
  4584. return super.send(...args);
  4585. }
  4586. }
  4587. }
  4588. c.prototype.__xmMc8__ = 0;
  4589. prototypeInherit(c.prototype, XMLHttpRequest_.prototype);
  4590. return c;
  4591. })();
  4592. }
  4593.  
  4594. // Alternative HACK -> Tabview Youtube
  4595. if (DISABLE_COOLDOWN_SCROLLING && typeof EventTarget.prototype.addEventListener52178 !== 'function' && typeof EventTarget.prototype.addEventListener === 'function') {
  4596.  
  4597. // ---- << this.overscrollConfig HACK >> -----
  4598.  
  4599. // 2024.04.19 - Playlist in Single Column Mode cannot be scrolled correctly.
  4600.  
  4601. /*
  4602.  
  4603. ;function gZb(a, b) {
  4604. b = void 0 === b ? !0 : b;
  4605. a.addEventListener("wheel", hZb);
  4606. a.overscrollConfig = {
  4607. cooldown: b
  4608. }
  4609. }
  4610. function iZb(a) {
  4611. a.overscrollConfig = void 0;
  4612. a.removeEventListener("wheel", hZb)
  4613. }
  4614. function hZb(a) {
  4615. var b = a.deltaY
  4616. , c = a.target
  4617. , d = null;
  4618. if (window.Polymer && window.Polymer.Element) {
  4619. if (c = a.path || a.composedPath && a.composedPath()) {
  4620. c = g(c);
  4621. for (var e = c.next(); !e.done && (e = e.value,
  4622. !jZb(e, b)); e = c.next())
  4623. if (e.overscrollConfig) {
  4624. d = e;
  4625. break
  4626. }
  4627. }
  4628. } else
  4629. for (; c && !jZb(c, b); ) {
  4630. if (c.overscrollConfig) {
  4631. d = c;
  4632. break
  4633. }
  4634. c = c.parentElement
  4635. }
  4636. d && (b = d.overscrollConfig,
  4637. b.cooldown ? (d = a.deltaY,
  4638. c = b.lastDeltaY || 0,
  4639. b.lastDeltaY = d,
  4640. e = b.lastStopped || 0,
  4641. c && e && 0 < c == 0 < d ? Math.abs(c) >= Math.abs(d) ? (d = e + 1200,
  4642. c = !1) : (d = e + 600,
  4643. c = !0) : (d = Date.now() + 600,
  4644. c = !0),
  4645. d > Date.now() && (a.preventDefault(),
  4646. c && (b.lastStopped = Date.now()))) : a.preventDefault())
  4647. }
  4648. */
  4649.  
  4650. let wheelHandler = function (a) {
  4651. if (window.Polymer && window.Polymer.Element) {
  4652. let c;
  4653. if (c = a.path || a.composedPath && a.composedPath()) {
  4654. for (const e of c) {
  4655. const cnt = insp(e);
  4656. if (e.overscrollConfig) e.overscrollConfig = void 0;
  4657. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  4658. }
  4659. }
  4660. } else {
  4661. let e = a.target;
  4662. for (; e instanceof Element; e = e.parentElement) {
  4663. const cnt = insp(e);
  4664. if (e.overscrollConfig) e.overscrollConfig = void 0;
  4665. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  4666. }
  4667. }
  4668. };
  4669.  
  4670. let checkWheelListenerObjs = null;
  4671.  
  4672. let getObjsFn = () => {
  4673. let euyVal = 0;
  4674. const eukElm = {};
  4675. Object.setPrototypeOf(eukElm, HTMLElement_.prototype);
  4676. const euzObj = new Proxy(eukElm, {
  4677. get(target, prop) {
  4678. throw `ErrorF31.get(${prop})`
  4679. },
  4680. set(target, prop, value) {
  4681. throw `ErrorF33.set(${prop}, ${value})`
  4682. }
  4683. });
  4684. const euxElm = new Proxy(eukElm, {
  4685. get(target, prop) {
  4686. if (prop === 'scrollTop') {
  4687. euyVal = euyVal | 8;
  4688. return 0;
  4689. }
  4690. if (prop === 'overscrollConfig') {
  4691. euyVal = euyVal | 16;
  4692. return void 0;
  4693. }
  4694. if (prop === 'scrollHeight' || prop === 'clientHeight' || prop === 'offsetHeight') {
  4695. return 640;
  4696. }
  4697. if (prop === 'scrollLeft') {
  4698. euyVal = euyVal | 8;
  4699. return 0;
  4700. }
  4701. if (prop === 'scrollWidth' || prop === 'clientWidth' || prop === 'offsetWidth') {
  4702. return 800;
  4703. }
  4704. throw `ErrorF45.get(${prop})`
  4705. },
  4706. set(target, prop, value) {
  4707. throw `ErrorF47.set(${prop}, ${value})`
  4708. }
  4709. });
  4710. const eukEvt = {};
  4711. Object.setPrototypeOf(eukEvt, WheelEvent.prototype);
  4712. const euyEvt = new Proxy(eukEvt, {
  4713. get(target, prop) {
  4714. if (prop === 'deltaY' || prop === 'deltaX') {
  4715. euyVal = euyVal | 1;
  4716. return -999;
  4717. }
  4718. if (prop === 'target') {
  4719. euyVal = euyVal | 2;
  4720. return euxElm
  4721. }
  4722. if (prop === 'path' || prop === 'composedPath') {
  4723. euyVal = euyVal | 2;
  4724. return [euxElm]
  4725. }
  4726. throw `ErrorF51.get(${prop})`
  4727. },
  4728. set(target, prop, value) {
  4729. throw `ErrorF53.set(${prop}, ${value})`
  4730. }
  4731. });
  4732. const setVal = (v) => {
  4733. euyVal = v;
  4734. }
  4735. const getVal = () => {
  4736. return euyVal;
  4737. }
  4738. return { euzObj, euyEvt, setVal, getVal };
  4739. }
  4740.  
  4741. let checkWheelListener = (callback) => {
  4742.  
  4743. let callbackIdentifier = '';
  4744.  
  4745. let res = null;
  4746. try {
  4747. const { euzObj, euyEvt, getVal, setVal } = checkWheelListenerObjs || (checkWheelListenerObjs = getObjsFn());
  4748. setVal(0);
  4749. if (callback.call(euzObj, euyEvt) !== void 0) throw 'ErrorF99';
  4750. throw `RESULT${getVal()}`;
  4751. } catch (e) {
  4752. res = e;
  4753. }
  4754.  
  4755. res = `${res}` || `${null}`;
  4756. if (res.length > 20) res = `${res.substring(0, 20)}...`;
  4757.  
  4758. callbackIdentifier = res;
  4759. if (callbackIdentifier === 'RESULT27') 0;
  4760. else if (callbackIdentifier === 'RESULT0') {
  4761. // a.isSearch && !a.disableWheelScroll && B("desktop_enable_dmpanel_wheel_scroll")
  4762. } else if (callbackIdentifier.startsWith('RESULT')) {
  4763. console.log('wheel eventListener - RESULT', callbackIdentifier, callback)
  4764. }
  4765. return callbackIdentifier;
  4766.  
  4767. };
  4768.  
  4769. let callbackFound = false;
  4770. EventTarget.prototype.addEventListener52178 = EventTarget.prototype.addEventListener;
  4771. EventTarget.prototype.addEventListener = function (type, callback, option = void 0) {
  4772. // M-youtube-js-engine-tamer.52178
  4773. if (type === 'wheel' && !option && typeof callback === 'function' && callback.length === 1) {
  4774. // (( match with signature `a.addEventListener("wheel", hZb);` )) [subject to further review]
  4775. const callbackIdentifier = callback.yaujmoms || (callbackFound ? 'IGNORE' : (callback.yaujmoms = checkWheelListener(callback)));
  4776. // RESULTXX / ErrorFXX / Other...
  4777. if (callbackIdentifier === 'RESULT27') {
  4778. this.overscrollConfigDisable = true;
  4779. if (!callbackFound) {
  4780. callbackFound = true; // suppose only one function is assigned to overscrollConfig cooldown [no function binding]
  4781. getObjsFn = checkWheelListener = null;
  4782. checkWheelListenerObjs = null;
  4783. wheelHandler = null;
  4784. }
  4785. return void 0;
  4786. } else if (!callbackFound && !this.overscrollConfigDisable) {
  4787. this.overscrollConfigDisable = true;
  4788. this.addEventListener52178('wheel', wheelHandler, { passive: false });
  4789. }
  4790. }
  4791. return this.addEventListener52178(type, callback, option);
  4792. };
  4793.  
  4794. // ---- << this.overscrollConfig HACK >> -----
  4795.  
  4796. }
  4797.  
  4798. const { pageMediaWatcher, shortcutKeysFixer, keyboardController } = (() => {
  4799.  
  4800. let p_a_objWR = null;
  4801. let isSpaceKeyImmediate = false; // for ADVANCED_FIX_SHORTCUTKEYS
  4802. let ytPageReady = 0;
  4803.  
  4804. let isSpeedMastSpacebarControlEnabled = false; // youtube experimental feature // can be forced by CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  4805. let isGlobalSpaceControl = true;
  4806. let mediaPlayerElementWR = null;
  4807. let focusedElementAtSelection = null;
  4808.  
  4809. // let want_control_video = false;
  4810.  
  4811. let spaceBarControl_keyG = '';
  4812.  
  4813. let lastUserAction = 0;
  4814.  
  4815. const wmKeyControlPhase = new WeakMap();
  4816.  
  4817. let currentSelectionText = null;
  4818.  
  4819. const getCurrentSelectionText = () => {
  4820. if (currentSelectionText !== null) return currentSelectionText
  4821. return (currentSelectionText = `${getSelection()}`)
  4822. }
  4823.  
  4824. const pageMediaWatcher = () => {
  4825.  
  4826. // CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && document.addEventListener('wheel', () => {
  4827. // want_control_video = false;
  4828. // }, { capture: true, passive: true });
  4829.  
  4830. document.addEventListener('yt-navigate', () => {
  4831. ytPageReady = 0;
  4832. });
  4833. document.addEventListener('yt-navigate-start', () => {
  4834. ytPageReady = 0;
  4835. });
  4836. document.addEventListener('yt-navigate-cache', () => {
  4837. ytPageReady = 0;
  4838. });
  4839.  
  4840. document.addEventListener('yt-navigate-finish', () => {
  4841. ytPageReady = 1;
  4842. });
  4843.  
  4844. document.addEventListener('durationchange', () => {
  4845. for (const elm of document.querySelectorAll('#movie_player video[src], #movie_player audio[src]')) {
  4846. if (elm.duration > 0.01) {
  4847. if (elm.closest('[hidden]')) continue;
  4848. mediaPlayerElementWR = mWeakRef(elm);
  4849. return;
  4850. }
  4851. }
  4852. }, { capture: true, passive: true });
  4853.  
  4854. document.addEventListener('selectionchange', (evt) => {
  4855. if (!evt || !evt.isTrusted || !(evt instanceof Event)) return;
  4856. currentSelectionText = null;
  4857. if (!(evt.target instanceof Node)) return;
  4858. focusedElementAtSelection = evt.target;
  4859. }, { capture: true, passive: true })
  4860.  
  4861. document.addEventListener('pointerdown', (evt) => {
  4862. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  4863. }, { capture: true, passive: true });
  4864.  
  4865.  
  4866. document.addEventListener('pointerup', (evt) => {
  4867. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  4868. }, { capture: true, passive: true });
  4869.  
  4870.  
  4871. document.addEventListener('keydown', (evt) => {
  4872. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  4873. }, { capture: true, passive: true });
  4874.  
  4875. document.addEventListener('keyup', (evt) => {
  4876. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  4877. }, { capture: true, passive: true });
  4878.  
  4879. };
  4880.  
  4881.  
  4882. const checkKeyB = (p_a_obj) => {
  4883.  
  4884. const boolList = new Set();
  4885. const p_a_obj_api = p_a_obj.api;
  4886.  
  4887. const nilFunc0 = function () {
  4888. return void 0
  4889. };
  4890. const mt = new Proxy({}, {
  4891. get(target, prop) {
  4892. if (prop === 'get') return nilFunc0;
  4893. return mt;
  4894. }
  4895. });
  4896. const nilFunc = function () {
  4897. return mt
  4898. };
  4899. const mw = new Proxy({}, {
  4900. get(target, prop) {
  4901. if (prop in p_a_obj_api) {
  4902. if (typeof p_a_obj_api.constructor.prototype[prop] === 'function') return nilFunc;
  4903. let q = Object.getOwnPropertyDescriptor(p_a_obj_api, prop);
  4904. if (q && q.value) {
  4905. if (!q.writable) return q.value;
  4906. if (typeof q.value === 'string') return '';
  4907. if (typeof q.value === 'number') return 0;
  4908. if (typeof q.value === 'boolean') return false;
  4909. if (q.value && typeof q.value === 'object') return {};
  4910. }
  4911. }
  4912. return undefined;
  4913. },
  4914. set(target, prop) {
  4915. throw 'mwSet';
  4916. }
  4917. });
  4918.  
  4919. const mq = new Proxy({}, {
  4920. get(target, prop) {
  4921. if (prop === 'api') return mw;
  4922. if (prop in p_a_obj) {
  4923. if (typeof p_a_obj.constructor.prototype[prop] === 'function') return nilFunc;
  4924. let q = Object.getOwnPropertyDescriptor(p_a_obj, prop);
  4925. if (q && q.value) {
  4926. if (!q.writable) return q.value;
  4927. if (typeof q.value === 'string') return '';
  4928. if (typeof q.value === 'number') return 0;
  4929. if (typeof q.value === 'boolean') return false;
  4930. if (q.value && typeof q.value === 'object') return {};
  4931. }
  4932. }
  4933. return undefined;
  4934. },
  4935. set(target, prop, val) {
  4936. if (typeof val === 'boolean') boolList.add(prop)
  4937. throw `mqSet(${prop},${val})`;
  4938. }
  4939. });
  4940.  
  4941. let res = ''
  4942. try {
  4943. res = `RESULT::${p_a_obj.handleGlobalKeyUp.call(mq, 9, false, false, false, false, "Tab", "Tab")}`;
  4944. } catch (e) {
  4945. res = `ERROR::${e}`;
  4946. }
  4947.  
  4948. if (boolList.size === 1) {
  4949. const value = boolList.values().next().value;
  4950. if (res === `ERROR::mqSet(${value},${true})`) {
  4951. p_a_obj.__uZWaD__ = value;
  4952. }
  4953. }
  4954.  
  4955. console.log('[yt-js-engine-tamer] global shortcut control', { '__uZWaD__': p_a_obj.__uZWaD__ });
  4956.  
  4957. }
  4958.  
  4959.  
  4960. let pm_p_a = null;
  4961.  
  4962. const p_a_init = function () {
  4963. const r = this.init91();
  4964. const keyBw = this.__cPzfo__ || '__NIL__';
  4965. const p_a_obj = this[keyBw];
  4966. if (!p_a_obj) return;
  4967. try {
  4968. checkKeyB(p_a_obj);
  4969. } catch (e) { }
  4970. p_a_objWR = mWeakRef(p_a_obj);
  4971. if (FIX_SHORTCUTKEYS > 0) {
  4972. if (p_a_obj && !p_a_obj.hVhtg) {
  4973. p_a_obj.hVhtg = 1;
  4974.  
  4975. p_a_obj.handleGlobalKeyUp91 = p_a_obj.handleGlobalKeyUp;
  4976. p_a_obj.handleGlobalKeyUp = p_a_xt.handleGlobalKeyUp;
  4977. p_a_obj.handleGlobalKeyDown91 = p_a_obj.handleGlobalKeyDown;
  4978. p_a_obj.handleGlobalKeyDown = p_a_xt.handleGlobalKeyDown;
  4979. p_a_obj.__handleGlobalKeyBefore__ = p_a_xt.__handleGlobalKeyBefore__;
  4980. p_a_obj.__handleGlobalKeyAfter__ = p_a_xt.__handleGlobalKeyAfter__;
  4981.  
  4982. }
  4983. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && p_a_obj && p_a_obj.api && !p_a_obj.api.hVhtg) {
  4984. // const api = p_a_obj.api
  4985. // api.hVhtg = 1;
  4986. // api.playVideo91 = api.playVideo;
  4987. // api.playVideo = p_a_jt.playVideo;
  4988. // api.pauseVideo91 = api.pauseVideo;
  4989. // api.pauseVideo = p_a_jt.pauseVideo;
  4990. // }
  4991. }
  4992. if (pm_p_a) {
  4993. pm_p_a.resolve();
  4994. pm_p_a = null;
  4995. }
  4996. return r;
  4997. };
  4998.  
  4999. const p_a_xt = {
  5000.  
  5001. __handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) {
  5002.  
  5003. if (FIX_SHORTCUTKEYS === 2) {
  5004.  
  5005. // if (flagSpeedMaster !== false && !getGlobalSpacebarControlFlag()) return false;
  5006.  
  5007. if (activeElement) {
  5008.  
  5009. const controlPhaseCache = wmKeyControlPhase.get(activeElement);
  5010.  
  5011. if (controlPhaseCache === 6 && getCurrentSelectionText() !== "") void 0;
  5012. else if (controlPhaseCache === 1 || controlPhaseCache === 2 || controlPhaseCache === 5) return false;
  5013. else if ((controlPhaseCache !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return false;
  5014.  
  5015. }
  5016.  
  5017. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  5018. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  5019. // console.log(582, isDelayedSpaceBar)
  5020. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  5021.  
  5022. if (activeElement && (h === 'Space' || h === 'Enter')) {
  5023. const controlPhase = wmKeyControlPhase.get(activeElement);
  5024. if (controlPhase === 4 || controlPhase === 5) return false;
  5025. }
  5026. if (focusedElementAtSelection === activeElement && getCurrentSelectionText() !== "") return false;
  5027. // if (!isSpeedMastSpacebarControlEnabled && a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space') {
  5028. // if (!isSpaceKeyImmediate) return false;
  5029. // }
  5030. }
  5031.  
  5032. },
  5033.  
  5034. __handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret) {
  5035.  
  5036. if (FIX_SHORTCUTKEYS === 2 && ret && a >= 32 && ytPageReady === 1 && Date.now() - lastUserAction < 40 && activeElement === document.activeElement) {
  5037.  
  5038. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  5039. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  5040. // console.log(583, isDelayedSpaceBar)
  5041. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  5042.  
  5043. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  5044.  
  5045. let mediaWorking = false;
  5046. if (mediaPlayerElement && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2 && mediaPlayerElement.duration > 0.01) {
  5047. mediaWorking = true;
  5048. } else if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  5049. mediaWorking = true;
  5050. }
  5051. // console.log(182, mediaWorking, mediaPlayerElement.readyState , mediaPlayerElement.networkState)
  5052. mediaWorking && Promise.resolve().then(() => {
  5053. if (activeElement === document.activeElement) {
  5054. return activeElement.blur()
  5055. } else {
  5056. return false
  5057. }
  5058. }).then((r) => {
  5059. r !== false && mediaPlayerElement.focus();
  5060. });
  5061. }
  5062. },
  5063.  
  5064.  
  5065. handleGlobalKeyUp(a, b, c, d, e, f, h) {
  5066.  
  5067. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  5068.  
  5069. const activeElement = document.activeElement;
  5070.  
  5071. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  5072. if (allow === false) return false;
  5073.  
  5074. const ret = this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  5075. // console.log('handleGlobalKeyUp',ret, a, b, c, d, e, f, h);
  5076.  
  5077. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  5078.  
  5079. return ret;
  5080. },
  5081. handleGlobalKeyDown(a, b, c, d, e, f, h, l) {
  5082.  
  5083.  
  5084. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  5085.  
  5086. const activeElement = document.activeElement;
  5087. // if (a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space' && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  5088. // return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  5089. // }
  5090. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  5091. if (allow === false) return false;
  5092.  
  5093. const ret = this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  5094. // console.log('handleGlobalKeyDown',ret, a, b, c, d, e, f, h,l)
  5095.  
  5096. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  5097.  
  5098. return ret;
  5099. }
  5100.  
  5101. };
  5102.  
  5103. let flagSpeedMaster = null;
  5104. const getSpeedMasterControlFlag = () => {
  5105.  
  5106. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  5107. isSpeedMastSpacebarControlEnabled = false;
  5108. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control) {
  5109. isSpeedMastSpacebarControlEnabled = true;
  5110. }
  5111. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control) {
  5112. isSpeedMastSpacebarControlEnabled = true;
  5113. }
  5114.  
  5115. if (flagSpeedMaster === null) {
  5116. const p = (((config || 0).WEB_PLAYER_CONTEXT_CONFIGS || 0).WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH || 0).serializedExperimentFlags;
  5117. if (!p) {
  5118. flagSpeedMaster = false;
  5119. } else {
  5120.  
  5121. flagSpeedMaster = (p.includes('web_enable_speedmaster=true') && p.includes('web_speedmaster_spacebar_control=true') && p.includes('web_speedmaster_updated_edu=true'));
  5122.  
  5123. }
  5124.  
  5125. }
  5126. if (!flagSpeedMaster) isSpeedMastSpacebarControlEnabled = false;
  5127.  
  5128. return isSpeedMastSpacebarControlEnabled;
  5129. }
  5130.  
  5131.  
  5132. const getGlobalSpacebarControlFlag = () => {
  5133.  
  5134. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  5135. isGlobalSpaceControl = false;
  5136. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.global_spacebar_pause) {
  5137. isGlobalSpaceControl = true;
  5138. }
  5139. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.global_spacebar_pause) {
  5140. isGlobalSpaceControl = true;
  5141. }
  5142.  
  5143. return isGlobalSpaceControl;
  5144. }
  5145.  
  5146. const keyboardController = async (_yt_player) => {
  5147.  
  5148. const keyQT = getQT(_yt_player);
  5149. const keySV = getSV(_yt_player);
  5150. const keyDX = getDX(_yt_player);
  5151. console.log(`[QT,SV,DX]`, [keyQT, keySV, keyDX]);
  5152.  
  5153. if (!keyDX) return;
  5154. if (keyDX === keyQT || keyDX === keySV) return;
  5155.  
  5156. if (typeof keyDX !== 'string') return;
  5157.  
  5158. let lastAccessKey = '';
  5159. let lastAccessKeyConfirmed = '';
  5160. const mb = new Proxy({}, {
  5161. get(target, prop) {
  5162. if (prop === 'handleGlobalKeyUp') lastAccessKeyConfirmed = lastAccessKey;
  5163. throw 'mbGet'
  5164. },
  5165. set(target, prop, val) {
  5166. throw 'mbSet'
  5167. }
  5168. });
  5169. const ma = new Proxy({}, {
  5170. get(target, prop) {
  5171. lastAccessKey = prop;
  5172. return mb
  5173. },
  5174. set(target, prop, val) {
  5175. throw 'maSet'
  5176. }
  5177. });
  5178.  
  5179. let keyBw = '';
  5180. try {
  5181. _yt_player[keyDX].prototype.handleGlobalKeyUp.call(ma);
  5182. } catch (e) {
  5183. if (e === 'mbGet' && typeof lastAccessKeyConfirmed === 'string' && lastAccessKeyConfirmed.length > 0) {
  5184. keyBw = lastAccessKeyConfirmed;
  5185. }
  5186. }
  5187.  
  5188. if (!keyBw) return;
  5189.  
  5190. if (typeof _yt_player[keyDX].prototype.init !== 'function' || _yt_player[keyDX].prototype.init.length !== 0) return;
  5191.  
  5192. pm_p_a = new PromiseExternal();
  5193.  
  5194. _yt_player[keyDX].prototype.__cPzfo__ = keyBw;
  5195.  
  5196. _yt_player[keyDX].prototype.init91 = _yt_player[keyDX].prototype.init;
  5197.  
  5198. _yt_player[keyDX].prototype.init = p_a_init;
  5199.  
  5200. await pm_p_a.then();
  5201. const p_a_obj = kRef(p_a_objWR);
  5202.  
  5203. const isSpeedMastSpacebarControlEnabledA = getSpeedMasterControlFlag();
  5204.  
  5205.  
  5206. if (CHANGE_SPEEDMASTER_SPACEBAR_CONTROL > 0) {
  5207.  
  5208. isSpeedMastSpacebarControlEnabled = CHANGE_SPEEDMASTER_SPACEBAR_CONTROL == 1;
  5209.  
  5210. if (!isSpeedMastSpacebarControlEnabled) {
  5211.  
  5212. if (config && config.EXPERIMENT_FLAGS) {
  5213. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = false;
  5214. }
  5215. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  5216. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = false;
  5217. }
  5218.  
  5219. } else {
  5220.  
  5221. if (config && config.EXPERIMENT_FLAGS) {
  5222. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = true;
  5223. }
  5224. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  5225. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = true;
  5226. }
  5227.  
  5228. }
  5229.  
  5230. }
  5231.  
  5232. const isSpeedMastSpacebarControlEnabledB = getSpeedMasterControlFlag();
  5233.  
  5234.  
  5235.  
  5236.  
  5237. console.log('[yt-js-engine-tamer] speedmaster by space (yt setting)', isSpeedMastSpacebarControlEnabledA, isSpeedMastSpacebarControlEnabledB);
  5238.  
  5239. // console.log(p_a_obj.handleGlobalKeyUp)
  5240. console.log('[yt-js-engine-tamer] p_a', p_a_obj);
  5241.  
  5242. // console.log(p_a_obj.api)
  5243.  
  5244.  
  5245. // QT -> DX(SV) -> p_a
  5246.  
  5247.  
  5248. /*
  5249. *
  5250. *
  5251. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  5252. b = void 0 === b ? !1 : b;
  5253. c = void 0 === c ? !1 : c;
  5254. d = void 0 === d ? !1 : d;
  5255. e = void 0 === e ? !1 : e;
  5256. var l = g.PT(this);
  5257. l && l.handleGlobalKeyUp(a, b, c, d, e, f, h)
  5258. }
  5259.  
  5260. */
  5261.  
  5262. /*
  5263. *
  5264. *
  5265. *
  5266. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  5267. return this.Bw ? this.Bw.handleGlobalKeyUp(a, b, c, d, e, f, h) : !1
  5268. }
  5269.  
  5270. */
  5271.  
  5272.  
  5273. // if(!keyDX) return;
  5274.  
  5275. // console.log(4999, keyDX)
  5276.  
  5277. };
  5278.  
  5279.  
  5280. const ytResumeFn = function () { // ADVANCED_FIX_SHORTCUTKEYS
  5281.  
  5282. const p_a_obj = kRef(p_a_objWR);
  5283. // const api = p_a_obj.api;
  5284.  
  5285.  
  5286. // console.log(540);
  5287.  
  5288. let boolList = null;
  5289. let ret;
  5290. isSpaceKeyImmediate = true;
  5291. try {
  5292.  
  5293. ret = 0;
  5294. ret = ret | (p_a_obj.handleGlobalKeyDown(32, false, false, false, false, ' ', 'Space', false) ? 1 : 0);
  5295. let p_a_objT;
  5296. if (!spaceBarControl_keyG) { // just in case
  5297. boolList = new Set();
  5298. p_a_objT = new Proxy(p_a_obj, {
  5299. get(target, prop, handler) {
  5300. const val = target[prop];
  5301. if (typeof val !== 'boolean') return val;
  5302. boolList.add(prop);
  5303. // console.log(555, prop, val);
  5304. if (typeof prop === 'string' && prop.length <= 3 && val === true && boolList.length === 1) {
  5305. spaceBarControl_keyG = prop;
  5306. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  5307. val = false;
  5308. }
  5309. return val;
  5310. }
  5311. });
  5312.  
  5313.  
  5314. } else if (p_a_obj[spaceBarControl_keyG] === true) {
  5315. p_a_obj[spaceBarControl_keyG] = false;
  5316. p_a_objT = p_a_obj;
  5317. // console.log(p_a_obj, spaceBarControl_keyG, p_a_obj[spaceBarControl_keyG] )
  5318. } else {
  5319.  
  5320. p_a_objT = p_a_obj;
  5321. }
  5322.  
  5323. ret = ret | (p_a_objT.handleGlobalKeyUp(32, false, false, false, false, ' ', 'Space') ? 2 : 0);
  5324.  
  5325.  
  5326. } catch (e) {
  5327. console.log(e)
  5328. }
  5329. isSpaceKeyImmediate = false;
  5330.  
  5331. if (boolList && boolList.size === 1) {
  5332. const value = boolList.values().next().value;
  5333. spaceBarControl_keyG = value;
  5334. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  5335.  
  5336. }
  5337.  
  5338. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  5339.  
  5340. return ret;
  5341. }
  5342.  
  5343. const shortcutKeysFixer = () => {
  5344.  
  5345. let pausePromiseControlJ = 0;
  5346.  
  5347.  
  5348. const obtainCurrentControlPhase = (evt, mediaPlayerElement) => {
  5349.  
  5350. let controlPhase = 0;
  5351. const aElm = document.activeElement;
  5352.  
  5353. if (aElm) {
  5354.  
  5355. const controlPhaseCache = wmKeyControlPhase.get(aElm);
  5356.  
  5357. if (typeof controlPhaseCache === 'number') {
  5358.  
  5359. controlPhase = controlPhaseCache;
  5360. } else {
  5361.  
  5362. if (aElm instanceof HTMLInputElement) controlPhase = 1;
  5363. else if (aElm instanceof HTMLTextAreaElement) controlPhase = 1;
  5364. else if (aElm instanceof HTMLButtonElement) controlPhase = 2;
  5365. else if (aElm instanceof HTMLIFrameElement) controlPhase = 2;
  5366. else if (aElm instanceof HTMLImageElement) controlPhase = 2;
  5367. else if (aElm instanceof HTMLEmbedElement) controlPhase = 2;
  5368. else {
  5369. if (aElm instanceof HTMLElement_ && aElm.closest('[role]')) controlPhase = 5;
  5370. if (aElm instanceof HTMLDivElement) controlPhase = 2;
  5371. else if (aElm instanceof HTMLAnchorElement) controlPhase = 2;
  5372. else if (!(aElm instanceof HTMLElement_) && (aElm instanceof Element)) controlPhase = 2; // svg
  5373. }
  5374.  
  5375. if ((controlPhase === 2 || controlPhase === 5) && (aElm instanceof HTMLElement_) && aElm.contains(mediaPlayerElement)) {
  5376. controlPhase = 0;
  5377. }
  5378.  
  5379. if ((controlPhase === 2 || controlPhase === 5) && evt && evt.target && evt.target === aElm) {
  5380. if (aElm.closest('[contenteditable], input, textarea')) {
  5381. controlPhase = 5;
  5382. } else if (aElm.closest('button')) {
  5383. controlPhase = 4;
  5384. }
  5385. }
  5386.  
  5387. if (aElm.closest('#movie_player')) controlPhase = 6;
  5388.  
  5389. wmKeyControlPhase.set(aElm, controlPhase);
  5390.  
  5391. }
  5392. }
  5393.  
  5394. return controlPhase;
  5395.  
  5396. }
  5397.  
  5398. const isStateControllable = (api) => {
  5399. let appState = null;
  5400. let playerState = null;
  5401. let adState = null;
  5402. try {
  5403. appState = api.getAppState();
  5404. playerState = api.getPlayerState();
  5405. adState = api.getAdState();
  5406. } catch (e) { }
  5407. // ignore playerState -1
  5408. return appState === 5 && adState === -1 && (playerState === 1 || playerState === 2 || playerState === 3);
  5409. };
  5410.  
  5411.  
  5412. const keyEventListener = (evt) => {
  5413. if (BY_PASS_KEYBOARD_CONTROL) return;
  5414.  
  5415. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  5416. if (isSpaceKeyImmediate || !evt.isTrusted || !(evt instanceof KeyboardEvent)) return;
  5417. if (!ytPageReady) return;
  5418.  
  5419. if (evt.defaultPrevented === true) return;
  5420.  
  5421. const p_a_obj = kRef(p_a_objWR);
  5422.  
  5423. if (!p_a_obj) return;
  5424.  
  5425.  
  5426. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  5427. if (!mediaPlayerElement) return;
  5428.  
  5429. // let focusBodyIfSuccess = false;
  5430.  
  5431. const controlPhase = obtainCurrentControlPhase(evt, mediaPlayerElement);
  5432.  
  5433. if (controlPhase === 6 && getCurrentSelectionText() !== "") void 0;
  5434. else if (controlPhase === 1 || controlPhase === 2 || controlPhase === 5) return;
  5435. else if ((controlPhase !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return;
  5436.  
  5437.  
  5438. if (evt.code === 'Space' && !getGlobalSpacebarControlFlag()) return;
  5439.  
  5440. // console.log(`${evt.type}::controlPhase`,controlPhase)
  5441.  
  5442. // if (controlPhase == 4) {
  5443. // focusBodyIfSuccess = true;
  5444. // }
  5445.  
  5446. spaceBarControl_keyG = spaceBarControl_keyG || p_a_obj.__uZWaD__ || ''
  5447. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  5448.  
  5449. if (FIX_SHORTCUTKEYS < 2) return;
  5450. if (!(!evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey)) return; // ignore if modifier key is pressed -> let other event listener to handle first
  5451.  
  5452. let rr;
  5453. const isSpaceBar = evt.code === 'Space' && !evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey;
  5454.  
  5455.  
  5456.  
  5457. let useImprovedPauseResume = false;
  5458.  
  5459. if (USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER && isSpaceBar && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  5460.  
  5461. const api = p_a_obj.api;
  5462. const stateControllable = isStateControllable(api);
  5463. // console.log(2122, appState, playerState, adState)
  5464.  
  5465. if (stateControllable && isWatchPageURL() && mediaPlayerElement.duration > 0.01 && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2) {
  5466.  
  5467. useImprovedPauseResume = true;
  5468.  
  5469. }
  5470.  
  5471.  
  5472. }
  5473.  
  5474.  
  5475. // force flag: CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  5476. if (evt.type === 'keydown') {
  5477.  
  5478. if (useImprovedPauseResume) {
  5479.  
  5480. const isPaused = mediaPlayerElement.paused;
  5481.  
  5482. const cj = ++pausePromiseControlJ;
  5483. Promise.resolve().then(() => {
  5484.  
  5485. if (cj !== pausePromiseControlJ) return;
  5486.  
  5487. if (mediaPlayerElement.paused !== isPaused) return;
  5488.  
  5489. const ret = ytResumeFn();
  5490. if (!ret) { // fallback
  5491. isPaused ? api.playVideo() : api.pauseVideo();
  5492. }
  5493.  
  5494. /*
  5495. let a = void 0;
  5496. console.log('Rb', api.Rb())
  5497. a = !window._yt_player.nL(api.Rb());
  5498. p_a_obj.Wd.kG(a)
  5499. a ? api.playVideo() : api.pauseVideo();
  5500.  
  5501. */
  5502.  
  5503.  
  5504. });
  5505. rr = true;
  5506. } else {
  5507.  
  5508. isSpaceKeyImmediate = true;
  5509. rr = p_a_obj.handleGlobalKeyDown(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code, evt.repeat);
  5510. isSpaceKeyImmediate = false;
  5511. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  5512.  
  5513. }
  5514.  
  5515.  
  5516. } else if (evt.type === 'keyup') {
  5517.  
  5518. if (isSpaceBar && useImprovedPauseResume && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  5519.  
  5520. rr = true;
  5521. } else {
  5522.  
  5523. isSpaceKeyImmediate = true;
  5524. rr = p_a_obj.handleGlobalKeyUp(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code);
  5525. isSpaceKeyImmediate = false;
  5526. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  5527.  
  5528. }
  5529.  
  5530.  
  5531. /*
  5532.  
  5533. if (d)
  5534. switch (c) {
  5535. case 32:
  5536. case 13:
  5537. if ("BUTTON" === d.tagName || "A" === d.tagName || "INPUT" === d.tagName)
  5538. b = !0,
  5539. e = !1;
  5540. else if (e) {
  5541. var m = d.getAttribute("role");
  5542. !m || "option" !== m && "button" !== m && 0 !== m.indexOf("menuitem") || (b = !0,
  5543. d.click(),
  5544. f = !0)
  5545. }
  5546. break;
  5547. case 37:
  5548. case 39:
  5549. case 36:
  5550. case 35:
  5551. b = "slider" === d.getAttribute("role");
  5552. break;
  5553. case 38:
  5554. case 40:
  5555. m = d.getAttribute("role"),
  5556. d = 38 === c ? d.previousSibling : d.nextSibling,
  5557. "slider" === m ? b = !0 : e && ("option" === m ? (d && "option" === d.getAttribute("role") && d.focus(),
  5558. f = b = !0) : m && 0 === m.indexOf("menuitem") && (d && d.hasAttribute("role") && 0 === d.getAttribute("role").indexOf("menuitem") && d.focus(),
  5559. f = b = !0))
  5560. }
  5561. if (e && !f)
  5562. switch (c) {
  5563. case 38:
  5564. f = Math.min(this.api.getVolume() + 5, 100);
  5565. XV(this.Wd, f, !1);
  5566. this.api.setVolume(f);
  5567. h = f = !0;
  5568. break;
  5569. case 40:
  5570. f = Math.max(this.api.getVolume() - 5, 0);
  5571. XV(this.Wd, f, !0);
  5572. this.api.setVolume(f);
  5573. h = f = !0;
  5574. break;
  5575. case 36:
  5576. this.api.Yh() && (this.api.startSeekCsiAction(),
  5577. this.api.seekTo(0, void 0, void 0, void 0, 79),
  5578. h = f = !0);
  5579. break;
  5580. case 35:
  5581. this.api.Yh() && (this.api.startSeekCsiAction(),
  5582. this.api.seekTo(Infinity, void 0, void 0, void 0, 80),
  5583. h = f = !0)
  5584. }
  5585. */
  5586.  
  5587. }
  5588.  
  5589.  
  5590. if (rr) {
  5591.  
  5592. // focusBodyIfSuccess && Promise.resolve().then(() => {
  5593. // activeElement === document.activeElement && activeElement.blur();
  5594. // });
  5595.  
  5596. evt.preventDefault();
  5597. evt.stopImmediatePropagation();
  5598. evt.stopPropagation();
  5599.  
  5600. }
  5601.  
  5602. };
  5603.  
  5604. document.addEventListener('keydown', keyEventListener, { capture: true });
  5605.  
  5606.  
  5607. document.addEventListener('keyup', keyEventListener, { capture: true });
  5608.  
  5609. }
  5610.  
  5611. return { pageMediaWatcher, shortcutKeysFixer, keyboardController };
  5612.  
  5613. })();
  5614.  
  5615.  
  5616. pageMediaWatcher();
  5617. FIX_SHORTCUTKEYS > 0 && shortcutKeysFixer();
  5618.  
  5619.  
  5620. const check_for_set_key_order = (() => {
  5621.  
  5622. let mySet = new Set();
  5623.  
  5624. mySet.add("value1");
  5625. mySet.add("value2");
  5626. mySet.add("value3");
  5627.  
  5628. // Function to convert Set values to an array
  5629. function getSetValues(set) {
  5630. return Array.from(set.values());
  5631. }
  5632.  
  5633. // Function to test if the Set maintains insertion order
  5634. function testSetOrder(set, expectedOrder) {
  5635. let values = getSetValues(set);
  5636. return expectedOrder.join(',') === values.join(',');
  5637. }
  5638.  
  5639. // Test 1: Initial order
  5640. if (mySet.values().next().value !== "value1") return false;
  5641. if (!testSetOrder(mySet, ["value1", "value2", "value3"])) return false;
  5642.  
  5643. // Test 2: After deleting an element
  5644. mySet.delete("value2");
  5645. if (mySet.values().next().value !== "value1") return false;
  5646. if (!testSetOrder(mySet, ["value1", "value3"])) return false;
  5647.  
  5648. // Test 3: After re-adding a deleted element
  5649. mySet.add("value2");
  5650. if (mySet.values().next().value !== "value1") return false;
  5651. if (!testSetOrder(mySet, ["value1", "value3", "value2"])) return false;
  5652.  
  5653. // Test 4: After adding a new element
  5654. mySet.add("value4");
  5655. if (mySet.values().next().value !== "value1") return false;
  5656. if (!testSetOrder(mySet, ["value1", "value3", "value2", "value4"])) return false;
  5657.  
  5658. // Test 5: Delete+Add
  5659. mySet.delete("value1");
  5660. mySet.delete("value3");
  5661. mySet.add("value3");
  5662. mySet.add("value1");
  5663. if (mySet.values().next().value !== "value2") return false;
  5664. if (!testSetOrder(mySet, ["value2", "value4", "value3", "value1"])) return false;
  5665.  
  5666. return true;
  5667. })();
  5668.  
  5669.  
  5670. // const qm47 = Symbol();
  5671. // const qm57 = Symbol();
  5672. const qm53 = Symbol();
  5673. const qn53 = Symbol();
  5674.  
  5675.  
  5676. const ump3 = new WeakMap();
  5677.  
  5678. const stp = document.createElement('noscript');
  5679. stp.id = 'weakref-placeholder';
  5680.  
  5681. PROP_OverReInclusion_AVOID && (() => {
  5682.  
  5683.  
  5684. if (typeof HTMLElement_.prototype.hasOwnProperty72 === 'function' || typeof HTMLElement_.prototype.hasOwnProperty !== 'function') return;
  5685. const f = HTMLElement_.prototype.hasOwnProperty72 = HTMLElement_.prototype.hasOwnProperty;
  5686. let byPassVal = null;
  5687. let byPassCount = 0;
  5688. let mmw = new Set();
  5689. HTMLElement_.prototype.hasOwnProperty = function (prop) {
  5690. if (arguments.length !== 1) return f.apply(this, arguments);
  5691. if (byPassVal !== null && typeof prop === 'string') {
  5692.  
  5693. if (PROP_OverReInclusion_LIST.has(prop)) {
  5694. byPassCount++;
  5695. return byPassVal;
  5696. }
  5697. PROP_OverReInclusion_DEBUGLOG && mmw.add(prop);
  5698.  
  5699. }
  5700. return this.hasOwnProperty72(prop);
  5701. };
  5702.  
  5703.  
  5704. /*
  5705.  
  5706.  
  5707. z.prototype.forwardDynamicProps = function() {
  5708. var B = m(this.inst);
  5709. B = h(B);
  5710. for (var F = B.next(); !F.done; F = B.next()) {
  5711. var H = h(F.value);
  5712. F = H.next().value;
  5713. H = H.next().value;
  5714. my(this, F, H);
  5715. r(b) && !ly(F) && Wua(this.inst, F)
  5716. }
  5717. }
  5718.  
  5719. */
  5720.  
  5721.  
  5722.  
  5723. let byPassZeroShowed = false;
  5724. const forwardDynamicPropsGeneral = function () {
  5725. byPassVal = true;
  5726. byPassCount = 0;
  5727. PROP_OverReInclusion_DEBUGLOG && mmw.clear();
  5728. const ret = this.forwardDynamicProps72();
  5729. byPassVal = null;
  5730. if (byPassCount === 0 && !byPassZeroShowed) {
  5731. byPassZeroShowed = true;
  5732. console.log('[yt-js-engine-tamer] byPassCount = 0 in forwardDynamicProps')
  5733. }
  5734. byPassCount = 0;
  5735. if (PROP_OverReInclusion_DEBUGLOG && mmw.size > 0) {
  5736. console.log(399, '[yt-js-engine-tamer]', [...mmw]);
  5737. mmw.clear();
  5738. }
  5739. return ret;
  5740. };
  5741.  
  5742. const propCheck = (proto) => {
  5743. if (typeof (proto || 0) == 'object' && typeof proto.forwardDynamicProps === 'function' && typeof proto.forwardDynamicProps72 !== 'function') {
  5744. proto.forwardDynamicProps72 = proto.forwardDynamicProps;
  5745. if (proto.forwardDynamicProps.length === 0) {
  5746. proto.forwardDynamicProps = forwardDynamicPropsGeneral;
  5747. }
  5748. }
  5749. };
  5750.  
  5751. const valMap = new WeakMap();
  5752. Object.defineProperty(HTMLElement_.prototype, 'didForwardDynamicProps', {
  5753. get() {
  5754. propCheck(this.constructor.prototype);
  5755. return valMap.get(this);
  5756. },
  5757. set(nv) {
  5758. propCheck(this.constructor.prototype);
  5759. valMap.set(this, nv);
  5760. return true;
  5761. },
  5762. enumerable: false,
  5763. configurable: true
  5764.  
  5765. });
  5766.  
  5767. promiseForCustomYtElementsReady.then(() => {
  5768. if (typeof customElements !== 'object' || typeof customElements.define72 === 'function' || typeof customElements.define !== 'function') return;
  5769. if (customElements.define.length !== 2) return;
  5770. customElements.define72 = customElements.define;
  5771. customElements.define = function (b, w) {
  5772. propCheck(w.prototype);
  5773. const ret = this.define72(b, w);
  5774. return ret;
  5775. }
  5776. });
  5777.  
  5778. })();
  5779.  
  5780. if (FIX_FlexibleItemSizing) { // for youtube flow chat
  5781.  
  5782. const flexibleItemListMo = new MutationObserver((mutations) => {
  5783. // cnt.onStamperFinished
  5784. // cnt.maybeUpdateFlexibleMenu
  5785. const set = new Set();
  5786. for (const mutation of mutations) {
  5787. if (mutation && ((mutation.addedNodes || 0).length > 0 || (mutation.removedNodes || 0).length > 0)) {
  5788. set.add(mutation.target);
  5789. }
  5790. }
  5791. for (const s of set) {
  5792. const cnt = insp(s);
  5793. if (typeof cnt.maybeUpdateFlexibleMenuImpl === 'function') {
  5794. cnt.maybeUpdateFlexibleMenuImpl();
  5795. } else if (typeof cnt.maybeUpdateFlexibleMenu === 'function') {
  5796. cnt.maybeUpdateFlexibleMenu();
  5797. } else if (typeof cnt.onStamperFinished === 'function') {
  5798. cnt.onStamperFinished();
  5799. }
  5800. }
  5801. set.clear();
  5802. });
  5803.  
  5804. let checkConfig = true;
  5805. const flexibleItemDocMo = new MutationObserver(() => {
  5806. for (const s of document.querySelectorAll('ytd-menu-renderer[has-flexible-items]:not([b289ad])')) {
  5807. s.setAttribute('b289ad', '');
  5808. flexibleItemListMo.observe(s, { subtree: false, childList: true });
  5809. s.appendChild(document.createComment('.')).remove();
  5810. }
  5811. if (checkConfig) {
  5812. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  5813. if (config && config.EXPERIMENT_FLAGS) {
  5814. checkConfig = false;
  5815. config.EXPERIMENT_FLAGS.web_fix_missing_action_buttons = true;
  5816. }
  5817. }
  5818. });
  5819. flexibleItemDocMo.observe(document, { subtree: true, childList: true });
  5820.  
  5821. }
  5822.  
  5823.  
  5824.  
  5825.  
  5826. const observablePromise = (proc, timeoutPromise) => {
  5827. let promise = null;
  5828. return {
  5829. obtain() {
  5830. if (!promise) {
  5831. promise = new Promise(resolve => {
  5832. let mo = null;
  5833. const f = () => {
  5834. let t = proc();
  5835. if (t) {
  5836. mo.disconnect();
  5837. mo.takeRecords();
  5838. mo = null;
  5839. resolve(t);
  5840. }
  5841. }
  5842. mo = new MutationObserver(f);
  5843. mo.observe(document, { subtree: true, childList: true })
  5844. f();
  5845. timeoutPromise && timeoutPromise.then(() => {
  5846. resolve(null)
  5847. });
  5848. });
  5849. }
  5850. return promise
  5851. }
  5852. }
  5853. }
  5854.  
  5855.  
  5856. if (HOOK_ACTIVE_MODULES_fetchUpdatedMetadata) {
  5857. observablePromise(() => {
  5858. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  5859. if (config && config.EXPERIMENT_FLAGS) {
  5860. config.EXPERIMENT_FLAGS.web_watch_get_updated_metadata_manager = true;
  5861. return true;
  5862. }
  5863. }).obtain();
  5864. }
  5865.  
  5866. if (FIX_ROLLING_NUMBER_UPDATE) {
  5867.  
  5868.  
  5869. observablePromise(() => {
  5870. if (typeof customElements === 'undefined') return;
  5871. const ce = customElements.get('yt-animated-rolling-number');
  5872. if (!ce) return;
  5873. return ce.prototype;
  5874. }).obtain().then(async (cProto) => {
  5875.  
  5876. const p = document.createElement('yt-animated-rolling-number');
  5877.  
  5878. const frag = document.createDocumentFragment();
  5879. frag.appendChild(p);
  5880. const pDoc = document.implementation.createHTMLDocument();
  5881. pDoc.body.appendChild(frag);
  5882.  
  5883. let p88 = p;
  5884.  
  5885. const __instance = await observablePromise(() => {
  5886. const __instance = (p88 || 0).__instance;
  5887. if (__instance && __instance.render) return __instance;
  5888. }).obtain();
  5889. p88 = null;
  5890.  
  5891. const itProto = Reflect.getPrototypeOf(__instance);
  5892.  
  5893. try {
  5894. p.remove();
  5895. } catch (e) { }
  5896.  
  5897. if (itProto.render && !itProto.render37 && itProto.render.length === 1) {
  5898.  
  5899. itProto.render37 = itProto.render;
  5900. itProto.render = function (t) {
  5901. // (this.xCounter = (this.xCounter & 1073741823)+1)
  5902. let c33 = '';
  5903. let r33 = null;
  5904. let kc = 0;
  5905.  
  5906. if (this && t && this.hookCounter >= 1 && !this.__unmounted && this.el) {
  5907. const el = this.el;
  5908. const ct = Date.now();
  5909. const lastFireTime = (el.__lastFireTime491__ || 0);
  5910.  
  5911. const fireTimeDiff = lastFireTime > 0 ? ct - lastFireTime : 1e9;
  5912.  
  5913. if (fireTimeDiff < 80 && this.__previousRender61__) {
  5914. return this.__previousRender61__;
  5915. }
  5916.  
  5917. const caseInt =
  5918. (t && typeof t.numberText === 'string' && Number.isFinite(t.numberValue)) ? 1 :
  5919. (t && typeof t.character === 'string') ? (
  5920. (typeof t.previousCharacter === 'string') ? 6 : 2
  5921. ) : 0;
  5922.  
  5923. if (caseInt === 6 && t.previousCharacter && t.character && this.__previousRender61__ && fireTimeDiff < 9400) {
  5924. if (this[`__lastCharRender62__${t.previousCharacter}>${t.character}`] === this.__previousRender61__) {
  5925. return this.__previousRender61__;
  5926. }
  5927. }
  5928. if (caseInt === 1 && t.numberText.length > 0 && this.__previousRender61__ && fireTimeDiff < 9400) {
  5929. if (this[`__lastCharRender65__${t.numberValue}>${t.numberText}`] === this.__previousRender61__) {
  5930. return this.__previousRender61__;
  5931. }
  5932. }
  5933.  
  5934. if (caseInt & 2) {
  5935.  
  5936. if (caseInt & 4) {
  5937.  
  5938. if (el.__lastCharacter353__ && el.__lastCharacter353__.length === 1 && t.character.length === 1 && t.previousCharacter.length === 1) {
  5939. if (t.character !== t.previousCharacter && t.character === el.__lastCharacter353__) {
  5940. t.previousCharacter = t.character;
  5941. kc = 1;
  5942. }
  5943. }
  5944.  
  5945. if (t && t.character && t.previousCharacter && t.shouldAnimate === true && t.character === t.previousCharacter) {
  5946. t.shouldAnimate = false;
  5947. }
  5948. }
  5949.  
  5950.  
  5951. c33 = `__lastCharRender62__${t.previousCharacter}>${t.character}`;
  5952.  
  5953. el.__lastCharacter353__ = t.character;
  5954.  
  5955. } else if (caseInt === 1) {
  5956.  
  5957. if (el.__lastNumberValue353__ === t.numberValue && t.shouldAnimate === true) {
  5958. t.shouldAnimate = false;
  5959. }
  5960. el.__lastNumberValue353__ = t.numberValue;
  5961.  
  5962. if (el.__lastNumberText353__ === t.numberText && t.shouldAnimate === true) {
  5963. t.shouldAnimate = false;
  5964. }
  5965. el.__lastNumberText353__ = t.numberText;
  5966.  
  5967. c33 = `__lastCharRender65__${t.numberValue}>${t.numberText}`;
  5968.  
  5969. }
  5970.  
  5971. // console.log(138002, this, t, caseInt, kc, fireTimeDiff);
  5972.  
  5973. el.__lastFireTime491__ = ct;
  5974. }
  5975.  
  5976. // // console.log(21399, t.character, t.previousCharacter, (t.xCounter = (t.xCounter & 1073741823)+1), t, (this.xCounter = (this.xCounter & 1073741823)+1) )
  5977. // // console.log(12883, this, t);
  5978. const r = r33 || this.render37(t);
  5979. this.__previousRender61__ = r;
  5980. if (c33) this[c33] = r;
  5981. return r
  5982. }
  5983.  
  5984. }
  5985.  
  5986. });
  5987.  
  5988. }
  5989.  
  5990. if (HOOK_ACTIVE_MODULES) {
  5991.  
  5992. let watchController;
  5993. const watchControllerObservable = observablePromise(() => {
  5994. const watchFlexy = document.querySelector('ytd-watch-flexy');
  5995. if (!watchFlexy) return;
  5996. return insp(watchFlexy).watchController;
  5997. }).obtain();
  5998. (async () => {
  5999. watchController = await watchControllerObservable;
  6000.  
  6001. const activeModules = watchController.activeModules;
  6002. if (!activeModules) return;
  6003.  
  6004. const checkFn = (activeModule) => {
  6005. if (activeModule && typeof activeModule.fetchUpdatedMetadata === 'function' && activeModule.fetchUpdatedMetadata.length === 2) {
  6006. HOOK_ACTIVE_MODULES_fetchUpdatedMetadata && hookActiveModuleFetchUpdatedMetadata(activeModule);
  6007. }
  6008. }
  6009. if (!activeModules.push8792 && activeModules.push) {
  6010. activeModules.push8792 = activeModules.push;
  6011. activeModules.push = function (a, ...args) {
  6012. checkFn(a);
  6013. let r = args.length >= 1 ? this.push8792(a, ...args) : this.push8792(a);
  6014. return r;
  6015. }
  6016. }
  6017. activeModules.forEach(checkFn);
  6018.  
  6019. })();
  6020.  
  6021. let yieldResultWrappingByPass = false;
  6022. let asyncProto = null;
  6023. const yieldResultWrapping = (f) => {
  6024. if (yieldResultWrappingByPass) return [f(), null];
  6025. yieldResultWrappingByPass = true;
  6026. let D = null;
  6027. let promise, e_;
  6028. if (asyncProto) {
  6029. Object.defineProperty(asyncProto, 'yieldResult', {
  6030. get() {
  6031. return undefined;
  6032. },
  6033. set(nv) {
  6034. delete asyncProto.yieldResult;
  6035. this.yieldResult = nv;
  6036. D = this;
  6037. // console.log(122, this);
  6038. return true;
  6039. },
  6040. enumerable: false,
  6041. configurable: true
  6042. });
  6043. try {
  6044. promise = f();
  6045. } catch (e) { e_ = e }
  6046. delete asyncProto.yieldResult;
  6047. yieldResultWrappingByPass = false;
  6048. } else {
  6049. Object.defineProperty(Object.prototype, 'yieldResult', {
  6050. get() {
  6051. return undefined;
  6052. },
  6053. set(nv) {
  6054. delete Object.prototype.yieldResult;
  6055. this.yieldResult = nv;
  6056. D = this;
  6057. // console.log(122, this);
  6058. return true;
  6059. },
  6060. enumerable: false,
  6061. configurable: true
  6062. });
  6063. try {
  6064. promise = f();
  6065. } catch (e) { e_ = e }
  6066. delete Object.prototype.yieldResult;
  6067. yieldResultWrappingByPass = false;
  6068. if (D) {
  6069. asyncProto = Reflect.getPrototypeOf(D);
  6070. }
  6071. }
  6072. if (e_) throw e_;
  6073. return [promise, D];
  6074. }
  6075.  
  6076. const hookActiveModuleFetchUpdatedMetadata = (activeModule) => {
  6077.  
  6078. const aProto = Reflect.getPrototypeOf(activeModule);
  6079.  
  6080. if (!aProto || !aProto.fetchUpdatedMetadata || aProto.fetchUpdatedMetadata517) return;
  6081.  
  6082. console.log('[yt-js-engine-tamer] hookActiveModuleFetchUpdatedMetadata');
  6083.  
  6084. // console.log(12885)
  6085. aProto.fetchUpdatedMetadata517 = aProto.fetchUpdatedMetadata;
  6086. // let qxt=false;
  6087. aProto.fetchUpdatedMetadata = function (t, P) {
  6088.  
  6089. // if (!qxt) {
  6090. // qxt = true;
  6091. // var y = watchController.subscribe("WATCH_NEXT_RESPONSE_UPDATED", function (...args) {
  6092. // console.log(199001,...args)
  6093. // });
  6094. // this.addOnDisposeCallback(function (...args) {
  6095.  
  6096. // console.log(199002,...args)
  6097. // watchController.unsubscribeByKey(y)
  6098. // qxt = false;
  6099. // });
  6100. // }
  6101. const [promise, D] = yieldResultWrapping(() => this.fetchUpdatedMetadata517(t, P));
  6102. if (D) promise.then(() => {
  6103. const yieldResult = D.yieldResult;
  6104. if (yieldResult) {
  6105. const mutations = (((yieldResult || 0).frameworkUpdates || 0).entityBatchUpdate || 0).mutations;
  6106.  
  6107. if (mutations && mutations.length >= 1) {
  6108. let likeCountEntity = null;
  6109. for (const mutation of mutations) {
  6110. if (typeof (mutation.entityKey || 0) === 'string' && (likeCountEntity = (mutation.payload || 0).likeCountEntity)) {
  6111. break;
  6112. }
  6113. }
  6114. if (likeCountEntity) {
  6115. const model = insp(document.querySelector('segmented-like-dislike-button-view-model'));
  6116. if (model && typeof model.update === 'function' && model.update.length === 0) {
  6117. const data = ((model || 0).props || 0).data;
  6118. if (data) {
  6119. if (typeof data.likeCountEntity !== 'object') data.likeCountEntity = {};
  6120. // console.log(12838, {...data.likeCountEntity}, {...likeCountEntity})
  6121. // const shouldModelUpdate = (data.likeCountEntity.key !== likeCountEntity.key); // to be reviewed
  6122. const shouldModelUpdate = true;
  6123. Object.assign(data.likeCountEntity, likeCountEntity);
  6124. // data.likeCountEntity = likeCountEntity;
  6125. // if (shouldModelupdate) model.update();
  6126. // else {
  6127. // if (typeof model.notifyPath === 'function' && model.notifyPath.length === 0) model.notifyPath();
  6128. // }
  6129.  
  6130. if (shouldModelUpdate) {
  6131. if (typeof model.enqueueUpdate === 'function' && model.enqueueUpdate.length === 0) {
  6132. // console.log('kk1a enqueueUpdate')
  6133. model.enqueueUpdate();
  6134. // console.log('kk1b enqueueUpdate')
  6135. } else if (typeof model.update === 'function' && model.update.length === 0) {
  6136. // console.log('kk2a update')
  6137. model.update();
  6138. // console.log('kk2b update')
  6139. } else {
  6140. console.warn('[yt-js-engine-tamer] cannot do model update.')
  6141. }
  6142. }
  6143.  
  6144. }
  6145. }
  6146. }
  6147. }
  6148. }
  6149. }).catch(console.warn);
  6150. return promise;
  6151. };
  6152.  
  6153. }
  6154.  
  6155. }
  6156.  
  6157. // ----------------------------
  6158.  
  6159. const nativeNow = Reflect.getPrototypeOf(performance).now.bind(performance);
  6160.  
  6161. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : (f) => (Promise.resolve().then(f), void 0);
  6162.  
  6163. FIX_ICON_RENDER && whenCEDefined('yt-icon').then(async () => {
  6164.  
  6165.  
  6166. // const globalPromiseStack = {};
  6167.  
  6168. // let dummy;
  6169. // while(!dummy){
  6170.  
  6171. // dummy = document.querySelector('yt-icon');
  6172. // await new Promise(r=>setTimeout(r,0));
  6173. // }
  6174.  
  6175. dummy = document.createElement('yt-icon');
  6176.  
  6177. let cProto;
  6178. if (!(dummy instanceof Element)) return;
  6179. cProto = insp(dummy).constructor.prototype;
  6180.  
  6181. cProto.handlePropertyChange671 = cProto.handlePropertyChange;
  6182. cProto.determineIconSet671 = cProto.determineIconSet;
  6183. cProto.switchToYtSysIconset671 = cProto.switchToYtSysIconset;
  6184. cProto.useYtSysIconsetForMissingIcons671 = cProto.useYtSysIconsetForMissingIcons;
  6185. cProto.getIconManager671 = cProto.getIconManager;
  6186. cProto.getIconShapeData671 = cProto.getIconShapeData;
  6187. cProto.renderIcon671 = cProto.renderIcon;
  6188.  
  6189. // cProto.attached488 = cProto.attached;
  6190. // cProto.attached = function(){
  6191. // console.log('attached')
  6192. // return this.attached488(...arguments);
  6193. // }
  6194. // cProto.detached488 = cProto.detached;
  6195. // cProto.detached = function(){
  6196. // console.log('detached')
  6197. // return this.detached488(...arguments);
  6198. // }
  6199.  
  6200. if (cProto.__renderIconFix__) return;
  6201. cProto.__renderIconFix__ = true;
  6202.  
  6203. let taskStack = [];
  6204. const cmObs = new MutationObserver(() => {
  6205. const tasks = taskStack.slice();
  6206. taskStack.length = 0;
  6207. for (const task of tasks) {
  6208. task();
  6209. }
  6210. })
  6211. const cm = document.createComment('1');
  6212. const stackTask = (f) => {
  6213. taskStack.push(f);
  6214. cm.data = `${(cm.data & 7) + 1}`;
  6215. }
  6216. cmObs.observe(cm, { characterData: true });
  6217.  
  6218. // let iconManagers = {}; // assume shared
  6219.  
  6220. // window.iconManagers = () => iconManagers;
  6221.  
  6222.  
  6223. const setupYtIcon = (inst) => {
  6224.  
  6225. if (inst.__ytIconSetup588__) return;
  6226. const cProto = Reflect.getPrototypeOf(inst);
  6227. cProto.__ytIconSetup588__ = true;
  6228.  
  6229.  
  6230. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  6231.  
  6232. config.EXPERIMENT_FLAGS.wil_icon_render_when_idle = false; // single rendering
  6233. config.EXPERIMENT_FLAGS.wil_icon_load_immediately = true; // single rendering
  6234. // config.EXPERIMENT_FLAGS.wil_icon_use_mask_rendering = false; // DON'T!
  6235. config.EXPERIMENT_FLAGS.wil_icon_network_first = true; // single rendering
  6236.  
  6237.  
  6238. // this.renderingMode = _.x("wil_icon_use_mask_rendering") ? 1 : 0;
  6239. // this.isNetworkFirstStrategy = _.x("wil_icon_network_first");
  6240. // this.renderWhenIdle = _.x("wil_icon_render_when_idle");
  6241. // this.waitForAnimationFrame = !_.x("wil_icon_load_immediately");
  6242.  
  6243.  
  6244.  
  6245. }
  6246.  
  6247. cProto.handlePropertyChange = function (...a) { // 10+
  6248.  
  6249. const __data = this.__data;
  6250. if (FIX_GUIDE_ICON && this.id === 'guide-icon' && __data && !__data.icon && typeof this.set === 'function') {
  6251. this.set('icon', "yt-icons:menu")
  6252. }
  6253.  
  6254. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6255. this.__resolved__ = {
  6256.  
  6257. };
  6258. const a01 = this.isAttached;
  6259. let a02, a03;
  6260.  
  6261.  
  6262. const t = this.__stackedKey3818__ = (this.__stackedKey3818__ & 1073741823) + 1;
  6263.  
  6264. const stackFn = () => {
  6265. if (t !== this.__stackedKey3818__) {
  6266. return;
  6267. }
  6268. a03 = this.isAttached;
  6269.  
  6270. if (a01 === false && a02 === false && a03 === false) return;
  6271.  
  6272. if (a01 === true && a02 === true && a03 === true) {
  6273.  
  6274. } else {
  6275. if (a01 === undefined && a02 === undefined && a03 === undefined && (this.hostElement || this).isConnected === false) {
  6276. // unknown yt-icon#label-icon
  6277. return;
  6278. } else {
  6279. console.log('[yt-icon] debug', a01, a02, a03, this)
  6280. }
  6281. }
  6282.  
  6283. this.handlePropertyChange671(...arguments);
  6284.  
  6285. };
  6286.  
  6287.  
  6288.  
  6289. Promise.resolve().then(() => {
  6290. a02 = this.isAttached;
  6291. stackTask(stackFn);
  6292. });
  6293.  
  6294.  
  6295. }
  6296.  
  6297. cProto.determineIconSet = function (a, b, c, d) { // 10-
  6298.  
  6299. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6300. // string bool? bool=false int=24
  6301. // NOTIFICATIONS_NONE OR LIKE
  6302. // console.log('yt-icon.determineIconSet', ...arguments);
  6303.  
  6304. const r = this.determineIconSet671(...arguments);
  6305. return r;
  6306. }
  6307.  
  6308. cProto.switchToYtSysIconset = function (a, b, c, d) { // 10-
  6309.  
  6310. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6311. // same as determineIconSet
  6312. // console.log('yt-icon.switchToYtSysIconset', ...arguments);
  6313. return this.switchToYtSysIconset671(...arguments);
  6314. }
  6315.  
  6316. cProto.useYtSysIconsetForMissingIcons = function (a, b, c, d) { // X
  6317.  
  6318. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6319. // console.log('yt-icon.useYtSysIconsetForMissingIcons', ...arguments);
  6320. return this.useYtSysIconsetForMissingIcons671(...arguments);
  6321. }
  6322.  
  6323. cProto.getIconManager = function () { // 10+
  6324.  
  6325. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6326. if (!this.__resolved__) this.__resolved__ = {};
  6327. if (!this.__resolved__.getIconManager) this.__resolved__.getIconManager = this.getIconManager671(...arguments);
  6328. const r = this.__resolved__.getIconManager;
  6329. return r;
  6330. }
  6331.  
  6332. cProto.getIconShapeData = function () { // 10+
  6333.  
  6334. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6335.  
  6336. // no argument
  6337. // console.log('yt-icon.getIconShapeData', ...arguments);
  6338. if (!this.__resolved__) this.__resolved__ = {};
  6339. if (!this.__resolved__.getIconShapeData) this.__resolved__.getIconShapeData = this.getIconShapeData671(...arguments);
  6340. const r = this.__resolved__.getIconShapeData;
  6341. return r
  6342. }
  6343.  
  6344. cProto.renderIcon = function (a, b) { // X
  6345.  
  6346. if (!this.__ytIconSetup588__) setupYtIcon(this);
  6347. // "" yt-icons:xxx
  6348. // console.log('yt-icon.renderIcon', ...arguments);
  6349. return this.renderIcon671(...arguments);
  6350. }
  6351.  
  6352. });
  6353.  
  6354.  
  6355. /**
  6356. * Compute the Longest Common Subsequence between two arrays.
  6357. * Returns an array of the LCS elements (in order).
  6358. */
  6359. function computeLCS(a, b) {
  6360. // Input validation
  6361. if (!Array.isArray(a) || !Array.isArray(b)) {
  6362. throw new Error('Inputs must be arrays');
  6363. }
  6364.  
  6365. const n = a.length, m = b.length;
  6366. // Early termination for trivial cases
  6367. if (n === 0 || m === 0) return [];
  6368. // Check for shallow equality
  6369. if (n === m && a.every((x, i) => x === b[i])) return a.slice();
  6370.  
  6371. // Use smaller dimension for space optimization
  6372. if (n > m) return computeLCS(b, a); // Ensure n <= m
  6373.  
  6374. // dp[i%2][j] = length of LCS of a[i..] and b[j..]
  6375. // Use Uint32Array for robustness with long sequences
  6376. const dp = [
  6377. new Uint32Array(m + 1),
  6378. new Uint32Array(m + 1),
  6379. ];
  6380. // Store predecessor for backtracking: 0=diagonal, 1=down, 2=right
  6381. // Optimize space by storing only necessary entries
  6382. const pred = new Uint8Array(n * m); // Single array for moves
  6383.  
  6384. for (let i = n - 1; i >= 0; i--) {
  6385. const curr = i % 2;
  6386. const next = 1 - curr;
  6387. // Clear current row for reuse
  6388. dp[curr].fill(0);
  6389.  
  6390. for (let j = m - 1; j >= 0; j--) {
  6391. const idx = i * m + j;
  6392. if (a[i] === b[j]) {
  6393. dp[curr][j] = dp[next][j + 1] + 1;
  6394. pred[idx] = 0; // Diagonal
  6395. } else if (dp[next][j] >= dp[curr][j + 1]) {
  6396. dp[curr][j] = dp[next][j];
  6397. pred[idx] = 1; // Down
  6398. } else {
  6399. dp[curr][j] = dp[curr][j + 1];
  6400. pred[idx] = 2; // Right
  6401. }
  6402. }
  6403. }
  6404.  
  6405. // Check for potential overflow
  6406. if (dp[0][0] > 0xFFFFFFFF) {
  6407. throw new Error('LCS length exceeds safe integer limit');
  6408. }
  6409.  
  6410. // Backtrack to build the actual LCS
  6411. const lcs = [];
  6412. let i = 0, j = 0;
  6413. while (i < n && j < m) {
  6414. const idx = i * m + j;
  6415. const p = pred[idx];
  6416. if (p === 0) {
  6417. lcs.push(a[i]);
  6418. i++; j++;
  6419. } else if (p === 1) {
  6420. i++;
  6421. } else {
  6422. j++;
  6423. }
  6424. }
  6425. return lcs;
  6426. }
  6427.  
  6428. /**
  6429. * Given original[] and modified[], produce an array of splice-ops:
  6430. * [ [start0, deleteCount0, addedItems0],
  6431. * [start1, deleteCount1, addedItems1],
  6432. * … ]
  6433. * When you do:
  6434. * let arr = original.slice();
  6435. * for (let [s, d, adds] of ops) arr.splice(s, d, ...adds);
  6436. * arr will equal modified.
  6437. */
  6438. function diffSplices(original, modified) {
  6439. // Input validation
  6440. if (!Array.isArray(original) || !Array.isArray(modified)) {
  6441. throw new Error('Inputs must be arrays');
  6442. }
  6443.  
  6444. const origLen = original.length;
  6445. const modLen = modified.length;
  6446. // Early termination for trivial cases
  6447. if (origLen === 0 && modLen === 0) return [];
  6448. if (origLen === 0) return [[0, 0, modified.slice()]];
  6449. if (modLen === 0) return [[0, origLen, []]];
  6450.  
  6451. // Trim common prefix and suffix
  6452. let prefixLen = 0;
  6453. while (prefixLen < origLen && prefixLen < modLen && original[prefixLen] === modified[prefixLen]) {
  6454. prefixLen++;
  6455. }
  6456. let suffixLen = 0;
  6457. while (
  6458. suffixLen < origLen - prefixLen &&
  6459. suffixLen < modLen - prefixLen &&
  6460. original[origLen - 1 - suffixLen] === modified[modLen - 1 - suffixLen]
  6461. ) {
  6462. suffixLen++;
  6463. }
  6464.  
  6465. // Cache references for speed
  6466. const orig = original.slice(prefixLen, origLen - suffixLen);
  6467. const mod = modified.slice(prefixLen, modLen - suffixLen);
  6468. const lcs = computeLCS(orig, mod);
  6469. // Pre-allocate ops array, accounting for potential moves
  6470. const ops = new Array(Math.ceil((orig.length + mod.length) / 1.5));
  6471. let opCount = 0;
  6472.  
  6473. let i = 0, j = 0, k = 0;
  6474. let curIndex = prefixLen;
  6475. const lcsLen = lcs.length;
  6476.  
  6477. while (k < lcsLen) {
  6478. const match = lcs[k];
  6479. let deleteCount = 0;
  6480. const deleted = [];
  6481. const added = [];
  6482.  
  6483. // 1) Collect deletions up to the next common element
  6484. while (i < orig.length && orig[i] !== match) {
  6485. deleted.push(orig[i]);
  6486. deleteCount++;
  6487. i++;
  6488. }
  6489.  
  6490. // 2) Collect insertions up to that same element
  6491. while (j < mod.length && mod[j] !== match) {
  6492. added.push(mod[j]);
  6493. j++;
  6494. }
  6495.  
  6496. // 3) Check for a move (deleted segment matches inserted segment)
  6497. let isMove = false;
  6498. if (deleteCount > 0 && deleteCount === added.length) {
  6499. isMove = deleted.every((x, idx) => x === added[idx]);
  6500. if (isMove) {
  6501. // If a move, split into delete and insert at different indices
  6502. if (deleteCount > 0) {
  6503. ops[opCount++] = [curIndex, deleteCount, []]; // Delete at current index
  6504. ops[opCount++] = [curIndex, 0, added]; // Insert at same index
  6505. curIndex += added.length; // Advance past inserted items
  6506. }
  6507. }
  6508. }
  6509.  
  6510. // 4) Combine delete and insert into a single operation if not a move
  6511. if (!isMove && (deleteCount > 0 || added.length > 0)) {
  6512. ops[opCount++] = [curIndex, deleteCount, added];
  6513. curIndex += added.length; // Advance past inserted items
  6514. }
  6515.  
  6516. // 5) Skip over the matching element itself
  6517. i++;
  6518. j++;
  6519. k++;
  6520. curIndex++;
  6521. }
  6522.  
  6523. // 6) Handle any trailing deletions and insertions as a single operation
  6524. const trailingDelete = orig.length - i;
  6525. const trailingAdd = mod.slice(j);
  6526. if (trailingDelete > 0 || trailingAdd.length > 0) {
  6527. // Check for trailing move
  6528. const trailingDeleted = orig.slice(i);
  6529. let isMove = false;
  6530. if (trailingDelete > 0 && trailingDelete === trailingAdd.length) {
  6531. isMove = trailingDeleted.every((x, idx) => x === trailingAdd[idx]);
  6532. if (isMove) {
  6533. ops[opCount++] = [curIndex, trailingDelete, []];
  6534. ops[opCount++] = [curIndex, 0, trailingAdd];
  6535. }
  6536. }
  6537. if (!isMove) {
  6538. ops[opCount++] = [curIndex, trailingDelete, trailingAdd];
  6539. }
  6540. }
  6541.  
  6542. // 7) Truncate ops array to actual size
  6543. ops.length = opCount;
  6544.  
  6545. return ops;
  6546. }
  6547. // class listPlaceholder {
  6548. // constructor(len){
  6549. // this.length = len;
  6550. // }
  6551. // }
  6552.  
  6553.  
  6554.  
  6555. // rendererStamperApplyChangeRecord_: function(path, key, changeRecord) {
  6556. // var renderJob = this.renderJobsMap_[key],
  6557. // renderCallback = null;
  6558.  
  6559. // if (path === changeRecord.path) {
  6560. // let value = changeRecord.value;
  6561.  
  6562. // if (!_.v_(value)) {
  6563. // value = (value === void 0 || value === null) ? [] : [value];
  6564. // }
  6565.  
  6566. // let stampDomEntry = this.stampDom[path];
  6567.  
  6568. // if (stampDomEntry.mapping) {
  6569. // renderCallback = this.stampDomArray_.bind(
  6570. // this,
  6571. // value,
  6572. // key,
  6573. // stampDomEntry.mapping,
  6574. // stampDomEntry.reuseComponents,
  6575. // stampDomEntry.events,
  6576. // stampDomEntry.stamperStableList
  6577. // );
  6578. // }
  6579.  
  6580. // if (renderJob) renderJob.cancel();
  6581.  
  6582. // let taskManager = stampDomEntry.usePageScheduler ? this.getTaskManager()() : void 0;
  6583.  
  6584. // if (!renderJob && stampDomEntry.initialRenderPriority == void 0) {
  6585. // if (stampDomEntry.renderPriority != void 0 && !renderJob) {
  6586. // renderJob = new _.X6(stampDomEntry.renderPriority, stampDomEntry.waitForSignal, taskManager);
  6587. // this.renderJobsMap_[key] = renderJob;
  6588. // }
  6589. // } else {
  6590. // renderJob = new _.X6(stampDomEntry.initialRenderPriority, stampDomEntry.waitForSignal, taskManager);
  6591. // this.renderJobsMap_[key] = renderJob;
  6592. // renderCallback = function(callback, job) {
  6593. // callback();
  6594. // q4C(job, 10);
  6595. // }.bind(this, renderCallback, renderJob);
  6596. // }
  6597. // } else {
  6598. // renderCallback = (path + ".splices" === changeRecord.path)
  6599. // ? this.stampDomArraySplices_.bind(this, path, key, changeRecord.value)
  6600. // : this.forwardRendererStamperChanges_.bind(this, path, key, changeRecord);
  6601. // }
  6602.  
  6603. // if (renderJob) {
  6604. // _.vY(renderJob, renderCallback);
  6605. // } else {
  6606. // renderCallback();
  6607. // }
  6608. // }
  6609.  
  6610.  
  6611.  
  6612.  
  6613. const createStampDomFnsC_ = () => {
  6614.  
  6615. const config = ((win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0);
  6616.  
  6617. if (config.DEFERRED_DETACH === true) config.DEFERRED_DETACH = false;
  6618. if (config.REUSE_COMPONENTS === true) config.REUSE_COMPONENTS = false;
  6619.  
  6620.  
  6621. // const rq0 = document.createElement('rp');
  6622. // rq0.setAttribute('yt-element-placholder', '');
  6623.  
  6624. const it0 = Date.now() - 80000000000;
  6625. const genId = () => `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${(Date.now() - it0).toString(36)}`;
  6626.  
  6627.  
  6628. const getStampContainer_ = function (containerId) {
  6629.  
  6630. return this.getStampContainer7409_(containerId);
  6631.  
  6632. }
  6633.  
  6634.  
  6635.  
  6636.  
  6637. const createComponent_ = function (componentConfig, data, canReuse) {
  6638.  
  6639. return this.createComponent7409_(componentConfig, data, canReuse);
  6640.  
  6641. }
  6642.  
  6643.  
  6644. const s52 = Symbol();
  6645.  
  6646. const deferRenderStamperBinding_ = function (component, typeOrConfig, data) {
  6647.  
  6648. // if(component.querySelectorAll('dom-if').length > 0){
  6649.  
  6650. // // console.log(1233, component.isConnected, component.parentNode, component.querySelectorAll('dom-if'))
  6651. // if (component.isConnected === false) {
  6652. // for (const s of component.querySelectorAll('dom-if')) {
  6653. // try {
  6654. // console.log(1299);
  6655. // insp(s).__teardownInstance();
  6656. // } catch (e) { }
  6657. // }
  6658. // }
  6659.  
  6660. // }
  6661.  
  6662. if (typeof (data || 0) === 'object') {
  6663. if (!data[s52]) data[s52] = genId();
  6664. component[s52] = data[s52];
  6665. // console.log(component[s52], data);
  6666. } else {
  6667. component[s52] = null;
  6668. }
  6669.  
  6670. return this.deferRenderStamperBinding7409_(component, typeOrConfig, data);
  6671.  
  6672. }
  6673.  
  6674. // let pr77 = Promise.resolve();
  6675.  
  6676. const flushRenderStamperComponentBindings_ = function () {
  6677. if (!this.__qsd477__ || !this.deferredBindingTasks_) return this.flushRenderStamperComponentBindings7409_();
  6678.  
  6679. if (this.deferredBindingTasks_.length >= 0) {
  6680.  
  6681. // const deferredBindingTasks_ = this.deferredBindingTasks_;
  6682.  
  6683. const gid = this[`__$$stampFlushKey$$__`] = genId();
  6684. const g = (() => {
  6685. if (gid !== this[`__$$stampFlushKey$$__`]) { return; }
  6686. // if (deferredBindingTasks_.length === 0) return;
  6687. // let q = this.deferredBindingTasks_;
  6688. // this.deferredBindingTasks_ = deferredBindingTasks_;
  6689. this.flushRenderStamperComponentBindings7409_();
  6690. // deferredBindingTasks_.length = 0;
  6691. // this.deferredBindingTasks_ = q;
  6692.  
  6693. const s = [...this.__lat457__];
  6694. this.__lat457__.clear();
  6695.  
  6696. for (const containerWr of s) {
  6697.  
  6698. const container = kRef(containerWr);
  6699. if (!container) continue;
  6700.  
  6701. // const s = new Set();
  6702. if (!container.querySelector('[ytx-flushing]')) {
  6703. if (container.hasAttribute('ytx-flushing')) {
  6704. const attrVal = container.getAttribute('ytx-flushing');
  6705. container.removeAttribute('ytx-flushing');
  6706. // s.add([container, attrVal]);
  6707. addTask(container, attrVal);
  6708. // addTaskIm(container, attrVal);
  6709. let ancestor = container.closest('[ytx-flushing]');
  6710. while (ancestor) {
  6711. if (ancestor.querySelector('[ytx-flushing]')) break;
  6712. const attrVal = ancestor.getAttribute('ytx-flushing');
  6713. ancestor.removeAttribute('ytx-flushing');
  6714. // s.add([ancestor, attrVal]);
  6715. addTask(ancestor, attrVal);
  6716. // addTaskIm(ancestor, attrVal);
  6717. ancestor = ancestor.closest('[ytx-flushing]');
  6718. }
  6719. }
  6720. }
  6721. }
  6722. executeTasks();
  6723.  
  6724.  
  6725. });
  6726. g();
  6727. // const useMicroTaskQueue = this.__qsd477__ === 2;
  6728. // useMicroTaskQueue ? addTask2(g) : g();
  6729. // executeTasks();
  6730.  
  6731. // addTask2(g);
  6732. // executeTasks();
  6733.  
  6734. }
  6735.  
  6736. throw new Error('e5bd8d2f');
  6737.  
  6738. }
  6739.  
  6740. let tasks = [];
  6741. let excuted = false;
  6742. const executeTasks = ()=>{
  6743. if(excuted || tasks.length === 0) return;
  6744. excuted = true;
  6745. let t0 = 0;
  6746. const perform = ()=>{
  6747. if(!t0) t0 = nativeNow();
  6748. const task = tasks.shift();
  6749. if(!task){
  6750. excuted = false;
  6751. return;
  6752. }
  6753. task.fn(task);
  6754. const t1 = nativeNow();
  6755. if(t1 - t0 > 10){
  6756. t0 = 0;
  6757. nextBrowserTick_(perform);
  6758. }else{
  6759. queueMicrotask_(perform);
  6760. }
  6761. }
  6762. queueMicrotask_(perform);
  6763. }
  6764.  
  6765. const taskFn = (task) => {
  6766.  
  6767. if(!task) return;
  6768. const { containerWr, attrVal } = task;
  6769. const container = kRef(containerWr);
  6770. if (!container) return;
  6771. if (attrVal === '0') return;
  6772. const bEventCb = attrVal === '2';
  6773. const producerWr = containerMapping.get(container);
  6774. const producer = kRef(producerWr);
  6775. if (!producer) return;
  6776. const hostElement = producer.hostElement;
  6777. if (!hostElement) return;
  6778. if (hostElement.isConnected !== true) return; // tbc
  6779. producer.markDirty && producer.markDirty();
  6780. bEventCb && dispatchYtEvent(hostElement, "yt-rendererstamper-finished", {
  6781. container
  6782. });
  6783.  
  6784. }
  6785.  
  6786. const addTask = (container, attrVal) => {
  6787. if (!container) return;
  6788. const containerWr = container[wk] || (container[wk] = mWeakRef(container));
  6789. tasks.push({
  6790. fn: taskFn,
  6791. containerWr: containerWr,
  6792. attrVal
  6793. });
  6794. // pr77 = pr77.then(()=>{
  6795.  
  6796. // })
  6797. // taskFn({
  6798. // containerWr: containerWr,
  6799. // attrVal
  6800. // })
  6801.  
  6802. }
  6803.  
  6804. const addTaskIm = (container, attrVal) => {
  6805. if (!container) return;
  6806. const containerWr = container[wk] || (container[wk] = mWeakRef(container));
  6807. taskFn({
  6808. fn: taskFn,
  6809. containerWr: containerWr,
  6810. attrVal
  6811. });
  6812.  
  6813. }
  6814.  
  6815.  
  6816. const addTask2 = (f) => {
  6817. // pr77 = pr77.then(f).catch(console.warn);
  6818. tasks.push({
  6819. fn: f
  6820. });
  6821.  
  6822. }
  6823.  
  6824. // const mo = new MutationObserver((mutations)=>{
  6825.  
  6826. // });
  6827. // mo.observe(document, {attributeFilter: ['ytx-flushing'], attributes: true, subtree: true, childList: false});
  6828.  
  6829. const containerMapping = new WeakMap();
  6830.  
  6831. // let pr77 = Promise.resolve();
  6832. // let pr88 = Promise.resolve();
  6833. const uA4 = function (t, P) {
  6834. for (let y in t)
  6835. if (t.hasOwnProperty(y) && P[y])
  6836. return y;
  6837. return null
  6838. }
  6839.  
  6840. const evaluteUseMicroTaskQueue = (ax_, containerId, hostIs_, producer, hostElement)=>{
  6841.  
  6842. const ax = ax_;
  6843. const useMicroTaskQueue = ax ? (ax[2] && ax[2]!==ax[0]) : false;
  6844. let useMicroTaskQueue2 = ax && ax[1] && ax[2];
  6845. // const useMicroTaskQueue = false;
  6846. if (ax && ax[2] && ax[2] === ax[0]) { // short ... execute job
  6847. ax[2].cancel();
  6848. useMicroTaskQueue2 = false;
  6849. }
  6850. // console.log(1992,containerId, this.hostElement.is)
  6851.  
  6852. // if (hostElement.nodeType !== 1 || !hostElement.is || hostElement.isConnected === false || !document.body.contains(hostElement)){
  6853. // console.log(12773, hostElement.nodeType !== 1, !hostElement.is, hostElement.isConnected === false, !document.body.contains(hostElement))
  6854. // return false;
  6855.  
  6856. // }
  6857.  
  6858. if (producer.hasFlexibleItems === true) {
  6859. return false;
  6860. }
  6861.  
  6862. if (hostElement.isConnected === false || hostElement.closest('[hidden]')) {
  6863. return false;
  6864. }
  6865.  
  6866. const hostIs = hostIs_;
  6867.  
  6868. if (hostIs === 'ytd-masthead' || hostIs === 'ytd-button-renderer' || hostIs === 'yt-button-shape' || hostIs === 'yt-icon-button' || hostIs === 'ytd-notification-topbar-button-renderer' || containerId === 'buttons' || containerId === 'button' || containerId === 'icon' || hostIs === 'yt-interaction' || containerId === 'interaction') return false;
  6869.  
  6870. if (containerId === 'overlays') useMicroTaskQueue2 = true;
  6871. else if (hostIs === 'ytd-rich-grid-media' || hostIs === 'ytd-rich-grid-renderer') useMicroTaskQueue2 = true;
  6872. // else if (hostIs === 'ytd-rich-grid-media' || hostIs === 'ytd-rich-grid-renderer') useMicroTaskQueue2 = false;
  6873. // else if (containerId === 'menu') useMicroTaskQueue2 = true;
  6874. else if (containerId === 'replies') useMicroTaskQueue2 = true;
  6875. else if (containerId === 'flexible-item-buttons' && hostIs === 'ytd-menu-renderer') useMicroTaskQueue2 = true;
  6876. else if(hostIs === 'ytd-menu-popup-renderer') useMicroTaskQueue2 = false;
  6877. else if ( containerId === 'ghost-comment-section' && hostIs === 'ytd-continuation-item-renderer') useMicroTaskQueue2 = true;
  6878. else if (hostIs === 'ytd-continuation-item-renderer') useMicroTaskQueue2 = false;
  6879. else if (hostIs === 'ytd-feed-filter-chip-bar-renderer' || hostIs === 'yt-chip-cloud-renderer' || containerId==='filter' || containerId ==='chips' || containerId==='left-arrow-button' ||containerId==='right-arrow-button') useMicroTaskQueue2 =false;
  6880. // else if (containerId === 'contents' || containerId === 'content' || containerId === 'header') useMicroTaskQueue2 = true;
  6881. // else if( containerId === 'items') useMicroTaskQueue2 = true;
  6882. else if (containerId === 'menu' && hostIs === 'ytd-playlist-panel-video-renderer') useMicroTaskQueue2 = true;
  6883. else if (containerId === 'top-level-buttons-computed' && hostIs === 'ytd-menu-renderer') useMicroTaskQueue2 = false;
  6884. else if (hostIs === 'ytd-comment-view-model') useMicroTaskQueue2 = true;
  6885. // else if (hostIs === 'ytd-rich-item-renderer') useMicroTaskQueue2 = true;
  6886. // else if (hostIs === 'ytd-rich-grid-media') useMicroTaskQueue2 = true;
  6887. else if (hostIs === 'ytd-video-preview') useMicroTaskQueue2 = true;
  6888. // else if (hostIs === 'ytd-game-card-renderer')useMicroTaskQueue2 = true;
  6889.  
  6890.  
  6891. // console.log(19920030+(useMicroTaskQueue2?1:0), containerId, hostIs)
  6892.  
  6893.  
  6894. // console.log(5992,stackAt)
  6895.  
  6896. // console.log(2883, this[`__quu477#${containerId}__`] )
  6897. // if (useMicroTaskQueue) {
  6898. // console.log(stackAt)
  6899. // }
  6900.  
  6901. // if (useMicroTaskQueue) {
  6902. // console.log(1120301)
  6903. // }
  6904.  
  6905. // if(hostElement.closest('ytd-feed-filter-chip-bar-renderer')) useMicroTaskQueue2 = false;
  6906.  
  6907. return useMicroTaskQueue2;
  6908.  
  6909. }
  6910.  
  6911. const frag385 = document.createDocumentFragment();
  6912. frag385.appendChild4202 = frag385.appendChild;
  6913. frag385.removeChild4202 = frag385.removeChild;
  6914. const cm385 = document.createComment('.');
  6915.  
  6916. const doc385 = document.implementation.createHTMLDocument();
  6917. const html385 = doc385.firstElementChild;
  6918. const node385 = html385.appendChild(document.createElement('div'));
  6919.  
  6920. const fixContainerApi = (container) => {
  6921. if (container instanceof Node) {
  6922. const containerDomApi = container.__domApi;
  6923. if (containerDomApi && !containerDomApi.removeChild588 && containerDomApi.removeChild) {
  6924. // console.log(123882, container)
  6925. containerDomApi.removeChild588 = containerDomApi.removeChild;
  6926. containerDomApi.removeChild = function (elem) {
  6927. let r;
  6928. for (const s of elem.querySelectorAll('[ytx-flushing]')) {
  6929. s.setAttribute('ytx-flushing', '0');
  6930. }
  6931. try {
  6932. r = this.removeChild588(elem);
  6933. } catch (e) { }
  6934. if (!r) {
  6935. frag385.appendChild4202(elem);
  6936. frag385.removeChild4202(elem);
  6937. r = elem;
  6938. }
  6939. for (const s of elem.querySelectorAll('[ytx-flushing]')) {
  6940. s.removeAttribute('ytx-flushing');
  6941. }
  6942. return r;
  6943. }
  6944. }
  6945. }
  6946. }
  6947.  
  6948. const stampDomArray_ = function (dataList, containerId, typeOrConfig, bReuse, bEventCb, bStableList) {
  6949.  
  6950. const sqq = this[`__$$stampSqq$$#${containerId}__`];
  6951. if (typeof sqq === 'function') sqq();
  6952.  
  6953. // trigger in rendererStamperApplyChangeRecord_
  6954.  
  6955. // const stackAt = `\n\n${new Error().stack}\n\n`.replace(/[\r\n]([^\r\n]*?\.user\.js[^\r\n]*?[\r\n]+)+/g, '\n').replace(/[\r\n]([^\r\n.]+[\r\n]+)+/g, '\n').trim().split(/[\r\n]+/)[0];
  6956. // const useMicroTaskQueue = (stackAt.includes('.rendererStamperApplyChangeRecord_'));
  6957. // const useMicroTaskQueue = stackAt.includes('.<anonymous>') ? true : false;
  6958. // const stackAt = `\n\n${new Error().stack}\n\n`.replace(/[\r\n]([^\r\n]*?\.user\.js[^\r\n]*?[\r\n]+)+/g, '\n').replace(/[\r\n]([^\r\n.]+[\r\n]+)+/g, '\n').trim().split(/[\r\n]+/)[0];
  6959.  
  6960. // const isRenderJob = this[`__quu477#${containerId}__`] || !!this.renderJobsMap_[containerId];
  6961. // const useMicroTaskQueue = isRenderJob && !stackAt.includes('scheduler.js') && 0 ? true : false; // avoid immediate job
  6962.  
  6963.  
  6964. const ax = this[`__quu477#${containerId}__`];
  6965. const hostIs = (this.hostElement || 0).is;
  6966. const useMicroTaskQueue2 = evaluteUseMicroTaskQueue(ax, containerId, hostIs, this, this.hostElement);
  6967.  
  6968. const container = this.getStampContainer7409_(containerId);
  6969. const pChildren = [...container.children];
  6970.  
  6971. containerMapping.set(container,
  6972. (this[wk] || (this[wk] = mWeakRef(this)))
  6973. );
  6974.  
  6975. if (bEventCb) container.setAttribute('ytx-flushing', '2');
  6976. else if (!container.hasAttribute('ytx-flushing')) container.setAttribute('ytx-flushing', '1');
  6977.  
  6978. // let dataList_ = dataList;
  6979. let dataList_ = typeof (dataList || 0) === 'object' ? (dataList.length >= 1 ? dataList.slice() : []) : dataList;
  6980.  
  6981. dataList = null;
  6982. const gid = this[`__$$stampSID$$#${containerId}__`] = genId();
  6983. let fq = 0;
  6984. const f = (() => {
  6985. if(fq) return;
  6986. fq = 1;
  6987. if (gid !== this[`__$$stampSID$$#${containerId}__`]) { return; }
  6988. this[`__$$stampSFn$$#${containerId}__`] = null;
  6989. const container = this.getStampContainer7409_(containerId);
  6990.  
  6991. this.__lat457__ = this.__lat457__ || new Set();
  6992. if(!container[wk]) container[wk] = mWeakRef(container);
  6993. this.__lat457__.add(container[wk]);
  6994. fixContainerApi(container);
  6995.  
  6996. // let q = this.deferredBindingTasks_;
  6997. // this.deferredBindingTasks_ = [];
  6998. this.__qsd477__ = useMicroTaskQueue2 ? 2 : 1;
  6999. let e_;
  7000. try {
  7001. this.stampDomArray7409_(dataList_, containerId, typeOrConfig, false, bEventCb, bStableList);
  7002. } catch (e) { e_ = e }
  7003. this.__qsd477__ = false;
  7004. dataList_ = typeOrConfig = null;
  7005. fixContainerApi(container);
  7006. // this.deferredBindingTasks_ = q;
  7007. if(e_ && e_.message !== 'e5bd8d2f') throw e_;
  7008. if (!e_) {
  7009. // container.setAttribute('ytx-flushing', '0');
  7010. }
  7011. // if( container.childElementCount === 0 ){
  7012. // container.setAttribute('ytx-flushing', '0');
  7013. // this.markDirty && this.markDirty();
  7014. // bEventCb && dispatchYtEvent(this.hostElement, "yt-rendererstamper-finished", {
  7015. // container
  7016. // });
  7017. // }
  7018.  
  7019.  
  7020.  
  7021.  
  7022. });
  7023. this[`__$$stampSFn$$#${containerId}__`] = f;
  7024. this[`__$$stampSqq$$#${containerId}__`] = f;
  7025. useMicroTaskQueue2 ? addTask2(f) : f();
  7026. executeTasks();
  7027.  
  7028. for (const node of pChildren) {
  7029. if (node.isConnected === false) {
  7030. _removedElements.addNode(node);
  7031. }
  7032. }
  7033.  
  7034. // console.log(58801, this.hostElement.parentNode instanceof HTMLElement_);
  7035.  
  7036. return undefined;
  7037.  
  7038. }
  7039.  
  7040. const stampDomArraySplices_ = function (stampKey, containerId, indexSplicesObj) {
  7041.  
  7042.  
  7043. const sqq = this[`__$$stampSqq$$#${containerId}__`];
  7044. if (typeof sqq === 'function') sqq();
  7045.  
  7046. // trigger in rendererStamperApplyChangeRecord_
  7047.  
  7048. if (typeof indexSplicesObj === 'object' && indexSplicesObj.indexSplices instanceof Array) {
  7049. } else {
  7050. return this.stampDomArraySplices7409_(stampKey, containerId, indexSplicesObj);
  7051. }
  7052.  
  7053.  
  7054. // trigger in rendererStamperApplyChangeRecord_
  7055.  
  7056. // const stackAt = `\n\n${new Error().stack}\n\n`.replace(/[\r\n]([^\r\n]*?\.user\.js[^\r\n]*?[\r\n]+)+/g, '\n').replace(/[\r\n]([^\r\n.]+[\r\n]+)+/g, '\n').trim().split(/[\r\n]+/)[0];
  7057. // const useMicroTaskQueue = (stackAt.includes('.rendererStamperApplyChangeRecord_'));
  7058. // const useMicroTaskQueue = stackAt.includes('.<anonymous>') ? true : false;
  7059.  
  7060. // const stackAt = `\n\n${new Error().stack}\n\n`.replace(/[\r\n]([^\r\n]*?\.user\.js[^\r\n]*?[\r\n]+)+/g, '\n').replace(/[\r\n]([^\r\n.]+[\r\n]+)+/g, '\n').trim().split(/[\r\n]+/)[0];
  7061.  
  7062. // const isRenderJob = this[`__quu477#${containerId}__`] || !!this.renderJobsMap_[containerId];
  7063. // const useMicroTaskQueue = isRenderJob && !stackAt.includes('scheduler.js') && 0 ? true : false; // avoid immediate job
  7064. // const useMicroTaskQueue = this[`__quu477#${containerId}__`] ? true : false;
  7065.  
  7066. const ax = this[`__quu477#${containerId}__`];
  7067. const hostIs = (this.hostElement || 0).is;
  7068. const useMicroTaskQueue2 = evaluteUseMicroTaskQueue(ax, containerId, hostIs, this, this.hostElement);
  7069.  
  7070.  
  7071. // const stackAt = `\n\n${new Error().stack}\n\n`.replace(/[\r\n]([^\r\n]*?\.user\.js[^\r\n]*?[\r\n]+)+/g, '\n').replace(/[\r\n]([^\r\n.]+[\r\n]+)+/g, '\n').trim().split(/[\r\n]+/)[0];
  7072. // const useMicroTaskQueue = true;
  7073. const container = this.getStampContainer7409_(containerId);
  7074.  
  7075. containerMapping.set(container,
  7076. (this[wk] || (this[wk] = mWeakRef(this)))
  7077. );
  7078. const bEventCb = this.stampDom[stampKey].events;
  7079. if (bEventCb) container.setAttribute('ytx-flushing', '2');
  7080. else if (!container.hasAttribute('ytx-flushing')) container.setAttribute('ytx-flushing', '1');
  7081.  
  7082. // let indexSplicesObj_ = indexSplicesObj;
  7083. // if (typeof indexSplicesObj === 'object' && indexSplicesObj.indexSplices instanceof Array) {
  7084. // indexSplicesObj_ = {
  7085. // indexSplices: indexSplicesObj.indexSplices.map(slice => {
  7086. // const { index, addedCount, removed, object, type } = slice;
  7087. // this[`__$$stampSpliceObj$$#${containerId}__`] = (object[wk] || (object[wk] = mWeakRef(object)));
  7088. // return { index, addedCount, removed, object, type };
  7089. // })
  7090. // };
  7091. // }
  7092.  
  7093.  
  7094. indexSplicesObj.indexSplices.forEach(slice => {
  7095. const object = slice.object;
  7096. if (!object || typeof object !== 'object') return;
  7097. // const { index, addedCount, removed, object, type } = slice;
  7098. this[`__$$stampSpliceObj$$#${containerId}__`] = (object[wk] || (object[wk] = mWeakRef(object)));
  7099. // return { index, addedCount, removed, object, type };
  7100. });
  7101.  
  7102. // let indexSplicesObj_ = indexSplicesObj;
  7103.  
  7104. // console.log(128783, indexSplicesObj)
  7105.  
  7106. // let indexSplicesObj_ = indexSplicesObj.map(slice => {
  7107. // const { index, addedCount, removed, object, type } = slice;
  7108. // return { index, addedCount, removed, object, type };
  7109. // });
  7110.  
  7111. indexSplicesObj = null;
  7112.  
  7113. if (!this[`__$$stampSID$$#${containerId}__`]) this[`__$$stampSID$$#${containerId}__`] = genId();
  7114. const gid = this[`__$$stampSID$$#${containerId}__`];
  7115. let fq = 0;
  7116. const f = (() => {
  7117. if(fq) return;
  7118. fq = 1;
  7119. if (gid !== this[`__$$stampSID$$#${containerId}__`]) { return; }
  7120. if (this[`__$$stampSFn$$#${containerId}__`]) this[`__$$stampSFn$$#${containerId}__`]();
  7121. const container = this.getStampContainer7409_(containerId);
  7122. if(!container) return;
  7123.  
  7124. // console.log(388 , kRef(this[`__$$stampSpliceObj$$#${containerId}__`]))
  7125.  
  7126. const object = kRef(this[`__$$stampSpliceObj$$#${containerId}__`]);
  7127. // const elementKeys = new Set(Array.prototype.map.call((container.__domApi || container).children, e=>e[s52]));
  7128. const mapping = this.stampDom[stampKey].mapping;
  7129.  
  7130. const map = new Map();
  7131.  
  7132. const currentObjKeys = object.map(objEntry => {
  7133. const mappingKey = uA4(mapping, objEntry);
  7134. if(!mappingKey) return null;
  7135. const data = objEntry[mappingKey];
  7136. if (!data[s52]) data[s52] = genId();
  7137. map.set(data[s52], objEntry);
  7138. // return ({
  7139. // objEntry,
  7140. // data: data,
  7141. // mappingKey: mappingKey,
  7142. // key: data[s52],
  7143. // exist: elementKeys.has(data[s52])
  7144. // });
  7145. return data[s52]
  7146.  
  7147. });
  7148.  
  7149. const oldDomKeys = Array.prototype.map.call((container.__domApi || container).children, node=>node[s52]);
  7150.  
  7151. // console.log(currentObjKeys, oldDomKeys, diffSplices(oldDomKeys, currentObjKeys));
  7152.  
  7153. const splices = diffSplices(oldDomKeys, currentObjKeys);
  7154.  
  7155. // let myObject = object;
  7156. let indexSplicesObj_ = {
  7157. indexSplices: splices.map(splice => {
  7158. const index = splice[0];
  7159. const removedLen = splice[1];
  7160. const added = splice[2];
  7161. const addedCount = added.length;
  7162. const object = {};
  7163. object.length = index + addedCount;
  7164. for (let i = 0; i < addedCount; i++) {
  7165. object[index + i] = map.get(added[i]);
  7166. }
  7167. const removed = {};
  7168. removed.length = removedLen;
  7169.  
  7170. return { index, removed, object, addedCount }
  7171. })
  7172. };
  7173. map.clear();
  7174.  
  7175.  
  7176. this.__lat457__ = this.__lat457__ || new Set();
  7177. if(!container[wk]) container[wk] = mWeakRef(container);
  7178. this.__lat457__.add(container[wk]);
  7179. fixContainerApi(container);
  7180.  
  7181. // console.log(3882, indexSplicesObj_)
  7182. // let q = this.deferredBindingTasks_;
  7183. // this.deferredBindingTasks_ = [];
  7184. this.__qsd477__ = useMicroTaskQueue2 ? 2 : 1;
  7185. let e_;
  7186. try {
  7187. this.stampDomArraySplices7409_(stampKey, containerId, indexSplicesObj_);
  7188. } catch (e) { e_ = e; }
  7189. this.__qsd477__ = false;
  7190. indexSplicesObj_ = null;
  7191. stampKey = indexSplicesObj_ = null;
  7192. fixContainerApi(container);
  7193. // this.deferredBindingTasks_ = q;
  7194. if(e_ && e_.message !== 'e5bd8d2f') throw e_;
  7195. if (!e_) {
  7196. // container.setAttribute('ytx-flushing', '0');
  7197. }
  7198.  
  7199.  
  7200. });
  7201. this[`__$$stampSqq$$#${containerId}__`] = f;
  7202. useMicroTaskQueue2 ? addTask2(f) : f();
  7203. executeTasks();
  7204.  
  7205. // console.log(58802, this.hostElement.parentNode instanceof HTMLElement_);
  7206.  
  7207. return undefined;
  7208.  
  7209. }
  7210.  
  7211.  
  7212. const stampDomArrayWB_ = function (objWr, containerId, xxx_, renderJob0, dt0a) {
  7213. const dt0 = dt0a[0];
  7214. const dt1 = Date.now();
  7215. const obj = kRef(objWr);
  7216. if (!obj) return;
  7217. const xxx = obj[`__stampDomArrayArgs_xxx__#${containerId}__`];
  7218. if (xxx !== xxx_) return;
  7219. const dataList = obj[`__stampDomArrayArgs_dataList__#${containerId}__`];
  7220. const typeOrConfig = kRef(obj[`__stampDomArrayArgs_typeOrConfig__#${containerId}__`]);
  7221. const bReuse = obj[`__stampDomArrayArgs_bReuse__#${containerId}__`];
  7222. const bEventCb = obj[`__stampDomArrayArgs_bEventCb__#${containerId}__`];
  7223. const bStableList = obj[`__stampDomArrayArgs_bStableList__#${containerId}__`];
  7224. const renderJob1 = obj.renderJobsMap_[containerId]
  7225. // console.log(3188, dt0, dt1, renderJob0, renderJob1)
  7226. obj[`__quu477#${containerId}__`] = [renderJob0, (dt1 - dt0 >= 1), renderJob1];
  7227. let e_, r;
  7228. try {
  7229. r = obj.stampDomArray_(dataList, containerId, typeOrConfig, bReuse, bEventCb, bStableList);
  7230. } catch (e) {
  7231. e_ = e;
  7232. }
  7233. obj[`__quu477#${containerId}__`] = false;
  7234. if (e_) throw e_;
  7235. return r;
  7236. };
  7237.  
  7238.  
  7239. stampDomArray_.bind = function (obj, ...args) {
  7240. let [dataList, containerId, typeOrConfig, bReuse, bEventCb, bStableList] = args;
  7241. if (!obj[wk]) obj[wk] = mWeakRef(obj);
  7242. obj[`__stampDomArrayArgs_dataList__#${containerId}__`] = dataList;
  7243. const typeOrConfig_ = typeof (typeOrConfig || 0) === 'object' ? (typeOrConfig[wk] || (typeOrConfig[wk] = mWeakRef(typeOrConfig))) : typeOrConfig;
  7244. obj[`__stampDomArrayArgs_typeOrConfig__#${containerId}__`] = typeOrConfig_;
  7245. obj[`__stampDomArrayArgs_bReuse__#${containerId}__`] = bReuse;
  7246. obj[`__stampDomArrayArgs_bEventCb__#${containerId}__`] = bEventCb;
  7247. obj[`__stampDomArrayArgs_bStableList__#${containerId}__`] = bStableList;
  7248. const xxx = obj[`__stampDomArrayArgs_xxx__#${containerId}__`] = `${Math.random()}_${Date.now()}`;
  7249.  
  7250.  
  7251. const renderJob = obj.renderJobsMap_[containerId];
  7252.  
  7253. const dt0a = [Date.now()];
  7254. queueMicrotask_(() => { dt0a[0] = 0 });
  7255. return stampDomArrayWB_.bind(null, obj[wk], containerId, xxx, renderJob, dt0a);
  7256. };
  7257.  
  7258. const stampDomArraySplicesWB_ = function (objWr, stampKey, containerId, indexSplicesObj, renderJob0, dt0a) {
  7259. const dt0 = dt0a[0];
  7260. const dt1 = Date.now();
  7261. const obj = kRef(objWr);
  7262. if (!obj) return;
  7263. const renderJob1 = obj.renderJobsMap_[containerId];
  7264. obj[`__quu477#${containerId}__`] = [renderJob0, (dt1 - dt0 >= 1), renderJob1];
  7265. let e_, r;
  7266. try {
  7267. r = obj.stampDomArraySplices_( stampKey, containerId, indexSplicesObj);
  7268. } catch (e) {
  7269. e_ = e;
  7270. }
  7271. obj[`__quu477#${containerId}__`] = false;
  7272. if (e_) throw e_;
  7273. return r;
  7274. };
  7275.  
  7276.  
  7277. stampDomArraySplices_.bind = function (obj, ...args) {
  7278. let [stampKey, containerId, indexSplicesObj] = args;
  7279. if (!obj[wk]) obj[wk] = mWeakRef(obj);
  7280.  
  7281. const renderJob = obj.renderJobsMap_[containerId];
  7282.  
  7283. const dt0a = [Date.now()];
  7284. queueMicrotask_(() => { dt0a[0] = 0 });
  7285. return stampDomArraySplicesWB_.bind(null, obj[wk], stampKey, containerId, indexSplicesObj, renderJob, dt0a);
  7286. };
  7287.  
  7288.  
  7289. return { getStampContainer_, createComponent_, deferRenderStamperBinding_, flushRenderStamperComponentBindings_, stampDomArray_, stampDomArraySplices_ };
  7290.  
  7291. }
  7292.  
  7293. const setupDiscreteTasks = (h, rb) => {
  7294.  
  7295. if (typeof h.onYtRendererstamperFinished === 'function' && !(h.onYtRendererstamperFinished.km34)) {
  7296. const f = h.onYtRendererstamperFinished;
  7297. const g = ump3.get(f) || function () {
  7298. if (this.updateChildVisibilityProperties && !this.markDirty) {
  7299. return f.apply(this, arguments);
  7300. }
  7301. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7302. }
  7303. ump3.set(f, g);
  7304. g.km34 = 1;
  7305. h.onYtRendererstamperFinished = g;
  7306.  
  7307. }
  7308.  
  7309. if (typeof h.onYtUpdateDescriptionAction === 'function' && !(h.onYtUpdateDescriptionAction.km34)) {
  7310. const f = h.onYtUpdateDescriptionAction;
  7311. const g = ump3.get(f) || function (a) {
  7312. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7313. }
  7314. ump3.set(f, g);
  7315. g.km34 = 1;
  7316. h.onYtUpdateDescriptionAction = g;
  7317.  
  7318. }
  7319.  
  7320. if (typeof h.handleUpdateDescriptionAction === 'function' && !(h.handleUpdateDescriptionAction.km34)) {
  7321. const f = h.handleUpdateDescriptionAction;
  7322. const g = ump3.get(f) || function (a) {
  7323. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7324. }
  7325. ump3.set(f, g);
  7326. g.km34 = 1;
  7327. h.handleUpdateDescriptionAction = g;
  7328.  
  7329. }
  7330.  
  7331. if (typeof h.handleUpdateLiveChatPollAction === 'function' && !(h.handleUpdateLiveChatPollAction.km34)) {
  7332. const f = h.handleUpdateLiveChatPollAction;
  7333. const g = ump3.get(f) || function (a) {
  7334. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7335. }
  7336. ump3.set(f, g);
  7337. g.km34 = 1;
  7338. h.handleUpdateLiveChatPollAction = g;
  7339.  
  7340. }
  7341.  
  7342. if (typeof h.onTextChanged === 'function' && !(h.onTextChanged.km34)) {
  7343. const f = h.onTextChanged;
  7344. const g = ump3.get(f) || function () {
  7345. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7346. }
  7347. ump3.set(f, g);
  7348. g.km34 = 1;
  7349. h.onTextChanged = g;
  7350.  
  7351. }
  7352.  
  7353. if (typeof h.onVideoDataChange === 'function' && !(h.onVideoDataChange.km34)) {
  7354. const f = h.onVideoDataChange;
  7355. const g = ump3.get(f) || function (a) {
  7356. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7357. }
  7358. ump3.set(f, g);
  7359. g.km34 = 1;
  7360. h.onVideoDataChange = g;
  7361.  
  7362. }
  7363.  
  7364. if (typeof h.onVideoDataChange_ === 'function' && !(h.onVideoDataChange_.km34)) {
  7365. const f = h.onVideoDataChange_;
  7366. const g = ump3.get(f) || function () {
  7367. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7368. }
  7369. ump3.set(f, g);
  7370. g.km34 = 1;
  7371. h.onVideoDataChange_ = g;
  7372.  
  7373. }
  7374.  
  7375. if (typeof h.addTooltips_ === 'function' && !(h.addTooltips_.km34)) {
  7376.  
  7377. const f = h.addTooltips_;
  7378. const g = ump3.get(f) || function () {
  7379. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7380. }
  7381. ump3.set(f, g);
  7382. g.km34 = 1;
  7383. h.addTooltips_ = g;
  7384.  
  7385. }
  7386.  
  7387. if (typeof h.updateRenderedElements === 'function' && !(h.updateRenderedElements.km34)) {
  7388.  
  7389. const f = h.updateRenderedElements;
  7390. const g = ump3.get(f) || function () {
  7391. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7392. }
  7393. ump3.set(f, g);
  7394. g.km34 = 1;
  7395. h.updateRenderedElements = g;
  7396.  
  7397. }
  7398.  
  7399. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.loadPage_ === 'function' && !(h.loadPage_.km34)) {
  7400. const f = h.loadPage_;
  7401. const g = ump3.get(f) || function (a) {
  7402. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7403. }
  7404. ump3.set(f, g);
  7405. g.km34 = 1;
  7406. h.loadPage_ = g;
  7407.  
  7408. }
  7409. // updatePageData_ : possible conflict with Omit ShadyDOM
  7410. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.updatePageData_ === 'function' && !(h.updatePageData_.km34)) {
  7411. const f = h.updatePageData_;
  7412. const g = ump3.get(f) || function (a) {
  7413. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7414. }
  7415. ump3.set(f, g);
  7416. g.km34 = 1;
  7417. h.updatePageData_ = g;
  7418.  
  7419. }
  7420.  
  7421.  
  7422. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onFocus_ === 'function' && !(h.onFocus_.km34)) {
  7423.  
  7424. const f = h.onFocus_;
  7425. const g = ump3.get(f) || function () {
  7426. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7427. }
  7428. ump3.set(f, g);
  7429. g.km34 = 1;
  7430. h.onFocus_ = g;
  7431.  
  7432. }
  7433.  
  7434. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onBlur_ === 'function' && !(h.onBlur_.km34)) {
  7435.  
  7436. const f = h.onBlur_;
  7437. const g = ump3.get(f) || function () {
  7438. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7439. }
  7440. ump3.set(f, g);
  7441. g.km34 = 1;
  7442. h.onBlur_ = g;
  7443.  
  7444. }
  7445.  
  7446.  
  7447. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonClassChanged_ === 'function' && !(h.buttonClassChanged_.km34)) {
  7448.  
  7449. const f = h.buttonClassChanged_;
  7450. const g = ump3.get(f) || function (a, b) {
  7451. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7452. }
  7453. ump3.set(f, g);
  7454. g.km34 = 1;
  7455. h.buttonClassChanged_ = g;
  7456.  
  7457. }
  7458.  
  7459. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonIconChanged_ === 'function' && !(h.buttonIconChanged_.km34)) {
  7460.  
  7461. const f = h.buttonIconChanged_;
  7462. const g = ump3.get(f) || function (a) {
  7463. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7464. }
  7465. ump3.set(f, g);
  7466. g.km34 = 1;
  7467. h.buttonIconChanged_ = g;
  7468.  
  7469. }
  7470.  
  7471. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.dataChangedInBehavior_ === 'function' && !(h.dataChangedInBehavior_.km34)) {
  7472.  
  7473. const f = h.dataChangedInBehavior_;
  7474. const g = ump3.get(f) || function () {
  7475. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7476. }
  7477. ump3.set(f, g);
  7478. g.km34 = 1;
  7479. h.dataChangedInBehavior_ = g;
  7480.  
  7481. }
  7482.  
  7483. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.continuationsChanged_ === 'function' && !(h.continuationsChanged_.km34)) {
  7484.  
  7485. const f = h.continuationsChanged_;
  7486. const g = ump3.get(f) || function () {
  7487. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7488. }
  7489. ump3.set(f, g);
  7490. g.km34 = 1;
  7491. h.continuationsChanged_ = g;
  7492.  
  7493. }
  7494.  
  7495.  
  7496. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.forceChatPoll_ === 'function' && !(h.forceChatPoll_.km34)) {
  7497.  
  7498. const f = h.forceChatPoll_;
  7499. const g = ump3.get(f) || function (a) {
  7500. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7501. }
  7502. ump3.set(f, g);
  7503. g.km34 = 1;
  7504. h.forceChatPoll_ = g;
  7505.  
  7506. }
  7507.  
  7508. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointClick_ === 'function' && !(h.onEndpointClick_.km34)) {
  7509.  
  7510. const f = h.onEndpointClick_;
  7511. const g = ump3.get(f) || function (a) {
  7512. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7513. }
  7514. ump3.set(f, g);
  7515. g.km34 = 1;
  7516. h.onEndpointClick_ = g;
  7517.  
  7518. }
  7519.  
  7520. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointTap_ === 'function' && !(h.onEndpointTap_.km34)) {
  7521.  
  7522. const f = h.onEndpointTap_;
  7523. const g = ump3.get(f) || function (a) {
  7524. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7525. }
  7526. ump3.set(f, g);
  7527. g.km34 = 1;
  7528. h.onEndpointTap_ = g;
  7529.  
  7530. }
  7531.  
  7532. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleClick_ === 'function' && !(h.handleClick_.km34)) {
  7533.  
  7534. const f = h.handleClick_;
  7535. const g = ump3.get(f) || function (a, b) {
  7536. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7537. }
  7538. ump3.set(f, g);
  7539. g.km34 = 1;
  7540. h.handleClick_ = g;
  7541.  
  7542. }
  7543.  
  7544. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChange_ === 'function' && !(h.onReadyStateChange_.km34)) {
  7545.  
  7546. const f = h.onReadyStateChange_;
  7547. const g = ump3.get(f) || function () {
  7548. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7549. }
  7550. ump3.set(f, g);
  7551. g.km34 = 1;
  7552. h.onReadyStateChange_ = g;
  7553.  
  7554. }
  7555.  
  7556. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChangeEntryPoint_ === 'function' && !(h.onReadyStateChangeEntryPoint_.km34)) {
  7557.  
  7558. const f = h.onReadyStateChangeEntryPoint_;
  7559. const g = ump3.get(f) || function () {
  7560. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7561. }
  7562. ump3.set(f, g);
  7563. g.km34 = 1;
  7564. h.onReadyStateChangeEntryPoint_ = g;
  7565.  
  7566. }
  7567.  
  7568. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.readyStateChangeHandler_ === 'function' && !(h.readyStateChangeHandler_.km34)) {
  7569.  
  7570. const f = h.readyStateChangeHandler_;
  7571. const g = ump3.get(f) || function (a) {
  7572. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7573. }
  7574. ump3.set(f, g);
  7575. g.km34 = 1;
  7576. h.readyStateChangeHandler_ = g;
  7577.  
  7578. }
  7579.  
  7580. if (typeof h.xmlHttpHandler_ === 'function' && !(h.xmlHttpHandler_.km34)) {
  7581.  
  7582. const f = h.xmlHttpHandler_;
  7583. const g = ump3.get(f) || function (a) {
  7584. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7585. }
  7586. ump3.set(f, g);
  7587. g.km34 = 1;
  7588. h.xmlHttpHandler_ = g;
  7589.  
  7590. }
  7591.  
  7592. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.executeCallbacks_ === 'function' && !(h.executeCallbacks_.km34)) {
  7593.  
  7594. const f = h.executeCallbacks_; // overloaded
  7595. const g = ump3.get(f) || function (a) {
  7596. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7597. }
  7598. ump3.set(f, g);
  7599. g.km34 = 1;
  7600. h.executeCallbacks_ = g;
  7601.  
  7602. }
  7603.  
  7604. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleInvalidationData_ === 'function' && !(h.handleInvalidationData_.km34)) {
  7605.  
  7606. const f = h.handleInvalidationData_;
  7607. const g = ump3.get(f) || function (a, b) {
  7608. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7609. }
  7610. ump3.set(f, g);
  7611. g.km34 = 1;
  7612. h.handleInvalidationData_ = g;
  7613.  
  7614. }
  7615.  
  7616. if (typeof h.onInput_ === 'function' && !(h.onInput_.km34)) {
  7617.  
  7618. const f = h.onInput_;
  7619. const g = ump3.get(f) || function () {
  7620. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7621. }
  7622. ump3.set(f, g);
  7623. g.km34 = 1;
  7624. h.onInput_ = g;
  7625.  
  7626. }
  7627. if (typeof h.trigger_ === 'function' && !(h.trigger_.km34)) {
  7628.  
  7629. const f = h.trigger_;
  7630. const g = ump3.get(f) || function (a) {
  7631. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7632. }
  7633. ump3.set(f, g);
  7634. g.km34 = 1;
  7635. h.trigger_ = g;
  7636.  
  7637. }
  7638.  
  7639. if (typeof h.requestData_ === 'function' && !(h.requestData_.km34)) {
  7640.  
  7641. const f = h.requestData_;
  7642. const g = ump3.get(f) || function (a) {
  7643. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7644. }
  7645. ump3.set(f, g);
  7646. g.km34 = 1;
  7647. h.requestData_ = g;
  7648.  
  7649. }
  7650.  
  7651. if (typeof h.onLoadReloadContinuation_ === 'function' && !(h.onLoadReloadContinuation_.km34)) {
  7652.  
  7653. const f = h.onLoadReloadContinuation_;
  7654. const g = ump3.get(f) || function (a, b) {
  7655. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7656. }
  7657. ump3.set(f, g);
  7658. g.km34 = 1;
  7659. h.onLoadReloadContinuation_ = g;
  7660.  
  7661. }
  7662.  
  7663. if (typeof h.onLoadIncrementalContinuation_ === 'function' && !(h.onLoadIncrementalContinuation_.km34)) {
  7664.  
  7665. const f = h.onLoadIncrementalContinuation_;
  7666. const g = ump3.get(f) || function (a, b) {
  7667. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7668. }
  7669. ump3.set(f, g);
  7670. g.km34 = 1;
  7671. h.onLoadIncrementalContinuation_ = g;
  7672.  
  7673. }
  7674.  
  7675. if (typeof h.onLoadSeekContinuation_ === 'function' && !(h.onLoadSeekContinuation_.km34)) {
  7676.  
  7677. const f = h.onLoadSeekContinuation_;
  7678. const g = ump3.get(f) || function (a, b) {
  7679. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7680. }
  7681. ump3.set(f, g);
  7682. g.km34 = 1;
  7683. h.onLoadSeekContinuation_ = g;
  7684.  
  7685. }
  7686. if (typeof h.onLoadReplayContinuation_ === 'function' && !(h.onLoadReplayContinuation_.km34)) {
  7687.  
  7688. const f = h.onLoadReplayContinuation_;
  7689. const g = ump3.get(f) || function (a, b) {
  7690. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7691. }
  7692. ump3.set(f, g);
  7693. g.km34 = 1;
  7694. h.onLoadReplayContinuation_ = g;
  7695.  
  7696. }
  7697. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onNavigate_ === 'function' && !(h.onNavigate_.km34)) {
  7698.  
  7699. const f = h.onNavigate_;
  7700. const g = ump3.get(f) || function (a) {
  7701. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7702. }
  7703. ump3.set(f, g);
  7704. g.km34 = 1;
  7705. h.onNavigate_ = g;
  7706.  
  7707. }
  7708.  
  7709. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorDataObserver_ === 'function' && !(h.ytRendererBehaviorDataObserver_.km34)) {
  7710.  
  7711. const f = h.ytRendererBehaviorDataObserver_;
  7712. const g = ump3.get(f) || function () {
  7713. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7714. }
  7715. ump3.set(f, g);
  7716. g.km34 = 1;
  7717. h.ytRendererBehaviorDataObserver_ = g;
  7718.  
  7719. }
  7720.  
  7721. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorTargetIdObserver_ === 'function' && !(h.ytRendererBehaviorTargetIdObserver_.km34)) {
  7722.  
  7723. const f = h.ytRendererBehaviorTargetIdObserver_;
  7724. const g = ump3.get(f) || function () {
  7725. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7726. }
  7727. ump3.set(f, g);
  7728. g.km34 = 1;
  7729. h.ytRendererBehaviorTargetIdObserver_ = g;
  7730.  
  7731. }
  7732.  
  7733. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.unregisterRenderer_ === 'function' && !(h.unregisterRenderer_.km34)) {
  7734.  
  7735. const f = h.unregisterRenderer_;
  7736. const g = ump3.get(f) || function (a) {
  7737. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7738. }
  7739. ump3.set(f, g);
  7740. g.km34 = 1;
  7741. h.unregisterRenderer_ = g;
  7742.  
  7743. }
  7744.  
  7745. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.textChanged_ === 'function' && !(h.textChanged_.km34)) {
  7746.  
  7747. const f = h.textChanged_;
  7748. const g = ump3.get(f) || function (a) {
  7749. if (void 0 !== this.isAttached) {
  7750. const hostElement = this.hostElement;
  7751. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  7752. return;
  7753. }
  7754. }
  7755. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7756. }
  7757. ump3.set(f, g);
  7758. g.km34 = 1;
  7759. h.textChanged_ = g;
  7760.  
  7761. }
  7762.  
  7763.  
  7764.  
  7765. /**
  7766. *
  7767. * Neglect following
  7768. *
  7769. * h.onYtAction_
  7770. * h.startLoadingWatch [ buggy for yt-player-updated ]
  7771. * h.deferRenderStamperBinding_
  7772. *
  7773. * h.stampDomArray_
  7774. * h.stampDomArraySplices_
  7775. *
  7776. */
  7777.  
  7778.  
  7779. // RP.prototype.searchChanged_ = RP.prototype.searchChanged_;
  7780. // RP.prototype.skinToneChanged_ = RP.prototype.skinToneChanged_;
  7781. // RP.prototype.onEmojiHover_ = RP.prototype.onEmojiHover_;
  7782. // RP.prototype.onSelectCategory_ = RP.prototype.onSelectCategory_;
  7783. // RP.prototype.onShowEmojiVariantSelector = RP.prototype.onShowEmojiVariantSelector;
  7784. // RP.prototype.updateCategoriesAndPlaceholder_ = RP.prototype.updateCategoriesAndPlaceholder_;
  7785.  
  7786. if (typeof h.searchChanged_ === 'function' && !(h.searchChanged_.km34)) {
  7787.  
  7788. const f = h.searchChanged_;
  7789. const g = ump3.get(f) || function () {
  7790. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7791. }
  7792. ump3.set(f, g);
  7793. g.km34 = 1;
  7794. h.searchChanged_ = g;
  7795.  
  7796. }
  7797.  
  7798. if (typeof h.skinToneChanged_ === 'function' && !(h.skinToneChanged_.km34)) {
  7799.  
  7800. const f = h.skinToneChanged_;
  7801. const g = ump3.get(f) || function (a) {
  7802. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7803. }
  7804. ump3.set(f, g);
  7805. g.km34 = 1;
  7806. h.skinToneChanged_ = g;
  7807.  
  7808. }
  7809.  
  7810. if (typeof h.onEmojiHover_ === 'function' && !(h.onEmojiHover_.km34)) {
  7811.  
  7812. const f = h.onEmojiHover_;
  7813. const g = ump3.get(f) || function (a) {
  7814. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7815. }
  7816. ump3.set(f, g);
  7817. g.km34 = 1;
  7818. h.onEmojiHover_ = g;
  7819.  
  7820. }
  7821.  
  7822. if (typeof h.onSelectCategory_ === 'function' && !(h.onSelectCategory_.km34)) {
  7823.  
  7824. const f = h.onSelectCategory_;
  7825. const g = ump3.get(f) || function (a) {
  7826. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7827. }
  7828. ump3.set(f, g);
  7829. g.km34 = 1;
  7830. h.onSelectCategory_ = g;
  7831.  
  7832. }
  7833.  
  7834. if (typeof h.onShowEmojiVariantSelector === 'function' && !(h.onShowEmojiVariantSelector.km34)) {
  7835.  
  7836. const f = h.onShowEmojiVariantSelector;
  7837. const g = ump3.get(f) || function (a) {
  7838. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7839. }
  7840. ump3.set(f, g);
  7841. g.km34 = 1;
  7842. h.onShowEmojiVariantSelector = g;
  7843.  
  7844. }
  7845.  
  7846. if (typeof h.updateCategoriesAndPlaceholder_ === 'function' && !(h.updateCategoriesAndPlaceholder_.km34)) {
  7847.  
  7848. const f = h.updateCategoriesAndPlaceholder_;
  7849. const g = ump3.get(f) || function () {
  7850. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7851. }
  7852. ump3.set(f, g);
  7853. g.km34 = 1;
  7854. h.updateCategoriesAndPlaceholder_ = g;
  7855.  
  7856. }
  7857.  
  7858. if (typeof h.watchPageActiveChanged_ === 'function' && !(h.watchPageActiveChanged_.km34)) {
  7859.  
  7860. const f = h.watchPageActiveChanged_;
  7861. const g = ump3.get(f) || function () {
  7862. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7863. }
  7864. ump3.set(f, g);
  7865. g.km34 = 1;
  7866. h.watchPageActiveChanged_ = g;
  7867.  
  7868. }
  7869.  
  7870. if (typeof h.activate_ === 'function' && !(h.activate_.km34)) {
  7871.  
  7872. const f = h.activate_;
  7873. const g = ump3.get(f) || function () {
  7874. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7875. }
  7876. ump3.set(f, g);
  7877. g.km34 = 1;
  7878. h.activate_ = g;
  7879.  
  7880. }
  7881. if (typeof h.onYtPlaylistDataUpdated_ === 'function' && !(h.onYtPlaylistDataUpdated_.km34)) {
  7882.  
  7883. const f = h.onYtPlaylistDataUpdated_;
  7884. const g = ump3.get(f) || function () {
  7885. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7886. }
  7887. ump3.set(f, g);
  7888. g.km34 = 1;
  7889. h.onYtPlaylistDataUpdated_ = g;
  7890.  
  7891. }
  7892.  
  7893.  
  7894.  
  7895. /**
  7896. *
  7897. * Neglect following
  7898. *
  7899. * h.rendererStamperObserver_
  7900. * h.rendererStamperApplyChangeRecord_
  7901. * h.flushRenderStamperComponentBindings_
  7902. * h.forwardRendererStamperChanges_
  7903. *
  7904. */
  7905.  
  7906. if (typeof h.tryRenderChunk_ === 'function' && !(h.tryRenderChunk_.km34)) {
  7907.  
  7908. const f = h.tryRenderChunk_;
  7909. const g = ump3.get(f) || function () {
  7910. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7911. }
  7912. ump3.set(f, g);
  7913. g.km34 = 1;
  7914. h.tryRenderChunk_ = g;
  7915.  
  7916. }
  7917.  
  7918.  
  7919. if (typeof h.renderChunk_ === 'function' && !(h.renderChunk_.km34)) {
  7920.  
  7921. const f = h.renderChunk_;
  7922. const g = ump3.get(f) || function () {
  7923. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7924. }
  7925. ump3.set(f, g);
  7926. g.km34 = 1;
  7927. h.renderChunk_ = g;
  7928.  
  7929. }
  7930.  
  7931. if (typeof h.deepLazyListObserver_ === 'function' && !(h.deepLazyListObserver_.km34)) {
  7932.  
  7933. const f = h.deepLazyListObserver_;
  7934. const g = ump3.get(f) || function () {
  7935. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7936. }
  7937. ump3.set(f, g);
  7938. g.km34 = 1;
  7939. h.deepLazyListObserver_ = g;
  7940.  
  7941. }
  7942.  
  7943. if (typeof h.onItemsUpdated_ === 'function' && !(h.onItemsUpdated_.km34)) {
  7944.  
  7945. const f = h.onItemsUpdated_;
  7946. const g = ump3.get(f) || function () {
  7947. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7948. }
  7949. ump3.set(f, g);
  7950. g.km34 = 1;
  7951. h.onItemsUpdated_ = g;
  7952.  
  7953. }
  7954.  
  7955. if (typeof h.requestRenderChunk_ === 'function' && !(h.requestRenderChunk_.km34)) {
  7956.  
  7957. const f = h.requestRenderChunk_;
  7958. const g = ump3.get(f) || function () {
  7959. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  7960. }
  7961. ump3.set(f, g);
  7962. g.km34 = 1;
  7963. h.requestRenderChunk_ = g;
  7964.  
  7965. }
  7966.  
  7967. /**
  7968. *
  7969. * Neglect following
  7970. *
  7971. * h.dataChanged_ [ buggy for page swtiching ]
  7972. *
  7973. * h.updateChangeRecord_ [ see https://github.com/cyfung1031/userscript-supports/issues/20 ]
  7974. *
  7975. * h.cancelPendingTasks_
  7976. * h.fillRange_
  7977. * h.addTextNodes_
  7978. * h.updateText_
  7979. * h.stampTypeChanged_
  7980. *
  7981. */
  7982.  
  7983.  
  7984. }
  7985.  
  7986. const keyStConnectedCallback = Symbol(); // avoid copying the value
  7987.  
  7988. const dmf = new WeakMap();
  7989.  
  7990.  
  7991. let nativeHTMLElement = Reflect.getPrototypeOf(HTMLFontElement);
  7992.  
  7993. try {
  7994.  
  7995. const q = document.createElement('template');
  7996. q.innerHTML = '<ytz-null361></ytz-null361>';
  7997. nativeHTMLElement = q.content.firstChild.constructor
  7998.  
  7999. } catch (e) { }
  8000.  
  8001. if (!nativeHTMLElement.prototype.connectedCallback) {
  8002. nativeHTMLElement.prototype.connectedCallback79 = nativeHTMLElement.prototype.connectedCallback;
  8003. nativeHTMLElement.prototype.connectedCallback = function () {
  8004. let r;
  8005. if (this.connectedCallback79) r = this.connectedCallback79.apply(this, arguments);
  8006. return r;
  8007. }
  8008. }
  8009. const pvr = Symbol()
  8010.  
  8011. let stampDomArrayFnStore = null;
  8012. const setupMap = new WeakSet();
  8013. const setupYtComponent = (cnt) => {
  8014. const cProto = Reflect.getPrototypeOf(cnt || 0) || 0;
  8015. if (!cProto || setupMap.has(cProto)) return;
  8016. setupMap.add(cProto);
  8017. if (FIX_stampDomArray && !(cProto[pvr] & 1) && 'stampDomArray_' in cProto) {
  8018. cProto[pvr] |= 1;
  8019.  
  8020.  
  8021.  
  8022. if (FIX_stampDomArray && !location.pathname.startsWith('/live_chat') && cProto.stampDomArray_) {
  8023. const b = cProto.stampDomArray_.length === 6
  8024. && cProto.getStampContainer_ && cProto.getStampContainer_.length === 1
  8025. && cProto.createComponent_ && cProto.createComponent_.length === 3
  8026. && cProto.deferRenderStamperBinding_ && cProto.deferRenderStamperBinding_.length === 3
  8027. && cProto.flushRenderStamperComponentBindings_ && cProto.flushRenderStamperComponentBindings_.length === 0
  8028. && cProto.deferRenderStamperBinding_ === cnt.deferRenderStamperBinding_
  8029. if (!b) {
  8030. console.warn("YouTube Coding Changed. createStampDomFns_() is not applied")
  8031. } else if(!cProto.createComponent7409_ && !cProto.deferRenderStamperBinding7409_ && !cProto.flushRenderStamperComponentBindings7409_) {
  8032. if(!stampDomArrayFnStore) stampDomArrayFnStore = createStampDomFnsC_();
  8033. const {getStampContainer_, createComponent_, deferRenderStamperBinding_, flushRenderStamperComponentBindings_, stampDomArray_, stampDomArraySplices_} = stampDomArrayFnStore;
  8034.  
  8035. cProto.getStampContainer7409_ = cProto.getStampContainer_;
  8036. cProto.createComponent7409_ = cProto.createComponent_;
  8037. cProto.deferRenderStamperBinding7409_ = cProto.deferRenderStamperBinding_;
  8038. cProto.flushRenderStamperComponentBindings7409_ = cProto.flushRenderStamperComponentBindings_;
  8039. cProto.stampDomArray7409_ = cProto.stampDomArray_;
  8040. cProto.stampDomArraySplices7409_ = cProto.stampDomArraySplices_;
  8041.  
  8042. cProto.getStampContainer_ = getStampContainer_;
  8043. cProto.createComponent_ = createComponent_;
  8044. cProto.deferRenderStamperBinding_ = deferRenderStamperBinding_;
  8045. cProto.flushRenderStamperComponentBindings_ = flushRenderStamperComponentBindings_;
  8046. cProto.stampDomArray_ = stampDomArray_;
  8047. cProto.stampDomArraySplices_ = stampDomArraySplices_;
  8048.  
  8049. }
  8050. }
  8051.  
  8052.  
  8053.  
  8054.  
  8055. // if(false && cProto._runEffectsForTemplate && !cProto._runEffectsForTemplate6344) {
  8056. // cProto._runEffectsForTemplate6344 = cProto._runEffectsForTemplate;
  8057.  
  8058. // if(cProto._runEffectsForTemplate6344.length === 4){
  8059.  
  8060. // cProto._runEffectsForTemplate = function (c, d, e, g) {
  8061. // const cnt = this;
  8062. // const { propertyEffects, nodeList, firstChild } = c;
  8063. // cnt._runEffectsForTemplate6344({ propertyEffects, nodeList, firstChild }, d, e, g);
  8064.  
  8065. // }
  8066.  
  8067. // }
  8068.  
  8069. // }
  8070.  
  8071. }
  8072. };
  8073.  
  8074. (FIX_stampDomArray) && Object.defineProperty(Object.prototype, 'connectedCallback', {
  8075. get() {
  8076. const f = this[keyStConnectedCallback];
  8077. if (this.is) {
  8078. setupYtComponent(this);
  8079. }
  8080. return f;
  8081. },
  8082. set(nv) {
  8083. let gv = nv;
  8084. this[keyStConnectedCallback] = gv; // proto or object
  8085. return true;
  8086. },
  8087. enumerable: false,
  8088. configurable: true
  8089.  
  8090. });
  8091.  
  8092. const pLoad = new Promise(resolve => {
  8093. if (document.readyState !== 'loading') {
  8094. resolve();
  8095. } else {
  8096. window.addEventListener("DOMContentLoaded", resolve, false);
  8097. }
  8098. });
  8099.  
  8100. if (FIX_ACTIONS_TOOLTIPS) {
  8101. pLoad.then(() => {
  8102. addNewCSS("#actions .tp-yt-paper-tooltip{white-space:nowrap}");
  8103. });
  8104. }
  8105.  
  8106. if (FIX_fix_requestIdleCallback_timing && !window.requestIdleCallback471 && typeof window.requestIdleCallback === 'function') {
  8107. window.requestIdleCallback471 = window.requestIdleCallback;
  8108. window.requestIdleCallback = function (f, ...args) {
  8109. return (this || window).requestIdleCallback471(async function () {
  8110. await pLoad.then();
  8111. // await new Promise(nextBrowserTick_);
  8112. f.call(this, ...arguments)
  8113. }, ...args);
  8114. }
  8115. }
  8116.  
  8117. pLoad.then(() => {
  8118.  
  8119. let nonce = document.querySelector('style[nonce]');
  8120. nonce = nonce ? nonce.getAttribute('nonce') : null;
  8121. const st = document.createElement('style');
  8122. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  8123. st.textContent = "none-element-k47{order:0}";
  8124. st.addEventListener('load', () => {
  8125. pf31.resolve();
  8126. p59 = 1;
  8127. }, false);
  8128. (document.body || document.head || document.documentElement).appendChild(st);
  8129.  
  8130. });
  8131.  
  8132. const prepareLogs = [];
  8133.  
  8134. const skipAdsDetection = new Set(['/robots.txt', '/live_chat', '/live_chat_replay']);
  8135.  
  8136. let winError00 = window.onerror;
  8137.  
  8138. let fix_error_many_stack_state = !FIX_error_many_stack ? 0 : skipAdsDetection.has(location.pathname) ? 2 : 1;
  8139.  
  8140. if (!JSON || !('parse' in JSON)) fix_error_many_stack_state = 0;
  8141.  
  8142. ; fix_error_many_stack_state === 1 && (() => {
  8143.  
  8144.  
  8145. let p1 = winError00;
  8146.  
  8147. let stackNeedleDetails = null;
  8148.  
  8149. Object.defineProperty(Object.prototype, 'matchAll', {
  8150. get() {
  8151. stackNeedleDetails = this;
  8152. return true;
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157.  
  8158. try {
  8159. JSON.parse("{}");
  8160. } catch (e) {
  8161. console.warn(e)
  8162. fix_error_many_stack_state = 0;
  8163. }
  8164.  
  8165. delete Object.prototype['matchAll'];
  8166.  
  8167. let p2 = window.onerror;
  8168.  
  8169. window.onerror = p1;
  8170.  
  8171. if (fix_error_many_stack_state === 0) return;
  8172.  
  8173. if (stackNeedleDetails) {
  8174. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  8175. stackNeedleDetails.matchAll = true;
  8176. }
  8177.  
  8178. if (p1 === p2) return (fix_error_many_stack_state = 0);
  8179.  
  8180. // p1!==p2
  8181. fix_error_many_stack_state = !stackNeedleDetails ? 4 : 3;
  8182.  
  8183. })();
  8184.  
  8185. ; fix_error_many_stack_state === 2 && (() => {
  8186.  
  8187.  
  8188. let p1 = winError00;
  8189.  
  8190. let objectPrune = null;
  8191. let stackNeedleDetails = null;
  8192.  
  8193. Object.defineProperty(Function.prototype, 'findOwner', {
  8194. get() {
  8195. objectPrune = this;
  8196. return this._findOwner;
  8197. },
  8198. set(nv) {
  8199. this._findOwner = nv;
  8200. return true;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205.  
  8206. Object.defineProperty(Object.prototype, 'matchAll', {
  8207. get() {
  8208. stackNeedleDetails = this;
  8209. return true;
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214.  
  8215. try {
  8216. JSON.parse("{}");
  8217. } catch (e) {
  8218. console.warn(e)
  8219. fix_error_many_stack_state = 0;
  8220. }
  8221.  
  8222. delete Function.prototype['findOwner'];
  8223. delete Object.prototype['matchAll'];
  8224.  
  8225. let p2 = window.onerror;
  8226.  
  8227. if (p1 !== p2) return (fix_error_many_stack_state = 4); // p1 != p2
  8228.  
  8229. if (fix_error_many_stack_state == 0) return;
  8230.  
  8231. // the following will only execute when Brave's scriptlets.js is executed.
  8232.  
  8233. prepareLogs.push("fix_error_many_stack_state NB")
  8234.  
  8235. if (stackNeedleDetails) {
  8236. stackNeedleDetails.pattern = null;
  8237. stackNeedleDetails.re = null;
  8238. stackNeedleDetails.expect = null;
  8239. stackNeedleDetails.matchAll = true;
  8240. }
  8241.  
  8242. if (objectPrune) {
  8243. objectPrune.findOwner = objectPrune.mustProcess = objectPrune.logJson = () => { }
  8244. delete objectPrune._findOwner;
  8245. }
  8246.  
  8247. fix_error_many_stack_state = 3;
  8248. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  8249. JSON.parse.objectPrune = objectPrune;
  8250.  
  8251. })();
  8252.  
  8253. ; fix_error_many_stack_state === 3 && (() => {
  8254.  
  8255.  
  8256. let p1 = winError00;
  8257.  
  8258. try {
  8259. JSON.parse("{}");
  8260. } catch (e) {
  8261. console.warn(e)
  8262. fix_error_many_stack_state = 0;
  8263. }
  8264.  
  8265. let p2 = window.onerror;
  8266.  
  8267. if (p1 === p2) return;
  8268.  
  8269. window.onerror = p1;
  8270.  
  8271. if (fix_error_many_stack_state === 0) return;
  8272.  
  8273. fix_error_many_stack_state = 4; // p1 != p2
  8274.  
  8275.  
  8276. })();
  8277.  
  8278. fix_error_many_stack_state === 4 && (() => {
  8279.  
  8280. // the following will only execute when Brave's scriptlets.js is executed.
  8281.  
  8282. prepareLogs.push("fix_error_many_stack_state AB")
  8283.  
  8284. JSON.parseProxy = JSON.parse;
  8285.  
  8286. JSON.parse = ((parse) => {
  8287.  
  8288. parse = parse.bind(JSON); // get a new instance of the current JSON.parse
  8289. return function (text, reviver) {
  8290. const onerror = window.onerror;
  8291. window.onerror = null;
  8292. let r;
  8293. try {
  8294. r = parse(...arguments);
  8295. } catch (e) {
  8296. r = e;
  8297. }
  8298. window.onerror = onerror;
  8299. if (r instanceof Error) {
  8300. throw r;
  8301. }
  8302. return r;
  8303. }
  8304.  
  8305. })(JSON.parse);
  8306.  
  8307.  
  8308. })();
  8309.  
  8310.  
  8311. // << if FIX_yt_player >>
  8312.  
  8313. // credit to @nopeless (https://greasyfork.org/scripts/471489-youtube-player-perf/)
  8314. const PERF_471489_ = true;
  8315. // PERF_471489_ is not exactly the same to Youtube Player perf v0.7
  8316. // This script uses a much gentle way to tamer the JS engine instead.
  8317.  
  8318. // << end >>
  8319.  
  8320. const steppingScaleN = 200; // transform: scaleX(k/N); 0<k<N
  8321.  
  8322.  
  8323.  
  8324. const nilFn = () => { };
  8325.  
  8326. let isMainWindow = false;
  8327. try {
  8328. isMainWindow = window.document === window.top.document
  8329. } catch (e) { }
  8330.  
  8331. let NO_PRELOAD_GENERATE_204_BYPASS = NO_PRELOAD_GENERATE_204 ? false : true;
  8332. let headLinkCollection = null;
  8333.  
  8334.  
  8335. // const assertor = (f) => f() || console.assert(false, `${f}`);
  8336.  
  8337. const fnIntegrity = (f, d) => {
  8338. if (!f || typeof f !== 'function') {
  8339. console.warn('f is not a function', f);
  8340. return;
  8341. }
  8342. let p = `${f}`, s = 0, j = -1, w = 0;
  8343. for (let i = 0, l = p.length; i < l; i++) {
  8344. const t = p[i];
  8345. if (((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'))) {
  8346. if (j < i - 1) w++;
  8347. j = i;
  8348. } else {
  8349. s++;
  8350. }
  8351. }
  8352. let itz = `${f.length}.${s}.${w}`;
  8353. if (!d) {
  8354. return itz;
  8355. } else {
  8356. return itz === d;
  8357. }
  8358. };
  8359.  
  8360. const getZqOu = (_yt_player) => {
  8361.  
  8362. const w = 'ZqOu';
  8363.  
  8364. let arr = [];
  8365.  
  8366. for (const [k, v] of Object.entries(_yt_player)) {
  8367.  
  8368. const p = typeof v === 'function' ? v.prototype : 0;
  8369. if (p
  8370. && typeof p.start === 'function' && p.start.length === 0 // Ou
  8371. && typeof p.isActive === 'function' && p.isActive.length === 0
  8372. && typeof p.stop === 'function' && p.stop.length === 0
  8373. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  8374. && !p.send && !p.abort
  8375. && !p.sample && !p.initialize && !p.fail && !p.getName
  8376. // && !p.dispose && !p.isDisposed
  8377.  
  8378. ) {
  8379. arr = addProtoToArr(_yt_player, k, arr) || arr;
  8380.  
  8381.  
  8382. }
  8383.  
  8384. }
  8385.  
  8386. if (arr.length === 0) {
  8387.  
  8388. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8389. } else {
  8390.  
  8391. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8392. return arr[0];
  8393. }
  8394.  
  8395. }
  8396.  
  8397. const getZqQu = (_yt_player) => {
  8398.  
  8399. const w = 'ZqQu';
  8400.  
  8401. let arr = [];
  8402.  
  8403.  
  8404. for (const [k, v] of Object.entries(_yt_player)) {
  8405.  
  8406. const p = typeof v === 'function' ? v.prototype : 0;
  8407. if (p
  8408. && typeof p.start === 'function' && p.start.length === 1 // Qu
  8409. && typeof p.isActive === 'function' && p.isActive.length === 0
  8410. && typeof p.stop === 'function' && p.stop.length === 0
  8411. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  8412. && !p.send && !p.abort
  8413. && !p.sample && !p.initialize && !p.fail && !p.getName
  8414. // && !p.dispose && !p.isDisposed
  8415.  
  8416. ) {
  8417. arr = addProtoToArr(_yt_player, k, arr) || arr;
  8418.  
  8419.  
  8420. }
  8421.  
  8422. }
  8423.  
  8424. if (arr.length === 0) {
  8425.  
  8426. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8427. } else {
  8428.  
  8429. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8430. return arr[0];
  8431. }
  8432.  
  8433. }
  8434.  
  8435.  
  8436. const getVG = (_yt_player) => {
  8437. const w = 'VG';
  8438.  
  8439. let arr = [];
  8440.  
  8441. for (const [k, v] of Object.entries(_yt_player)) {
  8442.  
  8443. const p = typeof v === 'function' ? v.prototype : 0;
  8444. if (p
  8445. && typeof p.show === 'function' && p.show.length === 1
  8446. && typeof p.hide === 'function' && p.hide.length === 0
  8447. && typeof p.stop === 'function' && p.stop.length === 0) {
  8448.  
  8449. arr = addProtoToArr(_yt_player, k, arr) || arr;
  8450.  
  8451. }
  8452.  
  8453. }
  8454.  
  8455.  
  8456. if (arr.length === 0) {
  8457.  
  8458. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8459. } else {
  8460.  
  8461. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8462. return arr[0];
  8463. }
  8464.  
  8465.  
  8466.  
  8467. }
  8468.  
  8469.  
  8470. const getzo = (_yt_player) => {
  8471. const w = 'zo';
  8472.  
  8473. let arr = [];
  8474.  
  8475. for (const [k, v] of Object.entries(_yt_player)) {
  8476.  
  8477. if (
  8478. typeof v === 'function' && v.length === 3 && k.length < 3
  8479. ) {
  8480. const vt = `${v}`;
  8481. if (vt.length >= 21 && vt.includes(".style[")) {
  8482. if (/\((\w{1,3}),(\w{1,3}),(\w{1,3})\)\{[\s\S]*\1\.style\[\2\]=\3\W/.test(vt)) {
  8483. arr.push(k);
  8484. } else {
  8485. console.warn('[yt-js-engine-tamer] unexpected zo::vt', vt);
  8486. }
  8487. }
  8488. }
  8489.  
  8490. }
  8491.  
  8492. if (arr.length === 0) {
  8493.  
  8494. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8495. } else {
  8496.  
  8497. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8498. return arr[0];
  8499. }
  8500.  
  8501. }
  8502.  
  8503. const addProtoToArr = (parent, key, arr) => {
  8504.  
  8505.  
  8506. let isChildProto = false;
  8507. for (const sr of arr) {
  8508. if (parent[key].prototype instanceof parent[sr]) {
  8509. isChildProto = true;
  8510. break;
  8511. }
  8512. }
  8513.  
  8514. if (isChildProto) return;
  8515.  
  8516. arr = arr.filter(sr => {
  8517. if (parent[sr].prototype instanceof parent[key]) {
  8518. return false;
  8519. }
  8520. return true;
  8521. });
  8522.  
  8523. arr.push(key);
  8524.  
  8525. return arr;
  8526.  
  8527.  
  8528. }
  8529.  
  8530. const getuG = (_yt_player) => {
  8531.  
  8532. const w = 'uG';
  8533.  
  8534. let arr = [];
  8535.  
  8536. for (const [k, v] of Object.entries(_yt_player)) {
  8537.  
  8538.  
  8539. const p = typeof v === 'function' ? v.prototype : 0;
  8540.  
  8541. if (p
  8542. && typeof p.createElement === 'function' && p.createElement.length === 2
  8543. && typeof p.detach === 'function' && p.detach.length === 0
  8544. && typeof p.update === 'function' && p.update.length === 1
  8545. && typeof p.updateValue === 'function' && p.updateValue.length === 2
  8546. ) {
  8547.  
  8548. arr = addProtoToArr(_yt_player, k, arr) || arr;
  8549.  
  8550. }
  8551.  
  8552. }
  8553.  
  8554.  
  8555.  
  8556.  
  8557.  
  8558. if (arr.length === 0) {
  8559.  
  8560. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8561. } else {
  8562.  
  8563. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8564. return arr[0];
  8565. }
  8566.  
  8567. }
  8568.  
  8569.  
  8570. const getQT = (_yt_player) => {
  8571. const w = 'QT';
  8572.  
  8573. let arr = [];
  8574. let brr = new Map();
  8575.  
  8576. for (const [k, v] of Object.entries(_yt_player)) {
  8577.  
  8578. const p = typeof v === 'function' ? v.prototype : 0;
  8579. if (p) {
  8580. let q = 0;
  8581. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  8582. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  8583. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  8584.  
  8585. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  8586.  
  8587. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  8588.  
  8589. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  8590. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  8591. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  8592. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  8593.  
  8594.  
  8595. // differentiate QT and DX
  8596.  
  8597. q += 280;
  8598. if (typeof p.cueVideoByPlayerVars === 'function') q += 4;
  8599. if (typeof p.loadVideoByPlayerVars === 'function') q += 4;
  8600. if (typeof p.preloadVideoByPlayerVars === 'function') q += 4;
  8601. if (typeof p.seekBy === 'function') q += 4;
  8602. if (typeof p.seekTo === 'function') q += 4;
  8603. if (typeof p.getStoryboardFormat === 'function') q += 4;
  8604. if (typeof p.getDuration === 'function') q += 4;
  8605. if (typeof p.loadModule === 'function') q += 4;
  8606. if (typeof p.unloadModule === 'function') q += 4;
  8607. if (typeof p.getOption === 'function') q += 4;
  8608. if (typeof p.getOptions === 'function') q += 4;
  8609. if (typeof p.setOption === 'function') q += 4;
  8610. if (typeof p.addCueRange === 'function') q += 4;
  8611. if (typeof p.getDebugText === 'function') q += 4;
  8612. if (typeof p.getCurrentBroadcastId === 'function') q += 4;
  8613. if (typeof p.setSizeStyle === 'function') q += 4;
  8614. if (typeof p.showControls === 'function') q += 4;
  8615. if (typeof p.hideControls === 'function') q += 4;
  8616. if (typeof p.getVideoContentRect === 'function') q += 4;
  8617. if (typeof p.toggleFullscreen === 'function') q += 4;
  8618. if (typeof p.isFullscreen === 'function') q += 4;
  8619. if (typeof p.cancelPlayback === 'function') q += 4;
  8620. if (typeof p.getProgressState === 'function') q += 4;
  8621. if (typeof p.isInline === 'function') q += 4;
  8622. if (typeof p.setInline === 'function') q += 4;
  8623. if (typeof p.toggleSubtitles === 'function') q += 4;
  8624. if (typeof p.getPlayerSize === 'function') q += 4;
  8625. if (typeof p.wakeUpControls === 'function') q += 4;
  8626. if (typeof p.setCenterCrop === 'function') q += 4;
  8627. if (typeof p.getLoopVideo === 'function') q += 4;
  8628. if (typeof p.setLoopVideo === 'function') q += 4;
  8629.  
  8630.  
  8631. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  8632.  
  8633. if (q > 0) brr.set(k, q);
  8634.  
  8635. }
  8636.  
  8637. }
  8638.  
  8639. if (arr.length === 0) {
  8640.  
  8641. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8642. } else {
  8643.  
  8644. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  8645.  
  8646. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  8647.  
  8648. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8649. return arr[0][0];
  8650. }
  8651.  
  8652.  
  8653.  
  8654. }
  8655.  
  8656.  
  8657.  
  8658. const getSV = (_yt_player) => {
  8659. const w = 'SV';
  8660.  
  8661. let arr = [];
  8662. let brr = new Map();
  8663.  
  8664. for (const [k, v] of Object.entries(_yt_player)) {
  8665.  
  8666. const p = typeof v === 'function' ? v.prototype : 0;
  8667. if (p) {
  8668. let q = 0;
  8669. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  8670. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  8671. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  8672.  
  8673. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q += 600; // SV
  8674.  
  8675. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  8676.  
  8677. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  8678. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  8679. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  8680. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  8681.  
  8682.  
  8683. // differentiate QT and DX
  8684.  
  8685.  
  8686. q += 280;
  8687.  
  8688. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  8689. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  8690. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  8691. if (typeof p.seekBy === 'function') q -= 4;
  8692. if (typeof p.seekTo === 'function') q -= 4;
  8693. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  8694. if (typeof p.getDuration === 'function') q -= 4;
  8695. if (typeof p.loadModule === 'function') q -= 4;
  8696. if (typeof p.unloadModule === 'function') q -= 4;
  8697. if (typeof p.getOption === 'function') q -= 4;
  8698. if (typeof p.getOptions === 'function') q -= 4;
  8699. if (typeof p.setOption === 'function') q -= 4;
  8700. if (typeof p.addCueRange === 'function') q -= 4;
  8701. if (typeof p.getDebugText === 'function') q -= 4;
  8702. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  8703. if (typeof p.setSizeStyle === 'function') q -= 4;
  8704. if (typeof p.showControls === 'function') q -= 4;
  8705. if (typeof p.hideControls === 'function') q -= 4;
  8706. if (typeof p.getVideoContentRect === 'function') q -= 4;
  8707. if (typeof p.toggleFullscreen === 'function') q -= 4;
  8708. if (typeof p.isFullscreen === 'function') q -= 4;
  8709. if (typeof p.cancelPlayback === 'function') q -= 4;
  8710. if (typeof p.getProgressState === 'function') q -= 4;
  8711. if (typeof p.isInline === 'function') q -= 4;
  8712. if (typeof p.setInline === 'function') q -= 4;
  8713. if (typeof p.toggleSubtitles === 'function') q -= 4;
  8714. if (typeof p.getPlayerSize === 'function') q -= 4;
  8715. if (typeof p.wakeUpControls === 'function') q -= 4;
  8716. if (typeof p.setCenterCrop === 'function') q -= 4;
  8717. if (typeof p.getLoopVideo === 'function') q -= 4;
  8718. if (typeof p.setLoopVideo === 'function') q -= 4;
  8719.  
  8720.  
  8721. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  8722.  
  8723. if (q > 0) brr.set(k, q);
  8724.  
  8725. }
  8726.  
  8727. }
  8728.  
  8729. if (arr.length === 0) {
  8730.  
  8731. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8732. } else {
  8733.  
  8734. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  8735.  
  8736. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  8737.  
  8738. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8739. return arr[0][0];
  8740. }
  8741.  
  8742.  
  8743.  
  8744. }
  8745.  
  8746.  
  8747.  
  8748.  
  8749. const getDX = (_yt_player) => {
  8750. const w = 'DX';
  8751.  
  8752. let arr = [];
  8753. let brr = new Map();
  8754.  
  8755. for (const [k, v] of Object.entries(_yt_player)) {
  8756.  
  8757. const p = typeof v === 'function' ? v.prototype : 0;
  8758. if (p) {
  8759. let q = 0;
  8760. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  8761. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  8762. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  8763.  
  8764. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  8765.  
  8766.  
  8767. if (!(typeof p.init === 'function' && p.init.length === 0)) q -= 300; // init is required
  8768.  
  8769. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  8770.  
  8771. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  8772. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  8773. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  8774. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  8775.  
  8776.  
  8777. // differentiate QT and DX
  8778.  
  8779.  
  8780. q += 280;
  8781.  
  8782. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  8783. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  8784. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  8785. if (typeof p.seekBy === 'function') q -= 4;
  8786. if (typeof p.seekTo === 'function') q -= 4;
  8787. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  8788. if (typeof p.getDuration === 'function') q -= 4;
  8789. if (typeof p.loadModule === 'function') q -= 4;
  8790. if (typeof p.unloadModule === 'function') q -= 4;
  8791. if (typeof p.getOption === 'function') q -= 4;
  8792. if (typeof p.getOptions === 'function') q -= 4;
  8793. if (typeof p.setOption === 'function') q -= 4;
  8794. if (typeof p.addCueRange === 'function') q -= 4;
  8795. if (typeof p.getDebugText === 'function') q -= 4;
  8796. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  8797. if (typeof p.setSizeStyle === 'function') q -= 4;
  8798. if (typeof p.showControls === 'function') q -= 4;
  8799. if (typeof p.hideControls === 'function') q -= 4;
  8800. if (typeof p.getVideoContentRect === 'function') q -= 4;
  8801. if (typeof p.toggleFullscreen === 'function') q -= 4;
  8802. if (typeof p.isFullscreen === 'function') q -= 4;
  8803. if (typeof p.cancelPlayback === 'function') q -= 4;
  8804. if (typeof p.getProgressState === 'function') q -= 4;
  8805. if (typeof p.isInline === 'function') q -= 4;
  8806. if (typeof p.setInline === 'function') q -= 4;
  8807. if (typeof p.toggleSubtitles === 'function') q -= 4;
  8808. if (typeof p.getPlayerSize === 'function') q -= 4;
  8809. if (typeof p.wakeUpControls === 'function') q -= 4;
  8810. if (typeof p.setCenterCrop === 'function') q -= 4;
  8811. if (typeof p.getLoopVideo === 'function') q -= 4;
  8812. if (typeof p.setLoopVideo === 'function') q -= 4;
  8813.  
  8814.  
  8815. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  8816.  
  8817. if (q > 0) brr.set(k, q);
  8818.  
  8819. }
  8820.  
  8821. }
  8822.  
  8823. if (arr.length === 0) {
  8824.  
  8825. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  8826. } else {
  8827.  
  8828. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  8829.  
  8830. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  8831.  
  8832. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  8833. return arr[0][0];
  8834. }
  8835.  
  8836.  
  8837.  
  8838. }
  8839.  
  8840.  
  8841.  
  8842. const isPrepareCachedV = (FIX_avoid_incorrect_video_meta ? true : false) && (window === top);
  8843.  
  8844. let pageSetupVideoId = null; // set at finish; '' for indeterminate state
  8845. let pageSetupState = 0;
  8846.  
  8847. isPrepareCachedV && (() => {
  8848.  
  8849. pageSetupVideoId = '';
  8850. const clearCachedV = () => {
  8851. pageSetupVideoId = '';
  8852. pageSetupState = 0;
  8853. }
  8854. document.addEventListener('yt-navigate-start', clearCachedV, false); // user action
  8855. document.addEventListener('yt-navigate-cache', clearCachedV, false); // pop state
  8856. document.addEventListener('yt-page-data-fetched', clearCachedV, false); // still consider invalid until url is ready in yt-navigate-finish
  8857. document.addEventListener('yt-navigate-finish', () => {
  8858. pageSetupState = 1;
  8859. try {
  8860. const url = new URL(location.href);
  8861. if (!url || !isWatchPageURL(url)) {
  8862. pageSetupVideoId = '';
  8863. } else {
  8864. pageSetupVideoId = url.searchParams.get('v') || '';
  8865. }
  8866. } catch (e) {
  8867. pageSetupVideoId = '';
  8868. }
  8869. }, false);
  8870.  
  8871. })();
  8872.  
  8873. let videoPlayingY = null;
  8874.  
  8875. isPrepareCachedV && (() => {
  8876.  
  8877. let getNext = true;
  8878. let videoPlayingX = {
  8879. get videoId() {
  8880. if (getNext) {
  8881. getNext = false;
  8882.  
  8883. let elements = document.querySelectorAll('ytd-watch-flexy[video-id]');
  8884. const arr = [];
  8885. for (const element of elements) {
  8886. if (!element.closest('[hidden]')) arr.push(element);
  8887. }
  8888. if (arr.length !== 1) this.__videoId__ = '';
  8889. else {
  8890. this.__videoId__ = arr[0].getAttribute('video-id');
  8891. }
  8892.  
  8893. }
  8894. return this.__videoId__ || '';
  8895. }
  8896. }
  8897.  
  8898. videoPlayingY = videoPlayingX;
  8899. const handler = (evt) => {
  8900. const target = (evt || 0).target;
  8901. if (target instanceof HTMLVideoElement) {
  8902. getNext = true;
  8903. }
  8904. }
  8905. document.addEventListener('loadedmetadata', handler, true);
  8906. document.addEventListener('durationchange', handler, true);
  8907.  
  8908. })();
  8909.  
  8910.  
  8911.  
  8912. const cleanContext = async (win) => {
  8913. const waitFn = requestAnimationFrame; // shall have been binded to window
  8914. try {
  8915. let mx = 16; // MAX TRIAL
  8916. const frameId = 'vanillajs-iframe-v1';
  8917. /** @type {HTMLIFrameElement | null} */
  8918. let frame = document.getElementById(frameId);
  8919. let removeIframeFn = null;
  8920. if (!frame) {
  8921. frame = document.createElement('iframe');
  8922. frame.id = frameId;
  8923. const blobURL = typeof webkitCancelAnimationFrame === 'function' && typeof kagi === 'undefined' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  8924. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  8925. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  8926. n.appendChild(frame);
  8927. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  8928. const root = document.documentElement;
  8929. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  8930. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  8931.  
  8932. removeIframeFn = (setTimeout) => {
  8933. const removeIframeOnDocumentReady = (e) => {
  8934. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  8935. e = n;
  8936. n = win = removeIframeFn = 0;
  8937. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  8938. }
  8939. if (!setTimeout || document.readyState !== 'loading') {
  8940. removeIframeOnDocumentReady();
  8941. } else {
  8942. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  8943. }
  8944. }
  8945. }
  8946. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  8947. const fc = frame.contentWindow;
  8948. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  8949. try {
  8950. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle } = fc;
  8951. const res = { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle };
  8952. for (let k in res) res[k] = res[k].bind(win); // necessary
  8953. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  8954. res.animate = fc.HTMLElement.prototype.animate;
  8955. res.perfNow = fc.performance.now;
  8956. return res;
  8957. } catch (e) {
  8958. if (removeIframeFn) removeIframeFn();
  8959. return null;
  8960. }
  8961. } catch (e) {
  8962. console.warn(e);
  8963. return null;
  8964. }
  8965. };
  8966.  
  8967. const promiseForYtActionCalled = new Promise(resolve => {
  8968.  
  8969. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-app';
  8970. if (typeof AbortSignal !== 'undefined') {
  8971. let hn = () => {
  8972. if (!hn) return;
  8973. hn = null;
  8974. resolve(document.querySelector(appTag));
  8975. };
  8976. document.addEventListener('yt-action', hn, { capture: true, passive: true, once: true });
  8977. } else {
  8978. let hn = () => {
  8979. if (!hn) return;
  8980. document.removeEventListener('yt-action', hn, true);
  8981. hn = null;
  8982. resolve(document.querySelector(appTag));
  8983. };
  8984. document.addEventListener('yt-action', hn, true);
  8985. }
  8986. });
  8987.  
  8988. cleanContext(window).then(__CONTEXT__ => {
  8989. if (!__CONTEXT__) return null;
  8990.  
  8991. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, animate, requestIdleCallback, getComputedStyle, perfNow } = __CONTEXT__;
  8992.  
  8993.  
  8994. performance.now17 = perfNow.bind(performance);
  8995.  
  8996.  
  8997.  
  8998. __requestAnimationFrame__ = requestAnimationFrame;
  8999.  
  9000.  
  9001. const isGPUAccelerationAvailable = (() => {
  9002. // https://gist.github.com/cvan/042b2448fcecefafbb6a91469484cdf8
  9003. try {
  9004. const canvas = document.createElement('canvas');
  9005. return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
  9006. } catch (e) {
  9007. return false;
  9008. }
  9009. })();
  9010.  
  9011. const foregroundPromiseFn_noGPU = (() => {
  9012.  
  9013. if (isGPUAccelerationAvailable) return null;
  9014.  
  9015. const pd = Object.getOwnPropertyDescriptor(Document.prototype, 'visibilityState');
  9016. if (!pd || typeof pd.get !== 'function') return null;
  9017. const pdGet = pd.get;
  9018.  
  9019. let pr = null;
  9020.  
  9021. let hState = pdGet.call(document) === 'hidden';
  9022. // let cid = 0;
  9023. pureAddEventListener.call(document, 'visibilitychange', (evt) => {
  9024. const newHState = pdGet.call(document) === 'hidden';
  9025. if (hState !== newHState) {
  9026. // if (cid > 0) cid = clearInterval(cid);
  9027. hState = newHState;
  9028. if (!hState && pr) pr = pr.resolve();
  9029. }
  9030. });
  9031.  
  9032. // cid = setInterval(() => {
  9033. // const newHState = document.visibilityState === 'hidden';
  9034. // if (hState !== newHState) {
  9035. // hState = newHState;
  9036. // if (!hState && pr) pr = pr.resolve();
  9037. // }
  9038. // }, 100);
  9039.  
  9040.  
  9041. return (() => {
  9042. if (pr) return pr;
  9043. const w = ((!hState && setTimeout(() => {
  9044. if (!hState && pr === w) pr = pr.resolve();
  9045. })), (pr = new PromiseExternal()));
  9046. return w;
  9047. });
  9048.  
  9049. })();
  9050.  
  9051.  
  9052. let rafPromise = null;
  9053. const getRafPromise = () => rafPromise || (rafPromise = new Promise(resolve => {
  9054. requestAnimationFrame(hRes => {
  9055. rafPromise = null;
  9056. resolve(hRes);
  9057. });
  9058. }));
  9059.  
  9060. const foregroundPromiseFn = foregroundPromiseFn_noGPU || getRafPromise;
  9061.  
  9062.  
  9063. const wmComputedStyle = new WeakMap();
  9064.  
  9065. if (!window.__native__getComputedStyle__ && !window.__jst__getComputedStyle__ && typeof window.getComputedStyle === 'function' && window.getComputedStyle.length === 1) {
  9066. window.__native__getComputedStyle__ = getComputedStyle;
  9067. if (ENABLE_COMPUTEDSTYLE_CACHE) {
  9068. window.__original__getComputedStyle__ = window.getComputedStyle;
  9069. window.getComputedStyle = function (elem) {
  9070. if (!(elem instanceof Element) || (arguments.length === 2 && arguments[1]) || (arguments.length > 2)) {
  9071. return window.__original__getComputedStyle__(...arguments);
  9072. }
  9073. let cs = wmComputedStyle.get(elem);
  9074. if (!cs) {
  9075. cs = window.__native__getComputedStyle__(elem);
  9076. wmComputedStyle.set(elem, cs);
  9077. }
  9078. return cs;
  9079. };
  9080. } else {
  9081. window.__original__getComputedStyle__ = null;
  9082. }
  9083. window.__jst__getComputedStyle__ = window.getComputedStyle;
  9084. }
  9085.  
  9086. NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE && promiseForYtActionCalled.then(() => {
  9087. if (typeof window.__jst__getComputedStyle__ === 'function' && window.__jst__getComputedStyle__.length === 1 && window.__jst__getComputedStyle__ !== window.getComputedStyle) {
  9088. window.getComputedStyle = window.__jst__getComputedStyle__;
  9089. }
  9090. });
  9091.  
  9092. const isUrlInEmbed = location.href.includes('.youtube.com/embed/');
  9093. const isAbortSignalSupported = typeof AbortSignal !== "undefined";
  9094.  
  9095. const promiseForTamerTimeout = new Promise(resolve => {
  9096. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  9097. setTimeout(resolve, 480);
  9098. }, { capture: true, passive: true, once: true });
  9099. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  9100. setTimeout(resolve, 1200);
  9101. });
  9102. setTimeout(resolve, 3000);
  9103. });
  9104.  
  9105. const promiseForPageInitied = new Promise(resolve => {
  9106. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  9107. setTimeout(resolve, 450);
  9108. }, { capture: true, passive: true, once: true });
  9109. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  9110. setTimeout(resolve, 900);
  9111. });
  9112. setTimeout(resolve, 1800);
  9113. });
  9114.  
  9115. NO_PRELOAD_GENERATE_204_BYPASS || promiseForPageInitied.then(() => {
  9116. NO_PRELOAD_GENERATE_204_BYPASS = true;
  9117. headLinkCollection = null;
  9118. });
  9119.  
  9120.  
  9121. NATIVE_CANVAS_ANIMATION && (() => {
  9122.  
  9123. observablePromise(() => {
  9124. HTMLCanvasElement.prototype.animate = animate;
  9125. }, promiseForTamerTimeout).obtain();
  9126.  
  9127. })();
  9128.  
  9129.  
  9130.  
  9131.  
  9132. FIX_ytAction_ && (async () => {
  9133.  
  9134. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-app';
  9135.  
  9136. const ytdApp = await new Promise(resolve => {
  9137.  
  9138. whenCEDefined(appTag).then(() => {
  9139. const ytdApp = document.querySelector(appTag);
  9140. if (ytdApp) {
  9141. resolve(ytdApp);
  9142. return;
  9143. }
  9144. let mo = new MutationObserver(() => {
  9145. const ytdApp = document.querySelector(appTag);
  9146. if (!ytdApp) return;
  9147. if (mo) {
  9148. mo.disconnect();
  9149. mo.takeRecords();
  9150. mo = null;
  9151. }
  9152. resolve(ytdApp);
  9153. });
  9154. mo.observe(document, { subtree: true, childList: true });
  9155. });
  9156.  
  9157. });
  9158.  
  9159. if (!ytdApp) return;
  9160. const cProto = insp(ytdApp).constructor.prototype;
  9161.  
  9162. if (!cProto) return;
  9163. let mbd = 0;
  9164.  
  9165. const fixer = (_ytdApp) => {
  9166. const ytdApp = insp(_ytdApp);
  9167. if (ytdApp && typeof ytdApp.onYtActionBoundListener_ === 'function' && !ytdApp.onYtActionBoundListener57_) {
  9168. ytdApp.onYtActionBoundListener57_ = ytdApp.onYtActionBoundListener_;
  9169. ytdApp.onYtActionBoundListener_ = ytdApp.onYtAction_.bind(ytdApp);
  9170. mbd++;
  9171. }
  9172. }
  9173.  
  9174. observablePromise(() => {
  9175.  
  9176. if (typeof cProto.created === 'function' && !cProto.created56) {
  9177. cProto.created56 = cProto.created;
  9178. cProto.created = function (...args) {
  9179. const r = this.created56(...args);
  9180. fixer(this);
  9181. return r;
  9182. };
  9183. mbd++;
  9184. }
  9185.  
  9186. if (typeof cProto.onYtAction_ === 'function' && !cProto.onYtAction57_) {
  9187. cProto.onYtAction57_ = cProto.onYtAction_;
  9188. cProto.onYtAction_ = function (...args) {
  9189. Promise.resolve().then(() => this.onYtAction57_(...args));
  9190. };
  9191. mbd++;
  9192. }
  9193.  
  9194. if (ytdApp) fixer(ytdApp);
  9195.  
  9196. /*
  9197. const actionRouter_ = ytdApp ? ytdApp.actionRouter_ : null;
  9198. if (actionRouter_ && typeof actionRouter_.handleAction === 'function' && !actionRouter_.handleAction57) {
  9199. actionRouter_.handleAction57 = actionRouter_.handleAction;
  9200. actionRouter_.handleAction = function (...args) {
  9201. Promise.resolve().then(() => this.handleAction57(...args));
  9202. }
  9203. mbd++;
  9204. }
  9205. */
  9206.  
  9207. // if(mbd === 3) return 1;
  9208. if (mbd >= 3) return 1;
  9209.  
  9210. }, new Promise(r => setTimeout(r, 1000))).obtain();
  9211.  
  9212. })();
  9213.  
  9214.  
  9215. FORCE_NO_REUSEABLE_ELEMENT_POOL && promiseForYtActionCalled.then(async () => {
  9216.  
  9217. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-watch-flexy';
  9218.  
  9219. const app = await observablePromise(() => {
  9220.  
  9221. return document.querySelector(appTag);
  9222.  
  9223. }).obtain();
  9224.  
  9225. if (!app) return;
  9226.  
  9227. const appCnt = insp(app);
  9228. FORCE_NO_REUSEABLE_ELEMENT_POOL_fn(appCnt);
  9229.  
  9230.  
  9231.  
  9232.  
  9233. });
  9234.  
  9235.  
  9236. // let _yt_player_promise = null;
  9237. /*
  9238. const getYtPlayerPromise = () => {
  9239. if (!_yt_player_promise) {
  9240. _yt_player_promise = new Promise(resolve => {
  9241. let cid = setInterval(() => {
  9242. let t = (((window || 0)._yt_player || 0) || 0);
  9243. if (t) {
  9244. clearInterval(cid);
  9245. resolve(t);
  9246. }
  9247. }, 1);
  9248. promiseForTamerTimeout.then(() => {
  9249. resolve(null)
  9250. });
  9251. });
  9252. }
  9253. return _yt_player_promise;
  9254. }
  9255. */
  9256. const _yt_player_observable = observablePromise(() => {
  9257. const _yt_player = (((window || 0)._yt_player || 0) || 0);
  9258. if (_yt_player) {
  9259. _yt_player[`__is_yt_player__${Date.now()}`] = 1;
  9260. return _yt_player;
  9261. }
  9262. }, promiseForTamerTimeout);
  9263.  
  9264. const polymerObservable = observablePromise(() => {
  9265. const Polymer = window.Polymer;
  9266. if (typeof Polymer !== 'function') return;
  9267. if (!(Polymer.Base || 0).connectedCallback || !(Polymer.Base || 0).disconnectedCallback) return;
  9268. return Polymer;
  9269. }, promiseForTamerTimeout);
  9270.  
  9271. const schedulerInstanceObservable = observablePromise(() => {
  9272. return (((window || 0).ytglobal || 0).schedulerInstanceInstance_ || 0);
  9273. }, promiseForTamerTimeout);
  9274.  
  9275. const timelineObservable = observablePromise(() => {
  9276. let t = (((document || 0).timeline || 0) || 0);
  9277. if (t && typeof t._play === 'function') {
  9278. return t;
  9279. }
  9280. }, promiseForTamerTimeout);
  9281. const animationObservable = observablePromise(() => {
  9282. let t = (((window || 0).Animation || 0) || 0);
  9283. if (t && typeof t === 'function' && t.length === 2 && typeof t.prototype._updatePromises === 'function') {
  9284. return t;
  9285. }
  9286. }, promiseForTamerTimeout);
  9287.  
  9288.  
  9289. const getScreenInfo = {
  9290. screenWidth: 0,
  9291. screenHeight: 0,
  9292. valueReady: false,
  9293. onResize: () => {
  9294. getScreenInfo.valueReady = false;
  9295. },
  9296. sizeProvided: () => {
  9297. if (getScreenInfo.valueReady) return true;
  9298. getScreenInfo.screenWidth = screen.width;
  9299. getScreenInfo.screenHeight = screen.height;
  9300. if (getScreenInfo.screenWidth * getScreenInfo.screenHeight > 1) {
  9301. getScreenInfo.valueReady = true;
  9302. return true;
  9303. }
  9304. return false;
  9305. }
  9306. };
  9307.  
  9308. window.addEventListener('resize', getScreenInfo.onResize, true);
  9309.  
  9310.  
  9311. // const hookLeftPending = new WeakMap();
  9312.  
  9313. const isNaNx = Number.isNaN;
  9314.  
  9315. const hookLeftPD = {
  9316. get() {
  9317. const p = 'left';
  9318. // const o = hookLeftPending.get(this);
  9319. // if (o && o.key) {
  9320. // this.setProperty(p, o.value);
  9321. // o.key = null
  9322. // }
  9323. return this.getPropertyValue(p);
  9324. },
  9325. set(v) {
  9326.  
  9327. const p = 'left';
  9328. const cv = this.getPropertyValue(p);
  9329. const sv = v;
  9330.  
  9331. // const did = Math.floor(Math.random() * 314159265359 + 314159265359).toString(36);
  9332.  
  9333. // console.log(8380,did, cv, sv)
  9334. if (!cv && !sv) return true;
  9335. if (cv === sv) return true;
  9336.  
  9337. // skip 0~9px => L>=4
  9338.  
  9339. const qsv = `${sv}`.length >= 4 && `${sv}`.endsWith('px') ? +sv.slice(0, -2) : NaN;
  9340.  
  9341. if (!isNaNx(qsv)) {
  9342. const qcv = `${cv}`.length >= 4 && `${cv}`.endsWith('px') ? +cv.slice(0, -2) : NaN;
  9343.  
  9344. if (!isNaNx(qcv) && getScreenInfo.sizeProvided()) {
  9345. const { screenWidth, screenHeight } = getScreenInfo;
  9346. let pWidth = screenWidth + 1024;
  9347. let pHeight = screenHeight + 768;
  9348. const minRatio = 0.003;
  9349. const dw = pWidth * 0.0003; // min dw = 0.3072
  9350. const dh = pHeight * 0.0003; // min dh = 0.2304
  9351. // console.log(8381,did, Math.abs(qcv - qsv) < dw)
  9352. if (Math.abs(qcv - qsv) < dw) return true;
  9353. }
  9354.  
  9355. v = `${qsv > -1e-5 && qsv < 1e-5 ? 0 : qsv.toFixed(4)}px`;
  9356. if (`${v}`.length > `${sv}`.length) v = sv;
  9357. // console.log(8382, did, sv, nv, cv, this)
  9358. }
  9359.  
  9360. // Promise.resolve().then(() => {
  9361. // const o = hookLeftPending.get(this);
  9362. // if (o && o.key === did) {
  9363. // this.setProperty(p, o.value);
  9364. // o.key = null;
  9365. // }
  9366. // });
  9367. // hookLeftPending.set(this, {
  9368. // key: did,
  9369. // value: nv
  9370. // });
  9371.  
  9372. // if (nv != v) {
  9373. // console.log(8387, v, nv);
  9374. // }
  9375.  
  9376. this.setProperty(p, v);
  9377. // console.log(8383, did, this.getPropertyValue(p))
  9378. return true;
  9379. },
  9380. enumerable: true,
  9381. configurable: true
  9382. };
  9383.  
  9384.  
  9385. if (HOOK_CSSPD_LEFT) {
  9386.  
  9387.  
  9388. Object.defineProperty(CSSStyleDeclaration.prototype, 'left', hookLeftPD);
  9389.  
  9390. }
  9391.  
  9392.  
  9393.  
  9394.  
  9395.  
  9396. const generalEvtHandler = async (_evKey, _fvKey, _debug) => {
  9397.  
  9398. const evKey = `${_evKey}`;
  9399. const fvKey = `${_fvKey}`;
  9400. const debug = !!_debug;
  9401.  
  9402. const _yt_player = await _yt_player_observable.obtain();
  9403.  
  9404.  
  9405. if (!_yt_player || typeof _yt_player !== 'object') return;
  9406.  
  9407.  
  9408. const getArr = (_yt_player) => {
  9409.  
  9410. let arr = [];
  9411.  
  9412. for (const [k, v] of Object.entries(_yt_player)) {
  9413.  
  9414. const p = typeof v === 'function' ? v.prototype : 0;
  9415. if (p
  9416. && typeof p[evKey] === 'function' && p[evKey].length >= 0 && !p[fvKey]
  9417.  
  9418. ) {
  9419. arr = addProtoToArr(_yt_player, k, arr) || arr;
  9420.  
  9421. }
  9422.  
  9423. }
  9424.  
  9425. if (arr.length === 0) {
  9426.  
  9427. console.warn(`Key prop [${evKey}] does not exist.`);
  9428. } else {
  9429.  
  9430. return arr;
  9431. }
  9432.  
  9433. };
  9434.  
  9435. const arr = getArr(_yt_player);
  9436.  
  9437.  
  9438. if (!arr) return;
  9439.  
  9440. debug && console.log(`FIX_${evKey}`, arr);
  9441.  
  9442. const f = function (...args) {
  9443. Promise.resolve().then(() => this[fvKey](...args));
  9444. };
  9445.  
  9446.  
  9447. for (const k of arr) {
  9448.  
  9449. const g = _yt_player;
  9450. const gk = g[k];
  9451. const gkp = gk.prototype;
  9452.  
  9453. debug && console.log(237, k, gkp)
  9454.  
  9455. if (typeof gkp[evKey] == 'function' && !gkp[fvKey]) {
  9456. gkp[fvKey] = gkp[evKey];
  9457. gkp[evKey] = f;
  9458. }
  9459. }
  9460.  
  9461.  
  9462.  
  9463.  
  9464. }
  9465.  
  9466. if (!isChatRoomURL) {
  9467.  
  9468. FIX_onVideoDataChange && generalEvtHandler('onVideoDataChange', 'onVideoDataChange57');
  9469. // FIX_onClick && generalEvtHandler('onClick', 'onClick57');
  9470. FIX_onStateChange && generalEvtHandler('onStateChange', 'onStateChange57');
  9471. FIX_onLoopRangeChange && generalEvtHandler('onLoopRangeChange', 'onLoopRangeChange57');
  9472. if (FIX_VideoEVENTS_v2) {
  9473. const FIX_VideoEVENTS_DEBUG = 0;
  9474. generalEvtHandler('onVideoProgress', 'onVideoProgress57', FIX_VideoEVENTS_DEBUG); // --
  9475. // generalEvtHandler('onAutoplayBlocked', 'onAutoplayBlocked57', FIX_VideoEVENTS_DEBUG);
  9476. // generalEvtHandler('onLoadProgress', 'onLoadProgress57', FIX_VideoEVENTS_DEBUG); // << CAUSE ISSUE >>
  9477. generalEvtHandler('onFullscreenChange', 'onFullscreenChange57', FIX_VideoEVENTS_DEBUG); // --
  9478. // generalEvtHandler('onLoadedMetadata', 'onLoadedMetadata57', FIX_VideoEVENTS_DEBUG);
  9479. // generalEvtHandler('onDrmOutputRestricted', 'onDrmOutputRestricted57', FIX_VideoEVENTS_DEBUG);
  9480. // generalEvtHandler('onAirPlayActiveChange', 'onAirPlayActiveChange57', FIX_VideoEVENTS_DEBUG);
  9481. // generalEvtHandler('onAirPlayAvailabilityChange', 'onAirPlayAvailabilityChange57', FIX_VideoEVENTS_DEBUG);
  9482. // generalEvtHandler('onApiChange', 'onApiChange57', FIX_VideoEVENTS_DEBUG);
  9483.  
  9484. }
  9485. // onMutedAutoplayChange
  9486. // onVolumeChange
  9487. // onPlaybackRateChange
  9488.  
  9489. // onAirPlayActiveChange
  9490. // onAirPlayAvailabilityChange
  9491. // onApiChange
  9492. // onAutoplayBlocked
  9493. // onDrmOutputRestricted
  9494. // onFullscreenChange
  9495. // onLoadProgress
  9496. // onLoadedMetadata
  9497. // onVideoDataChange
  9498. // onVideoProgress
  9499.  
  9500. }
  9501.  
  9502.  
  9503. let isAmended_Polymer_RenderStatus = false;
  9504.  
  9505. (FIX_Polymer_dom || FIX_Polymer_AF || FIX_stampDomArray) && (async () => {
  9506.  
  9507. const Polymer = await polymerObservable.obtain();
  9508. if (!Polymer) return;
  9509.  
  9510. if (FIX_Polymer_AF && Polymer && Polymer.RenderStatus && !isAmended_Polymer_RenderStatus) {
  9511. isAmended_Polymer_RenderStatus = true;
  9512.  
  9513. if (typeof Polymer.RenderStatus.beforeNextRender === 'function' && typeof Polymer.RenderStatus.afterNextRender === 'function' && Polymer.RenderStatus.beforeNextRender.length === 3 && Polymer.RenderStatus.afterNextRender.length === 3) {
  9514. let arrBefore = null, arrAfter = null;
  9515. const push = Array.prototype.push;
  9516. let arr = null;
  9517. Array.prototype.push = function () {
  9518. arr = this;
  9519. }
  9520. Polymer.RenderStatus.beforeNextRender({}, {}, {});
  9521. if (arr) arrBefore = arr;
  9522. arr = null;
  9523. Polymer.RenderStatus.afterNextRender({}, {}, {});
  9524. if (arr) arrAfter = arr;
  9525. arr = null;
  9526. Array.prototype.push = push;
  9527. Polymer.RenderStatus.arrBefore = arrBefore;
  9528. Polymer.RenderStatus.arrAfter = arrAfter;
  9529.  
  9530. if (arrBefore && arrAfter) {
  9531.  
  9532. Function.prototype.call7900 = Function.prototype.call;
  9533. Function.prototype.apply7900 = Function.prototype.apply;
  9534. Function.prototype.apply7948 = function (obj, args) {
  9535. const f = this;
  9536. let m = kRef(obj);
  9537. if (!m) return;
  9538. if (m.is && !m.nodeName) {
  9539. if (!m.isAttached || !m.hostElement) {
  9540. return;
  9541. }
  9542. }
  9543. try {
  9544. return !args ? f.call7900(m) : f.apply7900(m, args);
  9545. } catch (e) {
  9546. console.warn(e);
  9547. }
  9548. return null;
  9549. }
  9550.  
  9551. arrBefore.push = arrAfter.push = function (a) {
  9552. if (arguments.length !== 1 || !a || a.length === 0 || !a[0]) return push.apply(this, arguments);
  9553. if (a[0].deref) a[0] = kRef(a[0]);
  9554. const f = a[1]
  9555. const obj = a[0]
  9556. const args = a[2];
  9557. f.apply = f.apply7948;
  9558. if (!obj[wk]) obj[wk] = mWeakRef(obj);
  9559. a[0] = obj[wk]
  9560. // console.log(4992, a)
  9561. return push.call(this, a);
  9562. }
  9563.  
  9564. }
  9565.  
  9566.  
  9567. }
  9568. // Polymer.RenderStatus.beforeNextRender
  9569. }
  9570.  
  9571. if (FIX_Polymer_dom) {
  9572.  
  9573. const checkPDFuncValue = (pd) => {
  9574. return pd && pd.writable && pd.enumerable && pd.configurable && typeof pd.value == 'function'
  9575. }
  9576. const checkPDFuncValue2 = (pd) => {
  9577. return pd && typeof pd.value == 'function'
  9578. }
  9579.  
  9580. const checkPDFuncGet = (pd) => {
  9581. return pd && typeof pd.get == 'function'
  9582. }
  9583.  
  9584. const domX = Polymer.dom(document.createElement('null'));
  9585. const domXP = (((domX || 0).constructor || 0).prototype || 0);
  9586. const pd1 = Object.getOwnPropertyDescriptor(domXP, 'getOwnerRoot');
  9587. const pd2 = Object.getOwnPropertyDescriptor(Node.prototype, 'parentElement');
  9588. const pd3 = Object.getOwnPropertyDescriptor(domXP, 'querySelector'); // undefined
  9589. const pd4 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelector');
  9590. const pd4b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelector');
  9591. const pd5 = Object.getOwnPropertyDescriptor(domXP, 'querySelectorAll'); // undefined
  9592. const pd6 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelectorAll');
  9593. const pd6b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelectorAll');
  9594.  
  9595.  
  9596. if ((!pd3 || checkPDFuncValue(pd3)) && checkPDFuncValue2(pd4) && checkPDFuncValue2(pd4b) && !('querySelector15' in domXP)) {
  9597.  
  9598. domXP.querySelector15 = domXP.querySelector;
  9599.  
  9600. const querySelectorFn = function (query) {
  9601. try {
  9602. const p = this.node;
  9603.  
  9604. if (p instanceof Document && p.isConnected === true) {
  9605. return pd4b.value.call(p, query);
  9606. }
  9607.  
  9608. } catch (e) { }
  9609. return this.querySelector15(query);
  9610. }
  9611.  
  9612. Object.defineProperty(domXP, 'querySelector', {
  9613. get() {
  9614. return querySelectorFn;
  9615. },
  9616. set(nv) {
  9617. if (nv === querySelectorFn) return true;
  9618. this.querySelector15 = nv;
  9619. return true;
  9620. },
  9621.  
  9622. enumerable: false,
  9623. configurable: true
  9624. });
  9625.  
  9626. Polymer.__fixedQuerySelector__ = 1;
  9627. }
  9628.  
  9629. if ((!pd5 || checkPDFuncValue(pd5)) && checkPDFuncValue2(pd6) && checkPDFuncValue2(pd6b) && !('querySelectorAll15' in domXP)) {
  9630.  
  9631. domXP.querySelectorAll15 = domXP.querySelectorAll;
  9632.  
  9633. const querySelectorAllFn = function (query) {
  9634.  
  9635. try {
  9636.  
  9637. const p = this.node;
  9638.  
  9639. if (p instanceof Document && p.isConnected === true) {
  9640. return pd6b.value.call(p, query);
  9641. }
  9642.  
  9643. } catch (e) {
  9644.  
  9645. }
  9646. return this.querySelectorAll15(query);
  9647. }
  9648.  
  9649. Object.defineProperty(domXP, 'querySelectorAll', {
  9650. get() {
  9651. return querySelectorAllFn;
  9652. },
  9653. set(nv) {
  9654. if (nv === querySelectorAllFn) return true;
  9655. this.querySelectorAll15 = nv;
  9656. return true;
  9657. },
  9658.  
  9659. enumerable: false,
  9660. configurable: true
  9661. });
  9662.  
  9663. Polymer.__fixedQuerySelectorAll__ = 1;
  9664. }
  9665. }
  9666.  
  9667.  
  9668. if (FIX_stampDomArray) {
  9669.  
  9670. Polymer.Base.__connInit__ = function () {
  9671. setupYtComponent(this);
  9672. }
  9673.  
  9674.  
  9675. /** @type {Function} */
  9676. const connectedCallbackK = function (...args) {
  9677. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  9678. const r = this[qm53](...args);
  9679. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  9680. this.mh35 = 1;
  9681. return r;
  9682. };
  9683.  
  9684. connectedCallbackK.m353 = 1;
  9685.  
  9686.  
  9687. const qt53 = Polymer.Base.connectedCallback;
  9688. Polymer.Base[qm53] = dmf.get(qt53) || qt53;
  9689.  
  9690. Polymer.Base.connectedCallback = connectedCallbackK;
  9691.  
  9692.  
  9693. /** @type {Function} */
  9694. const createdK = function (...args) {
  9695. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  9696. const r = this[qn53](...args);
  9697. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  9698. this.mh36 = 1;
  9699. return r;
  9700. };
  9701.  
  9702.  
  9703. createdK.m353 = 1;
  9704. Polymer.Base[qn53] = Polymer.Base.created;
  9705. Polymer.Base.created = createdK;
  9706.  
  9707.  
  9708.  
  9709.  
  9710.  
  9711.  
  9712.  
  9713.  
  9714.  
  9715.  
  9716.  
  9717. }
  9718.  
  9719. })();
  9720.  
  9721.  
  9722. /*
  9723.  
  9724. e.nativeAppendChild = d.prototype.appendChild,
  9725. d.prototype.appendChild = function(h) {
  9726. return function(l) {
  9727. if (l instanceof DocumentFragment) {
  9728. var m = Array.from(l.children);
  9729. l = h.nativeAppendChild.call(this, l);
  9730. if (this.isConnected) {
  9731. m = g(m);
  9732. for (var p = m.next(); !p.done; p = m.next())
  9733. YD(p.value)
  9734. }
  9735. return l
  9736. }
  9737. m = l instanceof Element && l.isConnected;
  9738. p = h.nativeAppendChild.call(this, l);
  9739. m && ZD(l);
  9740. this.isConnected && YD(l);
  9741. return p
  9742. }
  9743. }(e),
  9744.  
  9745. */
  9746.  
  9747. CHANGE_appendChild && !Node.prototype.appendChild73 && Node.prototype.appendChild && (() => {
  9748.  
  9749. const f = Node.prototype.appendChild73 = Node.prototype.appendChild;
  9750. if (f) Node.prototype.appendChild = function (a) {
  9751. if (this instanceof Element) { // exclude DocumentFragment
  9752. try {
  9753. let checkFragmentA = (a instanceof DocumentFragment);
  9754. if (!NO_PRELOAD_GENERATE_204_BYPASS && document.head === this) {
  9755. if (headLinkCollection === null) headLinkCollection = document.head.getElementsByTagName('LINK');
  9756. for (const node of headLinkCollection) {
  9757. if (node.rel === 'preload' && node.as === 'fetch') {
  9758. node.rel = 'prefetch'; // see https://github.com/GoogleChromeLabs/quicklink
  9759. }
  9760. }
  9761. } else if (checkFragmentA && this.nodeName.startsWith('YT-')) { // yt-animated-rolling-number, yt-attributed-string
  9762. checkFragmentA = false;
  9763. }
  9764. if (checkFragmentA && a.firstElementChild === null) {
  9765. // no element in fragmentA
  9766. let doNormal = false;
  9767. for (let child = a.firstChild; child instanceof Node; child = child.nextSibling) {
  9768. if (child.nodeType === 3) { doNormal = true; break; }
  9769. }
  9770. if (!doNormal) return a;
  9771. }
  9772. } catch (e) {
  9773. console.log(e);
  9774. }
  9775. }
  9776. return arguments.length === 1 ? f.call(this, a) : f.apply(this, arguments);
  9777. }
  9778.  
  9779. })();
  9780.  
  9781. if (FIX_Shady) {
  9782.  
  9783. observablePromise(() => {
  9784. const { ShadyDOM, ShadyCSS } = window;
  9785. if (ShadyDOM) {
  9786. ShadyDOM.handlesDynamicScoping = false; // 9 of 10
  9787. ShadyDOM.noPatch = true; // 1 of 10
  9788. ShadyDOM.patchOnDemand = false; // 1 of 10
  9789. ShadyDOM.preferPerformance = true; // 1 of 10
  9790. ShadyDOM.querySelectorImplementation = undefined; // 1 of 10
  9791. }
  9792. if (ShadyCSS) {
  9793. ShadyCSS.nativeCss = true; // 1 of 10
  9794. ShadyCSS.nativeShadow = true; // 6 of 10
  9795. ShadyCSS.cssBuild = undefined; // 1 of 10
  9796. ShadyCSS.disableRuntime = true; // 1 of 10
  9797. }
  9798. if (ShadyDOM && ShadyCSS) return 1;
  9799. }, promiseForTamerTimeout).obtain(); // clear until 1 is return
  9800.  
  9801. }
  9802.  
  9803.  
  9804. // let schedulerInstancePropOfTimerType = '';
  9805. // let schedulerInstancePropOfTimerId = '';
  9806. (FIX_schedulerInstanceInstance & 2) && (async () => {
  9807.  
  9808. const schedulerInstanceInstance_ = await schedulerInstanceObservable.obtain();
  9809.  
  9810. if (!schedulerInstanceInstance_) return;
  9811.  
  9812. const checkOK = typeof schedulerInstanceInstance_.start === 'function' && !schedulerInstanceInstance_.start993 && !schedulerInstanceInstance_.stop && !schedulerInstanceInstance_.cancel && !schedulerInstanceInstance_.terminate && !schedulerInstanceInstance_.interupt;
  9813. if (checkOK) {
  9814.  
  9815. let resolveRendering = null;
  9816.  
  9817. let cmPr = new PromiseExternal();
  9818. const cm = document.createComment('0');
  9819. const cmObs = new MutationObserver(() => {
  9820. if (resolveRendering) {
  9821. resolveRendering();
  9822. resolveRendering = null;
  9823. }
  9824. cmPr.resolve();
  9825. cmPr = new PromiseExternal();
  9826. });
  9827. cmObs.observe(cm, {characterData: true})
  9828.  
  9829. let web_emulated_idle_callback_delay_val = null;
  9830.  
  9831. const getRenderIdleCallbackMs = () => {
  9832. if (typeof web_emulated_idle_callback_delay_val === 'number') return web_emulated_idle_callback_delay_val;
  9833. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  9834. const delay = (config.EXPERIMENT_FLAGS || 0).web_emulated_idle_callback_delay || (config.EXPERIMENTS_FORCED_FLAGS || 0).web_emulated_idle_callback_delay;
  9835. if (typeof delay === 'number') web_emulated_idle_callback_delay_val = delay;
  9836. return web_emulated_idle_callback_delay_val;
  9837. }
  9838. let isDelayRenderFn_firstCheck = true;
  9839. let isDelayRenderFn_key = null;
  9840. const isDelayRenderFn = (f) => {
  9841. if (!isDelayRenderFn_firstCheck) return (typeof ytglobal === 'undefined' ? false : ((ytglobal || 0).schedulerInstanceInstance_ || 0)[isDelayRenderFn_key] === f);
  9842. isDelayRenderFn_firstCheck = false;
  9843. if (typeof ytglobal === 'undefined') return false;
  9844. const globalInstance = ((ytglobal || 0).schedulerInstanceInstance_ || 0);
  9845. if (!globalInstance) return false;
  9846. for (const entry of Object.entries(Object.getOwnPropertyDescriptors(globalInstance))) {
  9847. if (entry[1].value === f && entry[1].enumerable && entry[1].writable && entry[1].configurable) {
  9848. isDelayRenderFn_key = entry[0]
  9849. console.log('[yt-js-engine-tamer] web_emulated_idle_callback fix applied');
  9850. return true;
  9851. }
  9852. }
  9853. return false;
  9854. }
  9855.  
  9856. schedulerInstanceInstance_.start993 = schedulerInstanceInstance_.start;
  9857.  
  9858. let requestingFn = null;
  9859. let requestingArgs = null;
  9860.  
  9861. const f = function () {
  9862. requestingFn = this.fn;
  9863. requestingArgs = [...arguments];
  9864. return 12373;
  9865. };
  9866.  
  9867. const fakeFns = [
  9868. f.bind({ fn: requestAnimationFrame }),
  9869. f.bind({ fn: setInterval }),
  9870. f.bind({ fn: setTimeout }),
  9871. f.bind({ fn: requestIdleCallback })
  9872. ];
  9873.  
  9874. let mzt = 0;
  9875.  
  9876. let _fnSelectorProp = null;
  9877. const mkFns = new Array(4);
  9878.  
  9879. /*
  9880. case 1:
  9881. var a = this.K;
  9882. this.g = this.I ? window.requestIdleCallback(a, {
  9883. timeout: 3E3
  9884. }) : window.setTimeout(a, ma);
  9885. break;
  9886. case 2:
  9887. this.g = window.setTimeout(this.M, this.N);
  9888. break;
  9889. case 3:
  9890. this.g = window.requestAnimationFrame(this.L);
  9891. break;
  9892. case 4:
  9893. this.g = window.setTimeout(this.J, 0)
  9894. }
  9895.  
  9896. */
  9897. const startFnHandler = {
  9898. get(target, prop, receiver) {
  9899. if (prop === '$$12377$$') return true;
  9900. if (prop === '$$12378$$') return target;
  9901.  
  9902. // console.log('get',prop)
  9903. return target[prop]
  9904. },
  9905. set(target, prop, value, receiver) {
  9906. // console.log('set', prop, value)
  9907.  
  9908.  
  9909. if (value >= 1 && value <= 4) _fnSelectorProp = prop;
  9910. if (value === 12373 && _fnSelectorProp) {
  9911.  
  9912. const schedulerTypeSelection = target[_fnSelectorProp];
  9913. const timerIdProp = prop;
  9914.  
  9915. // console.log(3991, requestingFn, requestingArgs[0], requestingArgs[1])
  9916. // if (schedulerTypeSelection && schedulerTypeSelection >= 1 && schedulerTypeSelection <= 4 && timerIdProp) {
  9917. // schedulerInstancePropOfTimerType = _fnSelectorProp || '';
  9918. // schedulerInstancePropOfTimerId = timerIdProp || '';
  9919. // }
  9920.  
  9921. if (schedulerTypeSelection === 3 && requestingFn === requestAnimationFrame) { // rAF(fn)
  9922. target[timerIdProp] = baseRAF.apply(window, requestingArgs);
  9923. } else if (schedulerTypeSelection === 2 && requestingFn === setTimeout) { // setTimeout(fn, delay)
  9924. // rare
  9925. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  9926. } else if (schedulerTypeSelection === 4 && requestingFn === setTimeout && !requestingArgs[1]) { // setTimeout(fn, 0)
  9927. // often
  9928. if ((FIX_schedulerInstanceInstance & 4)) {
  9929. const f = requestingArgs[0];
  9930. const tir = ++mzt;
  9931. nextBrowserTick_(() => {
  9932. if (target[timerIdProp] === -tir) f();
  9933. });
  9934. target[_fnSelectorProp] = 940;
  9935. target[timerIdProp] = -tir;
  9936. } else {
  9937. const f = requestingArgs[0];
  9938. const tir = ++mzt;
  9939. Promise.resolve().then(() => {
  9940. if (target[timerIdProp] === -tir) f();
  9941. });
  9942. target[_fnSelectorProp] = 930;
  9943. target[timerIdProp] = -tir;
  9944. }
  9945. } else if (schedulerTypeSelection === 1 && (requestingFn === requestIdleCallback || requestingFn === setTimeout)) { // setTimeout(requestIdleCallback)
  9946. // often
  9947. if (requestingFn === requestIdleCallback && (requestingArgs[0] || 0).name === "bound " && (requestingArgs[1] || 0).timeout === 3000 && isDelayRenderFn(requestingArgs[0])) {
  9948. cm.data = (cm.data & 7) + 1;
  9949. let renderFn = requestingArgs[0];
  9950. const resolveRendering_ = () => {
  9951. const renderFn_ = renderFn;
  9952. if (renderFn_) {
  9953. renderFn = null;
  9954. renderFn_();
  9955. }
  9956. };
  9957. resolveRendering = resolveRendering_;
  9958. // console.log(299,requestingArgs[0], requestingArgs[0].name)
  9959. target[timerIdProp] = requestIdleCallback(resolveRendering_, { timeout: 300 });
  9960.  
  9961. // cm.data = (cm.data & 7) + 1;
  9962. // target[timerIdProp] = Math.random();
  9963.  
  9964. } else if (requestingFn === setTimeout && (requestingArgs[0] || 0).name === "bound " && (requestingArgs[1] === getRenderIdleCallbackMs()) && isDelayRenderFn(requestingArgs[0])) {
  9965.  
  9966. cm.data = (cm.data & 7) + 1;
  9967.  
  9968. let renderFn = requestingArgs[0];
  9969. const resolveRendering_ = () => {
  9970. const renderFn_ = renderFn;
  9971. if (renderFn_) {
  9972. renderFn = null;
  9973. renderFn_();
  9974. }
  9975. };
  9976. resolveRendering = resolveRendering_;
  9977.  
  9978. target[timerIdProp] = mkFns[2].call(window, resolveRendering_, 300);
  9979.  
  9980.  
  9981. } else {
  9982. if (requestingFn === requestIdleCallback) {
  9983. target[timerIdProp] = requestIdleCallback.apply(window, requestingArgs);
  9984. } else {
  9985. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  9986. }
  9987. }
  9988. } else {
  9989. target[_fnSelectorProp] = 0;
  9990. target[timerIdProp] = 0;
  9991. }
  9992. } else {
  9993. target[prop] = value;
  9994. }
  9995. return true;
  9996. }
  9997. };
  9998.  
  9999. let startBusy = false;
  10000. schedulerInstanceInstance_.start = function () {
  10001. if (startBusy) return;
  10002. startBusy = true;
  10003. try {
  10004. mkFns[0] = window.requestAnimationFrame;
  10005. mkFns[1] = window.setInterval;
  10006. mkFns[2] = window.setTimeout;
  10007. mkFns[3] = window.requestIdleCallback;
  10008. const tThis = this['$$12378$$'] || this;
  10009. window.requestAnimationFrame = fakeFns[0]
  10010. window.setInterval = fakeFns[1]
  10011. window.setTimeout = fakeFns[2]
  10012. window.requestIdleCallback = fakeFns[3]
  10013. _fnSelectorProp = null;
  10014. tThis.start993.call(new Proxy(tThis, startFnHandler));
  10015. _fnSelectorProp = null;
  10016. window.requestAnimationFrame = mkFns[0];
  10017. window.setInterval = mkFns[1];
  10018. window.setTimeout = mkFns[2];
  10019. window.requestIdleCallback = mkFns[3];
  10020. } catch (e) {
  10021. console.warn(e);
  10022. }
  10023. startBusy = false;
  10024. }
  10025.  
  10026. schedulerInstanceInstance_.start.toString = schedulerInstanceInstance_.start993.toString.bind(schedulerInstanceInstance_.start993);
  10027.  
  10028. }
  10029. })();
  10030.  
  10031. FIX_yt_player && !isChatRoomURL && (async () => {
  10032.  
  10033. const fOption = 1 | 2 | 4;
  10034.  
  10035. const _yt_player = await _yt_player_observable.obtain();
  10036.  
  10037. if (!_yt_player || typeof _yt_player !== 'object') return;
  10038.  
  10039. const g = _yt_player;
  10040. let k;
  10041.  
  10042. if (fOption & 1) {
  10043.  
  10044. // rAf scheduling
  10045.  
  10046. const keyZqOu = getZqOu(_yt_player);
  10047. if (!keyZqOu) {
  10048. console.warn('[yt-js-engine-tamer] FIX_yt_player::keyZqOu error');
  10049. return;
  10050. }
  10051. k = keyZqOu
  10052.  
  10053. const gk = g[k];
  10054. if (typeof gk !== 'function') {
  10055. console.warn('[yt-js-engine-tamer] FIX_yt_player::g[keyZqOu] error');
  10056. return;
  10057. }
  10058. const gkp = gk.prototype;
  10059.  
  10060. const dummyObject = new gk;
  10061. const nilFunc = () => { };
  10062.  
  10063. const nilObj = {};
  10064.  
  10065. // console.log(1111111111)
  10066.  
  10067. let keyBoolD = '';
  10068. let keyWindow = '';
  10069. let keyFuncC = '';
  10070. let keyCidj = '';
  10071.  
  10072. for (const [t, y] of Object.entries(dummyObject)) {
  10073. if (y instanceof Window) keyWindow = t;
  10074. }
  10075.  
  10076. const dummyObjectProxyHandler = {
  10077. get(target, prop) {
  10078. let v = target[prop]
  10079. if (v instanceof Window && !keyWindow) {
  10080. keyWindow = t;
  10081. }
  10082. let y = typeof v === 'function' ? nilFunc : typeof v === 'object' ? nilObj : v;
  10083. if (prop === keyWindow) y = {
  10084. requestAnimationFrame(f) {
  10085. return 3;
  10086. },
  10087. cancelAnimationFrame() {
  10088.  
  10089. }
  10090. }
  10091. if (!keyFuncC && typeof v === 'function' && !(prop in target.constructor.prototype)) {
  10092. keyFuncC = prop;
  10093. }
  10094. // console.log('[get]', prop, typeof target[prop])
  10095.  
  10096.  
  10097. return y;
  10098. },
  10099. set(target, prop, value) {
  10100.  
  10101. if (typeof value === 'boolean' && !keyBoolD) {
  10102. keyBoolD = prop;
  10103. }
  10104. if (typeof value === 'number' && !keyCidj && value >= 2) {
  10105. keyCidj = prop;
  10106. }
  10107.  
  10108. // console.log('[set]', prop, value)
  10109. target[prop] = value;
  10110.  
  10111. return true;
  10112. }
  10113. };
  10114.  
  10115. dummyObject.start.call(new Proxy(dummyObject, dummyObjectProxyHandler));
  10116.  
  10117. // console.log('gkp.start',gkp.start);
  10118. // console.log('gkp.stop',gkp.stop);
  10119. gkp._activation = false;
  10120.  
  10121. gkp.start = function () {
  10122. // p59 || console.log(12100)
  10123. if (!this._activation) {
  10124. this._activation = true;
  10125. foregroundPromiseFn().then(() => {
  10126. this._activation = false;
  10127. if (this[keyCidj]) {
  10128. Promise.resolve().then(this[keyFuncC]);
  10129. }
  10130. });
  10131. }
  10132. this[keyCidj] = 1;
  10133. this[keyBoolD] = true;
  10134. };
  10135.  
  10136. gkp.stop = function () {
  10137. this[keyCidj] = null;
  10138. };
  10139.  
  10140.  
  10141. /*
  10142. g[k].start = function() {
  10143. this.stop();
  10144. this.D = true;
  10145. var a = requestAnimationFrame
  10146. , b = cancelAnimationFrame;
  10147. this.j = a.call(this.B, this.C)
  10148. }
  10149. ;
  10150. g[k].stop = function() {
  10151. if (this.isActive()) {
  10152. var a = requestAnimationFrame
  10153. , b = cancelAnimationFrame;
  10154. b.call(this.B, this.j)
  10155. }
  10156. this.j = null
  10157. }
  10158. */
  10159. }
  10160.  
  10161. if (fOption & 2) {
  10162. const keyzo = PERF_471489_ ? getzo(_yt_player) : null;
  10163.  
  10164. if (keyzo) {
  10165.  
  10166. k = keyzo;
  10167.  
  10168. const attrUpdateFn = g[k];
  10169. // console.log(5992, attrUpdateFn)
  10170. g['$$original$$' + k] = attrUpdateFn;
  10171. const zoTransform = async (a, c) => {
  10172.  
  10173. let transformType = '';
  10174. let transformValue = 0;
  10175. let transformUnit = '';
  10176. let transformTypeI = 0;
  10177.  
  10178. const aStyle = a.style;
  10179.  
  10180. let cType = 0;
  10181.  
  10182. const cl = c.length;
  10183.  
  10184. if (cl >= 8) {
  10185. // scale(1)
  10186. if (c.startsWith('scale') && c.charCodeAt(6) === 40 && c.charCodeAt(cl - 1) === 41) {
  10187. cType = 1;
  10188. let t = c.charCodeAt(5);
  10189. if (t === 88 || t === 120) cType = 1 | 4;
  10190. if (t === 89 || t === 121) cType = 1 | 8;
  10191. } else if (c.startsWith('translate') && c.charCodeAt(10) === 40 && c.charCodeAt(cl - 1) === 41) {
  10192. cType = 2;
  10193. let t = c.charCodeAt(9);
  10194. if (t === 88 || t === 120) cType = 2 | 4;
  10195. if (t === 89 || t === 121) cType = 2 | 8;
  10196. }
  10197. let w = 0;
  10198. if (w = (cType === 5) ? 1 : (cType === 9) ? 2 : 0) {
  10199. let p = c.substring(7, cl - 1);
  10200. let q = p.length >= 1 ? parseFloat(p) : NaN;
  10201. if (typeof q === 'number' && !isNaNx(q)) {
  10202. transformType = w === 1 ? 'scaleX' : 'scaleY';
  10203. transformValue = q;
  10204. transformUnit = '';
  10205. transformTypeI = 1;
  10206. } else {
  10207. cType = 256;
  10208. }
  10209. } else if (w = (cType === 6) ? 1 : (cType === 10) ? 2 : 0) {
  10210. if (c.endsWith('px)')) {
  10211. let p = c.substring(11, cl - 3);
  10212. let q = p.length >= 1 ? parseFloat(p) : NaN;
  10213. if (typeof q === 'number' && !isNaNx(q)) {
  10214. transformType = w === 1 ? 'translateX' : 'translateY';
  10215. transformValue = q;
  10216. transformUnit = 'px';
  10217. transformTypeI = 2;
  10218. } else if (p === 'NaN') {
  10219. return;
  10220. }
  10221. } else {
  10222. cType = 256;
  10223. }
  10224. } else if (cType > 0) {
  10225. cType = 256;
  10226. }
  10227. }
  10228.  
  10229.  
  10230. if (cType === 256) {
  10231. console.log('[yt-js-engine-tamer] zoTransform undefined', c);
  10232. }
  10233.  
  10234. if (transformTypeI === 1) {
  10235. const q = Math.round(transformValue * steppingScaleN) / steppingScaleN;
  10236. const vz = toFixed2(q, 3);
  10237. c = `${transformType}(${vz})`;
  10238. const cv = aStyle.transform;
  10239. if (c === cv) return;
  10240. aStyle.transform = c;
  10241. } else if (transformTypeI === 2) {
  10242. const q = transformValue;
  10243. const vz = toFixed2(q, 1);
  10244. c = `${transformType}(${vz}${transformUnit})`;
  10245. const cv = aStyle.transform;
  10246. if (c === cv) return;
  10247. aStyle.transform = c;
  10248. } else { // eg empty
  10249. const cv = aStyle.transform;
  10250. if (!c && !cv) return;
  10251. else if (c === cv) return;
  10252. aStyle.transform = c;
  10253. }
  10254.  
  10255. };
  10256.  
  10257. const elmTransformTemp = new WeakMap();
  10258. const elmPropTemps = {
  10259. 'display': new WeakMap(),
  10260. 'width': new WeakMap(),
  10261. 'height': new WeakMap(),
  10262. 'outlineWidth': new WeakMap(),
  10263. 'position': new WeakMap(),
  10264. 'padding': new WeakMap(),
  10265. "cssText": new WeakMap(),
  10266. "right": new WeakMap(),
  10267. "left": new WeakMap(),
  10268. "top": new WeakMap(),
  10269. "bottom": new WeakMap(),
  10270. "transitionDelay": new WeakMap(),
  10271. "marginLeft": new WeakMap(),
  10272. "marginTop": new WeakMap(),
  10273. "marginRight": new WeakMap(),
  10274. "marginBottom": new WeakMap(),
  10275. }
  10276.  
  10277. const ns5 = Symbol();
  10278. const nextModify = (a, c, m, f, immediate) => {
  10279. const a_ = a;
  10280. const m_ = m;
  10281. const noKey = !m_.has(a_);
  10282. if (immediate || noKey) {
  10283. m_.set(a_, ns5);
  10284. f(a_, c);
  10285. noKey && nextBrowserTick_(() => {
  10286. const d = m_.get(a_);
  10287. if (d === undefined) return;
  10288. m_.delete(a_);
  10289. if (d !== ns5) f(a_, d);
  10290. });
  10291. } else {
  10292. m_.set(a_, c);
  10293. }
  10294. };
  10295.  
  10296. const set66 = new Set();
  10297. const log77 = new Map();
  10298. // const set77 = new Set(['top', 'left', 'bottom', 'right']); // caption positioning - immediate change
  10299.  
  10300. const modifiedFn = function (a, b, c, immediateChange = false) { // arrow function does not have function.prototype
  10301.  
  10302. // console.log(140000, a, b, c);
  10303. if (typeof c === 'number' && typeof b === 'string' && a instanceof HTMLElement_) {
  10304. const num = c;
  10305. c = `${num}`;
  10306. if (c.length > 5) c = (num < 10 && num > -10) ? toFixed2(num, 3) : toFixed2(num, 1);
  10307. }
  10308.  
  10309. if (typeof b === 'string' && typeof c === 'string' && a instanceof HTMLElement_) {
  10310.  
  10311. let elmPropTemp = null;
  10312.  
  10313. if (b === "transform") {
  10314. // div.ytp-hover-progress.ytp-hover-progress-light
  10315. // div.ytp-play-progress.ytp-swatch-background-color
  10316.  
  10317. nextModify(a, c, elmTransformTemp, zoTransform, immediateChange);
  10318. return;
  10319.  
  10320. } else if (elmPropTemp = elmPropTemps[b]) {
  10321.  
  10322. // if (c.length > 5 && c.includes('.')) {
  10323. // console.log(123213, c)
  10324. // }
  10325.  
  10326. const b_ = b;
  10327. nextModify(a, c, elmPropTemp, (a, c) => {
  10328. const style = a.style;
  10329. const cv = style[b_];
  10330. if (!cv && !c) return;
  10331. if (cv === c) return;
  10332. style[b_] = c;
  10333. }, immediateChange);
  10334. return;
  10335.  
  10336. } else if (b === "outline-width") {
  10337.  
  10338. const b_ = 'outlineWidth';
  10339. elmPropTemp = elmPropTemps[b_];
  10340. nextModify(a, c, elmPropTemp, (a, c) => {
  10341. const style = a.style;
  10342. const cv = style[b_];
  10343. if (!cv && !c) return;
  10344. if (cv === c) return;
  10345. style[b_] = c;
  10346. }, immediateChange);
  10347. return;
  10348.  
  10349. } else if (b === 'maxWidth' || b === 'maxHeight') {
  10350. // I think these can be directly assigned.
  10351.  
  10352. const b_ = b;
  10353. const style = a.style;
  10354. const cv = style[b_];
  10355. if (!cv && !c) return;
  10356. if (cv === c) return;
  10357. style[b_] = c;
  10358. return;
  10359.  
  10360. } else {
  10361. // if(immediate && elmPropTemps[b]){
  10362. // console.log(5191, b)
  10363. // }
  10364. // caption-window
  10365. // margin-left max-height max-width font-family fill color font-size background white-space margin
  10366. // text-align background-color
  10367. // console.log(27304, a, b, c)
  10368. if (!set66.has(b)) {
  10369. set66.add(b);
  10370. nextBrowserTick_(() => {
  10371. if (!a.classList.contains('caption-window') && !a.classList.contains('ytp-caption-segment')) {
  10372. console.log(27304, a, b, c)
  10373. }
  10374. })
  10375. }
  10376. }
  10377.  
  10378. attrUpdateFn.call(this, a, b, c);
  10379. return;
  10380. } else if (typeof (b || 0) === 'object') {
  10381.  
  10382. // this is to fix caption positioning
  10383. // const immediate = (a.id || 0).length > 14 && (('top' in b) || ('left' in b) || ('right' in b) || ('bottom' in b));
  10384. const immediate = (a.id || 0).length > 14;
  10385. for (const [k, v] of Object.entries(b)) {
  10386. modifiedFn.call(this, a, k, v, immediate);
  10387. }
  10388.  
  10389. } else {
  10390.  
  10391. // a = circle, b = stroke-dasharray, c= "1.8422857142857143 32"
  10392. // ytp-ad-timed-pie-countdown-inner
  10393.  
  10394. if (typeof b === 'string') {
  10395.  
  10396. let m = log77.get(b);
  10397. if (!m) {
  10398. m = [];
  10399. console.log('attrUpdateFn.debug.27304', m);
  10400. log77.set(b, m);
  10401. }
  10402. m.push([a, b, c]);
  10403.  
  10404. } else {
  10405. console.log('attrUpdateFn.debug.27306', a, b, c);
  10406. }
  10407.  
  10408. attrUpdateFn.call(this, a, b, c);
  10409. return;
  10410. }
  10411.  
  10412. // console.log(130000, a, b, c);
  10413.  
  10414. };
  10415. g[k] = modifiedFn;
  10416.  
  10417.  
  10418. /*
  10419.  
  10420. g.zo = function(a, b, c) {
  10421. if ("string" === typeof b)
  10422. (b = yo(a, b)) && (a.style[b] = c);
  10423. else
  10424. for (var d in b) {
  10425. c = a;
  10426. var e = b[d]
  10427. , f = yo(c, d);
  10428. f && (c.style[f] = e)
  10429. }
  10430. }
  10431.  
  10432.  
  10433. */
  10434.  
  10435.  
  10436. }
  10437. }
  10438.  
  10439. if (fOption & 4) {
  10440. const keyuG = PERF_471489_ ? getuG(_yt_player) : null;
  10441.  
  10442. if (keyuG) {
  10443.  
  10444. k = keyuG;
  10445.  
  10446. const gk = g[k];
  10447. const gkp = gk.prototype;
  10448.  
  10449.  
  10450. /** @type { Map<string, WeakMap<any, any>> } */
  10451. const ntLogs = new Map();
  10452.  
  10453. if (typeof gkp.updateValue === 'function' && gkp.updateValue.length === 2 && !gkp.updateValue31) {
  10454.  
  10455. gkp.updateValue31 = gkp.updateValue;
  10456. gkp.updateValue = function (a, b) {
  10457. if (typeof a !== 'string') return this.updateValue31(a, b);
  10458.  
  10459. const element = this.element;
  10460. if (!(element instanceof HTMLElement_)) return this.updateValue31(a, b);
  10461.  
  10462. let ntLog = ntLogs.get(a);
  10463. if (!ntLog) ntLogs.set(a, (ntLog = new WeakMap()));
  10464.  
  10465. let cache = ntLog.get(element);
  10466. if (cache && cache.value === b) {
  10467. return;
  10468. }
  10469. if (!cache) {
  10470. this.__oldValueByUpdateValue__ = null;
  10471. ntLog.set(element, cache = { value: b });
  10472. } else {
  10473. this.__oldValueByUpdateValue__ = cache.value;
  10474. cache.value = b;
  10475. }
  10476.  
  10477. return this.updateValue31(a, b);
  10478. }
  10479.  
  10480. /*
  10481. g.k.update = function(a) {
  10482. for (var b = g.u(Object.keys(a)), c = b.next(); !c.done; c = b.next())
  10483. c = c.value,
  10484. this.updateValue(c, a[c])
  10485. }
  10486. ;
  10487. g.k.updateValue = function(a, b) {
  10488. (a = this.Td["{{" + a + "}}"]) && wG(this, a[0], a[1], b)
  10489. }
  10490. */
  10491.  
  10492. }
  10493.  
  10494.  
  10495. }
  10496. }
  10497.  
  10498.  
  10499.  
  10500. })();
  10501.  
  10502.  
  10503. FIX_yt_player && !isChatRoomURL && FIX_SHORTCUTKEYS > 0 && (async () => {
  10504. // keyboard shortcut keys controller
  10505.  
  10506. const _yt_player = await _yt_player_observable.obtain();
  10507.  
  10508. if (!_yt_player || typeof _yt_player !== 'object') return;
  10509.  
  10510. keyboardController(_yt_player);
  10511.  
  10512. })();
  10513.  
  10514. FIX_yt_player && !isChatRoomURL && (async () => {
  10515. // timer scheduling
  10516.  
  10517. const _yt_player = await _yt_player_observable.obtain();
  10518.  
  10519. if (!_yt_player || typeof _yt_player !== 'object') return;
  10520.  
  10521. let keyZqQu = getZqQu(_yt_player);
  10522.  
  10523. if (!keyZqQu) return;
  10524.  
  10525. const g = _yt_player
  10526. let k = keyZqQu
  10527.  
  10528. const gk = g[k];
  10529. if (typeof gk !== 'function') return;
  10530. const gkp = gk.prototype;
  10531.  
  10532. const extractKeysZqQu = () => {
  10533.  
  10534.  
  10535. let _keyeC = '';
  10536. try {
  10537. gkp.stop.call(new Proxy({
  10538. isActive: () => { }
  10539. }, {
  10540. set(target, prop, value) {
  10541. if (value === 0) _keyeC = prop;
  10542. return true;
  10543. }
  10544. }));
  10545. } catch (e) { }
  10546. if (!_keyeC) return;
  10547. const keyeC = _keyeC;
  10548.  
  10549. let keyC = ''; // this.C = this.ST.bind(this)
  10550. let keyhj = ''; // 1000ms
  10551. try {
  10552. gkp.start.call(new Proxy({
  10553. stop: () => { },
  10554. [keyeC]: 0,
  10555. }, {
  10556. get(target, prop) {
  10557. if (prop in target) return target[prop];
  10558. if (!keyC) {
  10559. keyC = prop;
  10560. return null; // throw error
  10561. }
  10562. else if (!keyhj) {
  10563. keyhj = prop;
  10564. }
  10565.  
  10566. }
  10567. }));
  10568. } catch (e) {
  10569. if (!keyC || !keyhj) {
  10570. console.log(e)
  10571. }
  10572. }
  10573.  
  10574. if (!keyC || !keyhj) return;
  10575. let keyST = '';
  10576. let keyj = '';
  10577. let keyB = '';
  10578. let keyxa = '';
  10579.  
  10580. const possibleKs = new Set();
  10581.  
  10582. for (const [k, v] of Object.entries(gkp)) {
  10583. if (k === 'stop' || k === 'start' || k === 'isActive' || k === 'constructor' || k === keyeC || k === keyC || k === keyhj) {
  10584. continue;
  10585. }
  10586. if (typeof v === 'function') {
  10587. const m = /this\.(\w+)\.call\(this\.(\w+)\)/.exec(v + '');
  10588. if (m) {
  10589. keyST = k;
  10590. keyj = m[1];
  10591. keyB = m[2];
  10592. } else {
  10593. possibleKs.add(k);
  10594. }
  10595. }
  10596. }
  10597.  
  10598. if (!keyST || !keyj || !keyB) return;
  10599.  
  10600. for (const k of possibleKs) {
  10601. if (k === keyST || k === keyj || k === keyB) {
  10602. continue;
  10603. }
  10604. const v = gkp[k];
  10605. if (typeof v === 'function' && (v + '').includes(`this.stop();delete this.${keyj};delete this.${keyB}`)) {
  10606. keyxa = k;
  10607. }
  10608. }
  10609.  
  10610. return [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa];
  10611.  
  10612. }
  10613.  
  10614. const keys = extractKeysZqQu();
  10615. if (!keys || !keys.length) return;
  10616. const [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa] = keys; // [timerId, binded executorFn, 1000ms, executorFn, dataJ, objectB, disposeFn]
  10617.  
  10618. if (!keyeC || !keyC || !keyhj || !keyST || !keyj || !keyB || !keyxa) return;
  10619.  
  10620. let disposeKeys = null;
  10621.  
  10622. gkp[keyxa] = function () {
  10623. // dispose
  10624. if (!disposeKeys) {
  10625. disposeKeys = Object.getOwnPropertyNames(this).filter(key => {
  10626. if (key != keyeC && key != keyC && key != keyhj && key != keyST && key != keyj && key != keyB && key != keyxa) {
  10627. const t = typeof this[key];
  10628. return t === 'undefined' || t === 'object'
  10629. }
  10630. return false;
  10631. });
  10632. }
  10633. for (const key of disposeKeys) {
  10634. const v = this[key];
  10635. if ((v || 0).length >= 1) v.length = 0; // function (){if(this.fn)for(;this.fn.length;)this.fn.shift()()}
  10636. }
  10637. if (this[keyeC] > 0) this.stop();
  10638. this[keyj] = null;
  10639. this[keyB] = null;
  10640. };
  10641.  
  10642. gkp.start = function (a) {
  10643. if (this[keyeC] > 0) this.stop();
  10644. const delay = void 0 !== a ? a : this[keyhj];
  10645. this[keyeC] = window.setTimeout(this[keyC], delay);
  10646. };
  10647. gkp.stop = function () {
  10648. if (this[keyeC] > 0) {
  10649. window.clearTimeout(this[keyeC]);
  10650. this[keyeC] = 0;
  10651. }
  10652. };
  10653.  
  10654. gkp.isActive = function () {
  10655. return this[keyeC] > 0;
  10656. };
  10657.  
  10658. gkp[keyST] = function () {
  10659. this.stop(); // this[keyeC] = 0;
  10660. const fn = this[keyj];
  10661. const obj = this[keyB];
  10662. let skip = false;
  10663. if (!fn) skip = true;
  10664. else if (IGNORE_bufferhealth_CHECK && obj) {
  10665. let m;
  10666. if ((m = obj[keyC]) instanceof Map || (m = obj[keyj]) instanceof Map) {
  10667. if (m.has("bufferhealth")) skip = true;
  10668. }
  10669. }
  10670. if (!skip) {
  10671. fn.call(obj);
  10672. }
  10673. };
  10674.  
  10675.  
  10676.  
  10677.  
  10678. /*
  10679.  
  10680. g.k.eC = 0;
  10681. g.k.xa = function() {
  10682. g.Qu.Vf.xa.call(this);
  10683. this.stop();
  10684. delete this.j;
  10685. delete this.B
  10686. }
  10687. ;
  10688. g.k.start = function(a) {
  10689. this.stop();
  10690. this.eC = g.gg(this.C, void 0 !== a ? a : this.hj)
  10691. }
  10692. ;
  10693. g.k.stop = function() {
  10694. this.isActive() && g.Sa.clearTimeout(this.eC);
  10695. this.eC = 0
  10696. }
  10697. ;
  10698. g.k.isActive = function() {
  10699. return 0 != this.eC
  10700. }
  10701. ;
  10702. g.k.ST = function() {
  10703. this.eC = 0;
  10704. this.j && this.j.call(this.B)
  10705. }
  10706. ;
  10707. */
  10708.  
  10709.  
  10710.  
  10711.  
  10712. })();
  10713.  
  10714. FIX_Animation_n_timeline && (async () => {
  10715.  
  10716. const [timeline, Animation] = await Promise.all([timelineObservable.obtain(), animationObservable.obtain()]);
  10717.  
  10718. if (!timeline || !Animation) return;
  10719.  
  10720. const animationsFix = (timeline) => {
  10721. const animations = (timeline || 0)._animations || 0;
  10722. const c = animations[0];
  10723. if (c) {
  10724. if (c && !c.id && c._isGroup === false && c._holdTime === 0 && c._paused === false && !c._callback && Number.isNaN(c._sequenceNumber) && c.effect.target instanceof HTMLCanvasElement) {
  10725. animations.shift(); // keep animating but no looping
  10726. // c.effect.remove();
  10727. }
  10728. }
  10729. }
  10730.  
  10731. const aniProto = Animation.prototype;
  10732. // aniProto.sequenceNumber = 0; // native YouTube engine bug - sequenceNumber is not set
  10733.  
  10734. const getXroto = (x) => {
  10735. try {
  10736. return x.__proto__;
  10737. } catch (e) { }
  10738. return null;
  10739. }
  10740. const timProto = getXroto(timeline);
  10741. if (!timProto) return;
  10742. if (
  10743. (
  10744. typeof timProto.getAnimations === 'function' && typeof timProto.play === 'function' &&
  10745. typeof timProto._discardAnimations === 'function' && typeof timProto._play === 'function' &&
  10746. typeof timProto._updateAnimationsPromises === 'function' && !timProto.nofCQ &&
  10747. typeof aniProto._updatePromises === 'function' && !aniProto.nofYH
  10748. )
  10749.  
  10750. ) {
  10751.  
  10752. timProto.nofCQ = 1;
  10753. aniProto.nofYH = 1;
  10754.  
  10755. const originalAnimationsWithPromises = ((_updateAnimationsPromises) => {
  10756.  
  10757.  
  10758. /*
  10759. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  10760. return c._updatePromises();
  10761. });
  10762. */
  10763.  
  10764. const p = Array.prototype.filter;
  10765.  
  10766. let res = null;
  10767. Array.prototype.filter = function () {
  10768.  
  10769. res = this;
  10770. return this;
  10771.  
  10772. };
  10773.  
  10774. _updateAnimationsPromises.call({});
  10775.  
  10776. Array.prototype.filter = p;
  10777.  
  10778. if (res && typeof res.length === 'number') {
  10779. /** @type {any[]} */
  10780. const _res = res;
  10781. return _res;
  10782. }
  10783.  
  10784.  
  10785. return null;
  10786.  
  10787.  
  10788.  
  10789.  
  10790. })(timProto._updateAnimationsPromises);
  10791.  
  10792. if (!originalAnimationsWithPromises || typeof originalAnimationsWithPromises.length !== 'number') return;
  10793.  
  10794. // console.log('originalAnimationsWithPromises', originalAnimationsWithPromises)
  10795.  
  10796. aniProto._updatePromises31 = aniProto._updatePromises;
  10797.  
  10798. /*
  10799. aniProto._updatePromises = function(){
  10800. console.log('eff',this._oldPlayState, this.playState)
  10801. return this._updatePromises31.apply(this, arguments)
  10802. }
  10803. */
  10804.  
  10805. aniProto._updatePromises = function () {
  10806. var oldPlayState = this._oldPlayState;
  10807. var newPlayState = this.playState;
  10808. // console.log('ett', oldPlayState, newPlayState)
  10809. if (newPlayState !== oldPlayState) {
  10810. this._oldPlayState = newPlayState;
  10811. if (this._readyPromise) {
  10812. if ("idle" == newPlayState) {
  10813. this._rejectReadyPromise();
  10814. this._readyPromise = void 0;
  10815. } else if ("pending" == oldPlayState) {
  10816. this._resolveReadyPromise();
  10817. } else if ("pending" == newPlayState) {
  10818. this._readyPromise = void 0;
  10819. }
  10820. }
  10821. if (this._finishedPromise) {
  10822. if ("idle" == newPlayState) {
  10823. this._rejectFinishedPromise();
  10824. this._finishedPromise = void 0;
  10825. } else if ("finished" == newPlayState) {
  10826. this._resolveFinishedPromise();
  10827. } else if ("finished" == oldPlayState) {
  10828. this._finishedPromise = void 0;
  10829. }
  10830. }
  10831. }
  10832. return this._readyPromise || this._finishedPromise;
  10833. };
  10834.  
  10835.  
  10836. let restartWebAnimationsNextTickFlag = false;
  10837.  
  10838. const looperMethodT = () => {
  10839.  
  10840. const runnerFn = (hRes) => {
  10841. var b = timeline;
  10842. b.currentTime = hRes;
  10843. b._discardAnimations();
  10844. FIX_Animation_n_timeline_cinematic && animationsFix(b);
  10845. if (0 == b._animations.length) {
  10846. restartWebAnimationsNextTickFlag = false;
  10847. } else {
  10848. getRafPromise().then(runnerFn);
  10849. }
  10850. }
  10851.  
  10852. const restartWebAnimationsNextTick = () => {
  10853. if (!restartWebAnimationsNextTickFlag) {
  10854. restartWebAnimationsNextTickFlag = true;
  10855. getRafPromise().then(runnerFn);
  10856. }
  10857. }
  10858.  
  10859. return { restartWebAnimationsNextTick }
  10860. };
  10861.  
  10862.  
  10863. const looperMethodN = () => {
  10864.  
  10865. const acs = document.createElement('a-f');
  10866. acs.id = 'a-f';
  10867.  
  10868. if (!document.getElementById('afscript')) {
  10869. const style = document.createElement('style');
  10870. style.id = 'afscript';
  10871. style.textContent = `
  10872. @keyFrames aF1 {
  10873. 0% {
  10874. order: 0;
  10875. }
  10876. 100% {
  10877. order: 1;
  10878. }
  10879. }
  10880. #a-f[id] {
  10881. visibility: collapse !important;
  10882. position: fixed !important;
  10883. display: block !important;
  10884. top: -100px !important;
  10885. left: -100px !important;
  10886. margin:0 !important;
  10887. padding:0 !important;
  10888. outline:0 !important;
  10889. border:0 !important;
  10890. z-index:-1 !important;
  10891. width: 0px !important;
  10892. height: 0px !important;
  10893. contain: strict !important;
  10894. pointer-events: none !important;
  10895. animation: 1ms steps(2, jump-none) 0ms infinite alternate forwards running aF1 !important;
  10896. }
  10897. `;
  10898. (document.head || document.documentElement).appendChild(style);
  10899. }
  10900.  
  10901. document.documentElement.insertBefore(acs, document.documentElement.firstChild);
  10902.  
  10903. const _onanimationiteration = function (evt) {
  10904. const hRes = evt.timeStamp;
  10905. var b = timeline;
  10906. b.currentTime = hRes;
  10907. b._discardAnimations();
  10908. FIX_Animation_n_timeline_cinematic && animationsFix(b);
  10909. if (0 == b._animations.length) {
  10910. restartWebAnimationsNextTickFlag = false;
  10911. acs.onanimationiteration = null;
  10912. } else {
  10913. acs.onanimationiteration = _onanimationiteration;
  10914. }
  10915.  
  10916. }
  10917.  
  10918.  
  10919.  
  10920. const restartWebAnimationsNextTick = () => {
  10921. if (!restartWebAnimationsNextTickFlag) {
  10922. restartWebAnimationsNextTickFlag = true;
  10923. acs.onanimationiteration = _onanimationiteration;
  10924.  
  10925. }
  10926. }
  10927.  
  10928. return { restartWebAnimationsNextTick }
  10929. };
  10930.  
  10931.  
  10932.  
  10933. const { restartWebAnimationsNextTick } = ('onanimationiteration' in document.documentElement) ? looperMethodN() : looperMethodT();
  10934.  
  10935.  
  10936. // console.log(571, timProto);
  10937. timProto._play = function (c) {
  10938. c = new Animation(c, this);
  10939. this._animations.push(c);
  10940. restartWebAnimationsNextTick();
  10941. c._updatePromises();
  10942. c._animation.play();
  10943. c._updatePromises();
  10944. return c
  10945. }
  10946.  
  10947. const animationsWithPromisesMap = new Set(originalAnimationsWithPromises);
  10948. originalAnimationsWithPromises.length = 0;
  10949. originalAnimationsWithPromises.push = null;
  10950. originalAnimationsWithPromises.splice = null;
  10951. originalAnimationsWithPromises.slice = null;
  10952. originalAnimationsWithPromises.indexOf = null;
  10953. originalAnimationsWithPromises.unshift = null;
  10954. originalAnimationsWithPromises.shift = null;
  10955. originalAnimationsWithPromises.pop = null;
  10956. originalAnimationsWithPromises.filter = null;
  10957. originalAnimationsWithPromises.forEach = null;
  10958. originalAnimationsWithPromises.map = null;
  10959.  
  10960.  
  10961. const _updateAnimationsPromises = () => {
  10962. animationsWithPromisesMap.forEach(c => {
  10963. if (!c._updatePromises()) animationsWithPromisesMap.delete(c);
  10964. });
  10965. /*
  10966. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  10967. return c._updatePromises();
  10968. });
  10969. */
  10970. }
  10971.  
  10972. timProto._updateAnimationsPromises31 = timProto._updateAnimationsPromises;
  10973.  
  10974. timProto._updateAnimationsPromises = _updateAnimationsPromises;
  10975.  
  10976. delete timProto._updateAnimationsPromises;
  10977. Object.defineProperty(timProto, '_updateAnimationsPromises', {
  10978. get() {
  10979. if (animationsWithPromisesMap.size === 0) return nilFn;
  10980. return _updateAnimationsPromises;
  10981. },
  10982. set(nv) {
  10983. delete this._updateAnimationsPromises;
  10984. this._updateAnimationsPromises = nv;
  10985. },
  10986. enumerable: true,
  10987. configurable: true,
  10988. });
  10989.  
  10990.  
  10991. let pdFinished = Object.getOwnPropertyDescriptor(aniProto, 'finished');
  10992. aniProto.__finished_native_get__ = pdFinished.get;
  10993. if (typeof pdFinished.get === 'function' && !pdFinished.set && pdFinished.configurable === true && pdFinished.enumerable === true) {
  10994.  
  10995.  
  10996. Object.defineProperty(aniProto, 'finished', {
  10997. get() {
  10998. this._finishedPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  10999. this._finishedPromise = new Promise((resolve, reject) => {
  11000. this._resolveFinishedPromise = function () {
  11001. resolve(this)
  11002. };
  11003. this._rejectFinishedPromise = function () {
  11004. reject({
  11005. type: DOMException.ABORT_ERR,
  11006. name: "AbortError"
  11007. })
  11008. };
  11009. }),
  11010. "finished" == this.playState && this._resolveFinishedPromise());
  11011. return this._finishedPromise
  11012. },
  11013. set: undefined,
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017.  
  11018. }
  11019.  
  11020.  
  11021.  
  11022. let pdReady = Object.getOwnPropertyDescriptor(aniProto, 'ready');
  11023. aniProto.__ready_native_get__ = pdReady.get;
  11024. if (typeof pdReady.get === 'function' && !pdReady.set && pdReady.configurable === true && pdReady.enumerable === true) {
  11025.  
  11026. Object.defineProperty(aniProto, 'ready', {
  11027. get() {
  11028. this._readyPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  11029. this._readyPromise = new Promise((resolve, reject) => {
  11030. this._resolveReadyPromise = function () {
  11031. resolve(this)
  11032. };
  11033. this._rejectReadyPromise = function () {
  11034. reject({
  11035. type: DOMException.ABORT_ERR,
  11036. name: "AbortError"
  11037. })
  11038. };
  11039. }),
  11040. "pending" !== this.playState && this._resolveReadyPromise());
  11041. return this._readyPromise
  11042. },
  11043. set: undefined,
  11044. enumerable: true,
  11045. configurable: true
  11046. });
  11047.  
  11048. }
  11049.  
  11050.  
  11051. if (IGNORE_bindAnimationForCustomEffect && typeof aniProto._rebuildUnderlyingAnimation === 'function' && !aniProto._rebuildUnderlyingAnimation21 && aniProto._rebuildUnderlyingAnimation.length === 0) {
  11052.  
  11053. aniProto._rebuildUnderlyingAnimation21 = aniProto._rebuildUnderlyingAnimation;
  11054. const _rebuildUnderlyingAnimation = function () {
  11055. // if (isNaN(this._sequenceNumber)) return; // do not rebuild underlying animation if native animation is used.
  11056. this.effect && this.effect._onsample && (this.effect._onsample = null);
  11057. return this._rebuildUnderlyingAnimation21();
  11058. }
  11059. aniProto._rebuildUnderlyingAnimation = _rebuildUnderlyingAnimation;
  11060. // delete aniProto._rebuildUnderlyingAnimation;
  11061. // Object.defineProperty(aniProto, '_rebuildUnderlyingAnimation', {
  11062. // get() {
  11063. // if (isNaN(this._sequenceNumber)) return nilFn;
  11064. // return this._rebuildUnderlyingAnimation21;
  11065. // },
  11066. // set(nv) {
  11067. // delete this._rebuildUnderlyingAnimation;
  11068. // this._rebuildUnderlyingAnimation = nv;
  11069. // },
  11070. // enumerable: true,
  11071. // configurable: true
  11072. // });
  11073. }
  11074.  
  11075.  
  11076. /*
  11077.  
  11078.  
  11079. function f(c) {
  11080. var b = v.timeline;
  11081. b.currentTime = c;
  11082. b._discardAnimations();
  11083. 0 == b._animations.length ? d = !1 : requestAnimationFrame(f)
  11084. }
  11085. var h = window.requestAnimationFrame;
  11086. window.requestAnimationFrame = function(c) {
  11087. return h(function(b) {
  11088. v.timeline._updateAnimationsPromises();
  11089. c(b);
  11090. v.timeline._updateAnimationsPromises()
  11091. })
  11092. }
  11093. ;
  11094. v.AnimationTimeline = function() {
  11095. this._animations = [];
  11096. this.currentTime = void 0
  11097. }
  11098. ;
  11099. v.AnimationTimeline.prototype = {
  11100. getAnimations: function() {
  11101. this._discardAnimations();
  11102. return this._animations.slice()
  11103. },
  11104. _updateAnimationsPromises: function() {
  11105. v.animationsWithPromises = v.animationsWithPromises.filter(function(c) {
  11106. return c._updatePromises()
  11107. })
  11108. },
  11109. _discardAnimations: function() {
  11110. this._updateAnimationsPromises();
  11111. this._animations = this._animations.filter(function(c) {
  11112. return "finished" != c.playState && "idle" != c.playState
  11113. })
  11114. },
  11115. _play: function(c) {
  11116. c = new v.Animation(c,this);
  11117. this._animations.push(c);
  11118. v.restartWebAnimationsNextTick();
  11119. c._updatePromises();
  11120. c._animation.play();
  11121. c._updatePromises();
  11122. return c
  11123. },
  11124. play: function(c) {
  11125. c && c.remove();
  11126. return this._play(c)
  11127. }
  11128. };
  11129. var d = !1;
  11130. v.restartWebAnimationsNextTick = function() {
  11131. d || (d = !0,
  11132. requestAnimationFrame(f))
  11133. }
  11134. ;
  11135. var a = new v.AnimationTimeline;
  11136. v.timeline = a;
  11137. try {
  11138. Object.defineProperty(window.document, "timeline", {
  11139. configurable: !0,
  11140. get: function() {
  11141. return a
  11142. }
  11143. })
  11144. } catch (c) {}
  11145. try {
  11146. window.document.timeline = a
  11147. } catch (c) {}
  11148.  
  11149. */
  11150.  
  11151.  
  11152.  
  11153. /*
  11154.  
  11155. var g = window.getComputedStyle;
  11156. Object.defineProperty(window, "getComputedStyle", {
  11157. configurable: !0,
  11158. enumerable: !0,
  11159. value: function() {
  11160. v.timeline._updateAnimationsPromises();
  11161. var e = g.apply(this, arguments);
  11162. h() && (e = g.apply(this, arguments));
  11163. v.timeline._updateAnimationsPromises();
  11164. return e
  11165. }
  11166. });
  11167.  
  11168. */
  11169.  
  11170.  
  11171.  
  11172.  
  11173. }
  11174.  
  11175.  
  11176.  
  11177.  
  11178. })();
  11179.  
  11180. !isUrlInEmbed && Promise.resolve().then(() => {
  11181.  
  11182. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  11183.  
  11184.  
  11185.  
  11186. class LimitedSizeSet extends Set {
  11187. constructor(n) {
  11188. super();
  11189. this.limit = n;
  11190. }
  11191.  
  11192. add(key) {
  11193. if (!super.has(key)) {
  11194. super.add(key);
  11195. let n = super.size - this.limit;
  11196. if (n > 0) {
  11197. const iterator = super.values();
  11198. do {
  11199. const firstKey = iterator.next().value; // Get the first (oldest) key
  11200. super.delete(firstKey); // Delete the oldest key
  11201. } while (--n > 0)
  11202. }
  11203. }
  11204. }
  11205.  
  11206. removeAdd(key) {
  11207. super.delete(key);
  11208. this.add(key);
  11209. }
  11210.  
  11211. }
  11212.  
  11213. // const wk3 = new WeakMap();
  11214.  
  11215. // let mtxVideoId = '';
  11216. // let aje3 = [];
  11217. const mfvContinuationRecorded = new LimitedSizeSet(8); // record all success continuation keys
  11218. const mfyContinuationIgnored = new LimitedSizeSet(8); // ignore continuation keys by copying the keys in the past
  11219. let mtzlastAllowedContinuation = ''; // the key stored at the last success; clear when scheduling changes
  11220. let mtzCount = 0; // the key keeps unchanged
  11221. // let mjtNextMainKey = '';
  11222. let mjtRecordedPrevKey = ''; // the key stored at the last success (no clear)
  11223. let mjtLockPreviousKey = ''; // the key before fetch() should be discarded. (uncertain continuation)
  11224. let mbCId322 = 0; // cid for delay fetchUpdatedMetadata
  11225. // let allowNoDelay322=false;
  11226. let mbDelayBelowNCalls = 0; // after N calls, by pass delay; reset when scheduling changes
  11227.  
  11228. let mpKey22 = ''; // last success continutation key & url pair
  11229. let mpUrl22 = ''; // last success continutation key & url pair
  11230. let mpKey21 = ''; // latest requested continutation key & url pair
  11231. let mpUrl21 = ''; // latest requested continutation key & url pair
  11232.  
  11233.  
  11234. async function sha1Hex(message) {
  11235. const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  11236. const hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8); // hash the message
  11237. const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  11238. const hashHex = hashArray
  11239. .map((b) => b.toString(16).padStart(2, "0"))
  11240. .join(""); // convert bytes to hex string
  11241. return hashHex;
  11242. }
  11243.  
  11244. async function continuationLog(a, ...args) {
  11245. let b = a;
  11246. try {
  11247. if (advanceLogging) b = await sha1Hex(a);
  11248. let c = args.map(e => {
  11249. return e === a ? b : e
  11250. });
  11251. console.log(...c)
  11252. } catch (e) { console.warn(e) }
  11253. }
  11254.  
  11255. function copyPreviousContiuationToIgnored374(toClearRecorded) {
  11256.  
  11257.  
  11258. if (mfvContinuationRecorded.length > 0) {
  11259. for (const [e, d] of mfvContinuationRecorded) {
  11260. mfyContinuationIgnored.removeAdd(e);
  11261. }
  11262. toClearRecorded && mfvContinuationRecorded.clear();
  11263. }
  11264.  
  11265. }
  11266.  
  11267. function setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr) {
  11268.  
  11269. const tmProto = taskMgr.constructor.prototype;
  11270. if (tmProto && typeof tmProto.addJob === 'function' && tmProto.addJob.length === 3 && typeof tmProto.cancelJob === 'function' && tmProto.cancelJob.length === 1) {
  11271.  
  11272. if (!tmProto.addJob714) {
  11273.  
  11274. tmProto.addJob714 = tmProto.addJob;
  11275.  
  11276. tmProto.addJob = function (a, b, c) {
  11277. const jobId = this.addJob714(a, b, c);
  11278. if (jobId > 0) {
  11279. // const ez = wk3.get(this);
  11280. // const dz = ez ? ez.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint : null;
  11281. // aje3.push({mtx, jobId, a,b,c, element: this, dz, data: (ez?.data || null) })
  11282.  
  11283. this.__lastJobId863__ = jobId;
  11284. }
  11285. return jobId;
  11286. }
  11287.  
  11288. }
  11289.  
  11290. if (!tmProto.cancelJob714) {
  11291.  
  11292. tmProto.cancelJob714 = tmProto.cancelJob;
  11293.  
  11294. tmProto.cancelJob = function (a) {
  11295. const res = this.cancelJob714(a);
  11296. // if (a > 0) {
  11297. // for (const e of aje3) {
  11298. // if (e.jobId === a) e.cancelled = true;
  11299. // }
  11300. // }
  11301. return res;
  11302. }
  11303.  
  11304. }
  11305.  
  11306. }
  11307. }
  11308.  
  11309.  
  11310. const FIX_avoid_incorrect_video_meta_bool = FIX_avoid_incorrect_video_meta && isPrepareCachedV && check_for_set_key_order && !isChatRoomURL;
  11311.  
  11312.  
  11313. FIX_avoid_incorrect_video_meta_bool && whenCEDefined('ytd-video-primary-info-renderer').then(() => {
  11314. let dummy;
  11315. let cProto;
  11316. // let mc = 4;
  11317. // dummy = await observablePromise(() => {
  11318. // const r = document.querySelector('ytd-video-primary-info-renderer');
  11319. // if (!r) return;
  11320. // let cProto = insp(r).constructor.prototype;
  11321. // if (cProto.fetchUpdatedMetadata) return r;
  11322. // if (--mc < 0) return -1;
  11323. // return null;
  11324. // }).obtain();
  11325. dummy = document.createElement('ytd-video-primary-info-renderer');
  11326. if (!(dummy instanceof Element)) return;
  11327. // console.log(5022, dummy)
  11328. cProto = insp(dummy).constructor.prototype;
  11329.  
  11330. cProto.__getEmittorTaskMgr859__ = function () {
  11331. let taskMgr_ = null;
  11332. try {
  11333. taskMgr_ = (this.ytTaskEmitterBehavior || 0).getTaskManager() || null;
  11334. } catch (e) { }
  11335. return taskMgr_;
  11336. }
  11337. if (typeof cProto.fetchUpdatedMetadata === 'function' && cProto.fetchUpdatedMetadata.length === 1 && !cProto.fetchUpdatedMetadata717) {
  11338. // console.log(1234, cProto, cProto.is)
  11339. cProto.fetchUpdatedMetadata717 = cProto.fetchUpdatedMetadata;
  11340.  
  11341. let c_;
  11342. cProto.fetchUpdatedMetadata718 = function (a) {
  11343. // delay or immediate call the actual fetchUpdatedMetadata
  11344.  
  11345. let doImmediately = false;
  11346. if (a && typeof a === 'string' && mjtRecordedPrevKey && mjtRecordedPrevKey === mpKey22 && a === mpKey22 && (!pageSetupVideoId || pageSetupVideoId !== mpUrl22)) {
  11347.  
  11348. if (!pageSetupVideoId && videoPlayingY.videoId === mpUrl22) doImmediately = true;
  11349.  
  11350. } else if (typeof a !== 'string' || mbDelayBelowNCalls > 3 || !mpKey22 || (mpKey22 === a && mpKey22 !== mjtLockPreviousKey) || (mjtLockPreviousKey && mjtLockPreviousKey !== a)) {
  11351.  
  11352. doImmediately = true;
  11353.  
  11354. }
  11355.  
  11356. if (mbCId322) {
  11357. clearTimeout(mbCId322);
  11358. mbCId322 = 0;
  11359. }
  11360.  
  11361. if (doImmediately) return this.fetchUpdatedMetadata717(a);
  11362.  
  11363. let delay = mjtLockPreviousKey === a ? 8000 : 800;
  11364.  
  11365. mbCId322 = setTimeout(() => {
  11366. this.fetchUpdatedMetadata717(a);
  11367. }, delay);
  11368.  
  11369. console.log('[yt-js-engine-tamer]', '5190 delayed fetchUpdatedMetadata', delay);
  11370.  
  11371. }
  11372.  
  11373. cProto.fetchUpdatedMetadata = function (a) {
  11374.  
  11375. if (!pageSetupState) {
  11376. if (c_) clearTimeout(c_);
  11377. c_ = setTimeout(() => {
  11378. this.fetchUpdatedMetadata718(a);
  11379. }, 300);
  11380. return;
  11381. }
  11382.  
  11383. // pageSetupState == 0
  11384.  
  11385. try {
  11386.  
  11387. mbDelayBelowNCalls++;
  11388.  
  11389. if (arguments.length > 1 || !(a === undefined || (typeof a === 'string' && a))) {
  11390. console.warn("CAUTION: fetchUpdatedMetadata coding might have to be updated.");
  11391. }
  11392.  
  11393. // console.log('fum377', a)
  11394. if (typeof a === 'string' && mfyContinuationIgnored.has(a)) {
  11395. console.log('[yt-js-engine-tamer]', '5040 skip fetchUpdatedMetadata', a);
  11396. return;
  11397. }
  11398.  
  11399. if (!a && (this.data || 0).updatedMetadataEndpoint) {
  11400. if (mjtRecordedPrevKey && mjtLockPreviousKey !== mjtRecordedPrevKey) {
  11401. mjtLockPreviousKey = mjtRecordedPrevKey;
  11402. LOG_FETCHMETA_UPDATE && continuationLog(mjtLockPreviousKey, '5150 Lock Key', mjtLockPreviousKey);
  11403. }
  11404. // mjtNextMainKey = true;
  11405. mtzlastAllowedContinuation = '';
  11406. mtzCount = 0;
  11407. // allowNoDelay322 = false;
  11408. // fetch new metadata, cancel all previous continuations
  11409. copyPreviousContiuationToIgnored374(true);
  11410. } else if (typeof a === 'string') {
  11411. const videoPlayingId = videoPlayingY.videoId;
  11412.  
  11413. // if(mjtNextMainKey === true) mjtNextMainKey = a;
  11414.  
  11415. let update21 = !!pageSetupVideoId;
  11416. if (mpKey22 === a && mpUrl22 === videoPlayingId && mpUrl22 && videoPlayingId && (!pageSetupVideoId || pageSetupVideoId === videoPlayingId)) {
  11417. update21 = true;
  11418. } else if (mpKey22 === a && mpUrl22 !== pageSetupVideoId) {
  11419. LOG_FETCHMETA_UPDATE && continuationLog(mpKey22, '5060 mpUrl22 mismatched', mpKey22, mpUrl22, pageSetupVideoId || '(null)', videoPlayingId || '(null)');
  11420. return;
  11421. }
  11422. if (update21) {
  11423. mpKey21 = a;
  11424. mpUrl21 = pageSetupVideoId || videoPlayingId;
  11425. }
  11426.  
  11427. if (!mfvContinuationRecorded.has(a)) mfvContinuationRecorded.add(a);
  11428. }
  11429. LOG_FETCHMETA_UPDATE && continuationLog(a, '5180 fetchUpdatedMetadata\t', a, pageSetupVideoId || '(null)', videoPlayingY.videoId || '(null)');
  11430. // if (!pageSetupVideoId && typeof a === 'string' && a.length > 40) return; // ignore incorrect continuation
  11431. // if(a === mjtNextMainKey) allowNoDelay322 = false;
  11432. return this.fetchUpdatedMetadata718(a);
  11433.  
  11434. } catch (e) {
  11435. console.log('Code Error in fetchUpdatedMetadata', e);
  11436. }
  11437. return this.fetchUpdatedMetadata717(a)
  11438. }
  11439. }
  11440.  
  11441.  
  11442. if (typeof cProto.scheduleInitialUpdatedMetadataRequest === 'function' && cProto.scheduleInitialUpdatedMetadataRequest.length === 0 && !cProto.scheduleInitialUpdatedMetadataRequest717) {
  11443. // console.log(1234, cProto, cProto.is)
  11444. cProto.scheduleInitialUpdatedMetadataRequest717 = cProto.scheduleInitialUpdatedMetadataRequest;
  11445. let mJob = null;
  11446.  
  11447. cProto.scheduleInitialUpdatedMetadataRequest = function () {
  11448.  
  11449. try {
  11450.  
  11451. if (arguments.length > 0) {
  11452. console.warn("CAUTION: scheduleInitialUpdatedMetadataRequest coding might have to be updated.");
  11453. }
  11454. // mfy = mfv;
  11455.  
  11456. // mjtNextMainKey = '';
  11457. mtzlastAllowedContinuation = '';
  11458. mtzCount = 0;
  11459. if (mbCId322) {
  11460. clearTimeout(mbCId322);
  11461. mbCId322 = 0;
  11462. }
  11463. mbDelayBelowNCalls = 0;
  11464. // allowNoDelay322 = false;
  11465. copyPreviousContiuationToIgnored374(true);
  11466.  
  11467. const taskMgr = this.__getEmittorTaskMgr859__();
  11468. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714 && taskMgr.addJob && taskMgr.cancelJob) setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr);
  11469. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714) {
  11470. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 507');
  11471. }
  11472.  
  11473. // prevent depulicated schedule job by clearing previous JobId
  11474. if (taskMgr && typeof taskMgr.addLowPriorityJob === 'function' && taskMgr.addLowPriorityJob.length === 2 && typeof taskMgr.cancelJob === 'function' && taskMgr.cancelJob.length === 1) {
  11475.  
  11476. let res;
  11477.  
  11478. if (mJob) {
  11479. const job = mJob;
  11480. mJob = null;
  11481. console.log('cancelJob', job)
  11482. taskMgr.cancelJob(job); // clear previous [Interval Meta Update] job
  11483. // p.cancelJob(a,b);
  11484. }
  11485.  
  11486. // const updatedMetadataEndpoint = this.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint
  11487.  
  11488. let pza = taskMgr.__lastJobId863__;
  11489. try { res = this.scheduleInitialUpdatedMetadataRequest717(); } catch (e) { }
  11490. let pzb = taskMgr.__lastJobId863__
  11491. if (pza !== pzb) {
  11492. mJob = pzb; // set [Interval Meta Update] jobId
  11493. }
  11494.  
  11495. // if (updatedMetadataEndpoint && updatedMetadataEndpoint.videoId) {
  11496. // mtxVideoId = updatedMetadataEndpoint.videoId || ''; // set the current target VideoId
  11497. // } else {
  11498. // mtxVideoId = ''; // sometimes updatedMetadataEndpoint is not ready
  11499. // }
  11500.  
  11501. return res;
  11502.  
  11503. } else {
  11504. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 601');
  11505. }
  11506.  
  11507. } catch (e) {
  11508. console.log('Code Error in scheduleInitialUpdatedMetadataRequest', e);
  11509. }
  11510.  
  11511.  
  11512. return this.scheduleInitialUpdatedMetadataRequest717();
  11513. }
  11514. }
  11515.  
  11516.  
  11517. });
  11518.  
  11519. FIX_avoid_incorrect_video_meta_bool && promiseForYtActionCalled.then((ytAppDom) => {
  11520. let dummy;
  11521. let cProto;
  11522. dummy = ytAppDom;
  11523. if (!(dummy instanceof Element)) return;
  11524. cProto = insp(dummy).constructor.prototype;
  11525. if (typeof cProto.sendServiceAjax_ === 'function' && cProto.sendServiceAjax_.length === 4 && !cProto.sendServiceAjax717_) {
  11526. // console.log(1234, cProto, cProto.is);
  11527. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  11528. // cProto.handleServiceRequest_ = function (a, b, c, d) {
  11529. // console.log(123401, arguments);
  11530. // return this.handleServiceRequest717_(a, b, c, d);
  11531. // }
  11532.  
  11533. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  11534.  
  11535. // cProto.handleServiceRequest_ = function(a,b,c,d){
  11536. // console.log(59901, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  11537. // if(a?.is === 'ytd-video-primary-info-renderer' && b?.updatedMetadataEndpoint?.videoId && c?.continuation && typeof c?.continuation ==='string'){
  11538. // console.log('mfv', c.continuation);
  11539. // mfv.add( c.continuation);
  11540. // }
  11541. // return this.handleServiceRequest717_(a,b,c,d);
  11542. // }
  11543.  
  11544. function extraArguments322(a, b, c) {
  11545. let is = (a || 0).is;
  11546. let videoId = ((b || 0).updatedMetadataEndpoint || 0).videoId;
  11547. let continuation = (c || 0).continuation;
  11548. if (typeof is !== 'string') is = null;
  11549. if (typeof videoId !== 'string') videoId = null;
  11550. if (typeof continuation !== 'string') continuation = null;
  11551. return { is, videoId, continuation };
  11552. }
  11553.  
  11554. cProto.sendServiceAjax717_ = cProto.sendServiceAjax_;
  11555. cProto.sendServiceAjax_ = function (a, b, c, d) {
  11556.  
  11557. // console.log(8001)
  11558. try {
  11559.  
  11560. const { is, videoId, continuation } = extraArguments322(a, b, c);
  11561.  
  11562. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  11563. console.warn("CAUTION: sendServiceAjax_ coding might have to be updated.");
  11564. }
  11565.  
  11566. if (pageSetupVideoId && videoId && continuation) {
  11567. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  11568. mfyContinuationIgnored.removeAdd(continuation);
  11569. mfvContinuationRecorded.delete(continuation);
  11570. return;
  11571. }
  11572. }
  11573.  
  11574. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  11575. copyPreviousContiuationToIgnored374(false);
  11576. mfyContinuationIgnored.delete(continuation);
  11577. mfvContinuationRecorded.removeAdd(continuation);
  11578. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  11579. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  11580. mjtLockPreviousKey = '';
  11581. }
  11582. // if (mjtNextMainKey === continuation) {
  11583. // copyPreviousContiuationToIgnored(false);
  11584. // mfyContinuationIgnored.delete(continuation);
  11585. // mfvContinuationRecorded.add(continuation);
  11586. // }
  11587.  
  11588.  
  11589. if (mfyContinuationIgnored && continuation) {
  11590. if (mfyContinuationIgnored.has(continuation)) {
  11591. LOG_FETCHMETA_UPDATE && continuationLog(continuation, '5260 matched01', continuation)
  11592. return;
  11593. }
  11594. }
  11595.  
  11596. // console.log(59902, a?.is, b,c,d)
  11597. // console.log(59903, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  11598. if (is === 'ytd-video-primary-info-renderer' && videoId && continuation && !mfvContinuationRecorded.has(continuation)) {
  11599. // console.log('mfv377', continuation);
  11600. mfvContinuationRecorded.add(continuation);
  11601. }
  11602.  
  11603. // if (videoId) {
  11604. // if (!pageSetupVideoId) return; // ignore page not ready
  11605. // // if (mtxVideoId && b.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  11606. // if (videoId !== pageSetupVideoId) {
  11607. // return;
  11608. // }
  11609. // }
  11610.  
  11611. } catch (e) {
  11612. console.log('Coding Error in sendServiceAjax_', e)
  11613. }
  11614. // console.log(8002)
  11615. // console.log(123402, arguments);
  11616. // console.log(5162, 'a',a?.is,'b',b,'c',c,'d',d);
  11617.  
  11618. // console.log(5211, b?.updatedMetadataEndpoint?.kdkw33);
  11619. // if(b &&b.updatedMetadataEndpoint && !b.updatedMetadataEndpoint.kdkw33){
  11620. // b.updatedMetadataEndpoint = new Proxy(b.updatedMetadataEndpoint, {
  11621. // get(target, prop, receiver){
  11622. // console.log('xxs99', target.videoId, mtx)
  11623. // if(prop ==='kdkw33') return 1;
  11624. // console.log(3322, prop, target)
  11625. // if(prop === 'initialDelayMs') {
  11626. // throw new Error("ABCC");
  11627. // }
  11628. // return target[prop];
  11629. // },
  11630. // set(target, prop, value, receiver){
  11631.  
  11632. // if(prop ==='kdkw33') return true;
  11633. // target[prop]=value;
  11634. // return true;
  11635. // }
  11636. // });
  11637. // }
  11638. // console.log(5533, b?.updatedMetadataEndpoint?.kdkw33)
  11639. return this.sendServiceAjax717_(a, b, c, d);
  11640. }
  11641. }
  11642.  
  11643. function delayClearOtherKeys(lztContinuation) {
  11644. // // schedule delayed removal if mfyContinuationIgnored is not empty
  11645. // getRafPromise().then(() => {
  11646. // // assume the repeat continuation could be only for popstate which is triggered by user interaction
  11647. // // foreground page only
  11648.  
  11649. // });
  11650.  
  11651.  
  11652. if (lztContinuation !== mtzlastAllowedContinuation) return;
  11653. if (lztContinuation !== mpKey21 || lztContinuation !== mpKey22) return;
  11654. if (!mfyContinuationIgnored.size) return;
  11655. if (mfyContinuationIgnored.size > 1) {
  11656. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, 'delayClearOtherKeys, current = ', lztContinuation);
  11657. }
  11658. mfyContinuationIgnored.forEach((value, key) => {
  11659. if (key !== lztContinuation) {
  11660. mfyContinuationIgnored.delete(key);
  11661. LOG_FETCHMETA_UPDATE && continuationLog(key, 'previous continuation removed from ignored store', key);
  11662. }
  11663. });
  11664.  
  11665. }
  11666. if (typeof cProto.getCancellableNetworkPromise_ === 'function' && cProto.getCancellableNetworkPromise_.length === 5 && !cProto.getCancellableNetworkPromise717_) {
  11667. cProto.getCancellableNetworkPromise717_ = cProto.getCancellableNetworkPromise_;
  11668. cProto.getCancellableNetworkPromise_ = function (a, b, c, d, e) {
  11669.  
  11670. // console.log(8003)
  11671. try {
  11672.  
  11673.  
  11674. const { is, videoId, continuation } = extraArguments322(b, c, d);
  11675.  
  11676. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  11677. console.warn("CAUTION: getCancellableNetworkPromise_ coding might have to be updated.");
  11678. }
  11679.  
  11680. if (pageSetupVideoId && videoId && continuation) {
  11681. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  11682. mfyContinuationIgnored.removeAdd(continuation);
  11683. mfvContinuationRecorded.delete(continuation);
  11684. return;
  11685. }
  11686. }
  11687.  
  11688. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  11689. copyPreviousContiuationToIgnored374(false);
  11690. mfyContinuationIgnored.delete(continuation);
  11691. mfvContinuationRecorded.removeAdd(continuation);
  11692. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  11693. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  11694. mjtLockPreviousKey = '';
  11695. }
  11696.  
  11697. // if (mjtNextMainKey === continuation) {
  11698. // copyPreviousContiuationToIgnored(false);
  11699. // mfyContinuationIgnored.delete(continuation);
  11700. // mfvContinuationRecorded.add(continuation);
  11701. // }
  11702.  
  11703. const lztContinuation = continuation;
  11704.  
  11705. if (mfyContinuationIgnored && lztContinuation && typeof lztContinuation === 'string') {
  11706. if (mfyContinuationIgnored.has(lztContinuation)) {
  11707. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5360 matched02', lztContinuation)
  11708. return;
  11709. }
  11710. }
  11711.  
  11712. // if (videoId) {
  11713. // if (!pageSetupVideoId) return; // ignore page not ready
  11714. // // if (mtxVideoId && c.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  11715. // if (videoId !== pageSetupVideoId) {
  11716. // return;
  11717. // }
  11718. // }
  11719.  
  11720. if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation !== lztContinuation) {
  11721. mtzlastAllowedContinuation = lztContinuation;
  11722. // console.log(70401, lztContinuation, mfyContinuationIgnored.size)
  11723.  
  11724. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5382 Continuation sets to\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  11725. mjtRecordedPrevKey = lztContinuation;
  11726. if (mjtLockPreviousKey === lztContinuation) mjtLockPreviousKey = '';
  11727. // if (mfyContinuationIgnored.size > 0) {
  11728. // delayClearOtherKeys(lztContinuation);
  11729. // }
  11730. mtzCount = 0;
  11731. // allowNoDelay322 = false;
  11732. } else if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation && mtzlastAllowedContinuation === lztContinuation) {
  11733. // repeated
  11734. if (++mtzCount > 1e9) mtzCount = 1e4;
  11735. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5386 Same Continuation\t\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  11736.  
  11737. // if (mtzCount >= 3) allowNoDelay322 = true;
  11738. if (mtzCount >= 3 && mfyContinuationIgnored.size > 0) {
  11739. Promise.resolve(lztContinuation).then(delayClearOtherKeys).catch(console.warn);
  11740. }
  11741. if (mtzCount === 5) {
  11742. mfvContinuationRecorded.clear();
  11743. mfvContinuationRecorded.add(lztContinuation);
  11744. }
  11745.  
  11746. }
  11747.  
  11748. if (typeof lztContinuation === 'string' && lztContinuation && (pageSetupVideoId || videoPlayingY.videoId)) {
  11749. mpKey22 = lztContinuation;
  11750. mpUrl22 = pageSetupVideoId || videoPlayingY.videoId;
  11751. }
  11752.  
  11753. if (mbCId322) {
  11754. clearTimeout(mbCId322);
  11755. mbCId322 = 0;
  11756. }
  11757. } catch (e) {
  11758. console.log('Coding Error in getCancellableNetworkPromise_', e)
  11759. }
  11760.  
  11761. // console.log(8004)
  11762. // console.log(123403, arguments);
  11763. // if(c.updatedMetadataEndpoint) console.log(123404, pageSetupVideoId, JSON.stringify(c.updatedMetadataEndpoint))
  11764.  
  11765. // console.log(5163, a?.is,b,c,d,e);
  11766. return this.getCancellableNetworkPromise717_(a, b, c, d, e);
  11767. }
  11768. }
  11769. });
  11770.  
  11771. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  11772.  
  11773.  
  11774. FIX_ytdExpander_childrenChanged && !isChatRoomURL && whenCEDefined('ytd-expander').then(() => {
  11775.  
  11776. let dummy;
  11777. let cProto;
  11778.  
  11779. dummy = document.createElement('ytd-expander');
  11780. cProto = insp(dummy).constructor.prototype;
  11781.  
  11782. if (fnIntegrity(cProto.initChildrenObserver, '0.48.21') && fnIntegrity(cProto.childrenChanged, '0.40.22')) {
  11783.  
  11784. cProto.initChildrenObserver14 = cProto.initChildrenObserver;
  11785. cProto.childrenChanged14 = cProto.childrenChanged;
  11786.  
  11787. cProto.initChildrenObserver = function () {
  11788. var a = this;
  11789. this.observer = new MutationObserver(function () {
  11790. a.childrenChanged()
  11791. }
  11792. );
  11793. this.observer.observe(this.content, {
  11794. subtree: !0,
  11795. childList: !0,
  11796. attributes: !0,
  11797. characterData: !0
  11798. });
  11799. this.childrenChanged()
  11800. }
  11801. ;
  11802. cProto.childrenChanged = function () {
  11803. if (this.alwaysToggleable) {
  11804. this.canToggle = this.alwaysToggleable;
  11805. } else if (!this.canToggleJobId) {
  11806. this.canToggleJobId = 1;
  11807. foregroundPromiseFn().then(() => {
  11808. this.canToggleJobId = 0;
  11809. this.calculateCanCollapse()
  11810. })
  11811. }
  11812. }
  11813.  
  11814. // console.log(cProto.initChildrenObserver)
  11815. console.debug('ytd-expander-fix-childrenChanged');
  11816.  
  11817. }
  11818.  
  11819. });
  11820.  
  11821.  
  11822. FIX_paper_ripple_animate && whenCEDefined('paper-ripple').then(() => {
  11823.  
  11824. let dummy;
  11825. let cProto;
  11826. dummy = document.createElement('paper-ripple');
  11827. cProto = insp(dummy).constructor.prototype;
  11828.  
  11829. if (fnIntegrity(cProto.animate, '0.74.5')) {
  11830.  
  11831.  
  11832. cProto.animate34 = cProto.animate;
  11833. cProto.animate = function () {
  11834. if (this._animating) {
  11835. var a;
  11836. const ripples = this.ripples;
  11837. for (a = 0; a < ripples.length; ++a) {
  11838. var b = ripples[a];
  11839. b.draw();
  11840. this.$.background.style.opacity = b.outerOpacity;
  11841. b.isOpacityFullyDecayed && !b.isRestingAtMaxRadius && this.removeRipple(b)
  11842. }
  11843. if ((this.shouldKeepAnimating || 0) !== ripples.length) {
  11844. if (!this._boundAnimate38) this._boundAnimate38 = this.animate.bind(this);
  11845. foregroundPromiseFn().then(this._boundAnimate38);
  11846. } else {
  11847. this.onAnimationComplete();
  11848. }
  11849. }
  11850. }
  11851.  
  11852. console.debug('FIX_paper_ripple_animate')
  11853.  
  11854. // console.log(cProto.animate)
  11855.  
  11856. }
  11857.  
  11858. });
  11859.  
  11860. if (FIX_doIdomRender) {
  11861.  
  11862. const xsetTimeout = function (f, d) {
  11863. if (xsetTimeout.m511 === 1 && !d) {
  11864. xsetTimeout.m511 = 2;
  11865. xsetTimeout.m568 = f;
  11866. } else {
  11867. return setTimeout.apply(window, arguments)
  11868. }
  11869.  
  11870. }
  11871.  
  11872. /**
  11873. *
  11874. IGb = function(a) {
  11875. var b, c = null == (b = a.requestAninmationFrameResolver) ? void 0 : b.promise;
  11876. c || (a.requestAninmationFrameResolver = new Vi,
  11877. c = a.requestAninmationFrameResolver.promise,
  11878. Da.requestAnimationFrame(function() {
  11879. var d;
  11880. null == (d = a.requestAninmationFrameResolver) || d.resolve();
  11881. a.requestAninmationFrameResolver = null
  11882. }));
  11883. return c
  11884. }
  11885.  
  11886.  
  11887. */
  11888.  
  11889. const xrequestAnimationFrame = function (f) {
  11890. const h = `${f}`;
  11891. if (h.startsWith("function(){setTimeout(function(){") && h.endsWith("})}")) {
  11892. let t = null;
  11893. xsetTimeout.m511 = 1;
  11894. f();
  11895. if (xsetTimeout.m511 === 2) {
  11896. t = xsetTimeout.m568;
  11897. xsetTimeout.m568 = null;
  11898. }
  11899. xsetTimeout.m511 = 0;
  11900. if (typeof t === 'function') {
  11901. foregroundPromiseFn().then(t);
  11902. }
  11903. } else if (h.includes("requestAninmationFrameResolver")) {
  11904. foregroundPromiseFn().then(f);
  11905. } else {
  11906. return requestAnimationFrame.apply(window, arguments);
  11907. }
  11908. }
  11909.  
  11910. let busy = false;
  11911. const doIdomRender = function () {
  11912.  
  11913. if (!this) return;
  11914. if (busy) {
  11915. return this.doIdomRender13(...arguments);
  11916. }
  11917. busy = true;
  11918. const { requestAnimationFrame, setTimeout } = window;
  11919. window.requestAnimationFrame = xrequestAnimationFrame;
  11920. window.setTimeout = xsetTimeout;
  11921. let r = this.doIdomRender13(...arguments);
  11922. window.requestAnimationFrame = requestAnimationFrame;
  11923. window.setTimeout = setTimeout;
  11924. busy = false;
  11925. return r;
  11926. };
  11927. for (const ytTag of ['ytd-lottie-player', 'yt-attributed-string', 'yt-image', 'yt-icon-shape', 'yt-button-shape', 'yt-button-view-model', 'yt-icon-badge-shape']) {
  11928.  
  11929.  
  11930. whenCEDefined(ytTag).then(() => {
  11931.  
  11932. let dummy;
  11933. let cProto;
  11934. dummy = document.createElement(ytTag);
  11935. cProto = insp(dummy).constructor.prototype;
  11936.  
  11937. cProto.doIdomRender13 = cProto.doIdomRender;
  11938. cProto.doIdomRender = doIdomRender;
  11939.  
  11940. if (cProto.doIdomRender13 === cProto.templatingFn) cProto.templatingFn = doIdomRender;
  11941.  
  11942. console.debug('[yt-js-engine-tamer] FIX_doIdomRender', ytTag)
  11943.  
  11944.  
  11945.  
  11946. });
  11947.  
  11948. }
  11949.  
  11950. }
  11951.  
  11952.  
  11953.  
  11954.  
  11955. FIX_POPUP_UNIQUE_ID && whenCEDefined('ytd-popup-container').then(async () => {
  11956.  
  11957. const sMap = new Map();
  11958.  
  11959. const ZTa = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  11960. const ZT = function () {
  11961. for (var a = Array(36), b = 0, c, d = 0; d < 36; d++)
  11962. d == 8 || d == 13 || d == 18 || d == 23 ? a[d] = "-" : d == 14 ? a[d] = "4" : (b <= 2 && (b = 33554432 + Math.random() * 16777216 | 0),
  11963. c = b & 15,
  11964. b >>= 4,
  11965. a[d] = ZTa[d == 19 ? c & 3 | 8 : c]);
  11966. return a.join("")
  11967. };
  11968.  
  11969.  
  11970. const popupContainerCollection = document.getElementsByTagName('ytd-popup-container');
  11971.  
  11972. const popupContainer = await observablePromise(() => {
  11973. return popupContainerCollection[0];
  11974. }).obtain();
  11975.  
  11976.  
  11977. let cProto;
  11978. cProto = insp(popupContainer).constructor.prototype;
  11979.  
  11980.  
  11981. if (!cProto || typeof cProto.handleOpenPopupAction !== 'function' || cProto.handleOpenPopupAction3868 || cProto.handleOpenPopupAction.length !== 2) {
  11982. console.log('FIX_POPUP_UNIQUE_ID NG')
  11983. return;
  11984. }
  11985. cProto.handleOpenPopupAction3868 = cProto.handleOpenPopupAction;
  11986.  
  11987. cProto.handleOpenPopupAction = function (a, b) {
  11988.  
  11989. if (typeof (a || 0) === 'object' && !a.__jOdQA__) {
  11990.  
  11991. a.__jOdQA__ = true;
  11992.  
  11993. try {
  11994.  
  11995. const h = this.hostElement;
  11996.  
  11997. if (h instanceof HTMLElement_) {
  11998.  
  11999. const map = h.__skme44__ = h.__skme44__ || new Map();
  12000.  
  12001. let mKey = '';
  12002. const wKey = firstObjectKey(a);
  12003. const wObj = wKey ? a[wKey] : null;
  12004. if (wKey && wObj && typeof (wObj.popup || 0) === 'object') {
  12005. const pKey = firstObjectKey(wObj.popup)
  12006. const pObj = pKey ? wObj.popup[pKey] : null;
  12007. let contentKey = '';
  12008. let headerKey = '';
  12009.  
  12010. if (pObj && pObj.identifier && pObj.content && pObj.header) {
  12011. contentKey = firstObjectKey(pObj.content)
  12012. headerKey = firstObjectKey(pObj.header)
  12013. }
  12014. if (contentKey && headerKey) {
  12015.  
  12016. mKey = `${wKey}(popupType:${wObj.popupType},popup(${pKey}(content(${contentKey}:...),header(${headerKey}:...),identifer(surface:${pObj.identifier.surface}))))`
  12017.  
  12018. if (mKey) {
  12019.  
  12020. if (!wObj.uniqueId) {
  12021. for (let i = 0; i < 8; i++) {
  12022. wObj.uniqueId = ZT();
  12023. if (!sMap.has(wObj.uniqueId)) break;
  12024. }
  12025. }
  12026. const oId = wObj.uniqueId
  12027.  
  12028. let nId_ = map.get(mKey);
  12029. if (!nId_) {
  12030. map.set(mKey, nId_ = oId);
  12031. }
  12032.  
  12033. wObj.uniqueId = nId_ || wObj.uniqueId;
  12034.  
  12035. const nId = wObj.uniqueId
  12036.  
  12037. sMap.set(oId, nId);
  12038. sMap.set(nId, nId);
  12039.  
  12040. wObj.uniqueId = nId;
  12041. pObj.targetId = nId;
  12042. pObj.identifier.tag = nId;
  12043.  
  12044. if (oId !== nId) {
  12045. console.log('FIX_POPUP_UNIQUE_ID', oId, nId);
  12046. }
  12047.  
  12048. }
  12049.  
  12050. }
  12051. }
  12052.  
  12053. // console.log(12213, mKey, a, b, h)
  12054.  
  12055. }
  12056.  
  12057. } catch (e) {
  12058. console.warn(e)
  12059. }
  12060.  
  12061. try {
  12062.  
  12063. const results = searchNestedObject(a, (x) => {
  12064. if (typeof x === 'string' && x.length === 36) {
  12065. if (/[a-zA-Z\d]{8}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{12}/.test(x)) return true;
  12066. }
  12067. return false;
  12068. });
  12069. for (const [obj, key] of results) {
  12070. const oId = obj[key];
  12071. const nId = sMap.get(oId);
  12072. if (nId) obj[key] = nId;
  12073. }
  12074. } catch (e) {
  12075. console.warn(e)
  12076. }
  12077.  
  12078.  
  12079. }
  12080.  
  12081. return this.handleOpenPopupAction3868(...arguments)
  12082. }
  12083.  
  12084. console.log('FIX_POPUP_UNIQUE_ID OK')
  12085.  
  12086.  
  12087. });
  12088.  
  12089.  
  12090. FIX_TRANSCRIPT_SEGMENTS && !isChatRoomURL && whenCEDefined('yt-formatted-string').then(async () => {
  12091.  
  12092. let dummy;
  12093. let cProto;
  12094. dummy = document.createElement('yt-formatted-string');
  12095. cProto = insp(dummy).constructor.prototype;
  12096.  
  12097. if (!cProto || typeof cProto.setNodeStyle_ !== 'function' || cProto.setNodeStyle17_ || cProto.setNodeStyle_.length !== 2) {
  12098. console.log('FIX_TRANSCRIPT_SEGMENTS(2) NG');
  12099. return;
  12100. }
  12101.  
  12102. cProto.setNodeStyle17_ = cProto.setNodeStyle_;
  12103. cProto.setNodeStyle_ = function (a, b) {
  12104. if (b instanceof HTMLElement_ && typeof (a || 0) === 'object') b.classList.toggle('yt-formatted-string-block-line', !!a.blockLine);
  12105. return this.setNodeStyle17_(a, b);
  12106. }
  12107.  
  12108. console.log('FIX_TRANSCRIPT_SEGMENTS(2) OK');
  12109. });
  12110.  
  12111. });
  12112.  
  12113. });
  12114.  
  12115.  
  12116.  
  12117.  
  12118. if (isMainWindow) {
  12119.  
  12120. console.groupCollapsed(
  12121. "%cYouTube JS Engine Tamer",
  12122. "background-color: #EDE43B ; color: #000 ; font-weight: bold ; padding: 4px ;"
  12123. );
  12124.  
  12125.  
  12126.  
  12127. console.log("Script is loaded.");
  12128. console.log("This script changes the core mechanisms of the YouTube JS engine.");
  12129.  
  12130. console.log("This script is experimental and subject to further changes.");
  12131.  
  12132. console.log("This might boost your YouTube performance.");
  12133.  
  12134. console.log("CAUTION: This might break your YouTube.");
  12135.  
  12136.  
  12137. if (prepareLogs.length >= 1) {
  12138. console.log(" =========================================================================== ");
  12139.  
  12140. for (const msg of prepareLogs) {
  12141. console.log(msg)
  12142. }
  12143.  
  12144. console.log(" =========================================================================== ");
  12145. }
  12146.  
  12147. console.groupEnd();
  12148.  
  12149. }
  12150.  
  12151.  
  12152.  
  12153. })();