Greasy Fork is available in English.

YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

2025-01-11 일자. 최신 버전을 확인하세요.

질문, 리뷰하거나, 이 스크립트를 신고하세요.
  1. // ==UserScript==
  2. // @name YouTube JS Engine Tamer
  3. // @namespace UserScripts
  4. // @version 0.17.3
  5. // @match https://www.youtube.com/*
  6. // @match https://www.youtube-nocookie.com/embed/*
  7. // @match https://studio.youtube.com/live_chat*
  8. // @license MIT
  9. // @author CY Fung
  10. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/yt-engine.png
  11. // @description To enhance YouTube performance by modifying YouTube JS Engine
  12. // @grant none
  13. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@7221a4efffd49d852de0074ec503d4febb99f28b/library/nextBrowserTick.min.js
  14. // @run-at document-start
  15. // @unwrap
  16. // @inject-into page
  17. // @allFrames true
  18. // ==/UserScript==
  19.  
  20. (() => {
  21.  
  22. /** @type {WeakMapConstructor} */
  23. const WeakMap = window.WeakMapOriginal || window.WeakMap;
  24.  
  25. const NATIVE_CANVAS_ANIMATION = false; // for #cinematics
  26. const FIX_schedulerInstanceInstance = 2 | 4;
  27. const FIX_yt_player = true; // DONT CHANGE
  28. const FIX_Animation_n_timeline = true;
  29. const NO_PRELOAD_GENERATE_204 = false;
  30. const ENABLE_COMPUTEDSTYLE_CACHE = true;
  31. const NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE = true;
  32. const CHANGE_appendChild = true; // discussions#236759
  33. const FIX_bind_self_this = false; // EXPERIMENTAL !!!!! this affect page switch after live ends
  34. const FIX_weakMap_weakRef = false; // EXPERIMENTAL !!!!! Might Incompatible to some userscripts (as the strong relationship is removed)
  35.  
  36. const FIX_error_many_stack = true; // should be a bug caused by uBlock Origin
  37. // const FIX_error_many_stack_keepAliveDuration = 200; // ms
  38. // const FIX_error_many_stack_keepAliveDuration_check_if_n_larger_than = 8;
  39.  
  40. const FIX_Iframe_NULL_SRC = false;
  41.  
  42. const IGNORE_bindAnimationForCustomEffect = true; // prevent `v.bindAnimationForCustomEffect(this);` being executed
  43.  
  44. const FIX_ytdExpander_childrenChanged = true;
  45. const FIX_paper_ripple_animate = true;
  46. const FIX_avoid_incorrect_video_meta = true; // omit the incorrect yt-animated-rolling-number
  47. const FIX_avoid_incorrect_video_meta_emitterBehavior = true;
  48.  
  49. const FIX_doIdomRender = true;
  50.  
  51. const FIX_Shady = true;
  52.  
  53. // [[ 2024.04.24 ]]
  54. const MODIFY_ShadyDOM_OBJ = true;
  55. // << if MODIFY_ShadyDOM_OBJ >>
  56. const WEAKREF_ShadyDOM = true;
  57. const OMIT_ShadyDOM_EXPERIMENTAL = 1 | 0; // 1 => enable; 2 => composedPath
  58. const OMIT_ShadyDOM_settings = 0 | 0 | 0; // 1: inUse; 2: handlesDynamicScoping; 4: force // {{ PRELIM TESTING PURPOSE }}
  59. // << end >>
  60.  
  61. const WEAK_REF_BINDING_CONTROL = 1 | 2; // 2 - conflict control with ShadyDOM weakref
  62.  
  63. const FIX_ytAction_ = true; // ytd-app
  64. const FIX_onVideoDataChange = false;
  65. // const FIX_onClick = true;
  66. const FIX_onStateChange = true;
  67. const FIX_onLoopRangeChange = true;
  68. // const FIX_maybeUpdateFlexibleMenu = true; // ytd-menu-renderer
  69. const FIX_VideoEVENTS_v2 = true; // true might cause bug in switching page
  70.  
  71. const ENABLE_discreteTasking = true;
  72. // << if ENABLE_discreteTasking >>
  73. const FIX_stampDomArray_stableList = true;
  74. const ENABLE_weakenStampReferences = true; // disabled in old browsers
  75. // << end >>
  76.  
  77. const FIX_perfNow = true; // history state issue; see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  78. const ENABLE_ASYNC_DISPATCHEVENT = false; // problematic
  79.  
  80. const FIX_Polymer_dom = true;
  81.  
  82. const SCRIPTLET_REMOVE_PRUNE_propNeedles = true; // brave scriptlet related
  83. const DEBUG_removePrune = false; // true for DEBUG
  84.  
  85. const FIX_XHR_REQUESTING = true;
  86.  
  87. const LOG_FETCHMETA_UPDATE = false; // for DEBUG
  88.  
  89. const IGNORE_bufferhealth_CHECK = false; // experimental; true will make "Stats for nerds" no info.
  90.  
  91. const DENY_requestStorageAccess = true; // remove document.requestStorageAccess
  92. const DISABLE_IFRAME_requestStorageAccess = true; // no effect if DENY_requestStorageAccess is true
  93.  
  94. const DISABLE_COOLDOWN_SCROLLING = true; // YT cause scroll hang in MacOS
  95.  
  96. const FIX_removeChild = true;
  97. const FIX_fix_requestIdleCallback_timing = true;
  98.  
  99. const HOOK_CSSPD_LEFT = true; // global css hack for style.left
  100. const FORCE_NO_REUSEABLE_ELEMENT_POOL = true;
  101.  
  102. const FIX_POPUP_UNIQUE_ID = true; // currently only for channel about popup;
  103.  
  104. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  105. // example. https://www.youtube.com/channel/UCgPev1KKSCMbnNRsvN83Hag/about
  106. // first tp-yt-paper-dialog: show once the page is loaded.
  107. // second tp-yt-paper-dialog: click "...more"
  108. // third tp-yt-paper-dialog: click "... and 3 more links"
  109. // check with document.querySelectorAll('ytd-popup-container tp-yt-paper-dialog').length
  110. // currently, uniqueId is preassigned by the network resolveCommand.
  111. // so don't modify the source side, just modify the display side (popup display) via handleOpenPopupAction
  112. // other related functions e.g. handleClosePopupCommand_, getAndMaybeCreatePopup_, handleClosePopupAction_, getAndMaybeCreatePopup_
  113. // handleOpenPopupAction -> createCacheKey
  114. // handleClosePopupAction_ -> createCacheKey
  115. // handleGetPopupOpenedAction_ -> createCacheKey
  116. // getAndMaybeCreatePopup_ -> createCacheKey
  117. // closePopup -> createCacheKey
  118.  
  119. // yt-close-popup-command -> handleClosePopupCommand_
  120.  
  121. // ensurePopup_ -> getAndMaybeCreatePopup_
  122.  
  123. // yt-close-popup-action -> handleClosePopupAction_
  124. // closePopup -> handleClosePopupAction_
  125. // handleOpenPopupAction -> handleClosePopupAction_
  126. // handleClosePopupCommand_ -> handleClosePopupAction_
  127. // closeSheet -> handleClosePopupAction_("yt-sheet-view-model")
  128.  
  129. // yt-open-popup-action -> handleOpenPopupAction
  130.  
  131.  
  132. // yt-close-popup-action -> handleClosePopupAction_ -> createCacheKey
  133. // yt-close-popup-command -> handleClosePopupCommand_ -> handleClosePopupAction_ -> createCacheKey
  134. // Experimental flag "ytpopup_disable_default_html_caching" is disabled by default.
  135. // Not sure enabling it can make GC or not (Yt Components are usually not GC-able)
  136. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  137.  
  138.  
  139. const FIX_DOM_IF_REPEAT = true; // semi-experimental (added in 0.17.0)
  140. const FIX_DOM_IF_TEMPLATE = true;
  141. // const FIX_DOM_REPEAT_TEMPLATE = true; // to be implemented
  142. const FIX_DOM_IFREPEAT_RenderDebouncerChange = true; // semi-experimental (added in 0.17.0)
  143. const DEBUG_DBR847 = false;
  144. const DEBUG_xx847 = false;
  145. const FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME = true; // default true. false might be required for future change
  146. const DEBUG_renderDebounceTs = false;
  147.  
  148. /*
  149.  
  150. FIX_DOM_IFREPEAT_RenderDebouncerChange
  151.  
  152. avoid Polymer.flush
  153. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  154.  
  155. var Is = function() {
  156. do {
  157. var a = window.ShadyDOM && ShadyDOM.flush();
  158. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  159. var b = NNa()
  160. } while (a || b)
  161. };
  162.  
  163. , NNa = function() {
  164. var a = !!ts.size;
  165. ts.forEach(function(b) {
  166. try {
  167. b.flush()
  168. } catch (c) {
  169. setTimeout(function() {
  170. throw c
  171. })
  172. }
  173. });
  174. return a
  175. };
  176.  
  177. // why flush twice after all ts are completed? (!!ts.size => true => loop again)
  178. // this coding logic should be incorrect (mistake).
  179.  
  180. */
  181.  
  182.  
  183.  
  184. // ----------------------------- Shortkey Keyboard Control -----------------------------
  185. // dependency: FIX_yt_player
  186.  
  187. const FIX_SHORTCUTKEYS = 2; // 0 - no fix; 1 - basic fix; 2 - advanced fix
  188. // [0] no fix - not recommended
  189. // [1] basic fix - just fix the global focus detection variable
  190. // [2] advanced fix - call the shortcut actions directly, auto foucs change, direct control of spacebar behavior, etc
  191. // (note) 0 or 1 if you find conflict with other userscripts/plugin
  192.  
  193. const CHANGE_SPEEDMASTER_SPACEBAR_CONTROL = 0; // 0 - disable; 1 - force true; 2 - force false
  194. const USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER = true; // only for SPEEDMASTER = false & FIX_SHORTCUTKEYS = 2
  195.  
  196. const PROP_OverReInclusion_AVOID = true;
  197. const PROP_OverReInclusion_DEBUGLOG = false;
  198. const PROP_OverReInclusion_LIST = new Set([
  199. 'hostElement72',
  200. 'parentComponent72',
  201. 'localVisibilityObserver_72',
  202. 'cachedProviderNode_72',
  203. '__template72',
  204. '__templatizeOwner72',
  205. '__templateInfo72',
  206. '__dataHost72',
  207. '__CE_shadowRoot72',
  208. 'elements_72',
  209.  
  210. 'ky36',
  211. 'kz62',
  212. 'm822',
  213.  
  214.  
  215.  
  216. // To be reviewed.
  217.  
  218. // chat messages
  219. 'disabled', 'allowedProps',
  220. 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons', 'allowedProps',
  221.  
  222. 'dimension', 'loadTime', 'pendingPaint',
  223.  
  224. 'countdownDurationMs', 'countdownMs', 'lastCountdownTimeMs', 'rafId', 'playerProgressSec', 'detlaSincePausedSecs', 'behaviorActionMap', 'selected', 'maxLikeCount', 'maxReplyCount', 'isMouseOver',
  225.  
  226. 'respectLangDir', 'noEndpoints',
  227.  
  228.  
  229. 'objectURL',
  230. 'buttonOverrides', 'queuedMessages',
  231. 'STEP', 'BLOCK_ON', 'MIN_PROGESS', 'MAX_PROGESS',
  232. 'DISMISSED_CONTENT_KEYSPACE', 'followUpDialogPromise', 'followUpDialogPromiseResolve', 'followUpDialogPromiseReject',
  233. 'hoverJobId', 'JSC$14573_touched',
  234.  
  235.  
  236. // tbc
  237. 'toggleable', 'isConnected',
  238. 'scrollDistance', 'dragging', 'dragMouseStart', 'dragOffsetStart', 'containerWidthDiff',
  239. 'disableDeselectEvent',
  240. 'emojiSize',
  241.  
  242. 'buttonOverride',
  243. 'shouldUseStickyPreferences', 'longPressTimeoutId',
  244.  
  245. // others
  246. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  247. // 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons',
  248. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  249. // 'dimension', 'loadTime', 'pendingPaint',
  250. // 'disabled', 'allowedProps',
  251.  
  252.  
  253. // 'enableMssLazyLoad', 'popupContainerConfig', 'actionRouterNode', 'actionRouterIsRoot', 'actionMap', 'dynamicActionMap',
  254. // 'actionMap',
  255.  
  256. // 'sharedTooltipPosition', 'sharedTooltipAnimationDelay', 'disableEmojiPickerIncrementalLoading', 'useResolveCommand', 'activeRequest', 'popoutWindowCheckIntervalId', 'supportedTooltipTargets', 'closeActionPanelTimerId', 'delayCloseActionPanelTimerId', 'tooltipTimerIds', 'queuedTooltips', 'isPopupConfigReady', 'popoutWindow', 'actionMap',
  257.  
  258. 'clearTimeout',
  259. 'switchTemplateAtRegistration', 'hasUnmounted',
  260. 'switchTemplateAtRegistration', 'stopKeyboardEventPropagation',
  261. 'tangoConfiguration',
  262. 'itemIdToDockDurationMap',
  263. 'actionMap',
  264.  
  265. 'emojiManager', 'inputMethodEditorActive', 'suggestionIndex', 'JSC$10745_lastSuggestionRange',
  266. 'actionMap', 'asyncHandle', 'shouldAnimateIn', 'lastFrameTimestamp', 'scrollClampRaf',
  267. 'scrollRatePixelsPerSecond', 'scrollStartTime', 'scrollStopHandle'
  268.  
  269. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  270. // 'stopKeyboardEventPropagation', 'emojiSize',
  271. // 'switchTemplateAtRegistration', 'hasUnmounted',
  272. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  273. // 'isReusable', 'tangoConfiguration',
  274. // 'itemIdToDockDurationMap', 'bottomAlignMessages', 'actionMap',
  275. // */
  276.  
  277. ]);
  278.  
  279.  
  280. // const CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE = false; // NO USE; TO BE REVIEWED
  281.  
  282. // ----------------------------- Shortkey Keyboard Control -----------------------------
  283.  
  284. /*
  285. window.addEventListener('edm',()=>{
  286. let p = [...this.onerror.errorTokens][0].token; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  287. });
  288.  
  289. window.addEventListener('edn',()=>{
  290. let p = [...this.onerror.errorTokens][0].token+"X"; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  291. });
  292. window.addEventListener('edr',()=>{
  293. let p = '123'; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  294. });
  295. */
  296.  
  297. // only for macOS with Chrome/Firefox 100+
  298. const advanceLogging = typeof AbortSignal !== 'undefined' && typeof (AbortSignal || 0).timeout === 'function' && typeof navigator !== 'undefined' && /\b(Macintosh|Mac\s*OS)\b/i.test((navigator || 0).userAgent || '');
  299.  
  300. const win = this instanceof Window ? this : window;
  301.  
  302. // Create a unique key for the script and check if it is already running
  303. const hkey_script = 'jswylcojvzts';
  304. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  305. win[hkey_script] = true;
  306.  
  307.  
  308. const [setTimeoutX0, clearTimeoutX0] = [setTimeout, clearTimeout];
  309.  
  310. let BY_PASS_KEYBOARD_CONTROL = false;
  311.  
  312.  
  313. // const setImmediate = ((self || 0).jmt || 0).setImmediate;
  314. /** @type {(f: ()=>{})=>{}} */
  315. const nextBrowserTick = (self || 0).nextBrowserTick || 0;
  316. const nextBrowserTick_ = nextBrowserTick || (f => f());
  317.  
  318. let p59 = 0;
  319.  
  320. const Promise = (async () => { })().constructor;
  321.  
  322. const PromiseExternal = ((resolve_, reject_) => {
  323. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  324. return class PromiseExternal extends Promise {
  325. constructor(cb = h) {
  326. super(cb);
  327. if (cb === h) {
  328. /** @type {(value: any) => void} */
  329. this.resolve = resolve_;
  330. /** @type {(reason?: any) => void} */
  331. this.reject = reject_;
  332. }
  333. }
  334. };
  335. })();
  336.  
  337. /**
  338. @param {number} x
  339. @param {number} d */
  340. const toFixed2 = (x, d) => {
  341. let t = x.toFixed(d);
  342. let y = `${+t}`;
  343. return y.length > t.length ? t : y;
  344. }
  345.  
  346.  
  347. let pf31 = new PromiseExternal();
  348.  
  349. // native RAF
  350. let __requestAnimationFrame__ = typeof webkitRequestAnimationFrame === 'function' ? window.webkitRequestAnimationFrame.bind(window) : window.requestAnimationFrame.bind(window);
  351.  
  352. // 1st wrapped RAF
  353. const baseRAF = (callback) => {
  354. return p59 ? __requestAnimationFrame__(callback) : __requestAnimationFrame__((hRes) => {
  355. pf31.then(() => {
  356. callback(hRes);
  357. });
  358. });
  359. };
  360.  
  361. // 2nd wrapped RAF
  362. window.requestAnimationFrame = baseRAF;
  363.  
  364. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  365. const indr = o => insp(o).$ || o.$ || 0;
  366.  
  367. const prototypeInherit = (d, b) => {
  368. const m = Object.getOwnPropertyDescriptors(b);
  369. for (const p in m) {
  370. if (!Object.getOwnPropertyDescriptor(d, p)) {
  371. Object.defineProperty(d, p, m[p]);
  372. }
  373. }
  374. };
  375.  
  376.  
  377. const firstObjectKey = (obj) => {
  378. for (const key in obj) {
  379. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  380. }
  381. return null;
  382. };
  383.  
  384. function searchNestedObject(obj, predicate, maxDepth = 64) {
  385. // normal case: depth until 36
  386. const result = [];
  387. const visited = new WeakSet();
  388.  
  389. function search(obj, depth) {
  390. visited.add(obj);
  391. for (const [key, value] of Object.entries(obj)) {
  392. // Recursively search nested objects and arrays
  393. if (value !== null && typeof value === 'object') {
  394. // Prevent infinite loops by checking if the object is already visited or depth exceeded
  395. if (depth + 1 <= maxDepth && !visited.has(value)) {
  396. search(value, depth + 1);
  397. }
  398. } else if (predicate(value)) {
  399. result.push([obj, key]);
  400. }
  401. }
  402. }
  403.  
  404. typeof (obj || 0) === 'object' && search(obj, 0);
  405. return result;
  406. }
  407.  
  408. /** @type {(o: Object | null) => WeakRef | null} */
  409. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  410.  
  411. /** @type {(wr: Object | null) => Object | null} */
  412. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  413.  
  414. const isIterable = (obj) => (Symbol.iterator in Object_(obj));
  415.  
  416. if (typeof Document.prototype.requestStorageAccessFor === 'function') {
  417. if (DENY_requestStorageAccess) {
  418. // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccessFor
  419. Document.prototype.requestStorageAccessFor = undefined;
  420. console.log('[yt-js-engine-tamer]', 'requestStorageAccessFor is removed.');
  421. } else if (DISABLE_IFRAME_requestStorageAccess && window !== top) {
  422. Document.prototype.requestStorageAccessFor = function () {
  423. return new Promise((resolve, reject) => {
  424. reject();
  425. });
  426. };
  427. }
  428. }
  429.  
  430. const traceStack = (stack) => {
  431. let result = new Set();
  432. let p = new Set();
  433. let u = ''
  434. for (const s of stack.split('\n')) {
  435. if (s.split(':').length < 3) continue;
  436. let m = /(([\w-_\.]+):\d+:\d+)[^:\r\n]*/.exec(s);
  437. if (!m) continue;
  438. p.add(m[2]);
  439. if (p.size >= 3) break;
  440. if(!u) u = m[2];
  441. else if(p.size === 2 && u && u=== m[2]) break;
  442. result.add(s);
  443. }
  444. return [...result].join('\n');
  445. }
  446.  
  447. if (FIX_bind_self_this && !Function.prototype.bind488 && !Function.prototype.bind588) {
  448. // window.m3bb = new Set();
  449.  
  450. // const smb = Symbol();
  451. const vmb = 'dtz02' // Symbol(); // return kThis for thisArg
  452. const vmc = 'dtz04' // Symbol(); // whether it is proxied fn
  453. const vmd = 'dtz08' // Symbol(); // self fn proxy (fn--fn)
  454.  
  455. // const fnProxySelf = function (...args) {
  456. // if (args[0] === smb) return this;
  457. // const cnt = kRef(this.ref);
  458. // if (cnt) {
  459. // if (typeof cnt[this.prop] !== 'function') console.error(`this.${this.prop} is not a function. [${cnt.is || 'nil'}]`)
  460. // return cnt[this.prop](...args); // might throw error
  461. // }
  462. // }
  463. // fnProxySelf.bind588 = fnProxySelf.bind;
  464. // const pFnHandler = {
  465. // get(target, prop){
  466. // if(prop === 'bind588') return 2;
  467. // const fnThis = target(smb);
  468. // if (fnThis && fnThis.prop && fnThis.ref) {
  469. // const cnt = kRef(fnThis.ref || null) || null;
  470. // if (cnt) {
  471. // const h = cnt[fnThis.prop];
  472. // const v = h[prop];
  473. // if (typeof v === 'function'){
  474. // if(typeof h === 'function'){
  475. // if (prop === 'call' || prop === 'bind' || prop === 'bind588' || prop === 'bind488' || prop === 'apply') {
  476. // if(h.bind588 === 1){
  477. // const g = function(...args){
  478. // console.log(1288, this)
  479. // return h.call(this, ...args);
  480. // };
  481. // console.log(399, g)
  482. // return g[prop];
  483. // // console.log(12778)
  484. // // console.log(target, target.call)
  485. // // return target[prop];
  486. // }
  487. // // independent of this
  488. // return v; // function.bind, function.call, function.apply
  489. // }
  490. // }
  491. // console.warn('cnt[fnThis.prop][prop] is function; might rely on this', { prop, fProp: fnThis.prop, is: cnt.is, h: h });
  492. // // return new Proxy(fnProxySelf.bind588({ prop: prop, ref: new WeakRef(cnt[fnThis.prop]) }), pFnHandler);
  493. // }
  494. // return v;
  495. // }
  496. // }
  497. // },
  498. // set(target, prop, value) {
  499. // const fnThis = target(smb);
  500. // if (fnThis && fnThis.prop && fnThis.ref) {
  501. // const cnt = kRef(fnThis.ref || null) || null;
  502. // if (cnt) {
  503. // const h = cnt[fnThis.prop];
  504. // if (h) {
  505. // h[prop] = value;
  506. // } else {
  507. // console.log('h is nout found', { prop, fProp: fnThis.prop, is: cnt.is, h: h });
  508. // }
  509. // }
  510. // }
  511. // return true;
  512. // }
  513. // };
  514.  
  515. const thisConversionFn = (thisArg) => {
  516. if (!thisArg) return null;
  517. const kThis = thisArg[vmb];
  518. if (kThis) {
  519. const ref = kThis.ref;
  520. return (ref ? kRef(ref) : null) || null;
  521. }
  522. return thisArg;
  523. }
  524.  
  525. const pFnHandler2 = {
  526. get(target, prop) {
  527. if (prop === vmc) return target;
  528. return Reflect.get(target, prop);
  529. },
  530. apply(target, thisArg, argumentsList) {
  531. thisArg = thisConversionFn(thisArg);
  532. if (thisArg) return Reflect.apply(target, thisArg, argumentsList);
  533. }
  534. }
  535.  
  536. const proxySelfHandler = {
  537. get(target, prop) {
  538. if(prop === vmb) return target;
  539. const ref = target.ref;
  540. const cnt = kRef(ref);
  541. if (!cnt) return;
  542. if (typeof cnt[prop] === 'function' && !cnt[prop][vmc] && !cnt[prop][vmb]) {
  543. if (!cnt[prop][vmd]) cnt[prop][vmd] = new Proxy(cnt[prop], pFnHandler2);
  544. return cnt[prop][vmd];
  545. }
  546. return cnt[prop];
  547. },
  548. set(target, prop, value) {
  549. const cnt = kRef(target.ref);
  550. if (!cnt) return true;
  551. if(value && (value[vmc] || value[vmb])){
  552. cnt[prop] = value[vmc] || thisConversionFn(value);
  553. return true;
  554. }
  555. cnt[prop] = value;
  556. return true;
  557. }
  558. };
  559.  
  560. const weakWrap = (thisArg) => {
  561. thisArg = thisConversionFn(thisArg);
  562. if (!thisArg) {
  563. console.error('thisArg is not found');
  564. return null;
  565. }
  566. return new Proxy({ ref: mWeakRef(thisArg) }, proxySelfHandler);
  567. }
  568.  
  569. if (!window.getComputedStyle533 && typeof window.getComputedStyle === 'function') {
  570. window.getComputedStyle533 = window.getComputedStyle;
  571. window.getComputedStyle = function (a, ...args) {
  572. a = thisConversionFn(a);
  573. if (a) {
  574. return getComputedStyle533(a, ...args);
  575. }
  576. return null;
  577. }
  578. }
  579.  
  580. Function._count_bind_00 = 0;
  581. // Function._count_bind_01 = 0;
  582.  
  583. // let matchNativeCode = (Object+"");
  584. // let matchNativeCode1 = matchNativeCode.includes("[native code]");
  585. // let matchNativeLen = matchNativeCode.length - Object.name.length;
  586.  
  587. // const matchConstructor = (thisArg) => {
  588. // const f = `${(thisArg || 0).constructor}`;
  589. // if (f.length > 45) return true;
  590. // if (matchNativeCode1 && f.length - thisArg.constructor.name.length === matchNativeLen) {
  591. // if (f.includes('[native code]')){
  592. // return false;
  593. // }
  594. // return true;
  595. // }
  596. // return false;
  597. // }
  598.  
  599. // const acceptThis = (thisArg)=>{
  600. // // if(!thisArg || typeof thisArg !=='object') return false;
  601. // // // if((((thisArg||0).constructor||0).name || 'XXXXXXXX').length < 3) return true;
  602. // // if(typeof thisArg.path === 'string') return true;
  603. // // if(typeof thisArg.fn === 'function') return true;
  604. // // if(typeof thisArg.id === 'string') return true;
  605. // // if(typeof thisArg.isLoaded === 'boolean') return true;
  606. // return false;
  607. // }
  608.  
  609. const patchFn = (fn) => {
  610.  
  611. let s = `${fn}`;
  612. if (s.length < 11 || s.includes('\n')) return false;
  613. if(s.includes('bind(this')) return true;
  614. if(s.includes('=this') && /[,\s][a-zA-Z_][a-zA-Z0-9_]*=this[;,]/.test(s) ) return true;
  615. // var a=this;
  616. // f.bind(this)
  617.  
  618.  
  619. return false;
  620. }
  621.  
  622. Function.prototype.bind488 = Function.prototype.bind;
  623. Function.prototype.bind = function(thisArg, ...args){
  624. if (thisConversionFn(thisArg) !== thisArg) {
  625. return this.bind488(thisArg, ...args);
  626. }
  627. if( thisArg && patchFn(this) ){
  628.  
  629. // console.log(599,`${this}`)
  630.  
  631. try {
  632. // let b1 = thisArg && typeof thisArg === 'object' && typeof thisArg.isAttached === 'boolean' && !thisArg.dtz06; // ready cnt
  633. // let b2 = !b1 && thisArg && (thisArg instanceof Node) && typeof thisArg.nodeName === 'string' && !thisArg.dtz06; // dom
  634. // let b3 = !b1 && !b2 && thisArg && typeof thisArg === 'object' && typeof thisArg.is === 'string' && !thisArg.dtz06; // init stage ?
  635. // // let b4 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && matchConstructor(thisArg);
  636. // // let b5 = !b1 && !b2 && !b3 && !b4 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && acceptThis(thisArg);
  637. // // let b5 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && !(thisArg instanceof Window);
  638. // // let b4 = false;
  639. // let b4 = !b1 && !b2 && !b3 && thisArg && !thisArg.dtz06;
  640. // // b3 = false;
  641. // // b4 = false;
  642. // // b5 = false;
  643. // if (b1 || b2 || b3 ||b4 ) {
  644. const f = this;
  645. const ps = thisArg.__proxySelf0__ || (thisArg.__proxySelf0__ = weakWrap(thisArg));
  646. if (ps && ps[vmb]) {
  647. Function._count_bind_00++;
  648. return f.bind488(ps, ...args)
  649. }
  650. // }
  651. } catch (e) {
  652. console.warn(e)
  653. }
  654. }
  655. return this.bind488(thisArg, ...args);
  656. }
  657. Function.prototype.bind588 = 1;
  658. }
  659.  
  660.  
  661. if (FIX_weakMap_weakRef && !window.WeakMapOriginal && typeof window.WeakMap === 'function' && typeof WeakRef === 'function') {
  662. const WeakMapOriginal = window.WeakMapOriginal = window.WeakMap;
  663. const wm6 = new WeakMapOriginal();
  664.  
  665. const skipW = new WeakSet();
  666.  
  667.  
  668. window.WeakMap = class WeakMap extends WeakMapOriginal {
  669. constructor(iterable = undefined) {
  670. super();
  671. if (iterable && iterable[Symbol.iterator]) {
  672. for (const entry of iterable) {
  673. entry && this.set(entry[0], entry[1]);
  674. }
  675. }
  676. }
  677. delete(a) {
  678. if (!this.has(a)) return false;
  679. super.delete(a);
  680. return true;
  681. }
  682. get(a) {
  683. const p = super.get(a);
  684. if (p && typeof p === 'object' && p.deref && !skipW.has(p)) {
  685. let v = kRef(p);
  686. if (!v) {
  687. super.delete(a);
  688. }
  689. return v || undefined;
  690. }
  691. return p;
  692. }
  693. has(a) {
  694. if (!super.has(a)) return false;
  695. const p = super.get(a);
  696. if (p && typeof p === 'object' && p.deref && !skipW.has(p)) {
  697. if (!kRef(p)) {
  698. super.delete(a);
  699. return false;
  700. }
  701. }
  702. return true;
  703. }
  704. set(a, b) {
  705. let wq = b;
  706. if (b && (typeof b === 'function' || typeof b === 'object')) {
  707. if (b.deref) {
  708. skipW.add(b);
  709. wq = b;
  710. } else {
  711. wq = wm6.get(b);
  712. if (!wq) {
  713. wq = mWeakRef(b);
  714. wm6.set(b, wq);
  715. }
  716. }
  717. }
  718. super.set(a, wq);
  719. return this;
  720. }
  721. }
  722. Object.defineProperty(window.WeakMap, Symbol.toStringTag, {
  723. configurable: true,
  724. enumerable: false,
  725. value: "WeakMap",
  726. writable: false
  727. });
  728. }
  729.  
  730. const isWatchPageURL = (url) => {
  731. url = url || location;
  732. return location.pathname === '/watch' || location.pathname.startsWith('/live/')
  733. };
  734.  
  735. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  736.  
  737. const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
  738. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  739. if (typeof customElements === 'undefined') {
  740. if (!('__CE_registry' in document)) {
  741. // https://github.com/webcomponents/polyfills/
  742. Object.defineProperty(document, '__CE_registry', {
  743. get() {
  744. // return undefined
  745. },
  746. set(nv) {
  747. if (typeof nv == 'object') {
  748. delete this.__CE_registry;
  749. this.__CE_registry = nv;
  750. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  751. }
  752. return true;
  753. },
  754. enumerable: false,
  755. configurable: true
  756. })
  757. }
  758. let eventHandler = (evt) => {
  759. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  760. const f = callback;
  761. callback = null;
  762. eventHandler = null;
  763. f();
  764. };
  765. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  766. } else {
  767. callback();
  768. }
  769. });
  770.  
  771. const whenCEDefined = isCustomElementsProvided
  772. ? (nodeName) => customElements.whenDefined(nodeName)
  773. : (nodeName) => promiseForCustomYtElementsReady.then(() => customElements.whenDefined(nodeName));
  774.  
  775. FIX_perfNow && performance.timeOrigin > 9 && (() => {
  776. if (performance.now23 || performance.now16 || typeof Performance.prototype.now !== 'function') return;
  777. const f = performance.now23 = Performance.prototype.now;
  778.  
  779. let k = 0; // 0 <= k < 9998m
  780. let u = 0;
  781. let s = ((performance.timeOrigin % 7) + 1) / 7 - 1e-2 / 7; // s > 0.14
  782.  
  783. // By definition, performance.now() is mono increasing.
  784. // Fixing in YouTube.com is required to ensure performance.now() is strictly increasing.
  785. performance.now = performance.now16 = function () {
  786. /**
  787. * Bug 1842437 - When attempting to go back on youtube.com, the content remains the same
  788. *
  789. * If consecutive session history entries had history.state.entryTime set to same value,
  790. * back button doesn't work as expected. The entryTime value is coming from performance.now()
  791. * and modifying its return value slightly to make sure two close consecutive calls don't
  792. * get the same result helped with resolving the issue.
  793. */
  794. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  795. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1842437
  796.  
  797. const v = typeof (this || 0).now23 === 'function' ? this.now23() + s : f.call(performance) + s; // v > 0.14
  798. if (u + 0.0015 < (u = v)) k = 0; // note: hRes should be accurate to 5 µs in isolated contexts
  799. else if (k < 0.001428) k += 1e-6 / 7; // M = 10000 * m; m * 9996 = 0.001428
  800. else { // more than 9998 consecutive calls
  801. /**
  802. *
  803. * max no. of consecutive calls
  804. *
  805. * Sample Size: 4800
  806. * Sample Avg = 1565.375
  807. * Sample Median = 1469.5
  808. * Sample Max = 5660 << 7500 << 9999
  809. *
  810. *
  811. * */
  812. k = 0;
  813. s += 1 / 7;
  814. }
  815. return v + k; // 0 < v - M < v - M + k < v
  816. }
  817.  
  818. let loggerMsg = '';
  819. if (`${performance.now()}` === `${performance.now()}`) {
  820. const msg1 = 'performance.now is modified but performance.now() is not strictly increasing.';
  821. const msg2 = 'performance.now cannot be modified and performance.now() is not strictly increasing.';
  822. loggerMsg = performance.now !== performance.now16 ? msg1 : msg2; // might not able to set in Firefox
  823. }
  824. loggerMsg && console.warn(loggerMsg);
  825. })();
  826.  
  827. FIX_removeChild && (() => {
  828. if (typeof Node.prototype.removeChild === 'function' && typeof Node.prototype.removeChild062 !== 'function') {
  829. Node.prototype.removeChild062 = Node.prototype.removeChild;
  830. Node.prototype.removeChild = function (child) {
  831. if (typeof this.__shady_native_removeChild !== 'function' || ((child instanceof Node) && child.parentNode === this)) {
  832. this.removeChild062(child);
  833. } else if ((child instanceof Element) && child.is === 'tp-yt-paper-tooltip') {
  834. // tooltip bug
  835. } else {
  836. console.warn('[yt-js-engine-tamer] Node is not removed from parent', { parent: this, child: child })
  837. }
  838. return child;
  839. }
  840. }
  841. })();
  842.  
  843. FIX_DOM_IF_REPEAT && (() => {
  844. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  845. // DOM-IF is still a core class of Polymer, so no polymerController is available.
  846. // Be careful of the mixture of polymer functions and native Element functions
  847. // Be careful of the coding design is different with the modern Yt elements
  848.  
  849.  
  850. /*
  851.  
  852.  
  853. function Ks(a, b, c) {
  854. if (kj && !BOa(a))
  855. throw Error("strictTemplatePolicy: template owner not trusted");
  856. c = c || {};
  857. if (a.__templatizeOwner)
  858. throw Error("A <template> can only be templatized once");
  859. a.__templatizeOwner = b;
  860. var d = (b ? b.constructor : Js)._parseTemplate(a)
  861. , e = d.templatizeInstanceClass;
  862. e || (e = COa(a, d, c),
  863. d.templatizeInstanceClass = e);
  864. var g = BOa(a);
  865. EOa(a, d, c, g);
  866. c = function() {
  867. return e.apply(this, arguments) || this
  868. }
  869. ;
  870. h(c, e);
  871. c.prototype._methodHost = g;
  872. c.prototype.__dataHost = a;
  873. c.prototype.__templatizeOwner = b;
  874. c.prototype.__hostProps = d.hostProps;
  875. return c
  876. }
  877.  
  878. */
  879.  
  880. // Polymer.enqueueDebouncer
  881.  
  882. const s81 = Symbol();
  883. const s83 = Symbol();
  884. const s84 = Symbol();
  885. const s85 = Symbol();
  886. const s85b = Symbol();
  887. const s85c = Symbol();
  888.  
  889. let renderDebounceTs = null;
  890.  
  891. let renderDebouncePromise = null;
  892. let qp;
  893.  
  894. let cme = 0;
  895.  
  896. const shadyFlushMO = new MutationObserver(() => {
  897.  
  898. if (!renderDebounceTs) return;
  899.  
  900. if (renderDebounceTs.size > 0) {
  901. console.warn('renderDebounceTs.size is incorect', renderDebounceTs.size);
  902. try {
  903. Polymer.flush();
  904. return;
  905. } catch (e) { }
  906. }
  907.  
  908. renderDebouncePromise && Promise.resolve().then(() => {
  909.  
  910. if (renderDebouncePromise) {
  911. renderDebouncePromise && renderDebouncePromise.resolve();
  912. renderDebouncePromise = null;
  913. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by MutationObserver')
  914. }
  915.  
  916. });
  917.  
  918. // Polymer.flush
  919.  
  920. window.ShadyDOM && ShadyDOM.flush();
  921. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  922.  
  923.  
  924. });
  925.  
  926. if (FIX_DOM_IFREPEAT_RenderDebouncerChange) {
  927.  
  928. const observablePromise = (proc, timeoutPromise) => {
  929. let promise = null;
  930. return {
  931. obtain() {
  932. if (!promise) {
  933. promise = new Promise(resolve => {
  934. let mo = null;
  935. const f = () => {
  936. let t = proc();
  937. if (t) {
  938. mo.disconnect();
  939. mo.takeRecords();
  940. mo = null;
  941. resolve(t);
  942. }
  943. }
  944. mo = new MutationObserver(f);
  945. mo.observe(document, { subtree: true, childList: true })
  946. f();
  947. timeoutPromise && timeoutPromise.then(() => {
  948. resolve(null)
  949. });
  950. });
  951. }
  952. return promise
  953. }
  954. }
  955. }
  956.  
  957.  
  958. let p = 0;
  959. qp = observablePromise(() => {
  960. if (!(p & 1)) {
  961.  
  962. if (window.ShadyDOM && ShadyDOM.flush) {
  963. p |= 1;
  964. if (!ShadyDOM.flush847) {
  965.  
  966. ShadyDOM.flush847 = ShadyDOM.flush;
  967. ShadyDOM.flush = function () {
  968.  
  969. DEBUG_xx847 && console.log('xx847 ShadyDOM.flush')
  970. renderDebouncePromise && Promise.resolve().then(() => {
  971. if (renderDebouncePromise) {
  972.  
  973. renderDebouncePromise && renderDebouncePromise.resolve();
  974. renderDebouncePromise = null;
  975.  
  976. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by ShadyDOM.flush')
  977.  
  978. }
  979.  
  980. });
  981. let r = this.flush847(...arguments);
  982. if (r) {
  983. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  984. }
  985. return r
  986. }
  987.  
  988. }
  989. }
  990. }
  991.  
  992. if (!(p & 2)) {
  993.  
  994. if (window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush) {
  995. p |= 2;
  996. const ScopingShim = window.ShadyCSS && window.ShadyCSS.ScopingShim;
  997. if (!ScopingShim.flush848) {
  998.  
  999. ScopingShim.flush848 = ScopingShim.flush;
  1000. ScopingShim.flush = function () {
  1001.  
  1002. DEBUG_xx847 && console.log('xx847 ScopingShim.flush')
  1003.  
  1004. renderDebouncePromise && Promise.resolve().then(() => {
  1005.  
  1006. if (renderDebouncePromise) {
  1007.  
  1008. renderDebouncePromise && renderDebouncePromise.resolve();
  1009. renderDebouncePromise = null;
  1010.  
  1011. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by ScopingShim.flush')
  1012.  
  1013.  
  1014.  
  1015. }
  1016.  
  1017. });
  1018. return this.flush848(...arguments);
  1019. }
  1020.  
  1021. }
  1022. }
  1023. }
  1024. if (p === 3) {
  1025. p |= 8;
  1026.  
  1027. let r = (window.ShadyDOM && ShadyDOM.flush && ShadyDOM.flush847
  1028. && window.ShadyCSS && window.ShadyCSS.ScopingShim &&
  1029. window.ShadyCSS.ScopingShim.flush && window.ShadyCSS.ScopingShim.flush848);
  1030.  
  1031. if (r) {
  1032. let w = Set.prototype.add;
  1033. let u = null;
  1034. Set.prototype.add = function () {
  1035. u = this;
  1036. throw new Error();
  1037. }
  1038. try {
  1039. Polymer.enqueueDebouncer()
  1040. } catch (e) { }
  1041. Set.prototype.add = w;
  1042. if (u !== null) {
  1043. renderDebounceTs = u;
  1044. if (DEBUG_renderDebounceTs) {
  1045. renderDebounceTs.add58438 = renderDebounceTs.add;
  1046. renderDebounceTs.add = function () {
  1047. console.log('renderDebounceTs.add')
  1048. console.log(traceStack((new Error()).stack))
  1049. // debugger;
  1050. return this.add58438(...arguments)
  1051. }
  1052.  
  1053. renderDebounceTs.delete58438 = renderDebounceTs.delete;
  1054. renderDebounceTs.delete = function () {
  1055. console.log('renderDebounceTs.delete')
  1056. const stack = `${(new Error()).stack}`
  1057. let isCallbackRemoval = false;
  1058. if (stack) {
  1059. let t = stack.replace(/[^\r\n]+renderDebounceTs\.delete[^\r\n]+/, '').replace('://','');
  1060. const s = t.split(':');
  1061. if (s.length === 3 && +s[1] > 0 && +s[2] > 0) {
  1062. isCallbackRemoval = true;
  1063. }
  1064. }
  1065. if (isCallbackRemoval) {
  1066. return this.delete58438(...arguments)
  1067. }
  1068. console.log(traceStack((new Error()).stack))
  1069. // debugger;
  1070. return this.delete58438(...arguments)
  1071. }
  1072. }
  1073. DEBUG_renderDebounceTs && (window.renderDebounceTs = renderDebounceTs);
  1074. console.log('renderDebounceTs', renderDebounceTs, `debug=${DEBUG_renderDebounceTs}`);
  1075. }
  1076. }
  1077.  
  1078. return true;
  1079. }
  1080. })
  1081.  
  1082. // if(window.ShadyDOM && ShadyDOM.flush){
  1083. // console.log('FIX_DOM_IF_RenderDebouncerChange X1')
  1084.  
  1085. // }
  1086. // if(window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush){
  1087.  
  1088. // console.log('FIX_DOM_IF_RenderDebouncerChange X2')
  1089. // }
  1090.  
  1091. // console.log('FIX_DOM_IF_RenderDebouncerChange X3')
  1092.  
  1093. }
  1094.  
  1095. Object.defineProperty(Object.prototype, '_lastIf', {
  1096. get() {
  1097. return this[s81];
  1098. },
  1099. set(nv) {
  1100. if (nv === false && this.nodeName === "DOM-IF" && this.__renderDebouncer === null && this[s81] === undefined) {
  1101. // DOM-IF initialization
  1102. nv = null; // avoid (this.if == this._lastIf) primitive type conversion (object vs false)
  1103.  
  1104. this.__xiWB8__ = 2;
  1105.  
  1106. const cProto = this.__proto__;
  1107. if (cProto && !cProto.__xiWB7__) {
  1108. cProto.__xiWB7__ = 1;
  1109.  
  1110. // dom-if __template
  1111. // dom-repeat template
  1112. if (FIX_DOM_IF_TEMPLATE && !cProto.__template && !cProto.__template847) {
  1113. cProto.__template847 = true;
  1114. try {
  1115. // note: this is not "_template" in Polymer ( see POLYMER_COMPONENT_DEFINITION )
  1116. Object.defineProperty(cProto, '__template', {
  1117. get() {
  1118. const v = this[s84];
  1119. return (typeof (v || 0) === 'object' && v.deref) ? kRef(v) : v;
  1120. },
  1121. set(nv) {
  1122. if (typeof (nv || 0) === 'object' && !nv.deref) nv = mWeakRef(nv);
  1123. this[s84] = nv;
  1124. return true;
  1125. }
  1126. });
  1127. } catch (e) {
  1128. console.warn(e);
  1129. }
  1130.  
  1131. console.log('FIX_DOM_IF - __template')
  1132. }
  1133.  
  1134. // dom-if __ensureTemplate
  1135. // dom-repeat __ensureTemplatized
  1136. if (FIX_DOM_IF_TEMPLATE && !cProto.__ensureTemplate847 && typeof cProto.__ensureTemplate === 'function' && cProto.__ensureTemplate.length === 0 && this instanceof HTMLElement && `${cProto.__ensureTemplate}`.length > 20) {
  1137. // note that "_templateInfo" diffs the different version of DOM-IF
  1138.  
  1139. cProto.__ensureTemplate847 = cProto.__ensureTemplate;
  1140. cProto.__ensureTemplate = function () {
  1141. if (!(this instanceof HTMLElement) || arguments.length > 0) return this.__ensureTemplate847(...arguments);
  1142. if (!this.__template) {
  1143. let b;
  1144. if (this._templateInfo) {
  1145. b = this;
  1146. } else {
  1147. if (!this.__templateCollection011__) this.__templateCollection011__ = this.getElementsByTagName('template');
  1148. b = this.__templateCollection011__[0];
  1149. if (!b) {
  1150. let a = mWeakRef(this);
  1151. let c = new MutationObserver(function () {
  1152. if (!this.__templateCollection011__[0]) throw Error("dom-if requires a <template> child"); // to be reviewed
  1153. if (c && a) {
  1154. c.disconnect();
  1155. a = kRef(a);
  1156. a && a.__render();
  1157. a && (a.__templateCollection011__ = null);
  1158. }
  1159. c = null;
  1160. a = null;
  1161. });
  1162. c && c.observe(this, {
  1163. childList: !0
  1164. });
  1165. return !1
  1166. } else {
  1167. this.__templateCollection011__ = null;
  1168. }
  1169. }
  1170. this.__template = b
  1171. }
  1172. return !0
  1173. }
  1174.  
  1175. console.log('FIX_DOM_IF - __ensureTemplate')
  1176.  
  1177. }
  1178.  
  1179.  
  1180. // if(!cProto.__createAndInsertInstance847 && typeof cProto.__createAndInsertInstance === 'function' && cProto.__createAndInsertInstance.length === 1 && `${cProto.__createAndInsertInstance}`.length >20){
  1181.  
  1182. // cProto.__createAndInsertInstance847 = cProto.__createAndInsertInstance;
  1183.  
  1184. // cProto.__createAndInsertInstance = function (a) {
  1185. // Promise.resolve().then(()=>{
  1186. // console.log('__createAndInsertInstance')
  1187. // window.lm5 = window.lm5 || [];
  1188. // window.lm5.push([mWeakRef(this), mWeakRef(this.__instance)])
  1189. // });
  1190. // return this.__createAndInsertInstance847(a);
  1191. // }
  1192.  
  1193. // }
  1194.  
  1195.  
  1196. // if(!cProto._bindTemplate847 && typeof cProto._bindTemplate === 'function' && cProto._bindTemplate.length === 2){
  1197.  
  1198. // cProto._bindTemplate847 = cProto._bindTemplate;
  1199.  
  1200. // cProto._bindTemplate = function (a, b) {
  1201. // return this._bindTemplate847(kRef(a), b); // might throw Error as a -> null inside _bindTemplate847
  1202. // }
  1203.  
  1204. // }
  1205. // if(!cProto._stampTemplate847 && typeof cProto._stampTemplate === 'function' && cProto._stampTemplate.length === 2){
  1206.  
  1207. // cProto._stampTemplate847 = cProto._stampTemplate;
  1208.  
  1209. // cProto._stampTemplate = function (a, b) {
  1210. // return this._stampTemplate847(kRef(a), b); // might throw Error as a -> null inside _stampTemplate847
  1211. // }
  1212.  
  1213. // }
  1214. console.log('FIX_DOM_IF OK', Object.keys(cProto))
  1215. }
  1216.  
  1217.  
  1218. // need to fix __observeEffects
  1219. // this.__observeEffects.if[0].info.method === this.__debounceRender
  1220. const f = () => {
  1221.  
  1222. const __observeEffects = this.__observeEffects;
  1223.  
  1224. if (__observeEffects && __observeEffects.if && isIterable(__observeEffects.if)) {
  1225. for (const effect of __observeEffects.if) {
  1226. const info = effect.info;
  1227. if (info && typeof info.method === 'function') {
  1228.  
  1229. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  1230. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  1231. }
  1232.  
  1233. }
  1234. }
  1235. }
  1236.  
  1237.  
  1238. if (__observeEffects && __observeEffects.restamp && isIterable(__observeEffects.restamp)) {
  1239. for (const effect of __observeEffects.restamp) {
  1240. const info = effect.info;
  1241. if (info && typeof info.method === 'function') {
  1242.  
  1243. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  1244. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  1245. }
  1246.  
  1247. }
  1248. }
  1249. }
  1250.  
  1251. // console.log(5881, this.__observeEffects)
  1252. }
  1253. if (FIX_DOM_IFREPEAT_RenderDebouncerChange) {
  1254. f();
  1255. Promise.resolve().then(f);
  1256. // afterward, don't care adding fn directly (the fn is already modified)
  1257. }
  1258.  
  1259. }
  1260. this[s81] = nv;
  1261. return true;
  1262. }
  1263. });
  1264.  
  1265.  
  1266. Object.defineProperty(Object.prototype, '__renderDebouncer', {
  1267. get() {
  1268. return this[s85];
  1269. },
  1270. set(nv) {
  1271. if (nv === null && this[s85] === undefined) {
  1272. // DOM-IF / DOM-REPEAT initialization
  1273.  
  1274.  
  1275. const cProto = this.__proto__;
  1276. if (qp) {
  1277. qp.obtain();
  1278. qp = null;
  1279. shadyFlushMO.observe(document.documentElement, { attributes: ['nw3a24np'] });
  1280. }
  1281. if (FIX_DOM_IFREPEAT_RenderDebouncerChange && !cProto.__debounceRender847 && typeof cProto.__debounceRender === 'function' && !(`${cProto.__debounceRender}`.includes("{}"))) {
  1282.  
  1283. cProto.__debounceRender847 = cProto.__debounceRender;
  1284.  
  1285. if (cProto.__debounceRender.length === 2) {
  1286.  
  1287. cProto.__debounceRender = function (a, b) {
  1288.  
  1289. if (!renderDebounceTs) return this.__debounceRender847(a, b);
  1290.  
  1291. b = b === void 0 ? 0 : b;
  1292.  
  1293. /*
  1294. b = b === void 0 ? 0 : b;
  1295. this.__renderDebouncer = us(this.__renderDebouncer, b > 0 ? Rr.after(b) : Tr, a.bind(this));
  1296. vs(this.__renderDebouncer)
  1297. */
  1298.  
  1299. this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1300.  
  1301. if (!renderDebouncePromise) {
  1302. renderDebouncePromise = new PromiseExternal();
  1303. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1304. }
  1305.  
  1306. renderDebouncePromise.then(async () => {
  1307. if (b > 0) await delayPn(b);
  1308.  
  1309. const f = this.__dsIRYqw1__;
  1310. if (f === cme) return;
  1311. this.__dsIRYqw1__ = cme;
  1312. a.call(this);
  1313. DEBUG_DBR847 && console.log(`__DBR847__ done 01 (delay=${b})`, this.__DBR848__)
  1314.  
  1315. });
  1316.  
  1317. DEBUG_DBR847 && console.log(`__DBR847__ add 01 (delay=${b})`, this.__DBR848__)
  1318. }
  1319.  
  1320. } else if (cProto.__debounceRender.length === 0) {
  1321.  
  1322.  
  1323. cProto.__debounceRender = function () {
  1324.  
  1325. if (!renderDebounceTs) return this.__debounceRender847();
  1326.  
  1327. this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1328. /*
  1329. var a = this;
  1330. this.__renderDebouncer = us(this.__renderDebouncer, Tr, function() {
  1331. return a.__render()
  1332. });
  1333. vs(this.__renderDebouncer)
  1334. */
  1335.  
  1336. if (!renderDebouncePromise) {
  1337. renderDebouncePromise = new PromiseExternal();
  1338. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1339. }
  1340. renderDebouncePromise.then(() => {
  1341. const f = this.__dsIRYqw1__;
  1342. if (f === cme) return;
  1343. this.__dsIRYqw1__ = cme;
  1344. this.__render()
  1345. DEBUG_DBR847 && console.log('__DBR847__ done 02', this.__DBR848__)
  1346. });
  1347. DEBUG_DBR847 && console.log('__DBR847__ add 02', this.__DBR848__)
  1348.  
  1349.  
  1350. }
  1351. }
  1352. }
  1353.  
  1354.  
  1355.  
  1356. // if(FIX_DOM_IFREPEAT_RenderDebouncerChange && !cProto.render847 && typeof cProto.render === 'function' && cProto.render.length === 0 && !(`${cProto.render}`.includes("{}"))){
  1357. // cProto.render847 = cProto.render;
  1358. // cProto.render = function(){
  1359.  
  1360. // this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1361. // try{
  1362. // this.render847();
  1363. // }catch(e){}
  1364. // // if(this.__DBR847__){
  1365. // // this.__DBR847__.resolve();
  1366. // // DEBUG_DBR847 && console.log('__DBR847__ resolve', this.__DBR848__)
  1367. // // }
  1368.  
  1369. // // renderDebouncePromise && renderDebouncePromise.resolve()
  1370. // // renderDebouncePromise = null;
  1371. // // DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by render', this.__DBR848__)
  1372.  
  1373. // }
  1374. // console.log('FIX_DOM_IF - render', `${cProto.render847}`, cProto.render847)
  1375. // }
  1376.  
  1377. }
  1378. this[s85] = nv;
  1379. return true;
  1380. }
  1381. });
  1382.  
  1383. // PS-DOM-REPEAT
  1384.  
  1385. Object.defineProperty(Object.prototype, 'JSC$10034_renderDebouncer', {
  1386. get() {
  1387. return this[s85b];
  1388. },
  1389. set(nv) {
  1390.  
  1391. this[s85b] = nv;
  1392. return true;
  1393. }
  1394. })
  1395.  
  1396. Object.defineProperty(Object.prototype, 'JSC$10027_renderDebouncer', {
  1397. get() {
  1398. return this[s85c];
  1399. },
  1400. set(nv) {
  1401.  
  1402. this[s85c] = nv;
  1403. return true;
  1404. }
  1405. })
  1406.  
  1407.  
  1408. })();
  1409.  
  1410. // WEAKREF_ShadyDOM
  1411.  
  1412. MODIFY_ShadyDOM_OBJ && ((WeakRef) => {
  1413.  
  1414. const setupPlainShadyDOM = (b) => {
  1415. (OMIT_ShadyDOM_settings & 1) && (b.inUse === true) && (b.inUse = false);
  1416. (OMIT_ShadyDOM_settings & 2) && (b.handlesDynamicScoping === true) && (b.handlesDynamicScoping = false);
  1417. (OMIT_ShadyDOM_settings & 4) && (b.force === true) && (b.force = false);
  1418. b.patchOnDemand = true;
  1419. b.preferPerformance = true;
  1420. b.noPatch = true;
  1421. }
  1422.  
  1423. const isPlainObject = (b, m) => {
  1424. if (!b || typeof b !== 'object') return false;
  1425. const e = Object.getOwnPropertyDescriptors(b);
  1426. if (e.length <= m) return false;
  1427. let pr = 0;
  1428. for (const k in e) {
  1429. const d = e[k];
  1430. if (!d || d.get || d.set || !d.enumerable || !d.configurable) return false;
  1431. if (!('value' in d) || typeof d.value === 'function') return false;
  1432. pr++;
  1433. }
  1434. return pr > m;
  1435. }
  1436.  
  1437. let b;
  1438.  
  1439. let lz = 0;
  1440.  
  1441. const sdp = Object.getOwnPropertyDescriptor(window, 'ShadyDOM');
  1442. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable) {
  1443.  
  1444. // Brave - ShadyDOM exists before userscripting
  1445. b = sdp.value;
  1446.  
  1447. if (b && typeof b === 'object' && isPlainObject(b, 0)) {
  1448. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(b);
  1449. lz = 1;
  1450. }
  1451.  
  1452. }
  1453.  
  1454.  
  1455. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable && !sdp.get && !sdp.set) {
  1456. } else if (!sdp) {
  1457. } else {
  1458. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [ PropertyDescriptor issue ]', sdp);
  1459. return;
  1460. }
  1461.  
  1462. const shadyDOMNodeWRM = new WeakMap();
  1463.  
  1464. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 01 >>', b);
  1465.  
  1466. const weakWrapperNodeHandlerFn = () => ({
  1467. get() {
  1468. let w = shadyDOMNodeWRM.get(this);
  1469. if (typeof w === 'object') w = kRef(w) || (shadyDOMNodeWRM.delete(this), undefined);
  1470. return w;
  1471. },
  1472. set(nv) {
  1473. shadyDOMNodeWRM.set(this, mWeakRef(nv));
  1474. return true;
  1475. },
  1476. enumerable: true,
  1477. configurable: true
  1478. });
  1479.  
  1480. function weakWrapper(_ShadyDOM) {
  1481. const ShadyDOM = _ShadyDOM;
  1482. if (WEAKREF_ShadyDOM && lz < 3 && typeof WeakRef === 'function' && typeof ShadyDOM.Wrapper === 'function' && ShadyDOM.Wrapper.length === 1 && typeof (ShadyDOM.Wrapper.prototype || 0) === 'object') {
  1483. let nullElement = { node: null };
  1484. Object.setPrototypeOf(nullElement, Element.prototype);
  1485. let p = new ShadyDOM.Wrapper(nullElement);
  1486. let d = Object.getOwnPropertyDescriptor(p, 'node');
  1487. if (d.configurable && d.enumerable && !d.get && !d.set && d.writable && d.value === nullElement && !Object.getOwnPropertyDescriptor(ShadyDOM.Wrapper.prototype, 'node')) {
  1488. Object.defineProperty(ShadyDOM.Wrapper.prototype, 'node', weakWrapperNodeHandlerFn());
  1489. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << WEAKREF_ShadyDOM >>')
  1490. }
  1491. }
  1492. }
  1493.  
  1494. let previousWrapStore = null;
  1495.  
  1496. const standardWrap = function (a) {
  1497. if (a instanceof ShadowRoot || a instanceof ShadyDOM.Wrapper) return a;
  1498. if (previousWrapStore) {
  1499. const s = kRef(previousWrapStore.get(a)); // kRef for play safe only
  1500. if (s) {
  1501. previousWrapStore.delete(a);
  1502. shadyDOMNodeWRM.set(a, mWeakRef(s));
  1503. }
  1504. }
  1505. let u = kRef(shadyDOMNodeWRM.get(a));
  1506. if (!u) {
  1507. u = new ShadyDOM.Wrapper(a);
  1508. shadyDOMNodeWRM.set(a, mWeakRef(u));
  1509. }
  1510. return u;
  1511. }
  1512.  
  1513.  
  1514. function setupWrapFunc(_ShadyDOM) {
  1515. const ShadyDOM = _ShadyDOM;
  1516.  
  1517.  
  1518. const wmPD = Object.getOwnPropertyDescriptor(WeakMap.prototype, 'get');
  1519. if (!(wmPD && wmPD.writable && !wmPD.enumerable && wmPD.configurable && wmPD.value && !wmPD.get && !wmPD.set)) {
  1520. return;
  1521. }
  1522. let mm = new Set();
  1523. const pget = wmPD.value;
  1524. WeakMap.prototype.get = function (a) {
  1525. mm.add(this);
  1526. return a;
  1527. }
  1528. try {
  1529. let nullElement = { node: null };
  1530. Object.setPrototypeOf(nullElement, Element.prototype);
  1531. ShadyDOM.wrapIfNeeded(nullElement)
  1532. ShadyDOM.wrap(nullElement)
  1533. } catch (e) { }
  1534. WeakMap.prototype.get = pget;
  1535. if (mm.size !== 1) {
  1536. mm.clear();
  1537. return;
  1538. }
  1539. const p = mm.values().next().value;
  1540. if (!(p instanceof WeakMap)) return;
  1541. // p.clear();
  1542. // p.get = function (a) { return a }
  1543. // p.set = function (a, b) { return this }
  1544. // console.log(188, window.n2n = mm, window.n2p = p)
  1545.  
  1546. // console.log(34929,p.size)
  1547. previousWrapStore = p;
  1548.  
  1549. if (typeof ShadyDOM.wrap === 'function' && ShadyDOM.wrap.length === 1) {
  1550. ShadyDOM.wrap = function (a) { 0 && console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrap'); return standardWrap(a) }
  1551. }
  1552. if (typeof ShadyDOM.wrapIfNeeded === 'function' && ShadyDOM.wrapIfNeeded.length === 1) {
  1553. ShadyDOM.wrapIfNeeded = function (a) { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrapIfNeeded'); return standardWrap(a) }
  1554. }
  1555.  
  1556. }
  1557.  
  1558. function setupLZ3(nv) {
  1559.  
  1560. const ShadyDOM = nv;
  1561.  
  1562. const ShadyDOMSettings = ShadyDOM.settings;
  1563. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  1564. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  1565. return false;
  1566. }
  1567.  
  1568. weakWrapper(ShadyDOM);
  1569.  
  1570. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  1571.  
  1572. setupPlainShadyDOM(ShadyDOMSettings);
  1573. setupPlainShadyDOM(ShadyDOM);
  1574.  
  1575. ShadyDOM.isShadyRoot = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - isShadyRoot'); return false; }
  1576.  
  1577. setupWrapFunc(ShadyDOM);
  1578. ShadyDOM.patchElementProto = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patchElementProto') }
  1579. ShadyDOM.patch = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patch') }
  1580.  
  1581. // To be confirmed
  1582. if (OMIT_ShadyDOM_EXPERIMENTAL & 2) {
  1583. ShadyDOM.composedPath = function (e) {
  1584. const t = (e || 0).target || null;
  1585. if (!(t instanceof HTMLElement)) {
  1586. console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM&2) composedPath', t)
  1587. }
  1588. return t instanceof HTMLElement ? [t] : [];
  1589. };
  1590. }
  1591.  
  1592. }
  1593.  
  1594. }
  1595.  
  1596.  
  1597. function setupLZ6(nv) {
  1598.  
  1599. const ShadyDOM = nv;
  1600.  
  1601. const ShadyDOMSettings = ShadyDOM.settings;
  1602.  
  1603. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  1604. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  1605. return false;
  1606. }
  1607.  
  1608. weakWrapper(ShadyDOM);
  1609.  
  1610. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  1611.  
  1612. setupPlainShadyDOM(ShadyDOMSettings);
  1613. setupPlainShadyDOM(ShadyDOM);
  1614.  
  1615. setupWrapFunc(ShadyDOM);
  1616.  
  1617. }
  1618.  
  1619. }
  1620.  
  1621. if (b && typeof b.Wrapper === 'function' && typeof b.settings === 'object' && typeof b.wrap === 'function') {
  1622.  
  1623. const nv = b;
  1624.  
  1625. if (setupLZ6(nv) === false) return;
  1626.  
  1627. lz = 6;
  1628.  
  1629. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02b >>', nv)
  1630.  
  1631. return;
  1632. }
  1633.  
  1634. delete window.ShadyDOM;
  1635.  
  1636. Object.defineProperty(window, 'ShadyDOM', {
  1637. get() {
  1638. return b;
  1639. },
  1640. set(nv) {
  1641. let ret = 0;
  1642. try {
  1643. do {
  1644. if (!nv || !nv.settings) {
  1645. if (lz < 1 && nv && typeof nv === 'object' && isPlainObject(nv, 0)) {
  1646. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(nv);
  1647. lz = 1;
  1648. break;
  1649. } else {
  1650. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [nv:null]', nv);
  1651. break;
  1652. }
  1653. }
  1654.  
  1655. const sdp = Object.getOwnPropertyDescriptor(this || {}, 'ShadyDOM');
  1656. if (!(sdp && sdp.configurable && sdp.get && sdp.set)) {
  1657. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [ incorrect PropertyDescriptor ]', nv);
  1658. break;
  1659. }
  1660.  
  1661. if (setupLZ3(nv) === false) break;
  1662.  
  1663. lz = 3;
  1664.  
  1665. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02a >>', nv)
  1666.  
  1667. ret = 1;
  1668.  
  1669. } while (0);
  1670. } catch (e) {
  1671. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << ERROR >>', e)
  1672. }
  1673.  
  1674. if (!ret) b = nv;
  1675. else {
  1676. delete this.ShadyDOM;
  1677. this.ShadyDOM = nv;
  1678. }
  1679. return true;
  1680. },
  1681. enumerable: false,
  1682. configurable: true
  1683. });
  1684.  
  1685. })(typeof WeakRef !== 'undefined' ? WeakRef : function () { });
  1686.  
  1687. if (ENABLE_ASYNC_DISPATCHEVENT && nextBrowserTick) {
  1688. const filter = new Set([
  1689. 'yt-action',
  1690. // 'iframe-src-replaced',
  1691. 'shown-items-changed',
  1692. 'can-show-more-changed', 'collapsed-changed',
  1693.  
  1694. 'yt-navigate', 'yt-navigate-start', 'yt-navigate-cache',
  1695. 'yt-player-updated', 'yt-page-data-fetched', 'yt-page-type-changed', 'yt-page-data-updated',
  1696. 'yt-navigate-finish',
  1697.  
  1698. // 'data-changed','yt-watch-comments-ready'
  1699. ])
  1700. EventTarget.prototype.dispatchEvent938 = EventTarget.prototype.dispatchEvent;
  1701. EventTarget.prototype.dispatchEvent = function (event) {
  1702. const type = (event || 0).type;
  1703. if (typeof type === 'string' && event.isTrusted === false && (event instanceof CustomEvent) && event.cancelable === false) {
  1704. if (!filter.has(type) && !type.endsWith('-changed')) {
  1705. if (this instanceof Node || this instanceof Window) {
  1706. nextBrowserTick(() => this.dispatchEvent938(event));
  1707. return true;
  1708. }
  1709. }
  1710. }
  1711. return this.dispatchEvent938(event);
  1712. }
  1713. }
  1714.  
  1715. // avoid REGEXP testPattern execution in Brave's scriptlet for performance boost
  1716. SCRIPTLET_REMOVE_PRUNE_propNeedles && (() => {
  1717. // const xhr = new XMLHttpRequest;
  1718. const pdOri = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
  1719. if (!pdOri || pdOri.configurable !== true) return;
  1720. let propNeedles = null;
  1721. const pdNew = {
  1722. configurable: true,
  1723. enumerable: true,
  1724. get: function () {
  1725. propNeedles = this;
  1726. if (DEBUG_removePrune) debugger; // to locate Brave scriptlets
  1727. throw new Error();
  1728. }
  1729. }
  1730. Object.defineProperty(Map.prototype, 'size', pdNew);
  1731. try {
  1732. XMLHttpRequest.prototype.open.call(0);
  1733. // xhr.open.call(null)
  1734. } catch (e) { }
  1735. Object.defineProperty(Map.prototype, 'size', pdOri);
  1736. if (!propNeedles) return;
  1737. const entries = [...propNeedles.entries()];
  1738. propNeedles.clear();
  1739. console.log('[yt-js-engine-tamer] propNeedles is cleared from scriptlet', entries, propNeedles);
  1740. })();
  1741.  
  1742. if (FIX_XHR_REQUESTING) {
  1743.  
  1744. const URL = window.URL || new Function('return URL')();
  1745. const createObjectURL = URL.createObjectURL.bind(URL);
  1746.  
  1747. XMLHttpRequest = (() => {
  1748. const XMLHttpRequest_ = XMLHttpRequest;
  1749. if ('__xmMc8__' in XMLHttpRequest_.prototype) return XMLHttpRequest_;
  1750. const url0 = createObjectURL(new Blob([], { type: 'text/plain' }));
  1751. const c = class XMLHttpRequest extends XMLHttpRequest_ {
  1752. constructor(...args) {
  1753. super(...args);
  1754. }
  1755. open(method, url, ...args) {
  1756. let skip = false;
  1757. if (!url || typeof url !== 'string') skip = true;
  1758. else if (typeof url === 'string') {
  1759. let turl = url[0] === '/' ? `.youtube.com${url}` : `${url}`;
  1760. if (turl.includes('googleads') || turl.includes('doubleclick.net')) {
  1761. skip = true;
  1762. } else if (turl.includes('.youtube.com/pagead/')) {
  1763. skip = true;
  1764. } else if (turl.includes('.youtube.com/ptracking')) {
  1765. skip = true;
  1766. } else if (turl.includes('.youtube.com/youtubei/v1/log_event?')) {
  1767. skip = true;
  1768. } else if (turl.includes('.youtube.com/api/stats/')) { // /api/stats/
  1769. if (turl.includes('.youtube.com/api/stats/qoe?')) {
  1770. skip = true;
  1771. } else if (turl.includes('.youtube.com/api/stats/ads?')) {
  1772. skip = true;
  1773. } else {
  1774. // skip = true; // for user activity logging e.g. watched videos
  1775. }
  1776. } else if (turl.includes('play.google.com/log')) {
  1777. skip = true;
  1778. } else if (turl.includes('.youtube.com//?')) { // //?cpn=
  1779. skip = true;
  1780. }
  1781. }
  1782. if (!skip) {
  1783. this.__xmMc8__ = 1;
  1784. return super.open(method, url, ...args);
  1785. } else {
  1786. this.__xmMc8__ = 2;
  1787. return super.open('GET', url0);
  1788. }
  1789. }
  1790. send(...args) {
  1791. if (this.__xmMc8__ === 1) {
  1792. return super.send(...args);
  1793. } else if (this.__xmMc8__ === 2) {
  1794. return super.send();
  1795. } else {
  1796. console.log('[yt-js-engine-tamer]', 'xhr warning');
  1797. return super.send(...args);
  1798. }
  1799. }
  1800. }
  1801. c.prototype.__xmMc8__ = 0;
  1802. prototypeInherit(c.prototype, XMLHttpRequest_.prototype);
  1803. return c;
  1804. })();
  1805. }
  1806.  
  1807. // Alternative HACK -> Tabview Youtube
  1808. if (DISABLE_COOLDOWN_SCROLLING && typeof EventTarget.prototype.addEventListener52178 !== 'function' && typeof EventTarget.prototype.addEventListener === 'function') {
  1809.  
  1810. // ---- << this.overscrollConfig HACK >> -----
  1811.  
  1812. // 2024.04.19 - Playlist in Single Column Mode cannot be scrolled correctly.
  1813.  
  1814. /*
  1815.  
  1816. ;function gZb(a, b) {
  1817. b = void 0 === b ? !0 : b;
  1818. a.addEventListener("wheel", hZb);
  1819. a.overscrollConfig = {
  1820. cooldown: b
  1821. }
  1822. }
  1823. function iZb(a) {
  1824. a.overscrollConfig = void 0;
  1825. a.removeEventListener("wheel", hZb)
  1826. }
  1827. function hZb(a) {
  1828. var b = a.deltaY
  1829. , c = a.target
  1830. , d = null;
  1831. if (window.Polymer && window.Polymer.Element) {
  1832. if (c = a.path || a.composedPath && a.composedPath()) {
  1833. c = g(c);
  1834. for (var e = c.next(); !e.done && (e = e.value,
  1835. !jZb(e, b)); e = c.next())
  1836. if (e.overscrollConfig) {
  1837. d = e;
  1838. break
  1839. }
  1840. }
  1841. } else
  1842. for (; c && !jZb(c, b); ) {
  1843. if (c.overscrollConfig) {
  1844. d = c;
  1845. break
  1846. }
  1847. c = c.parentElement
  1848. }
  1849. d && (b = d.overscrollConfig,
  1850. b.cooldown ? (d = a.deltaY,
  1851. c = b.lastDeltaY || 0,
  1852. b.lastDeltaY = d,
  1853. e = b.lastStopped || 0,
  1854. c && e && 0 < c == 0 < d ? Math.abs(c) >= Math.abs(d) ? (d = e + 1200,
  1855. c = !1) : (d = e + 600,
  1856. c = !0) : (d = Date.now() + 600,
  1857. c = !0),
  1858. d > Date.now() && (a.preventDefault(),
  1859. c && (b.lastStopped = Date.now()))) : a.preventDefault())
  1860. }
  1861. */
  1862.  
  1863. let wheelHandler = function (a) {
  1864. if (window.Polymer && window.Polymer.Element) {
  1865. let c;
  1866. if (c = a.path || a.composedPath && a.composedPath()) {
  1867. for (const e of c) {
  1868. const cnt = insp(e);
  1869. if (e.overscrollConfig) e.overscrollConfig = void 0;
  1870. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  1871. }
  1872. }
  1873. } else {
  1874. let e = a.target;
  1875. for (; e instanceof Element; e = e.parentElement) {
  1876. const cnt = insp(e);
  1877. if (e.overscrollConfig) e.overscrollConfig = void 0;
  1878. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  1879. }
  1880. }
  1881. };
  1882.  
  1883. let checkWheelListenerObjs = null;
  1884.  
  1885. let getObjsFn = () => {
  1886. let euyVal = 0;
  1887. const eukElm = {};
  1888. Object.setPrototypeOf(eukElm, HTMLElement.prototype);
  1889. const euzObj = new Proxy(eukElm, {
  1890. get(target, prop) {
  1891. throw `ErrorF31.get(${prop})`
  1892. },
  1893. set(target, prop, value) {
  1894. throw `ErrorF33.set(${prop}, ${value})`
  1895. }
  1896. });
  1897. const euxElm = new Proxy(eukElm, {
  1898. get(target, prop) {
  1899. if (prop === 'scrollTop') {
  1900. euyVal = euyVal | 8;
  1901. return 0;
  1902. }
  1903. if (prop === 'overscrollConfig') {
  1904. euyVal = euyVal | 16;
  1905. return void 0;
  1906. }
  1907. if (prop === 'scrollHeight' || prop === 'clientHeight' || prop === 'offsetHeight') {
  1908. return 640;
  1909. }
  1910. if (prop === 'scrollLeft') {
  1911. euyVal = euyVal | 8;
  1912. return 0;
  1913. }
  1914. if (prop === 'scrollWidth' || prop === 'clientWidth' || prop === 'offsetWidth') {
  1915. return 800;
  1916. }
  1917. throw `ErrorF45.get(${prop})`
  1918. },
  1919. set(target, prop, value) {
  1920. throw `ErrorF47.set(${prop}, ${value})`
  1921. }
  1922. });
  1923. const eukEvt = {};
  1924. Object.setPrototypeOf(eukEvt, WheelEvent.prototype);
  1925. const euyEvt = new Proxy(eukEvt, {
  1926. get(target, prop) {
  1927. if (prop === 'deltaY' || prop === 'deltaX') {
  1928. euyVal = euyVal | 1;
  1929. return -999;
  1930. }
  1931. if (prop === 'target') {
  1932. euyVal = euyVal | 2;
  1933. return euxElm
  1934. }
  1935. if (prop === 'path' || prop === 'composedPath') {
  1936. euyVal = euyVal | 2;
  1937. return [euxElm]
  1938. }
  1939. throw `ErrorF51.get(${prop})`
  1940. },
  1941. set(target, prop, value) {
  1942. throw `ErrorF53.set(${prop}, ${value})`
  1943. }
  1944. });
  1945. const setVal = (v) => {
  1946. euyVal = v;
  1947. }
  1948. const getVal = () => {
  1949. return euyVal;
  1950. }
  1951. return { euzObj, euyEvt, setVal, getVal };
  1952. }
  1953.  
  1954. let checkWheelListener = (callback) => {
  1955.  
  1956. let callbackIdentifier = '';
  1957.  
  1958. let res = null;
  1959. try {
  1960. const { euzObj, euyEvt, getVal, setVal } = checkWheelListenerObjs || (checkWheelListenerObjs = getObjsFn());
  1961. setVal(0);
  1962. if (callback.call(euzObj, euyEvt) !== void 0) throw 'ErrorF99';
  1963. throw `RESULT${getVal()}`;
  1964. } catch (e) {
  1965. res = e;
  1966. }
  1967.  
  1968. res = `${res}` || `${null}`;
  1969. if (res.length > 20) res = `${res.substring(0, 20)}...`;
  1970.  
  1971. callbackIdentifier = res;
  1972. if (callbackIdentifier === 'RESULT27') 0;
  1973. else if (callbackIdentifier === 'RESULT0') {
  1974. // a.isSearch && !a.disableWheelScroll && B("desktop_enable_dmpanel_wheel_scroll")
  1975. } else if (callbackIdentifier.startsWith('RESULT')) {
  1976. console.log('wheel eventListener - RESULT', callbackIdentifier, callback)
  1977. }
  1978. return callbackIdentifier;
  1979.  
  1980. };
  1981.  
  1982. let callbackFound = false;
  1983. EventTarget.prototype.addEventListener52178 = EventTarget.prototype.addEventListener;
  1984. EventTarget.prototype.addEventListener = function (type, callback, option = void 0) {
  1985. // M-youtube-js-engine-tamer.52178
  1986. if (type === 'wheel' && !option && typeof callback === 'function' && callback.length === 1) {
  1987. // (( match with signature `a.addEventListener("wheel", hZb);` )) [subject to further review]
  1988. const callbackIdentifier = callback.yaujmoms || (callbackFound ? 'IGNORE' : (callback.yaujmoms = checkWheelListener(callback)));
  1989. // RESULTXX / ErrorFXX / Other...
  1990. if (callbackIdentifier === 'RESULT27') {
  1991. this.overscrollConfigDisable = true;
  1992. if (!callbackFound) {
  1993. callbackFound = true; // suppose only one function is assigned to overscrollConfig cooldown [no function binding]
  1994. getObjsFn = checkWheelListener = null;
  1995. checkWheelListenerObjs = null;
  1996. wheelHandler = null;
  1997. }
  1998. return void 0;
  1999. } else if (!callbackFound && !this.overscrollConfigDisable) {
  2000. this.overscrollConfigDisable = true;
  2001. this.addEventListener52178('wheel', wheelHandler, { passive: false });
  2002. }
  2003. }
  2004. return this.addEventListener52178(type, callback, option);
  2005. };
  2006.  
  2007. // ---- << this.overscrollConfig HACK >> -----
  2008.  
  2009. }
  2010.  
  2011. const { pageMediaWatcher, shortcutKeysFixer, keyboardController } = (() => {
  2012.  
  2013. let p_a_objWR = null;
  2014. let isSpaceKeyImmediate = false; // for ADVANCED_FIX_SHORTCUTKEYS
  2015. let ytPageReady = 0;
  2016.  
  2017. let isSpeedMastSpacebarControlEnabled = false; // youtube experimental feature // can be forced by CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  2018. let isGlobalSpaceControl = true;
  2019. let mediaPlayerElementWR = null;
  2020. let focusedElementAtSelection = null;
  2021.  
  2022. // let want_control_video = false;
  2023.  
  2024. let spaceBarControl_keyG = '';
  2025.  
  2026. let lastUserAction = 0;
  2027.  
  2028. const wmKeyControlPhase = new WeakMap();
  2029.  
  2030. let currentSelectionText = null;
  2031.  
  2032. const getCurrentSelectionText = () => {
  2033. if (currentSelectionText !== null) return currentSelectionText
  2034. return (currentSelectionText = `${getSelection()}`)
  2035. }
  2036.  
  2037. const pageMediaWatcher = () => {
  2038.  
  2039. // CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && document.addEventListener('wheel', () => {
  2040. // want_control_video = false;
  2041. // }, { capture: true, passive: true });
  2042.  
  2043. document.addEventListener('yt-navigate', () => {
  2044. ytPageReady = 0;
  2045. });
  2046. document.addEventListener('yt-navigate-start', () => {
  2047. ytPageReady = 0;
  2048. });
  2049. document.addEventListener('yt-navigate-cache', () => {
  2050. ytPageReady = 0;
  2051. });
  2052.  
  2053. document.addEventListener('yt-navigate-finish', () => {
  2054. ytPageReady = 1;
  2055. });
  2056.  
  2057. document.addEventListener('durationchange', () => {
  2058. for (const elm of document.querySelectorAll('#movie_player video[src], #movie_player audio[src]')) {
  2059. if (elm.duration > 0.01) {
  2060. if (elm.closest('[hidden]')) continue;
  2061. mediaPlayerElementWR = mWeakRef(elm);
  2062. return;
  2063. }
  2064. }
  2065. }, { capture: true, passive: true });
  2066.  
  2067. document.addEventListener('selectionchange', (evt) => {
  2068. if (!evt || !evt.isTrusted || !(evt instanceof Event)) return;
  2069. currentSelectionText = null;
  2070. if (!(evt.target instanceof Node)) return;
  2071. focusedElementAtSelection = evt.target;
  2072. }, { capture: true, passive: true })
  2073.  
  2074. document.addEventListener('pointerdown', (evt) => {
  2075. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2076. }, { capture: true, passive: true });
  2077.  
  2078.  
  2079. document.addEventListener('pointerup', (evt) => {
  2080. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2081. }, { capture: true, passive: true });
  2082.  
  2083.  
  2084. document.addEventListener('keydown', (evt) => {
  2085. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2086. }, { capture: true, passive: true });
  2087.  
  2088. document.addEventListener('keyup', (evt) => {
  2089. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2090. }, { capture: true, passive: true });
  2091.  
  2092. };
  2093.  
  2094.  
  2095. const checkKeyB = (p_a_obj) => {
  2096.  
  2097. const boolList = new Set();
  2098. const p_a_obj_api = p_a_obj.api;
  2099.  
  2100. const nilFunc0 = function () {
  2101. return void 0
  2102. };
  2103. const mt = new Proxy({}, {
  2104. get(target, prop) {
  2105. if (prop === 'get') return nilFunc0;
  2106. return mt;
  2107. }
  2108. });
  2109. const nilFunc = function () {
  2110. return mt
  2111. };
  2112. const mw = new Proxy({}, {
  2113. get(target, prop) {
  2114. if (prop in p_a_obj_api) {
  2115. if (typeof p_a_obj_api.constructor.prototype[prop] === 'function') return nilFunc;
  2116. let q = Object.getOwnPropertyDescriptor(p_a_obj_api, prop);
  2117. if (q && q.value) {
  2118. if (!q.writable) return q.value;
  2119. if (typeof q.value === 'string') return '';
  2120. if (typeof q.value === 'number') return 0;
  2121. if (typeof q.value === 'boolean') return false;
  2122. if (q.value && typeof q.value === 'object') return {};
  2123. }
  2124. }
  2125. return undefined;
  2126. },
  2127. set(target, prop) {
  2128. throw 'mwSet';
  2129. }
  2130. });
  2131.  
  2132. const mq = new Proxy({}, {
  2133. get(target, prop) {
  2134. if (prop === 'api') return mw;
  2135. if (prop in p_a_obj) {
  2136. if (typeof p_a_obj.constructor.prototype[prop] === 'function') return nilFunc;
  2137. let q = Object.getOwnPropertyDescriptor(p_a_obj, prop);
  2138. if (q && q.value) {
  2139. if (!q.writable) return q.value;
  2140. if (typeof q.value === 'string') return '';
  2141. if (typeof q.value === 'number') return 0;
  2142. if (typeof q.value === 'boolean') return false;
  2143. if (q.value && typeof q.value === 'object') return {};
  2144. }
  2145. }
  2146. return undefined;
  2147. },
  2148. set(target, prop, val) {
  2149. if (typeof val === 'boolean') boolList.add(prop)
  2150. throw `mqSet(${prop},${val})`;
  2151. }
  2152. });
  2153.  
  2154. let res = ''
  2155. try {
  2156. res = `RESULT::${p_a_obj.handleGlobalKeyUp.call(mq, 9, false, false, false, false, "Tab", "Tab")}`;
  2157. } catch (e) {
  2158. res = `ERROR::${e}`;
  2159. }
  2160.  
  2161. if (boolList.size === 1) {
  2162. const value = boolList.values().next().value;
  2163. if (res === `ERROR::mqSet(${value},${true})`) {
  2164. p_a_obj.__uZWaD__ = value;
  2165. }
  2166. }
  2167.  
  2168. console.log('[yt-js-engine-tamer] global shortcut control', { '__uZWaD__': p_a_obj.__uZWaD__ });
  2169.  
  2170. }
  2171.  
  2172.  
  2173. let pm_p_a = null;
  2174.  
  2175. const p_a_init = function () {
  2176. const r = this.init91();
  2177. const keyBw = this.__cPzfo__ || '__NIL__';
  2178. const p_a_obj = this[keyBw];
  2179. if (!p_a_obj) return;
  2180. try {
  2181. checkKeyB(p_a_obj);
  2182. } catch (e) { }
  2183. p_a_objWR = mWeakRef(p_a_obj);
  2184. if (FIX_SHORTCUTKEYS > 0) {
  2185. if (p_a_obj && !p_a_obj.hVhtg) {
  2186. p_a_obj.hVhtg = 1;
  2187.  
  2188. p_a_obj.handleGlobalKeyUp91 = p_a_obj.handleGlobalKeyUp;
  2189. p_a_obj.handleGlobalKeyUp = p_a_xt.handleGlobalKeyUp;
  2190. p_a_obj.handleGlobalKeyDown91 = p_a_obj.handleGlobalKeyDown;
  2191. p_a_obj.handleGlobalKeyDown = p_a_xt.handleGlobalKeyDown;
  2192. p_a_obj.__handleGlobalKeyBefore__ = p_a_xt.__handleGlobalKeyBefore__;
  2193. p_a_obj.__handleGlobalKeyAfter__ = p_a_xt.__handleGlobalKeyAfter__;
  2194.  
  2195. }
  2196. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && p_a_obj && p_a_obj.api && !p_a_obj.api.hVhtg) {
  2197. // const api = p_a_obj.api
  2198. // api.hVhtg = 1;
  2199. // api.playVideo91 = api.playVideo;
  2200. // api.playVideo = p_a_jt.playVideo;
  2201. // api.pauseVideo91 = api.pauseVideo;
  2202. // api.pauseVideo = p_a_jt.pauseVideo;
  2203. // }
  2204. }
  2205. if (pm_p_a) {
  2206. pm_p_a.resolve();
  2207. pm_p_a = null;
  2208. }
  2209. return r;
  2210. };
  2211.  
  2212. const p_a_xt = {
  2213.  
  2214. __handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) {
  2215.  
  2216. if (FIX_SHORTCUTKEYS === 2) {
  2217.  
  2218. // if (flagSpeedMaster !== false && !getGlobalSpacebarControlFlag()) return false;
  2219.  
  2220. if (activeElement) {
  2221.  
  2222. const controlPhaseCache = wmKeyControlPhase.get(activeElement);
  2223.  
  2224. if (controlPhaseCache === 6 && getCurrentSelectionText() !== "") void 0;
  2225. else if (controlPhaseCache === 1 || controlPhaseCache === 2 || controlPhaseCache === 5) return false;
  2226. else if ((controlPhaseCache !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return false;
  2227.  
  2228. }
  2229.  
  2230. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  2231. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  2232. // console.log(582, isDelayedSpaceBar)
  2233. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  2234.  
  2235. if (activeElement && (h === 'Space' || h === 'Enter')) {
  2236. const controlPhase = wmKeyControlPhase.get(activeElement);
  2237. if (controlPhase === 4 || controlPhase === 5) return false;
  2238. }
  2239. if (focusedElementAtSelection === activeElement && getCurrentSelectionText() !== "") return false;
  2240. // if (!isSpeedMastSpacebarControlEnabled && a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space') {
  2241. // if (!isSpaceKeyImmediate) return false;
  2242. // }
  2243. }
  2244.  
  2245. },
  2246.  
  2247. __handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret) {
  2248.  
  2249. if (FIX_SHORTCUTKEYS === 2 && ret && a >= 32 && ytPageReady === 1 && Date.now() - lastUserAction < 40 && activeElement === document.activeElement) {
  2250.  
  2251. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  2252. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  2253. // console.log(583, isDelayedSpaceBar)
  2254. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  2255.  
  2256. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2257.  
  2258. let mediaWorking = false;
  2259. if (mediaPlayerElement && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2 && mediaPlayerElement.duration > 0.01) {
  2260. mediaWorking = true;
  2261. } else if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2262. mediaWorking = true;
  2263. }
  2264. // console.log(182, mediaWorking, mediaPlayerElement.readyState , mediaPlayerElement.networkState)
  2265. mediaWorking && Promise.resolve().then(() => {
  2266. if (activeElement === document.activeElement) {
  2267. return activeElement.blur()
  2268. } else {
  2269. return false
  2270. }
  2271. }).then((r) => {
  2272. r !== false && mediaPlayerElement.focus();
  2273. });
  2274. }
  2275. },
  2276.  
  2277.  
  2278. handleGlobalKeyUp(a, b, c, d, e, f, h) {
  2279.  
  2280. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  2281.  
  2282. const activeElement = document.activeElement;
  2283.  
  2284. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  2285. if (allow === false) return false;
  2286.  
  2287. const ret = this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  2288. // console.log('handleGlobalKeyUp',ret, a, b, c, d, e, f, h);
  2289.  
  2290. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  2291.  
  2292. return ret;
  2293. },
  2294. handleGlobalKeyDown(a, b, c, d, e, f, h, l) {
  2295.  
  2296.  
  2297. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2298.  
  2299. const activeElement = document.activeElement;
  2300. // if (a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space' && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  2301. // return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2302. // }
  2303. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  2304. if (allow === false) return false;
  2305.  
  2306. const ret = this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2307. // console.log('handleGlobalKeyDown',ret, a, b, c, d, e, f, h,l)
  2308.  
  2309. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  2310.  
  2311. return ret;
  2312. }
  2313.  
  2314. };
  2315.  
  2316. // const p_a_jt = { // API
  2317.  
  2318. // playVideo(a) { // without spinner effect
  2319.  
  2320. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  2321.  
  2322. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2323. // if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2324. // want_control_video = true;
  2325. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  2326. // }
  2327.  
  2328. // }
  2329. // return this.playVideo91(a);
  2330.  
  2331. // },
  2332.  
  2333. // pauseVideo(a) { // without spinner effect
  2334.  
  2335. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  2336.  
  2337. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2338. // if (mediaPlayerElement && mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2339. // want_control_video = true;
  2340. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  2341. // }
  2342.  
  2343. // }
  2344. // return this.pauseVideo91(a);
  2345.  
  2346. // }
  2347. // };
  2348.  
  2349. let flagSpeedMaster = null;
  2350. const getSpeedMasterControlFlag = () => {
  2351.  
  2352. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  2353. isSpeedMastSpacebarControlEnabled = false;
  2354. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control) {
  2355. isSpeedMastSpacebarControlEnabled = true;
  2356. }
  2357. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control) {
  2358. isSpeedMastSpacebarControlEnabled = true;
  2359. }
  2360.  
  2361. if (flagSpeedMaster === null) {
  2362. const p = (((config || 0).WEB_PLAYER_CONTEXT_CONFIGS || 0).WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH || 0).serializedExperimentFlags;
  2363. if (!p) {
  2364. flagSpeedMaster = false;
  2365. } else {
  2366.  
  2367. flagSpeedMaster = (p.includes('web_enable_speedmaster=true') && p.includes('web_speedmaster_spacebar_control=true') && p.includes('web_speedmaster_updated_edu=true'));
  2368.  
  2369. }
  2370.  
  2371. }
  2372. if (!flagSpeedMaster) isSpeedMastSpacebarControlEnabled = false;
  2373.  
  2374. return isSpeedMastSpacebarControlEnabled;
  2375. }
  2376.  
  2377.  
  2378. const getGlobalSpacebarControlFlag = () => {
  2379.  
  2380. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  2381. isGlobalSpaceControl = false;
  2382. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.global_spacebar_pause) {
  2383. isGlobalSpaceControl = true;
  2384. }
  2385. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.global_spacebar_pause) {
  2386. isGlobalSpaceControl = true;
  2387. }
  2388.  
  2389. return isGlobalSpaceControl;
  2390. }
  2391.  
  2392. const keyboardController = async (_yt_player) => {
  2393.  
  2394. const keyQT = getQT(_yt_player);
  2395. const keySV = getSV(_yt_player);
  2396. const keyDX = getDX(_yt_player);
  2397. console.log(`[QT,SV,DX]`, [keyQT, keySV, keyDX]);
  2398.  
  2399. if (!keyDX) return;
  2400. if (keyDX === keyQT || keyDX === keySV) return;
  2401.  
  2402. if (typeof keyDX !== 'string') return;
  2403.  
  2404. let lastAccessKey = '';
  2405. let lastAccessKeyConfirmed = '';
  2406. const mb = new Proxy({}, {
  2407. get(target, prop) {
  2408. if (prop === 'handleGlobalKeyUp') lastAccessKeyConfirmed = lastAccessKey;
  2409. throw 'mbGet'
  2410. },
  2411. set(target, prop, val) {
  2412. throw 'mbSet'
  2413. }
  2414. });
  2415. const ma = new Proxy({}, {
  2416. get(target, prop) {
  2417. lastAccessKey = prop;
  2418. return mb
  2419. },
  2420. set(target, prop, val) {
  2421. throw 'maSet'
  2422. }
  2423. });
  2424.  
  2425. let keyBw = '';
  2426. try {
  2427. _yt_player[keyDX].prototype.handleGlobalKeyUp.call(ma);
  2428. } catch (e) {
  2429. if (e === 'mbGet' && typeof lastAccessKeyConfirmed === 'string' && lastAccessKeyConfirmed.length > 0) {
  2430. keyBw = lastAccessKeyConfirmed;
  2431. }
  2432. }
  2433.  
  2434. if (!keyBw) return;
  2435.  
  2436. if (typeof _yt_player[keyDX].prototype.init !== 'function' || _yt_player[keyDX].prototype.init.length !== 0) return;
  2437.  
  2438. pm_p_a = new PromiseExternal();
  2439.  
  2440. _yt_player[keyDX].prototype.__cPzfo__ = keyBw;
  2441.  
  2442. _yt_player[keyDX].prototype.init91 = _yt_player[keyDX].prototype.init;
  2443.  
  2444. _yt_player[keyDX].prototype.init = p_a_init;
  2445.  
  2446. await pm_p_a.then();
  2447. const p_a_obj = kRef(p_a_objWR);
  2448.  
  2449. const isSpeedMastSpacebarControlEnabledA = getSpeedMasterControlFlag();
  2450.  
  2451.  
  2452. if (CHANGE_SPEEDMASTER_SPACEBAR_CONTROL > 0) {
  2453.  
  2454. isSpeedMastSpacebarControlEnabled = CHANGE_SPEEDMASTER_SPACEBAR_CONTROL == 1;
  2455.  
  2456. if (!isSpeedMastSpacebarControlEnabled) {
  2457.  
  2458. if (config && config.EXPERIMENT_FLAGS) {
  2459. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = false;
  2460. }
  2461. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  2462. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = false;
  2463. }
  2464.  
  2465. } else {
  2466.  
  2467. if (config && config.EXPERIMENT_FLAGS) {
  2468. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = true;
  2469. }
  2470. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  2471. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = true;
  2472. }
  2473.  
  2474. }
  2475.  
  2476. }
  2477.  
  2478. const isSpeedMastSpacebarControlEnabledB = getSpeedMasterControlFlag();
  2479.  
  2480.  
  2481.  
  2482.  
  2483. console.log('[yt-js-engine-tamer] speedmaster by space (yt setting)', isSpeedMastSpacebarControlEnabledA, isSpeedMastSpacebarControlEnabledB);
  2484.  
  2485. // console.log(p_a_obj.handleGlobalKeyUp)
  2486. console.log('[yt-js-engine-tamer] p_a', p_a_obj);
  2487.  
  2488. // console.log(p_a_obj.api)
  2489.  
  2490.  
  2491. // QT -> DX(SV) -> p_a
  2492.  
  2493.  
  2494. /*
  2495. *
  2496. *
  2497. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  2498. b = void 0 === b ? !1 : b;
  2499. c = void 0 === c ? !1 : c;
  2500. d = void 0 === d ? !1 : d;
  2501. e = void 0 === e ? !1 : e;
  2502. var l = g.PT(this);
  2503. l && l.handleGlobalKeyUp(a, b, c, d, e, f, h)
  2504. }
  2505.  
  2506. */
  2507.  
  2508. /*
  2509. *
  2510. *
  2511. *
  2512. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  2513. return this.Bw ? this.Bw.handleGlobalKeyUp(a, b, c, d, e, f, h) : !1
  2514. }
  2515.  
  2516. */
  2517.  
  2518.  
  2519. // if(!keyDX) return;
  2520.  
  2521. // console.log(4999, keyDX)
  2522.  
  2523. };
  2524.  
  2525.  
  2526. const ytResumeFn = function () { // ADVANCED_FIX_SHORTCUTKEYS
  2527.  
  2528. const p_a_obj = kRef(p_a_objWR);
  2529. // const api = p_a_obj.api;
  2530.  
  2531.  
  2532. // console.log(540);
  2533.  
  2534. let boolList = null;
  2535. let ret;
  2536. isSpaceKeyImmediate = true;
  2537. try {
  2538.  
  2539. ret = 0;
  2540. ret = ret | (p_a_obj.handleGlobalKeyDown(32, false, false, false, false, ' ', 'Space', false) ? 1 : 0);
  2541. let p_a_objT;
  2542. if (!spaceBarControl_keyG) { // just in case
  2543. boolList = new Set();
  2544. p_a_objT = new Proxy(p_a_obj, {
  2545. get(target, prop, handler) {
  2546. const val = target[prop];
  2547. if (typeof val !== 'boolean') return val;
  2548. boolList.add(prop);
  2549. // console.log(555, prop, val);
  2550. if (typeof prop === 'string' && prop.length <= 3 && val === true && boolList.length === 1) {
  2551. spaceBarControl_keyG = prop;
  2552. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  2553. val = false;
  2554. }
  2555. return val;
  2556. }
  2557. });
  2558.  
  2559.  
  2560. } else if (p_a_obj[spaceBarControl_keyG] === true) {
  2561. p_a_obj[spaceBarControl_keyG] = false;
  2562. p_a_objT = p_a_obj;
  2563. // console.log(p_a_obj, spaceBarControl_keyG, p_a_obj[spaceBarControl_keyG] )
  2564. } else {
  2565.  
  2566. p_a_objT = p_a_obj;
  2567. }
  2568.  
  2569. ret = ret | (p_a_objT.handleGlobalKeyUp(32, false, false, false, false, ' ', 'Space') ? 2 : 0);
  2570.  
  2571.  
  2572. } catch (e) {
  2573. console.log(e)
  2574. }
  2575. isSpaceKeyImmediate = false;
  2576.  
  2577. if (boolList && boolList.size === 1) {
  2578. const value = boolList.values().next().value;
  2579. spaceBarControl_keyG = value;
  2580. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  2581.  
  2582. }
  2583.  
  2584. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  2585.  
  2586. return ret;
  2587. }
  2588.  
  2589. const shortcutKeysFixer = () => {
  2590.  
  2591. let pausePromiseControlJ = 0;
  2592.  
  2593.  
  2594. const obtainCurrentControlPhase = (evt, mediaPlayerElement) => {
  2595.  
  2596. let controlPhase = 0;
  2597. const aElm = document.activeElement;
  2598.  
  2599. if (aElm) {
  2600.  
  2601. const controlPhaseCache = wmKeyControlPhase.get(aElm);
  2602.  
  2603. if (typeof controlPhaseCache === 'number') {
  2604.  
  2605. controlPhase = controlPhaseCache;
  2606. } else {
  2607.  
  2608. if (aElm instanceof HTMLInputElement) controlPhase = 1;
  2609. else if (aElm instanceof HTMLTextAreaElement) controlPhase = 1;
  2610. else if (aElm instanceof HTMLButtonElement) controlPhase = 2;
  2611. else if (aElm instanceof HTMLIFrameElement) controlPhase = 2;
  2612. else if (aElm instanceof HTMLImageElement) controlPhase = 2;
  2613. else if (aElm instanceof HTMLEmbedElement) controlPhase = 2;
  2614. else {
  2615. if (aElm instanceof HTMLElement && aElm.closest('[role]')) controlPhase = 5;
  2616. if (aElm instanceof HTMLDivElement) controlPhase = 2;
  2617. else if (aElm instanceof HTMLAnchorElement) controlPhase = 2;
  2618. else if (!(aElm instanceof HTMLElement) && (aElm instanceof Element)) controlPhase = 2; // svg
  2619. }
  2620.  
  2621. if ((controlPhase === 2 || controlPhase === 5) && (aElm instanceof HTMLElement) && aElm.contains(mediaPlayerElement)) {
  2622. controlPhase = 0;
  2623. }
  2624.  
  2625. if ((controlPhase === 2 || controlPhase === 5) && evt && evt.target && evt.target === aElm) {
  2626. if (aElm.closest('[contenteditable], input, textarea')) {
  2627. controlPhase = 5;
  2628. } else if (aElm.closest('button')) {
  2629. controlPhase = 4;
  2630. }
  2631. }
  2632.  
  2633. if (aElm.closest('#movie_player')) controlPhase = 6;
  2634.  
  2635. wmKeyControlPhase.set(aElm, controlPhase);
  2636.  
  2637. }
  2638. }
  2639.  
  2640. return controlPhase;
  2641.  
  2642. }
  2643.  
  2644. const isStateControllable = (api) => {
  2645. let appState = null;
  2646. let playerState = null;
  2647. let adState = null;
  2648. try {
  2649. appState = api.getAppState();
  2650. playerState = api.getPlayerState();
  2651. adState = api.getAdState();
  2652. } catch (e) { }
  2653. // ignore playerState -1
  2654. return appState === 5 && adState === -1 && (playerState === 1 || playerState === 2 || playerState === 3);
  2655. };
  2656.  
  2657.  
  2658. const keyEventListener = (evt) => {
  2659. if (BY_PASS_KEYBOARD_CONTROL) return;
  2660.  
  2661. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2662. if (isSpaceKeyImmediate || !evt.isTrusted || !(evt instanceof KeyboardEvent)) return;
  2663. if (!ytPageReady) return;
  2664.  
  2665. if (evt.defaultPrevented === true) return;
  2666.  
  2667. const p_a_obj = kRef(p_a_objWR);
  2668.  
  2669. if (!p_a_obj) return;
  2670.  
  2671.  
  2672. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2673. if (!mediaPlayerElement) return;
  2674.  
  2675. // let focusBodyIfSuccess = false;
  2676.  
  2677. const controlPhase = obtainCurrentControlPhase(evt, mediaPlayerElement);
  2678.  
  2679. if (controlPhase === 6 && getCurrentSelectionText() !== "") void 0;
  2680. else if (controlPhase === 1 || controlPhase === 2 || controlPhase === 5) return;
  2681. else if ((controlPhase !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return;
  2682.  
  2683.  
  2684. if (evt.code === 'Space' && !getGlobalSpacebarControlFlag()) return;
  2685.  
  2686. // console.log(`${evt.type}::controlPhase`,controlPhase)
  2687.  
  2688. // if (controlPhase == 4) {
  2689. // focusBodyIfSuccess = true;
  2690. // }
  2691.  
  2692. spaceBarControl_keyG = spaceBarControl_keyG || p_a_obj.__uZWaD__ || ''
  2693. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  2694.  
  2695. if (FIX_SHORTCUTKEYS < 2) return;
  2696. if (!(!evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey)) return; // ignore if modifier key is pressed -> let other event listener to handle first
  2697.  
  2698. let rr;
  2699. const isSpaceBar = evt.code === 'Space' && !evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey;
  2700.  
  2701.  
  2702.  
  2703. let useImprovedPauseResume = false;
  2704.  
  2705. if (USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER && isSpaceBar && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  2706.  
  2707. const api = p_a_obj.api;
  2708. const stateControllable = isStateControllable(api);
  2709. // console.log(2122, appState, playerState, adState)
  2710.  
  2711. if (stateControllable && isWatchPageURL() && mediaPlayerElement.duration > 0.01 && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2) {
  2712.  
  2713. useImprovedPauseResume = true;
  2714.  
  2715. }
  2716.  
  2717.  
  2718. }
  2719.  
  2720.  
  2721. // force flag: CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  2722. if (evt.type === 'keydown') {
  2723.  
  2724. if (useImprovedPauseResume) {
  2725.  
  2726. const isPaused = mediaPlayerElement.paused;
  2727.  
  2728. const cj = ++pausePromiseControlJ;
  2729. Promise.resolve().then(() => {
  2730.  
  2731. if (cj !== pausePromiseControlJ) return;
  2732.  
  2733. if (mediaPlayerElement.paused !== isPaused) return;
  2734.  
  2735. const ret = ytResumeFn();
  2736. if (!ret) { // fallback
  2737. isPaused ? api.playVideo() : api.pauseVideo();
  2738. }
  2739.  
  2740. /*
  2741. let a = void 0;
  2742. console.log('Rb', api.Rb())
  2743. a = !window._yt_player.nL(api.Rb());
  2744. p_a_obj.Wd.kG(a)
  2745. a ? api.playVideo() : api.pauseVideo();
  2746.  
  2747. */
  2748.  
  2749.  
  2750. });
  2751. rr = true;
  2752. } else {
  2753.  
  2754. isSpaceKeyImmediate = true;
  2755. rr = p_a_obj.handleGlobalKeyDown(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code, evt.repeat);
  2756. isSpaceKeyImmediate = false;
  2757. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  2758.  
  2759. }
  2760.  
  2761.  
  2762. } else if (evt.type === 'keyup') {
  2763.  
  2764. if (isSpaceBar && useImprovedPauseResume && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  2765.  
  2766. rr = true;
  2767. } else {
  2768.  
  2769. isSpaceKeyImmediate = true;
  2770. rr = p_a_obj.handleGlobalKeyUp(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code);
  2771. isSpaceKeyImmediate = false;
  2772. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  2773.  
  2774. }
  2775.  
  2776.  
  2777. /*
  2778.  
  2779. if (d)
  2780. switch (c) {
  2781. case 32:
  2782. case 13:
  2783. if ("BUTTON" === d.tagName || "A" === d.tagName || "INPUT" === d.tagName)
  2784. b = !0,
  2785. e = !1;
  2786. else if (e) {
  2787. var m = d.getAttribute("role");
  2788. !m || "option" !== m && "button" !== m && 0 !== m.indexOf("menuitem") || (b = !0,
  2789. d.click(),
  2790. f = !0)
  2791. }
  2792. break;
  2793. case 37:
  2794. case 39:
  2795. case 36:
  2796. case 35:
  2797. b = "slider" === d.getAttribute("role");
  2798. break;
  2799. case 38:
  2800. case 40:
  2801. m = d.getAttribute("role"),
  2802. d = 38 === c ? d.previousSibling : d.nextSibling,
  2803. "slider" === m ? b = !0 : e && ("option" === m ? (d && "option" === d.getAttribute("role") && d.focus(),
  2804. f = b = !0) : m && 0 === m.indexOf("menuitem") && (d && d.hasAttribute("role") && 0 === d.getAttribute("role").indexOf("menuitem") && d.focus(),
  2805. f = b = !0))
  2806. }
  2807. if (e && !f)
  2808. switch (c) {
  2809. case 38:
  2810. f = Math.min(this.api.getVolume() + 5, 100);
  2811. XV(this.Wd, f, !1);
  2812. this.api.setVolume(f);
  2813. h = f = !0;
  2814. break;
  2815. case 40:
  2816. f = Math.max(this.api.getVolume() - 5, 0);
  2817. XV(this.Wd, f, !0);
  2818. this.api.setVolume(f);
  2819. h = f = !0;
  2820. break;
  2821. case 36:
  2822. this.api.Yh() && (this.api.startSeekCsiAction(),
  2823. this.api.seekTo(0, void 0, void 0, void 0, 79),
  2824. h = f = !0);
  2825. break;
  2826. case 35:
  2827. this.api.Yh() && (this.api.startSeekCsiAction(),
  2828. this.api.seekTo(Infinity, void 0, void 0, void 0, 80),
  2829. h = f = !0)
  2830. }
  2831. */
  2832.  
  2833. }
  2834.  
  2835.  
  2836. if (rr) {
  2837.  
  2838. // focusBodyIfSuccess && Promise.resolve().then(() => {
  2839. // activeElement === document.activeElement && activeElement.blur();
  2840. // });
  2841.  
  2842. evt.preventDefault();
  2843. evt.stopImmediatePropagation();
  2844. evt.stopPropagation();
  2845.  
  2846. }
  2847.  
  2848. };
  2849.  
  2850. document.addEventListener('keydown', keyEventListener, { capture: true });
  2851.  
  2852.  
  2853. document.addEventListener('keyup', keyEventListener, { capture: true });
  2854.  
  2855. }
  2856.  
  2857. return { pageMediaWatcher, shortcutKeysFixer, keyboardController };
  2858.  
  2859. })();
  2860.  
  2861.  
  2862. pageMediaWatcher();
  2863. FIX_SHORTCUTKEYS > 0 && shortcutKeysFixer();
  2864.  
  2865.  
  2866. const check_for_set_key_order = (() => {
  2867.  
  2868. let mySet = new Set();
  2869.  
  2870. mySet.add("value1");
  2871. mySet.add("value2");
  2872. mySet.add("value3");
  2873.  
  2874. // Function to convert Set values to an array
  2875. function getSetValues(set) {
  2876. return Array.from(set.values());
  2877. }
  2878.  
  2879. // Function to test if the Set maintains insertion order
  2880. function testSetOrder(set, expectedOrder) {
  2881. let values = getSetValues(set);
  2882. return expectedOrder.join(',') === values.join(',');
  2883. }
  2884.  
  2885. // Test 1: Initial order
  2886. if (mySet.values().next().value !== "value1") return false;
  2887. if (!testSetOrder(mySet, ["value1", "value2", "value3"])) return false;
  2888.  
  2889. // Test 2: After deleting an element
  2890. mySet.delete("value2");
  2891. if (mySet.values().next().value !== "value1") return false;
  2892. if (!testSetOrder(mySet, ["value1", "value3"])) return false;
  2893.  
  2894. // Test 3: After re-adding a deleted element
  2895. mySet.add("value2");
  2896. if (mySet.values().next().value !== "value1") return false;
  2897. if (!testSetOrder(mySet, ["value1", "value3", "value2"])) return false;
  2898.  
  2899. // Test 4: After adding a new element
  2900. mySet.add("value4");
  2901. if (mySet.values().next().value !== "value1") return false;
  2902. if (!testSetOrder(mySet, ["value1", "value3", "value2", "value4"])) return false;
  2903.  
  2904. // Test 5: Delete+Add
  2905. mySet.delete("value1");
  2906. mySet.delete("value3");
  2907. mySet.add("value3");
  2908. mySet.add("value1");
  2909. if (mySet.values().next().value !== "value2") return false;
  2910. if (!testSetOrder(mySet, ["value2", "value4", "value3", "value1"])) return false;
  2911.  
  2912. return true;
  2913. })();
  2914.  
  2915.  
  2916. // const qm47 = Symbol();
  2917. const qm57 = Symbol();
  2918. const qm53 = Symbol();
  2919. const qn53 = Symbol();
  2920.  
  2921.  
  2922. const ump3 = new WeakMap();
  2923.  
  2924. const stp = document.createElement('noscript');
  2925. stp.id = 'weakref-placeholder'
  2926.  
  2927.  
  2928. const handlerWFs = {};
  2929.  
  2930. const createHandlerWF = (z, usePlaceholder) => {
  2931.  
  2932. return {
  2933. get() {
  2934. const elm = this;
  2935. const wr = elm[z];
  2936. if (!wr) return null;
  2937. const m = kRef(wr);
  2938. if (!m && usePlaceholder) {
  2939. if (typeof usePlaceholder === 'function') usePlaceholder(elm);
  2940. return stp;
  2941. }
  2942. return m;
  2943. },
  2944. set(nv) {
  2945. const elm = this;
  2946. elm[z] = nv ? mWeakRef(nv) : null;
  2947. return true;
  2948. },
  2949. configurable: true,
  2950. enumerable: true
  2951.  
  2952. }
  2953. }
  2954.  
  2955. const setupWF = typeof WeakRef !== 'undefined' ? (elm, s, usePlaceholder) => {
  2956. const z = `${s}72`;
  2957. if (z in elm) return;
  2958. const pd = Object.getOwnPropertyDescriptor(elm, s);
  2959. if (pd && pd.configurable && !pd.get && !pd.set) {
  2960. const p = pd.value;
  2961. delete elm[s];
  2962. const handlerWF = handlerWFs[s] || (handlerWFs[s] = createHandlerWF(z, usePlaceholder));
  2963. Object.defineProperty(elm, s, handlerWF);
  2964. elm[s] = p;
  2965. elm = null;
  2966. }
  2967. } : null;
  2968.  
  2969. const mxMapPD = new WeakMap();
  2970.  
  2971. const identifierWD = Symbol();
  2972. const handlerWD = {
  2973. get(obj, prop) {
  2974. if (prop === identifierWD) return true;
  2975. const val = obj[prop];
  2976. if (typeof (val || 0).deref === 'function') {
  2977. return val.deref();
  2978. }
  2979. return val;
  2980. },
  2981. set(obj, prop, val) {
  2982. if (val instanceof Node) {
  2983. obj[prop] = mWeakRef(val);
  2984. } else {
  2985. obj[prop] = val;
  2986. }
  2987. return true;
  2988. }
  2989. };
  2990.  
  2991.  
  2992. const configureVisibilityObserverT_ = function () {
  2993. const hostElement = this.hostElement;
  2994. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  2995. this.unobserve_();
  2996. } else {
  2997. return this.configureVisibilityObserver27_();
  2998. }
  2999. };
  3000. const getParentRendererT = function () {
  3001. const hostElement = this.hostElement;
  3002. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  3003. return null;
  3004. } else {
  3005. return this.getParentRenderer27();
  3006. }
  3007. }
  3008.  
  3009. const attachedT = function () {
  3010. const hostElement = this.hostElement;
  3011. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  3012. if (this.isAttached === true) this.isAttached = false;
  3013. return void 0;
  3014. } else {
  3015. return this.attached27();
  3016. }
  3017. }
  3018.  
  3019. const hostElementCleanUp = (dh) => {
  3020. if (typeof dh.dispose === 'function') {
  3021. try {
  3022. if (dh.visibilityMonitor || dh.visibilityObserver) {
  3023. dh.dispose();
  3024. dh.visibilityMonitor = null;
  3025. dh.visibilityObserver = null;
  3026. }
  3027. } catch (e) { }
  3028. }
  3029. if (typeof dh.detached === 'function') {
  3030. try {
  3031. if (dh.visibilityObserverForChild_ || dh.localVisibilityObserver_) {
  3032. dh.detached();
  3033. dh.visibilityObserverForChild_ = null;
  3034. dh.localVisibilityObserver_ = null;
  3035. }
  3036. } catch (e) { }
  3037. }
  3038. };
  3039.  
  3040. const setupDataHost_ = (eh) => {
  3041. if (typeof eh.configureVisibilityObserver_ === 'function' && !eh.configureVisibilityObserver27_) {
  3042. eh.configureVisibilityObserver27_ = eh.configureVisibilityObserver_;
  3043. eh.configureVisibilityObserver_ = configureVisibilityObserverT_;
  3044. }
  3045. if (typeof eh.getParentRenderer === 'function' && !eh.getParentRenderer27) {
  3046. eh.getParentRenderer27 = eh.getParentRenderer;
  3047. eh.getParentRenderer = getParentRendererT;
  3048. }
  3049. if (typeof eh.attached === 'function' && !eh.attached27) {
  3050. eh.attached27 = eh.attached;
  3051. eh.attached = attachedT;
  3052. }
  3053. }
  3054.  
  3055. PROP_OverReInclusion_AVOID && (() => {
  3056.  
  3057.  
  3058. if (typeof HTMLElement.prototype.hasOwnProperty72 === 'function' || typeof HTMLElement.prototype.hasOwnProperty !== 'function') return;
  3059. const f = HTMLElement.prototype.hasOwnProperty72 = HTMLElement.prototype.hasOwnProperty;
  3060. let byPassVal = null;
  3061. let byPassCount = 0;
  3062. let mmw = new Set();
  3063. HTMLElement.prototype.hasOwnProperty = function (prop) {
  3064. if (arguments.length !== 1) return f.apply(this, arguments);
  3065. if (byPassVal !== null && typeof prop === 'string') {
  3066.  
  3067. if (PROP_OverReInclusion_LIST.has(prop)) {
  3068. byPassCount++;
  3069. return byPassVal;
  3070. }
  3071. PROP_OverReInclusion_DEBUGLOG && mmw.add(prop);
  3072.  
  3073. }
  3074. return this.hasOwnProperty72(prop);
  3075. };
  3076.  
  3077.  
  3078. /*
  3079. z.prototype.forwardDynamicProps = function() {
  3080. var B = m(this.inst);
  3081. B = h(B);
  3082. for (var F = B.next(); !F.done; F = B.next()) {
  3083. var H = h(F.value);
  3084. F = H.next().value;
  3085. H = H.next().value;
  3086. my(this, F, H);
  3087. r(b) && !ly(F) && Wua(this.inst, F)
  3088. }
  3089. }
  3090. */
  3091.  
  3092.  
  3093.  
  3094. let byPassZeroShowed = false;
  3095. const forwardDynamicPropsGeneral = function () {
  3096. byPassVal = true;
  3097. byPassCount = 0;
  3098. PROP_OverReInclusion_DEBUGLOG && mmw.clear();
  3099. const ret = this.forwardDynamicProps72();
  3100. byPassVal = null;
  3101. if (byPassCount === 0 && !byPassZeroShowed) {
  3102. byPassZeroShowed = true;
  3103. console.log('[yt-js-engine-tamer] byPassCount = 0 in forwardDynamicProps')
  3104. }
  3105. byPassCount = 0;
  3106. if (PROP_OverReInclusion_DEBUGLOG && mmw.size > 0) {
  3107. console.log(399, '[yt-js-engine-tamer]', [...mmw]);
  3108. mmw.clear();
  3109. }
  3110. return ret;
  3111. };
  3112.  
  3113. const propCheck = (proto) => {
  3114. if (typeof (proto || 0) == 'object' && typeof proto.forwardDynamicProps === 'function' && typeof proto.forwardDynamicProps72 !== 'function') {
  3115. proto.forwardDynamicProps72 = proto.forwardDynamicProps;
  3116. if (proto.forwardDynamicProps.length === 0) {
  3117. proto.forwardDynamicProps = forwardDynamicPropsGeneral;
  3118. }
  3119. }
  3120. };
  3121.  
  3122. const valMap = new WeakMap();
  3123. Object.defineProperty(HTMLElement.prototype, 'didForwardDynamicProps', {
  3124. get() {
  3125. propCheck(this.constructor.prototype);
  3126. return valMap.get(this);
  3127. },
  3128. set(nv) {
  3129. propCheck(this.constructor.prototype);
  3130. valMap.set(this, nv);
  3131. return true;
  3132. },
  3133. enumerable: false,
  3134. configurable: true
  3135.  
  3136. });
  3137.  
  3138. promiseForCustomYtElementsReady.then(() => {
  3139. if (typeof customElements !== 'object' || typeof customElements.define72 === 'function' || typeof customElements.define !== 'function') return;
  3140. if (customElements.define.length !== 2) return;
  3141. customElements.define72 = customElements.define;
  3142. customElements.define = function (b, w) {
  3143. propCheck(w.prototype);
  3144. const ret = this.define72(b, w);
  3145. return ret;
  3146. }
  3147. });
  3148.  
  3149. })();
  3150.  
  3151.  
  3152. const convertionFuncMap = new WeakMap();
  3153. let val_kevlar_should_maintain_stable_list = null;
  3154.  
  3155. const createStampDomArrayFn_ = (fn) => {
  3156. if (val_kevlar_should_maintain_stable_list === null) {
  3157. const config_ = ((window.yt || 0).config_ || 0);
  3158. val_kevlar_should_maintain_stable_list = ((config_ || 0).EXPERIMENT_FLAGS || 0).kevlar_should_maintain_stable_list === true
  3159. }
  3160. const gn = function (a, b, c, d, e, h) {
  3161. const isNonEmptyArray = (a || 0).length >= 1
  3162. if (!isNonEmptyArray) {
  3163. return fn.call(this, undefined, b, undefined, d);
  3164. } else if (h === undefined && typeof b === 'string' && c && typeof c === 'object' && this.is && val_kevlar_should_maintain_stable_list) {
  3165. if (c.clientSideToggleMenuItemRenderer) {
  3166. h = false;
  3167. } else {
  3168. h = true;
  3169. }
  3170. }
  3171. return fn.call(this, a, b, c, d, e, h)
  3172. }
  3173. gn.originalFn = fn;
  3174. convertionFuncMap.set(fn, gn);
  3175. return gn;
  3176. }
  3177.  
  3178. const fixStampDomArrayStableList = (h) => {
  3179. if (!h.stampDomArray_) return;
  3180. const proto = h.__proto__;
  3181. const f = proto.stampDomArray_;
  3182. if (!proto.stampDomArrayF001_ && typeof f === 'function' && f.length === 6) {
  3183. proto.stampDomArrayF001_ = 1;
  3184. proto.stampDomArray_ = convertionFuncMap.get(f) || createStampDomArrayFn_(f);
  3185. }
  3186. }
  3187.  
  3188. const weakenStampReferences = (() => {
  3189.  
  3190. const DEBUG_STAMP = false;
  3191.  
  3192. const s1 = Symbol();
  3193. const handler1 = {
  3194. get(target, prop, receiver) {
  3195. if (prop === 'object') {
  3196. return kRef(target[s1]); // avoid memory leakage
  3197. }
  3198. if (prop === '__proxy312__') return 1;
  3199. return target[prop];
  3200. }
  3201. };
  3202. const handler2 = {
  3203. get(target, prop, receiver) {
  3204. if (prop === 'indexSplices') {
  3205. return kRef(target[s1]); // avoid memory leakage
  3206. }
  3207. if (prop === '__proxy312__') return 1;
  3208. return target[prop];
  3209. }
  3210. }
  3211. return (h) => {
  3212.  
  3213. if (h.rendererStamperApplyChangeRecord_ || h.stampDomArraySplices_) {
  3214. const proto = h.__proto__;
  3215. if (!proto.yzxer && (proto.rendererStamperApplyChangeRecord_ || proto.stampDomArraySplices_)) {
  3216. proto.yzxer = 1;
  3217.  
  3218. const list = [
  3219. // "rendererStamperObserver_", // 3 ==> rendererStamperApplyChangeRecord_
  3220. "rendererStamperApplyChangeRecord_", // 3
  3221. "forwardRendererStamperChanges_", // 3
  3222. "stampDomArraySplices_", // 3
  3223. "stampDomArray_", // 6
  3224. "deferRenderStamperBinding_", // 3
  3225. ];
  3226. for (const key of list) {
  3227. const pey = `${key}$wq0iw_`;
  3228. const vKey = proto[key];
  3229. if (typeof vKey !== 'function') continue;
  3230. if (proto[pey] || vKey.length === 0) continue;
  3231.  
  3232. if (key === 'stampDomArraySplices_' && vKey.length === 3) {
  3233. proto[pey] = vKey;
  3234. proto[key] = function (a, b, c) {
  3235.  
  3236. if (typeof a === 'string' && typeof b === 'string' && typeof c === 'object' && c && c.indexSplices && c.indexSplices.length >= 1 && !c.indexSplices.rzgjr) {
  3237.  
  3238. c.indexSplices = c.indexSplices.map(e => {
  3239. if (e.__proxy312__) return e;
  3240. e[s1] = mWeakRef(e.object);
  3241. e.object = null;
  3242. return new Proxy(e, handler1);
  3243. });
  3244. c.indexSplices.rzgjr = 1;
  3245.  
  3246. c[s1] = mWeakRef(c.indexSplices);
  3247. c.indexSplices = null;
  3248. c = new Proxy(c, handler2)
  3249. arguments[2] = c;
  3250.  
  3251. }
  3252. // console.log(key, arguments.length, [...arguments]);
  3253. return proto[pey].call(this, a, b, c);
  3254. }
  3255.  
  3256. } else if (key === 'rendererStamperApplyChangeRecord_' && vKey.length === 3) {
  3257.  
  3258. // Nil
  3259.  
  3260. } else if (DEBUG_STAMP) {
  3261.  
  3262. console.log(proto.isRenderer_, 'ms_' + key, vKey.length, h.is)
  3263. proto[pey] = vKey;
  3264. proto[key] = function () {
  3265. if (key === 'rendererStamperApplyChangeRecord_' && typeof arguments[3] === 'object') {
  3266. console.log(key, arguments.length, { value: arguments[3].value, base: arguments[3].base, })
  3267. }
  3268. console.log(key, arguments.length, [...arguments]);
  3269. return proto[pey].apply(this, arguments);
  3270. }
  3271.  
  3272. }
  3273.  
  3274. }
  3275.  
  3276.  
  3277. // const m = (Object.mkss = Object.mkss || new Set());
  3278. // Object.keys(h.__proto__).filter(e => e.toLowerCase().includes('stamp') && typeof h[e] === 'function').forEach(e => m.add(e))
  3279. // console.log([...m])
  3280. }
  3281. }
  3282.  
  3283. }
  3284. })();
  3285.  
  3286. const setupDiscreteTasks = (h, rb) => {
  3287.  
  3288. if (rb) {
  3289. if (h.ky36) return;
  3290. }
  3291.  
  3292.  
  3293. if (typeof h.onYtRendererstamperFinished === 'function' && !(h.onYtRendererstamperFinished.km34)) {
  3294. const f = h.onYtRendererstamperFinished;
  3295. const g = ump3.get(f) || function () {
  3296. if (this.updateChildVisibilityProperties && !this.markDirty) {
  3297. return f.apply(this, arguments);
  3298. }
  3299. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3300. }
  3301. ump3.set(f, g);
  3302. g.km34 = 1;
  3303. h.onYtRendererstamperFinished = g;
  3304.  
  3305. }
  3306.  
  3307. if (typeof h.onYtUpdateDescriptionAction === 'function' && !(h.onYtUpdateDescriptionAction.km34)) {
  3308. const f = h.onYtUpdateDescriptionAction;
  3309. const g = ump3.get(f) || function (a) {
  3310. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3311. }
  3312. ump3.set(f, g);
  3313. g.km34 = 1;
  3314. h.onYtUpdateDescriptionAction = g;
  3315.  
  3316. }
  3317.  
  3318. if (typeof h.handleUpdateDescriptionAction === 'function' && !(h.handleUpdateDescriptionAction.km34)) {
  3319. const f = h.handleUpdateDescriptionAction;
  3320. const g = ump3.get(f) || function (a) {
  3321. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3322. }
  3323. ump3.set(f, g);
  3324. g.km34 = 1;
  3325. h.handleUpdateDescriptionAction = g;
  3326.  
  3327. }
  3328.  
  3329. if (typeof h.handleUpdateLiveChatPollAction === 'function' && !(h.handleUpdateLiveChatPollAction.km34)) {
  3330. const f = h.handleUpdateLiveChatPollAction;
  3331. const g = ump3.get(f) || function (a) {
  3332. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3333. }
  3334. ump3.set(f, g);
  3335. g.km34 = 1;
  3336. h.handleUpdateLiveChatPollAction = g;
  3337.  
  3338. }
  3339.  
  3340. if (typeof h.onTextChanged === 'function' && !(h.onTextChanged.km34)) {
  3341. const f = h.onTextChanged;
  3342. const g = ump3.get(f) || function () {
  3343. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3344. }
  3345. ump3.set(f, g);
  3346. g.km34 = 1;
  3347. h.onTextChanged = g;
  3348.  
  3349. }
  3350.  
  3351. if (typeof h.onVideoDataChange === 'function' && !(h.onVideoDataChange.km34)) {
  3352. const f = h.onVideoDataChange;
  3353. const g = ump3.get(f) || function (a) {
  3354. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3355. }
  3356. ump3.set(f, g);
  3357. g.km34 = 1;
  3358. h.onVideoDataChange = g;
  3359.  
  3360. }
  3361.  
  3362. if (typeof h.onVideoDataChange_ === 'function' && !(h.onVideoDataChange_.km34)) {
  3363. const f = h.onVideoDataChange_;
  3364. const g = ump3.get(f) || function () {
  3365. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3366. }
  3367. ump3.set(f, g);
  3368. g.km34 = 1;
  3369. h.onVideoDataChange_ = g;
  3370.  
  3371. }
  3372.  
  3373. /*
  3374. // affect chat message icon tooltips
  3375. if (typeof h.addTooltips === 'function' && !(h.addTooltips.km34)) {
  3376.  
  3377. const f = h.addTooltips;
  3378. const g = ump3.get(f) || function () {
  3379. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3380. }
  3381. ump3.set(f, g);
  3382. g.km34 = 1;
  3383. h.addTooltips = g;
  3384.  
  3385. }
  3386. */
  3387. /*
  3388. if (typeof h.onMouseOver_ === 'function' && !(h.onMouseOver_.km34) && typeof h.createTooltipIfRequired_ === 'function') {
  3389. console.log(212, h.is);
  3390. const f = h.onMouseOver_;
  3391. const g = ump3.get(f) || function () {
  3392. if (!this.__mEZ__) {
  3393. const w = document.createElement;
  3394. let EU = null;
  3395. document.createElement = function () {
  3396. let r = w.apply(this, arguments);
  3397. EU = r;
  3398. return r;
  3399. };
  3400. let done = false;
  3401. try {
  3402. this.polymerController.createTooltipIfRequired_();
  3403. done = true;
  3404. } catch (e) {
  3405. }
  3406. if (!done) {
  3407. try {
  3408. this.createTooltipIfRequired_();
  3409. done = true;
  3410. } catch (e) {
  3411. }
  3412. }
  3413. this.__mEZ__ = EU;
  3414. document.createElement = w;
  3415. }
  3416. if(this.__mEZ__){
  3417. this.__mEZ__.remove();
  3418. // this.__mEZ__.for = null;
  3419. [...this.__mEZ__.querySelectorAll('.hidden')].forEach(e=>e.classList.remove('hidden'))
  3420. }
  3421. console.log(212,this, this.is, this.__mEZ__)
  3422. return f.apply(this, arguments)
  3423. }
  3424. ump3.set(f, g);
  3425. g.km34 = 1;
  3426. h.onMouseOver_ = g;
  3427. }
  3428. */
  3429.  
  3430.  
  3431. if (typeof h.addTooltips_ === 'function' && !(h.addTooltips_.km34)) {
  3432.  
  3433. const f = h.addTooltips_;
  3434. const g = ump3.get(f) || function () {
  3435. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3436. }
  3437. ump3.set(f, g);
  3438. g.km34 = 1;
  3439. h.addTooltips_ = g;
  3440.  
  3441. }
  3442.  
  3443. if (typeof h.updateRenderedElements === 'function' && !(h.updateRenderedElements.km34)) {
  3444.  
  3445. const f = h.updateRenderedElements;
  3446. const g = ump3.get(f) || function () {
  3447. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3448. }
  3449. ump3.set(f, g);
  3450. g.km34 = 1;
  3451. h.updateRenderedElements = g;
  3452.  
  3453. }
  3454.  
  3455. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.loadPage_ === 'function' && !(h.loadPage_.km34)) {
  3456. const f = h.loadPage_;
  3457. const g = ump3.get(f) || function (a) {
  3458. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3459. }
  3460. ump3.set(f, g);
  3461. g.km34 = 1;
  3462. h.loadPage_ = g;
  3463.  
  3464. }
  3465. // updatePageData_ : possible conflict with Omit ShadyDOM
  3466. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.updatePageData_ === 'function' && !(h.updatePageData_.km34)) {
  3467. const f = h.updatePageData_;
  3468. const g = ump3.get(f) || function (a) {
  3469. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3470. }
  3471. ump3.set(f, g);
  3472. g.km34 = 1;
  3473. h.updatePageData_ = g;
  3474.  
  3475. }
  3476.  
  3477.  
  3478. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onFocus_ === 'function' && !(h.onFocus_.km34)) {
  3479.  
  3480. const f = h.onFocus_;
  3481. const g = ump3.get(f) || function () {
  3482. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3483. }
  3484. ump3.set(f, g);
  3485. g.km34 = 1;
  3486. h.onFocus_ = g;
  3487.  
  3488. }
  3489.  
  3490. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onBlur_ === 'function' && !(h.onBlur_.km34)) {
  3491.  
  3492. const f = h.onBlur_;
  3493. const g = ump3.get(f) || function () {
  3494. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3495. }
  3496. ump3.set(f, g);
  3497. g.km34 = 1;
  3498. h.onBlur_ = g;
  3499.  
  3500. }
  3501.  
  3502.  
  3503. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonClassChanged_ === 'function' && !(h.buttonClassChanged_.km34)) {
  3504.  
  3505. const f = h.buttonClassChanged_;
  3506. const g = ump3.get(f) || function (a, b) {
  3507. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3508. }
  3509. ump3.set(f, g);
  3510. g.km34 = 1;
  3511. h.buttonClassChanged_ = g;
  3512.  
  3513. }
  3514.  
  3515. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonIconChanged_ === 'function' && !(h.buttonIconChanged_.km34)) {
  3516.  
  3517. const f = h.buttonIconChanged_;
  3518. const g = ump3.get(f) || function (a) {
  3519. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3520. }
  3521. ump3.set(f, g);
  3522. g.km34 = 1;
  3523. h.buttonIconChanged_ = g;
  3524.  
  3525. }
  3526.  
  3527. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.dataChangedInBehavior_ === 'function' && !(h.dataChangedInBehavior_.km34)) {
  3528.  
  3529. const f = h.dataChangedInBehavior_;
  3530. const g = ump3.get(f) || function () {
  3531. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3532. }
  3533. ump3.set(f, g);
  3534. g.km34 = 1;
  3535. h.dataChangedInBehavior_ = g;
  3536.  
  3537. }
  3538.  
  3539. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.continuationsChanged_ === 'function' && !(h.continuationsChanged_.km34)) {
  3540.  
  3541. const f = h.continuationsChanged_;
  3542. const g = ump3.get(f) || function () {
  3543. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3544. }
  3545. ump3.set(f, g);
  3546. g.km34 = 1;
  3547. h.continuationsChanged_ = g;
  3548.  
  3549. }
  3550.  
  3551.  
  3552. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.forceChatPoll_ === 'function' && !(h.forceChatPoll_.km34)) {
  3553.  
  3554. const f = h.forceChatPoll_;
  3555. const g = ump3.get(f) || function (a) {
  3556. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3557. }
  3558. ump3.set(f, g);
  3559. g.km34 = 1;
  3560. h.forceChatPoll_ = g;
  3561.  
  3562. }
  3563.  
  3564. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointClick_ === 'function' && !(h.onEndpointClick_.km34)) {
  3565.  
  3566. const f = h.onEndpointClick_;
  3567. const g = ump3.get(f) || function (a) {
  3568. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3569. }
  3570. ump3.set(f, g);
  3571. g.km34 = 1;
  3572. h.onEndpointClick_ = g;
  3573.  
  3574. }
  3575.  
  3576. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointTap_ === 'function' && !(h.onEndpointTap_.km34)) {
  3577.  
  3578. const f = h.onEndpointTap_;
  3579. const g = ump3.get(f) || function (a) {
  3580. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3581. }
  3582. ump3.set(f, g);
  3583. g.km34 = 1;
  3584. h.onEndpointTap_ = g;
  3585.  
  3586. }
  3587.  
  3588. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleClick_ === 'function' && !(h.handleClick_.km34)) {
  3589.  
  3590. const f = h.handleClick_;
  3591. const g = ump3.get(f) || function (a, b) {
  3592. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3593. }
  3594. ump3.set(f, g);
  3595. g.km34 = 1;
  3596. h.handleClick_ = g;
  3597.  
  3598. }
  3599.  
  3600. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChange_ === 'function' && !(h.onReadyStateChange_.km34)) {
  3601.  
  3602. const f = h.onReadyStateChange_;
  3603. const g = ump3.get(f) || function () {
  3604. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3605. }
  3606. ump3.set(f, g);
  3607. g.km34 = 1;
  3608. h.onReadyStateChange_ = g;
  3609.  
  3610. }
  3611.  
  3612. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChangeEntryPoint_ === 'function' && !(h.onReadyStateChangeEntryPoint_.km34)) {
  3613.  
  3614. const f = h.onReadyStateChangeEntryPoint_;
  3615. const g = ump3.get(f) || function () {
  3616. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3617. }
  3618. ump3.set(f, g);
  3619. g.km34 = 1;
  3620. h.onReadyStateChangeEntryPoint_ = g;
  3621.  
  3622. }
  3623.  
  3624. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.readyStateChangeHandler_ === 'function' && !(h.readyStateChangeHandler_.km34)) {
  3625.  
  3626. const f = h.readyStateChangeHandler_;
  3627. const g = ump3.get(f) || function (a) {
  3628. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3629. }
  3630. ump3.set(f, g);
  3631. g.km34 = 1;
  3632. h.readyStateChangeHandler_ = g;
  3633.  
  3634. }
  3635.  
  3636. if (typeof h.xmlHttpHandler_ === 'function' && !(h.xmlHttpHandler_.km34)) {
  3637.  
  3638. const f = h.xmlHttpHandler_;
  3639. const g = ump3.get(f) || function (a) {
  3640. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3641. }
  3642. ump3.set(f, g);
  3643. g.km34 = 1;
  3644. h.xmlHttpHandler_ = g;
  3645.  
  3646. }
  3647.  
  3648. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.executeCallbacks_ === 'function' && !(h.executeCallbacks_.km34)) {
  3649.  
  3650. const f = h.executeCallbacks_; // overloaded
  3651. const g = ump3.get(f) || function (a) {
  3652. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3653. }
  3654. ump3.set(f, g);
  3655. g.km34 = 1;
  3656. h.executeCallbacks_ = g;
  3657.  
  3658. }
  3659.  
  3660. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleInvalidationData_ === 'function' && !(h.handleInvalidationData_.km34)) {
  3661.  
  3662. const f = h.handleInvalidationData_;
  3663. const g = ump3.get(f) || function (a, b) {
  3664. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3665. }
  3666. ump3.set(f, g);
  3667. g.km34 = 1;
  3668. h.handleInvalidationData_ = g;
  3669.  
  3670. }
  3671.  
  3672. if (typeof h.onInput_ === 'function' && !(h.onInput_.km34)) {
  3673.  
  3674. const f = h.onInput_;
  3675. const g = ump3.get(f) || function () {
  3676. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3677. }
  3678. ump3.set(f, g);
  3679. g.km34 = 1;
  3680. h.onInput_ = g;
  3681.  
  3682. }
  3683. if (typeof h.trigger_ === 'function' && !(h.trigger_.km34)) {
  3684.  
  3685. const f = h.trigger_;
  3686. const g = ump3.get(f) || function (a) {
  3687. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3688. }
  3689. ump3.set(f, g);
  3690. g.km34 = 1;
  3691. h.trigger_ = g;
  3692.  
  3693. }
  3694.  
  3695. if (typeof h.requestData_ === 'function' && !(h.requestData_.km34)) {
  3696.  
  3697. const f = h.requestData_;
  3698. const g = ump3.get(f) || function (a) {
  3699. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3700. }
  3701. ump3.set(f, g);
  3702. g.km34 = 1;
  3703. h.requestData_ = g;
  3704.  
  3705. }
  3706.  
  3707. if (typeof h.onLoadReloadContinuation_ === 'function' && !(h.onLoadReloadContinuation_.km34)) {
  3708.  
  3709. const f = h.onLoadReloadContinuation_;
  3710. const g = ump3.get(f) || function (a, b) {
  3711. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3712. }
  3713. ump3.set(f, g);
  3714. g.km34 = 1;
  3715. h.onLoadReloadContinuation_ = g;
  3716.  
  3717. }
  3718.  
  3719. if (typeof h.onLoadIncrementalContinuation_ === 'function' && !(h.onLoadIncrementalContinuation_.km34)) {
  3720.  
  3721. const f = h.onLoadIncrementalContinuation_;
  3722. const g = ump3.get(f) || function (a, b) {
  3723. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3724. }
  3725. ump3.set(f, g);
  3726. g.km34 = 1;
  3727. h.onLoadIncrementalContinuation_ = g;
  3728.  
  3729. }
  3730.  
  3731. if (typeof h.onLoadSeekContinuation_ === 'function' && !(h.onLoadSeekContinuation_.km34)) {
  3732.  
  3733. const f = h.onLoadSeekContinuation_;
  3734. const g = ump3.get(f) || function (a, b) {
  3735. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3736. }
  3737. ump3.set(f, g);
  3738. g.km34 = 1;
  3739. h.onLoadSeekContinuation_ = g;
  3740.  
  3741. }
  3742. if (typeof h.onLoadReplayContinuation_ === 'function' && !(h.onLoadReplayContinuation_.km34)) {
  3743.  
  3744. const f = h.onLoadReplayContinuation_;
  3745. const g = ump3.get(f) || function (a, b) {
  3746. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3747. }
  3748. ump3.set(f, g);
  3749. g.km34 = 1;
  3750. h.onLoadReplayContinuation_ = g;
  3751.  
  3752. }
  3753. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onNavigate_ === 'function' && !(h.onNavigate_.km34)) {
  3754.  
  3755. const f = h.onNavigate_;
  3756. const g = ump3.get(f) || function (a) {
  3757. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3758. }
  3759. ump3.set(f, g);
  3760. g.km34 = 1;
  3761. h.onNavigate_ = g;
  3762.  
  3763. }
  3764.  
  3765. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorDataObserver_ === 'function' && !(h.ytRendererBehaviorDataObserver_.km34)) {
  3766.  
  3767. const f = h.ytRendererBehaviorDataObserver_;
  3768. const g = ump3.get(f) || function () {
  3769. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3770. }
  3771. ump3.set(f, g);
  3772. g.km34 = 1;
  3773. h.ytRendererBehaviorDataObserver_ = g;
  3774.  
  3775. }
  3776.  
  3777. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorTargetIdObserver_ === 'function' && !(h.ytRendererBehaviorTargetIdObserver_.km34)) {
  3778.  
  3779. const f = h.ytRendererBehaviorTargetIdObserver_;
  3780. const g = ump3.get(f) || function () {
  3781. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3782. }
  3783. ump3.set(f, g);
  3784. g.km34 = 1;
  3785. h.ytRendererBehaviorTargetIdObserver_ = g;
  3786.  
  3787. }
  3788.  
  3789. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.unregisterRenderer_ === 'function' && !(h.unregisterRenderer_.km34)) {
  3790.  
  3791. const f = h.unregisterRenderer_;
  3792. const g = ump3.get(f) || function (a) {
  3793. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3794. }
  3795. ump3.set(f, g);
  3796. g.km34 = 1;
  3797. h.unregisterRenderer_ = g;
  3798.  
  3799. }
  3800.  
  3801. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.textChanged_ === 'function' && !(h.textChanged_.km34)) {
  3802.  
  3803. const f = h.textChanged_;
  3804. const g = ump3.get(f) || function (a) {
  3805. if (void 0 !== this.isAttached) {
  3806. const hostElement = this.hostElement;
  3807. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  3808. return;
  3809. }
  3810. }
  3811. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3812. }
  3813. ump3.set(f, g);
  3814. g.km34 = 1;
  3815. h.textChanged_ = g;
  3816.  
  3817. }
  3818.  
  3819.  
  3820.  
  3821. /**
  3822. *
  3823. * Neglect following
  3824. *
  3825. * h.onYtAction_
  3826. * h.startLoadingWatch [ buggy for yt-player-updated ]
  3827. * h.deferRenderStamperBinding_
  3828. *
  3829. * h.stampDomArray_
  3830. * h.stampDomArraySplices_
  3831. *
  3832. */
  3833.  
  3834.  
  3835. // RP.prototype.searchChanged_ = RP.prototype.searchChanged_;
  3836. // RP.prototype.skinToneChanged_ = RP.prototype.skinToneChanged_;
  3837. // RP.prototype.onEmojiHover_ = RP.prototype.onEmojiHover_;
  3838. // RP.prototype.onSelectCategory_ = RP.prototype.onSelectCategory_;
  3839. // RP.prototype.onShowEmojiVariantSelector = RP.prototype.onShowEmojiVariantSelector;
  3840. // RP.prototype.updateCategoriesAndPlaceholder_ = RP.prototype.updateCategoriesAndPlaceholder_;
  3841.  
  3842. if (typeof h.searchChanged_ === 'function' && !(h.searchChanged_.km34)) {
  3843.  
  3844. const f = h.searchChanged_;
  3845. const g = ump3.get(f) || function () {
  3846. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3847. }
  3848. ump3.set(f, g);
  3849. g.km34 = 1;
  3850. h.searchChanged_ = g;
  3851.  
  3852. }
  3853.  
  3854. if (typeof h.skinToneChanged_ === 'function' && !(h.skinToneChanged_.km34)) {
  3855.  
  3856. const f = h.skinToneChanged_;
  3857. const g = ump3.get(f) || function (a) {
  3858. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3859. }
  3860. ump3.set(f, g);
  3861. g.km34 = 1;
  3862. h.skinToneChanged_ = g;
  3863.  
  3864. }
  3865.  
  3866. if (typeof h.onEmojiHover_ === 'function' && !(h.onEmojiHover_.km34)) {
  3867.  
  3868. const f = h.onEmojiHover_;
  3869. const g = ump3.get(f) || function (a) {
  3870. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3871. }
  3872. ump3.set(f, g);
  3873. g.km34 = 1;
  3874. h.onEmojiHover_ = g;
  3875.  
  3876. }
  3877.  
  3878. if (typeof h.onSelectCategory_ === 'function' && !(h.onSelectCategory_.km34)) {
  3879.  
  3880. const f = h.onSelectCategory_;
  3881. const g = ump3.get(f) || function (a) {
  3882. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3883. }
  3884. ump3.set(f, g);
  3885. g.km34 = 1;
  3886. h.onSelectCategory_ = g;
  3887.  
  3888. }
  3889.  
  3890. if (typeof h.onShowEmojiVariantSelector === 'function' && !(h.onShowEmojiVariantSelector.km34)) {
  3891.  
  3892. const f = h.onShowEmojiVariantSelector;
  3893. const g = ump3.get(f) || function (a) {
  3894. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3895. }
  3896. ump3.set(f, g);
  3897. g.km34 = 1;
  3898. h.onShowEmojiVariantSelector = g;
  3899.  
  3900. }
  3901.  
  3902. if (typeof h.updateCategoriesAndPlaceholder_ === 'function' && !(h.updateCategoriesAndPlaceholder_.km34)) {
  3903.  
  3904. const f = h.updateCategoriesAndPlaceholder_;
  3905. const g = ump3.get(f) || function () {
  3906. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3907. }
  3908. ump3.set(f, g);
  3909. g.km34 = 1;
  3910. h.updateCategoriesAndPlaceholder_ = g;
  3911.  
  3912. }
  3913.  
  3914. if (typeof h.watchPageActiveChanged_ === 'function' && !(h.watchPageActiveChanged_.km34)) {
  3915.  
  3916. const f = h.watchPageActiveChanged_;
  3917. const g = ump3.get(f) || function () {
  3918. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3919. }
  3920. ump3.set(f, g);
  3921. g.km34 = 1;
  3922. h.watchPageActiveChanged_ = g;
  3923.  
  3924. }
  3925.  
  3926. if (typeof h.activate_ === 'function' && !(h.activate_.km34)) {
  3927.  
  3928. const f = h.activate_;
  3929. const g = ump3.get(f) || function () {
  3930. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3931. }
  3932. ump3.set(f, g);
  3933. g.km34 = 1;
  3934. h.activate_ = g;
  3935.  
  3936. }
  3937. if (typeof h.onYtPlaylistDataUpdated_ === 'function' && !(h.onYtPlaylistDataUpdated_.km34)) {
  3938.  
  3939. const f = h.onYtPlaylistDataUpdated_;
  3940. const g = ump3.get(f) || function () {
  3941. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3942. }
  3943. ump3.set(f, g);
  3944. g.km34 = 1;
  3945. h.onYtPlaylistDataUpdated_ = g;
  3946.  
  3947. }
  3948.  
  3949. FIX_stampDomArray_stableList && fixStampDomArrayStableList(h);
  3950. const ENABLE_weakenStampReferencesQ = ENABLE_weakenStampReferences && typeof DocumentTimeline !== 'undefined' && typeof WeakRef !== 'undefined';
  3951. ENABLE_weakenStampReferencesQ && weakenStampReferences(h);
  3952.  
  3953.  
  3954. /**
  3955. *
  3956. * Neglect following
  3957. *
  3958. * h.rendererStamperObserver_
  3959. * h.rendererStamperApplyChangeRecord_
  3960. * h.flushRenderStamperComponentBindings_
  3961. * h.forwardRendererStamperChanges_
  3962. *
  3963. */
  3964.  
  3965. if (typeof h.tryRenderChunk_ === 'function' && !(h.tryRenderChunk_.km34)) {
  3966.  
  3967. const f = h.tryRenderChunk_;
  3968. const g = ump3.get(f) || function () {
  3969. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3970. }
  3971. ump3.set(f, g);
  3972. g.km34 = 1;
  3973. h.tryRenderChunk_ = g;
  3974.  
  3975. }
  3976.  
  3977.  
  3978. if (typeof h.renderChunk_ === 'function' && !(h.renderChunk_.km34)) {
  3979.  
  3980. const f = h.renderChunk_;
  3981. const g = ump3.get(f) || function () {
  3982. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3983. }
  3984. ump3.set(f, g);
  3985. g.km34 = 1;
  3986. h.renderChunk_ = g;
  3987.  
  3988. }
  3989.  
  3990. if (typeof h.deepLazyListObserver_ === 'function' && !(h.deepLazyListObserver_.km34)) {
  3991.  
  3992. const f = h.deepLazyListObserver_;
  3993. const g = ump3.get(f) || function () {
  3994. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3995. }
  3996. ump3.set(f, g);
  3997. g.km34 = 1;
  3998. h.deepLazyListObserver_ = g;
  3999.  
  4000. }
  4001.  
  4002. if (typeof h.onItemsUpdated_ === 'function' && !(h.onItemsUpdated_.km34)) {
  4003.  
  4004. const f = h.onItemsUpdated_;
  4005. const g = ump3.get(f) || function () {
  4006. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4007. }
  4008. ump3.set(f, g);
  4009. g.km34 = 1;
  4010. h.onItemsUpdated_ = g;
  4011.  
  4012. }
  4013.  
  4014. if (typeof h.requestRenderChunk_ === 'function' && !(h.requestRenderChunk_.km34)) {
  4015.  
  4016. const f = h.requestRenderChunk_;
  4017. const g = ump3.get(f) || function () {
  4018. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4019. }
  4020. ump3.set(f, g);
  4021. g.km34 = 1;
  4022. h.requestRenderChunk_ = g;
  4023.  
  4024. }
  4025.  
  4026. /**
  4027. *
  4028. * Neglect following
  4029. *
  4030. * h.dataChanged_ [ buggy for page swtiching ]
  4031. *
  4032. * h.updateChangeRecord_ [ see https://github.com/cyfung1031/userscript-supports/issues/20 ]
  4033. *
  4034. * h.cancelPendingTasks_
  4035. * h.fillRange_
  4036. * h.addTextNodes_
  4037. * h.updateText_
  4038. * h.stampTypeChanged_
  4039. *
  4040. */
  4041.  
  4042.  
  4043. }
  4044.  
  4045. const keyStConnectedCallback = Symbol(); // avoid copying the value
  4046.  
  4047. // const keyStDisconnectedCallback = Symbol(); // avoid copying the value
  4048. const cmf = new WeakMap();
  4049. const dmf = new WeakMap();
  4050.  
  4051. const gvGenerator = (nv) => {
  4052. return function () {
  4053. const cnt = insp(this);
  4054. const hostElement = cnt.hostElement || 0;
  4055. const dollar = hostElement ? (this.$ || indr(this)) : 0;
  4056. let p = (hostElement instanceof HTMLElement) && (dollar || !this.is);
  4057. if (p && (!dollar && !this.is)) {
  4058. const nodeName = hostElement.nodeName;
  4059. if (typeof nodeName !== 'string') {
  4060. // just in case
  4061. } else if (nodeName.startsWith("DOM-")) {
  4062. // dom-if, dom-repeat, etc
  4063. } else {
  4064. // yt element - new model, yt-xxxx, anixxxxxx
  4065. p = false;
  4066. }
  4067. }
  4068. if (p) {
  4069. if (typeof cnt.markDirty === 'function') {
  4070. // the yt element might call markDirty (occasionally)
  4071. p = false;
  4072. } else if (this.is === 'ytd-engagement-panel-section-list-renderer') {
  4073. // see https://github.com/cyfung1031/userscript-supports/issues/20
  4074. p = false;
  4075. }
  4076. }
  4077. if (p) {
  4078.  
  4079. // << dom-repeat & dom-if >>
  4080.  
  4081. // sequence on the same instance
  4082. this[qm57] = (this[qm57] || Promise.resolve()).then(() => nv.apply(this, arguments)).catch(console.log);
  4083. } else {
  4084. nv.apply(this, arguments);
  4085. }
  4086. };
  4087. }
  4088.  
  4089. // const assignedHolderWS = new WeakSet();
  4090.  
  4091. const setupWeakRef = (h) => {
  4092.  
  4093.  
  4094. }
  4095.  
  4096.  
  4097. let nativeHTMLElement = window.HTMLElement;
  4098.  
  4099. try {
  4100.  
  4101. const q = document.createElement('template');
  4102. q.innerHTML = '<ytz-null361></ytz-null361>';
  4103. nativeHTMLElement = q.content.firstChild.constructor
  4104.  
  4105. } catch (e) { }
  4106.  
  4107. if (!nativeHTMLElement.prototype.connectedCallback) {
  4108. nativeHTMLElement.prototype.connectedCallback79 = nativeHTMLElement.prototype.connectedCallback;
  4109. nativeHTMLElement.prototype.connectedCallback = function () {
  4110. let r;
  4111. if (this.connectedCallback79) r = this.connectedCallback79.apply(this, arguments);
  4112. return r;
  4113. }
  4114. }
  4115.  
  4116. ENABLE_discreteTasking && Object.defineProperty(Object.prototype, 'connectedCallback', {
  4117. get() {
  4118. const f = this[keyStConnectedCallback];
  4119. if (this.is) {
  4120. setupDiscreteTasks(this, true);
  4121. if (f) this.ky36 = 1;
  4122. }
  4123. return f;
  4124. },
  4125. set(nv) {
  4126. let gv;
  4127. if (typeof nv === 'function') {
  4128.  
  4129. gv = cmf.get(nv) || gvGenerator(nv);
  4130. if (gv !== nv) {
  4131. cmf.set(nv, gv);
  4132. cmf.set(gv, gv);
  4133. dmf.set(gv, nv);
  4134. }
  4135.  
  4136. } else {
  4137. gv = nv;
  4138. }
  4139. this[keyStConnectedCallback] = gv; // proto or object
  4140. if (this.is) {
  4141. setupDiscreteTasks(this);
  4142. }
  4143. return true;
  4144. },
  4145. enumerable: false,
  4146. configurable: true
  4147.  
  4148. });
  4149.  
  4150. const pLoad = new Promise(resolve => {
  4151. if (document.readyState !== 'loading') {
  4152. resolve();
  4153. } else {
  4154. window.addEventListener("DOMContentLoaded", resolve, false);
  4155. }
  4156. });
  4157.  
  4158. if (FIX_fix_requestIdleCallback_timing && !window.requestIdleCallback471 && typeof window.requestIdleCallback === 'function') {
  4159. window.requestIdleCallback471 = window.requestIdleCallback;
  4160. window.requestIdleCallback = function (f, ...args) {
  4161. return (this || window).requestIdleCallback471(async function () {
  4162. await pLoad.then();
  4163. f.call(this, ...arguments)
  4164. }, ...args);
  4165. }
  4166. }
  4167.  
  4168. pLoad.then(() => {
  4169.  
  4170. let nonce = document.querySelector('style[nonce]');
  4171. nonce = nonce ? nonce.getAttribute('nonce') : null;
  4172. const st = document.createElement('style');
  4173. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  4174. st.textContent = "none-element-k47{order:0}";
  4175. st.addEventListener('load', () => {
  4176. pf31.resolve();
  4177. p59 = 1;
  4178. }, false);
  4179. (document.body || document.head || document.documentElement).appendChild(st);
  4180.  
  4181. });
  4182.  
  4183. const prepareLogs = [];
  4184.  
  4185. const skipAdsDetection = new Set(['/robots.txt', '/live_chat', '/live_chat_replay']);
  4186.  
  4187. let winError00 = window.onerror;
  4188.  
  4189. let fix_error_many_stack_state = !FIX_error_many_stack ? 0 : skipAdsDetection.has(location.pathname) ? 2 : 1;
  4190.  
  4191. if (!JSON || !('parse' in JSON)) fix_error_many_stack_state = 0;
  4192.  
  4193. ; FIX_Iframe_NULL_SRC && typeof kagi === 'undefined' && (() => {
  4194.  
  4195. const emptyBlobUrl = URL.createObjectURL(new Blob([], { type: 'text/html' }));
  4196. const lcOpt = { sensitivity: 'base' };
  4197. document.createElement24 = document.createElement;
  4198. document.createElement = function (t) {
  4199. if (typeof t === 'string' && t.length === 6) {
  4200. if (t.localeCompare('iframe', undefined, lcOpt) === 0) {
  4201. const p = this.createElement24(t);
  4202. try {
  4203. const stack = new Error().stack;
  4204. const isSearchbox = stack.includes('initializeSearchbox'); // see https://greasyfork.org/scripts/473972-youtube-js-engine-tamer/discussions/217084
  4205. if (!isSearchbox) {
  4206. p.src = emptyBlobUrl; // avoid iframe is appended to DOM without any url
  4207. }
  4208. } catch (e) { }
  4209. return p;
  4210. }
  4211. }
  4212. return this.createElement24.apply(this, arguments);
  4213. };
  4214.  
  4215. })();
  4216.  
  4217. ; fix_error_many_stack_state === 1 && (() => {
  4218.  
  4219.  
  4220. let p1 = winError00;
  4221.  
  4222. let stackNeedleDetails = null;
  4223.  
  4224. Object.defineProperty(Object.prototype, 'matchAll', {
  4225. get() {
  4226. stackNeedleDetails = this;
  4227. return true;
  4228. },
  4229. enumerable: true,
  4230. configurable: true
  4231. });
  4232.  
  4233. try {
  4234. JSON.parse("{}");
  4235. } catch (e) {
  4236. console.warn(e)
  4237. fix_error_many_stack_state = 0;
  4238. }
  4239.  
  4240. delete Object.prototype['matchAll'];
  4241.  
  4242. let p2 = window.onerror;
  4243.  
  4244. window.onerror = p1;
  4245.  
  4246. if (fix_error_many_stack_state === 0) return;
  4247.  
  4248. if (stackNeedleDetails) {
  4249. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  4250. stackNeedleDetails.matchAll = true;
  4251. }
  4252.  
  4253. if (p1 === p2) return (fix_error_many_stack_state = 0);
  4254.  
  4255. // p1!==p2
  4256. fix_error_many_stack_state = !stackNeedleDetails ? 4 : 3;
  4257.  
  4258. })();
  4259.  
  4260. ; fix_error_many_stack_state === 2 && (() => {
  4261.  
  4262.  
  4263. let p1 = winError00;
  4264.  
  4265. let objectPrune = null;
  4266. let stackNeedleDetails = null;
  4267.  
  4268. Object.defineProperty(Function.prototype, 'findOwner', {
  4269. get() {
  4270. objectPrune = this;
  4271. return this._findOwner;
  4272. },
  4273. set(nv) {
  4274. this._findOwner = nv;
  4275. return true;
  4276. },
  4277. enumerable: true,
  4278. configurable: true
  4279. });
  4280.  
  4281. Object.defineProperty(Object.prototype, 'matchAll', {
  4282. get() {
  4283. stackNeedleDetails = this;
  4284. return true;
  4285. },
  4286. enumerable: true,
  4287. configurable: true
  4288. });
  4289.  
  4290. try {
  4291. JSON.parse("{}");
  4292. } catch (e) {
  4293. console.warn(e)
  4294. fix_error_many_stack_state = 0;
  4295. }
  4296.  
  4297. delete Function.prototype['findOwner'];
  4298. delete Object.prototype['matchAll'];
  4299.  
  4300. let p2 = window.onerror;
  4301.  
  4302. if (p1 !== p2) return (fix_error_many_stack_state = 4); // p1 != p2
  4303.  
  4304. if (fix_error_many_stack_state == 0) return;
  4305.  
  4306. // the following will only execute when Brave's scriptlets.js is executed.
  4307.  
  4308. prepareLogs.push("fix_error_many_stack_state NB")
  4309.  
  4310. if (stackNeedleDetails) {
  4311. stackNeedleDetails.pattern = null;
  4312. stackNeedleDetails.re = null;
  4313. stackNeedleDetails.expect = null;
  4314. stackNeedleDetails.matchAll = true;
  4315. }
  4316.  
  4317. if (objectPrune) {
  4318. objectPrune.findOwner = objectPrune.mustProcess = objectPrune.logJson = () => { }
  4319. delete objectPrune._findOwner;
  4320. }
  4321.  
  4322. fix_error_many_stack_state = 3;
  4323. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  4324. JSON.parse.objectPrune = objectPrune;
  4325.  
  4326. })();
  4327.  
  4328. ; fix_error_many_stack_state === 3 && (() => {
  4329.  
  4330.  
  4331. let p1 = winError00;
  4332.  
  4333. try {
  4334. JSON.parse("{}");
  4335. } catch (e) {
  4336. console.warn(e)
  4337. fix_error_many_stack_state = 0;
  4338. }
  4339.  
  4340. let p2 = window.onerror;
  4341.  
  4342. if (p1 === p2) return;
  4343.  
  4344. window.onerror = p1;
  4345.  
  4346. if (fix_error_many_stack_state === 0) return;
  4347.  
  4348. fix_error_many_stack_state = 4; // p1 != p2
  4349.  
  4350.  
  4351. })();
  4352.  
  4353. fix_error_many_stack_state === 4 && (() => {
  4354.  
  4355. // the following will only execute when Brave's scriptlets.js is executed.
  4356.  
  4357. prepareLogs.push("fix_error_many_stack_state AB")
  4358.  
  4359. JSON.parseProxy = JSON.parse;
  4360.  
  4361. JSON.parse = ((parse) => {
  4362.  
  4363. parse = parse.bind(JSON); // get a new instance of the current JSON.parse
  4364. return function (text, reviver) {
  4365. const onerror = window.onerror;
  4366. window.onerror = null;
  4367. let r;
  4368. try {
  4369. r = parse(...arguments);
  4370. } catch (e) {
  4371. r = e;
  4372. }
  4373. window.onerror = onerror;
  4374. if (r instanceof Error) {
  4375. throw r;
  4376. }
  4377. return r;
  4378. }
  4379.  
  4380. })(JSON.parse);
  4381.  
  4382.  
  4383. })();
  4384.  
  4385.  
  4386. // << if FIX_yt_player >>
  4387.  
  4388. // credit to @nopeless (https://greasyfork.org/scripts/471489-youtube-player-perf/)
  4389. const PERF_471489_ = true;
  4390. // PERF_471489_ is not exactly the same to Youtube Player perf v0.7
  4391. // This script uses a much gentle way to tamer the JS engine instead.
  4392.  
  4393. // << end >>
  4394.  
  4395. const steppingScaleN = 200; // transform: scaleX(k/N); 0<k<N
  4396.  
  4397.  
  4398.  
  4399. const nilFn = () => { };
  4400.  
  4401. let isMainWindow = false;
  4402. try {
  4403. isMainWindow = window.document === window.top.document
  4404. } catch (e) { }
  4405.  
  4406. let NO_PRELOAD_GENERATE_204_BYPASS = NO_PRELOAD_GENERATE_204 ? false : true;
  4407. let headLinkCollection = null;
  4408.  
  4409.  
  4410. // const assertor = (f) => f() || console.assert(false, `${f}`);
  4411.  
  4412. const fnIntegrity = (f, d) => {
  4413. if (!f || typeof f !== 'function') {
  4414. console.warn('f is not a function', f);
  4415. return;
  4416. }
  4417. let p = `${f}`, s = 0, j = -1, w = 0;
  4418. for (let i = 0, l = p.length; i < l; i++) {
  4419. const t = p[i];
  4420. if (((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'))) {
  4421. if (j < i - 1) w++;
  4422. j = i;
  4423. } else {
  4424. s++;
  4425. }
  4426. }
  4427. let itz = `${f.length}.${s}.${w}`;
  4428. if (!d) {
  4429. return itz;
  4430. } else {
  4431. return itz === d;
  4432. }
  4433. };
  4434.  
  4435. const getZqOu = (_yt_player) => {
  4436.  
  4437. const w = 'ZqOu';
  4438.  
  4439. let arr = [];
  4440.  
  4441. for (const [k, v] of Object.entries(_yt_player)) {
  4442.  
  4443. const p = typeof v === 'function' ? v.prototype : 0;
  4444. if (p
  4445. && typeof p.start === 'function' && p.start.length === 0 // Ou
  4446. && typeof p.isActive === 'function' && p.isActive.length === 0
  4447. && typeof p.stop === 'function' && p.stop.length === 0
  4448. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  4449. && !p.send && !p.abort
  4450. && !p.sample && !p.initialize && !p.fail && !p.getName
  4451. // && !p.dispose && !p.isDisposed
  4452.  
  4453. ) {
  4454. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4455.  
  4456.  
  4457. }
  4458.  
  4459. }
  4460.  
  4461. if (arr.length === 0) {
  4462.  
  4463. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4464. } else {
  4465.  
  4466. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4467. return arr[0];
  4468. }
  4469.  
  4470. }
  4471.  
  4472. const getZqQu = (_yt_player) => {
  4473.  
  4474. const w = 'ZqQu';
  4475.  
  4476. let arr = [];
  4477.  
  4478.  
  4479. for (const [k, v] of Object.entries(_yt_player)) {
  4480.  
  4481. const p = typeof v === 'function' ? v.prototype : 0;
  4482. if (p
  4483. && typeof p.start === 'function' && p.start.length === 1 // Qu
  4484. && typeof p.isActive === 'function' && p.isActive.length === 0
  4485. && typeof p.stop === 'function' && p.stop.length === 0
  4486. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  4487. && !p.send && !p.abort
  4488. && !p.sample && !p.initialize && !p.fail && !p.getName
  4489. // && !p.dispose && !p.isDisposed
  4490.  
  4491. ) {
  4492. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4493.  
  4494.  
  4495. }
  4496.  
  4497. }
  4498.  
  4499. if (arr.length === 0) {
  4500.  
  4501. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4502. } else {
  4503.  
  4504. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4505. return arr[0];
  4506. }
  4507.  
  4508. }
  4509.  
  4510.  
  4511. const getVG = (_yt_player) => {
  4512. const w = 'VG';
  4513.  
  4514. let arr = [];
  4515.  
  4516. for (const [k, v] of Object.entries(_yt_player)) {
  4517.  
  4518. const p = typeof v === 'function' ? v.prototype : 0;
  4519. if (p
  4520. && typeof p.show === 'function' && p.show.length === 1
  4521. && typeof p.hide === 'function' && p.hide.length === 0
  4522. && typeof p.stop === 'function' && p.stop.length === 0) {
  4523.  
  4524. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4525.  
  4526. }
  4527.  
  4528. }
  4529.  
  4530.  
  4531. if (arr.length === 0) {
  4532.  
  4533. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4534. } else {
  4535.  
  4536. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4537. return arr[0];
  4538. }
  4539.  
  4540.  
  4541.  
  4542. }
  4543.  
  4544.  
  4545. const getzo = (_yt_player) => {
  4546. const w = 'zo';
  4547.  
  4548. let arr = [];
  4549.  
  4550. for (const [k, v] of Object.entries(_yt_player)) {
  4551.  
  4552. if (
  4553. typeof v === 'function' && v.length === 3 && k.length < 3
  4554. ) {
  4555. const vt = `${v}`;
  4556. if (vt.length >= 21 && vt.includes(".style[")) {
  4557. if (/\((\w{1,3}),(\w{1,3}),(\w{1,3})\)\{[\s\S]*\1\.style\[\2\]=\3\W/.test(vt)) {
  4558. arr.push(k);
  4559. } else {
  4560. console.warn('[yt-js-engine-tamer] unexpected zo::vt', vt);
  4561. }
  4562. }
  4563. }
  4564.  
  4565. }
  4566.  
  4567. if (arr.length === 0) {
  4568.  
  4569. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4570. } else {
  4571.  
  4572. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4573. return arr[0];
  4574. }
  4575.  
  4576. }
  4577.  
  4578. const addProtoToArr = (parent, key, arr) => {
  4579.  
  4580.  
  4581. let isChildProto = false;
  4582. for (const sr of arr) {
  4583. if (parent[key].prototype instanceof parent[sr]) {
  4584. isChildProto = true;
  4585. break;
  4586. }
  4587. }
  4588.  
  4589. if (isChildProto) return;
  4590.  
  4591. arr = arr.filter(sr => {
  4592. if (parent[sr].prototype instanceof parent[key]) {
  4593. return false;
  4594. }
  4595. return true;
  4596. });
  4597.  
  4598. arr.push(key);
  4599.  
  4600. return arr;
  4601.  
  4602.  
  4603. }
  4604.  
  4605. const getuG = (_yt_player) => {
  4606.  
  4607. const w = 'uG';
  4608.  
  4609. let arr = [];
  4610.  
  4611. for (const [k, v] of Object.entries(_yt_player)) {
  4612.  
  4613.  
  4614. const p = typeof v === 'function' ? v.prototype : 0;
  4615.  
  4616. if (p
  4617. && typeof p.createElement === 'function' && p.createElement.length === 2
  4618. && typeof p.detach === 'function' && p.detach.length === 0
  4619. && typeof p.update === 'function' && p.update.length === 1
  4620. && typeof p.updateValue === 'function' && p.updateValue.length === 2
  4621. ) {
  4622.  
  4623. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4624.  
  4625. }
  4626.  
  4627. }
  4628.  
  4629.  
  4630.  
  4631.  
  4632.  
  4633. if (arr.length === 0) {
  4634.  
  4635. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4636. } else {
  4637.  
  4638. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4639. return arr[0];
  4640. }
  4641.  
  4642. }
  4643.  
  4644.  
  4645. const getQT = (_yt_player) => {
  4646. const w = 'QT';
  4647.  
  4648. let arr = [];
  4649. let brr = new Map();
  4650.  
  4651. for (const [k, v] of Object.entries(_yt_player)) {
  4652.  
  4653. const p = typeof v === 'function' ? v.prototype : 0;
  4654. if (p) {
  4655. let q = 0;
  4656. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  4657. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  4658. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  4659.  
  4660. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  4661.  
  4662. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  4663.  
  4664. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  4665. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  4666. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  4667. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  4668.  
  4669.  
  4670. // differentiate QT and DX
  4671.  
  4672. q += 280;
  4673. if (typeof p.cueVideoByPlayerVars === 'function') q += 4;
  4674. if (typeof p.loadVideoByPlayerVars === 'function') q += 4;
  4675. if (typeof p.preloadVideoByPlayerVars === 'function') q += 4;
  4676. if (typeof p.seekBy === 'function') q += 4;
  4677. if (typeof p.seekTo === 'function') q += 4;
  4678. if (typeof p.getStoryboardFormat === 'function') q += 4;
  4679. if (typeof p.getDuration === 'function') q += 4;
  4680. if (typeof p.loadModule === 'function') q += 4;
  4681. if (typeof p.unloadModule === 'function') q += 4;
  4682. if (typeof p.getOption === 'function') q += 4;
  4683. if (typeof p.getOptions === 'function') q += 4;
  4684. if (typeof p.setOption === 'function') q += 4;
  4685. if (typeof p.addCueRange === 'function') q += 4;
  4686. if (typeof p.getDebugText === 'function') q += 4;
  4687. if (typeof p.getCurrentBroadcastId === 'function') q += 4;
  4688. if (typeof p.setSizeStyle === 'function') q += 4;
  4689. if (typeof p.showControls === 'function') q += 4;
  4690. if (typeof p.hideControls === 'function') q += 4;
  4691. if (typeof p.getVideoContentRect === 'function') q += 4;
  4692. if (typeof p.toggleFullscreen === 'function') q += 4;
  4693. if (typeof p.isFullscreen === 'function') q += 4;
  4694. if (typeof p.cancelPlayback === 'function') q += 4;
  4695. if (typeof p.getProgressState === 'function') q += 4;
  4696. if (typeof p.isInline === 'function') q += 4;
  4697. if (typeof p.setInline === 'function') q += 4;
  4698. if (typeof p.toggleSubtitles === 'function') q += 4;
  4699. if (typeof p.getPlayerSize === 'function') q += 4;
  4700. if (typeof p.wakeUpControls === 'function') q += 4;
  4701. if (typeof p.setCenterCrop === 'function') q += 4;
  4702. if (typeof p.getLoopVideo === 'function') q += 4;
  4703. if (typeof p.setLoopVideo === 'function') q += 4;
  4704.  
  4705.  
  4706. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  4707.  
  4708. if (q > 0) brr.set(k, q);
  4709.  
  4710. }
  4711.  
  4712. }
  4713.  
  4714. if (arr.length === 0) {
  4715.  
  4716. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4717. } else {
  4718.  
  4719. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  4720.  
  4721. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  4722.  
  4723. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4724. return arr[0][0];
  4725. }
  4726.  
  4727.  
  4728.  
  4729. }
  4730.  
  4731.  
  4732.  
  4733. const getSV = (_yt_player) => {
  4734. const w = 'SV';
  4735.  
  4736. let arr = [];
  4737. let brr = new Map();
  4738.  
  4739. for (const [k, v] of Object.entries(_yt_player)) {
  4740.  
  4741. const p = typeof v === 'function' ? v.prototype : 0;
  4742. if (p) {
  4743. let q = 0;
  4744. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  4745. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  4746. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  4747.  
  4748. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q += 600; // SV
  4749.  
  4750. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  4751.  
  4752. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  4753. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  4754. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  4755. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  4756.  
  4757.  
  4758. // differentiate QT and DX
  4759.  
  4760.  
  4761. q += 280;
  4762.  
  4763. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  4764. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  4765. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  4766. if (typeof p.seekBy === 'function') q -= 4;
  4767. if (typeof p.seekTo === 'function') q -= 4;
  4768. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  4769. if (typeof p.getDuration === 'function') q -= 4;
  4770. if (typeof p.loadModule === 'function') q -= 4;
  4771. if (typeof p.unloadModule === 'function') q -= 4;
  4772. if (typeof p.getOption === 'function') q -= 4;
  4773. if (typeof p.getOptions === 'function') q -= 4;
  4774. if (typeof p.setOption === 'function') q -= 4;
  4775. if (typeof p.addCueRange === 'function') q -= 4;
  4776. if (typeof p.getDebugText === 'function') q -= 4;
  4777. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  4778. if (typeof p.setSizeStyle === 'function') q -= 4;
  4779. if (typeof p.showControls === 'function') q -= 4;
  4780. if (typeof p.hideControls === 'function') q -= 4;
  4781. if (typeof p.getVideoContentRect === 'function') q -= 4;
  4782. if (typeof p.toggleFullscreen === 'function') q -= 4;
  4783. if (typeof p.isFullscreen === 'function') q -= 4;
  4784. if (typeof p.cancelPlayback === 'function') q -= 4;
  4785. if (typeof p.getProgressState === 'function') q -= 4;
  4786. if (typeof p.isInline === 'function') q -= 4;
  4787. if (typeof p.setInline === 'function') q -= 4;
  4788. if (typeof p.toggleSubtitles === 'function') q -= 4;
  4789. if (typeof p.getPlayerSize === 'function') q -= 4;
  4790. if (typeof p.wakeUpControls === 'function') q -= 4;
  4791. if (typeof p.setCenterCrop === 'function') q -= 4;
  4792. if (typeof p.getLoopVideo === 'function') q -= 4;
  4793. if (typeof p.setLoopVideo === 'function') q -= 4;
  4794.  
  4795.  
  4796. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  4797.  
  4798. if (q > 0) brr.set(k, q);
  4799.  
  4800. }
  4801.  
  4802. }
  4803.  
  4804. if (arr.length === 0) {
  4805.  
  4806. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4807. } else {
  4808.  
  4809. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  4810.  
  4811. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  4812.  
  4813. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4814. return arr[0][0];
  4815. }
  4816.  
  4817.  
  4818.  
  4819. }
  4820.  
  4821.  
  4822.  
  4823.  
  4824. const getDX = (_yt_player) => {
  4825. const w = 'DX';
  4826.  
  4827. let arr = [];
  4828. let brr = new Map();
  4829.  
  4830. for (const [k, v] of Object.entries(_yt_player)) {
  4831.  
  4832. const p = typeof v === 'function' ? v.prototype : 0;
  4833. if (p) {
  4834. let q = 0;
  4835. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  4836. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  4837. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  4838.  
  4839. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  4840.  
  4841.  
  4842. if (!(typeof p.init === 'function' && p.init.length === 0)) q -= 300; // init is required
  4843.  
  4844. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  4845.  
  4846. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  4847. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  4848. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  4849. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  4850.  
  4851.  
  4852. // differentiate QT and DX
  4853.  
  4854.  
  4855. q += 280;
  4856.  
  4857. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  4858. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  4859. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  4860. if (typeof p.seekBy === 'function') q -= 4;
  4861. if (typeof p.seekTo === 'function') q -= 4;
  4862. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  4863. if (typeof p.getDuration === 'function') q -= 4;
  4864. if (typeof p.loadModule === 'function') q -= 4;
  4865. if (typeof p.unloadModule === 'function') q -= 4;
  4866. if (typeof p.getOption === 'function') q -= 4;
  4867. if (typeof p.getOptions === 'function') q -= 4;
  4868. if (typeof p.setOption === 'function') q -= 4;
  4869. if (typeof p.addCueRange === 'function') q -= 4;
  4870. if (typeof p.getDebugText === 'function') q -= 4;
  4871. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  4872. if (typeof p.setSizeStyle === 'function') q -= 4;
  4873. if (typeof p.showControls === 'function') q -= 4;
  4874. if (typeof p.hideControls === 'function') q -= 4;
  4875. if (typeof p.getVideoContentRect === 'function') q -= 4;
  4876. if (typeof p.toggleFullscreen === 'function') q -= 4;
  4877. if (typeof p.isFullscreen === 'function') q -= 4;
  4878. if (typeof p.cancelPlayback === 'function') q -= 4;
  4879. if (typeof p.getProgressState === 'function') q -= 4;
  4880. if (typeof p.isInline === 'function') q -= 4;
  4881. if (typeof p.setInline === 'function') q -= 4;
  4882. if (typeof p.toggleSubtitles === 'function') q -= 4;
  4883. if (typeof p.getPlayerSize === 'function') q -= 4;
  4884. if (typeof p.wakeUpControls === 'function') q -= 4;
  4885. if (typeof p.setCenterCrop === 'function') q -= 4;
  4886. if (typeof p.getLoopVideo === 'function') q -= 4;
  4887. if (typeof p.setLoopVideo === 'function') q -= 4;
  4888.  
  4889.  
  4890. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  4891.  
  4892. if (q > 0) brr.set(k, q);
  4893.  
  4894. }
  4895.  
  4896. }
  4897.  
  4898. if (arr.length === 0) {
  4899.  
  4900. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4901. } else {
  4902.  
  4903. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  4904.  
  4905. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  4906.  
  4907. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4908. return arr[0][0];
  4909. }
  4910.  
  4911.  
  4912.  
  4913. }
  4914.  
  4915.  
  4916.  
  4917. const isPrepareCachedV = (FIX_avoid_incorrect_video_meta ? true : false) && (window === top);
  4918.  
  4919. let pageSetupVideoId = null; // set at finish; '' for indeterminate state
  4920. let pageSetupState = 0;
  4921.  
  4922. isPrepareCachedV && (() => {
  4923.  
  4924. pageSetupVideoId = '';
  4925. const clearCachedV = () => {
  4926. pageSetupVideoId = '';
  4927. pageSetupState = 0;
  4928. }
  4929. document.addEventListener('yt-navigate-start', clearCachedV, false); // user action
  4930. document.addEventListener('yt-navigate-cache', clearCachedV, false); // pop state
  4931. document.addEventListener('yt-page-data-fetched', clearCachedV, false); // still consider invalid until url is ready in yt-navigate-finish
  4932. document.addEventListener('yt-navigate-finish', () => {
  4933. pageSetupState = 1;
  4934. try {
  4935. const url = new URL(location.href);
  4936. if (!url || !isWatchPageURL(url)) {
  4937. pageSetupVideoId = '';
  4938. } else {
  4939. pageSetupVideoId = url.searchParams.get('v') || '';
  4940. }
  4941. } catch (e) {
  4942. pageSetupVideoId = '';
  4943. }
  4944. }, false);
  4945.  
  4946. })();
  4947.  
  4948. let videoPlayingY = null;
  4949.  
  4950. isPrepareCachedV && (() => {
  4951.  
  4952. let getNext = true;
  4953. let videoPlayingX = {
  4954. get videoId() {
  4955. if (getNext) {
  4956. getNext = false;
  4957.  
  4958. let elements = document.querySelectorAll('ytd-watch-flexy[video-id]');
  4959. const arr = [];
  4960. for (const element of elements) {
  4961. if (!element.closest('[hidden]')) arr.push(element);
  4962. }
  4963. if (arr.length !== 1) this.__videoId__ = '';
  4964. else {
  4965. this.__videoId__ = arr[0].getAttribute('video-id');
  4966. }
  4967.  
  4968. }
  4969. return this.__videoId__ || '';
  4970. }
  4971. }
  4972.  
  4973. videoPlayingY = videoPlayingX;
  4974. const handler = (evt) => {
  4975. const target = (evt || 0).target;
  4976. if (target instanceof HTMLVideoElement) {
  4977. getNext = true;
  4978. }
  4979. }
  4980. document.addEventListener('loadedmetadata', handler, true);
  4981. document.addEventListener('durationchange', handler, true);
  4982.  
  4983. })();
  4984.  
  4985.  
  4986.  
  4987. const cleanContext = async (win) => {
  4988. const waitFn = requestAnimationFrame; // shall have been binded to window
  4989. try {
  4990. let mx = 16; // MAX TRIAL
  4991. const frameId = 'vanillajs-iframe-v1';
  4992. /** @type {HTMLIFrameElement | null} */
  4993. let frame = document.getElementById(frameId);
  4994. let removeIframeFn = null;
  4995. if (!frame) {
  4996. frame = document.createElement('iframe');
  4997. frame.id = frameId;
  4998. const blobURL = typeof webkitCancelAnimationFrame === 'function' && typeof kagi === 'undefined' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  4999. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  5000. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  5001. n.appendChild(frame);
  5002. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  5003. const root = document.documentElement;
  5004. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  5005. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  5006.  
  5007. removeIframeFn = (setTimeout) => {
  5008. const removeIframeOnDocumentReady = (e) => {
  5009. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  5010. e = n;
  5011. n = win = removeIframeFn = 0;
  5012. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  5013. }
  5014. if (!setTimeout || document.readyState !== 'loading') {
  5015. removeIframeOnDocumentReady();
  5016. } else {
  5017. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  5018. }
  5019. }
  5020. }
  5021. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  5022. const fc = frame.contentWindow;
  5023. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  5024. try {
  5025. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle } = fc;
  5026. const res = { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle };
  5027. for (let k in res) res[k] = res[k].bind(win); // necessary
  5028. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  5029. res.animate = fc.HTMLElement.prototype.animate;
  5030. res.perfNow = fc.performance.now;
  5031. return res;
  5032. } catch (e) {
  5033. if (removeIframeFn) removeIframeFn();
  5034. return null;
  5035. }
  5036. } catch (e) {
  5037. console.warn(e);
  5038. return null;
  5039. }
  5040. };
  5041.  
  5042. const promiseForYtActionCalled = new Promise(resolve => {
  5043.  
  5044. const appTag = location.pathname.startsWith('/live_chat') ? 'yt-live-chat-app':'ytd-app';
  5045. if (typeof AbortSignal !== 'undefined') {
  5046. let hn = () => {
  5047. if (!hn) return;
  5048. hn = null;
  5049. resolve(document.querySelector(appTag));
  5050. };
  5051. document.addEventListener('yt-action', hn, { capture: true, passive: true, once: true });
  5052. } else {
  5053. let hn = () => {
  5054. if (!hn) return;
  5055. document.removeEventListener('yt-action', hn, true);
  5056. hn = null;
  5057. resolve(document.querySelector(appTag));
  5058. };
  5059. document.addEventListener('yt-action', hn, true);
  5060. }
  5061. });
  5062.  
  5063. cleanContext(window).then(__CONTEXT__ => {
  5064. if (!__CONTEXT__) return null;
  5065.  
  5066. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, animate, requestIdleCallback, getComputedStyle, perfNow } = __CONTEXT__;
  5067.  
  5068.  
  5069. performance.now17 = perfNow.bind(performance);
  5070.  
  5071.  
  5072.  
  5073. __requestAnimationFrame__ = requestAnimationFrame;
  5074.  
  5075.  
  5076. const isGPUAccelerationAvailable = (() => {
  5077. // https://gist.github.com/cvan/042b2448fcecefafbb6a91469484cdf8
  5078. try {
  5079. const canvas = document.createElement('canvas');
  5080. return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
  5081. } catch (e) {
  5082. return false;
  5083. }
  5084. })();
  5085.  
  5086. const foregroundPromiseFn_noGPU = (() => {
  5087.  
  5088. if (isGPUAccelerationAvailable) return null;
  5089.  
  5090. const pd = Object.getOwnPropertyDescriptor(Document.prototype, 'visibilityState');
  5091. if (!pd || typeof pd.get !== 'function') return null;
  5092. const pdGet = pd.get;
  5093.  
  5094. let pr = null;
  5095.  
  5096. let hState = pdGet.call(document) === 'hidden';
  5097. // let cid = 0;
  5098. pureAddEventListener.call(document, 'visibilitychange', (evt) => {
  5099. const newHState = pdGet.call(document) === 'hidden';
  5100. if (hState !== newHState) {
  5101. // if (cid > 0) cid = clearInterval(cid);
  5102. hState = newHState;
  5103. if (!hState && pr) pr = pr.resolve();
  5104. }
  5105. });
  5106.  
  5107. // cid = setInterval(() => {
  5108. // const newHState = document.visibilityState === 'hidden';
  5109. // if (hState !== newHState) {
  5110. // hState = newHState;
  5111. // if (!hState && pr) pr = pr.resolve();
  5112. // }
  5113. // }, 100);
  5114.  
  5115.  
  5116. return (() => {
  5117. if (pr) return pr;
  5118. const w = ((!hState && setTimeout(() => {
  5119. if (!hState && pr === w) pr = pr.resolve();
  5120. })), (pr = new PromiseExternal()));
  5121. return w;
  5122. });
  5123.  
  5124. })();
  5125.  
  5126.  
  5127. let rafPromise = null;
  5128. const getRafPromise = () => rafPromise || (rafPromise = new Promise(resolve => {
  5129. requestAnimationFrame(hRes => {
  5130. rafPromise = null;
  5131. resolve(hRes);
  5132. });
  5133. }));
  5134.  
  5135. const foregroundPromiseFn = foregroundPromiseFn_noGPU || getRafPromise;
  5136.  
  5137.  
  5138. const wmComputedStyle = new WeakMap();
  5139.  
  5140. if (!window.__native__getComputedStyle__ && !window.__jst__getComputedStyle__ && typeof window.getComputedStyle === 'function' && window.getComputedStyle.length === 1) {
  5141. window.__native__getComputedStyle__ = getComputedStyle;
  5142. if (ENABLE_COMPUTEDSTYLE_CACHE) {
  5143. window.__original__getComputedStyle__ = window.getComputedStyle;
  5144. window.getComputedStyle = function (elem) {
  5145. if (!(elem instanceof Element) || (arguments.length === 2 && arguments[1]) || (arguments.length > 2)) {
  5146. return window.__original__getComputedStyle__(...arguments);
  5147. }
  5148. let cs = wmComputedStyle.get(elem);
  5149. if (!cs) {
  5150. cs = window.__native__getComputedStyle__(elem);
  5151. wmComputedStyle.set(elem, cs);
  5152. }
  5153. return cs;
  5154. };
  5155. } else {
  5156. window.__original__getComputedStyle__ = null;
  5157. }
  5158. window.__jst__getComputedStyle__ = window.getComputedStyle;
  5159. }
  5160.  
  5161. NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE && promiseForYtActionCalled.then(() => {
  5162. if (typeof window.__jst__getComputedStyle__ === 'function' && window.__jst__getComputedStyle__.length === 1 && window.__jst__getComputedStyle__ !== window.getComputedStyle) {
  5163. window.getComputedStyle = window.__jst__getComputedStyle__;
  5164. }
  5165. });
  5166.  
  5167. const isUrlInEmbed = location.href.includes('.youtube.com/embed/');
  5168. const isAbortSignalSupported = typeof AbortSignal !== "undefined";
  5169.  
  5170. const promiseForTamerTimeout = new Promise(resolve => {
  5171. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  5172. setTimeout(resolve, 480);
  5173. }, { capture: true, passive: true, once: true });
  5174. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  5175. setTimeout(resolve, 1200);
  5176. });
  5177. setTimeout(resolve, 3000);
  5178. });
  5179.  
  5180. const promiseForPageInitied = new Promise(resolve => {
  5181. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  5182. setTimeout(resolve, 450);
  5183. }, { capture: true, passive: true, once: true });
  5184. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  5185. setTimeout(resolve, 900);
  5186. });
  5187. setTimeout(resolve, 1800);
  5188. });
  5189.  
  5190. NO_PRELOAD_GENERATE_204_BYPASS || promiseForPageInitied.then(() => {
  5191. NO_PRELOAD_GENERATE_204_BYPASS = true;
  5192. headLinkCollection = null;
  5193. });
  5194.  
  5195.  
  5196. NATIVE_CANVAS_ANIMATION && (() => {
  5197.  
  5198. observablePromise(() => {
  5199. HTMLCanvasElement.prototype.animate = animate;
  5200. }, promiseForTamerTimeout).obtain();
  5201.  
  5202. })();
  5203.  
  5204.  
  5205.  
  5206. FIX_ytAction_ && (async () => {
  5207.  
  5208. const appTag = location.pathname.startsWith('/live_chat') ? 'yt-live-chat-app':'ytd-app';
  5209.  
  5210. const ytdApp = await new Promise(resolve => {
  5211.  
  5212. whenCEDefined(appTag).then(() => {
  5213. const ytdApp = document.querySelector(appTag);
  5214. if (ytdApp) {
  5215. resolve(ytdApp);
  5216. return;
  5217. }
  5218. let mo = new MutationObserver(() => {
  5219. const ytdApp = document.querySelector(appTag);
  5220. if (!ytdApp) return;
  5221. if (mo) {
  5222. mo.disconnect();
  5223. mo.takeRecords();
  5224. mo = null;
  5225. }
  5226. resolve(ytdApp);
  5227. });
  5228. mo.observe(document, { subtree: true, childList: true });
  5229. });
  5230.  
  5231. });
  5232.  
  5233. if (!ytdApp) return;
  5234. const cProto = insp(ytdApp).constructor.prototype;
  5235.  
  5236. if (!cProto) return;
  5237. let mbd = 0;
  5238.  
  5239. const fixer = (_ytdApp) => {
  5240. const ytdApp = insp(_ytdApp);
  5241. if (ytdApp && typeof ytdApp.onYtActionBoundListener_ === 'function' && !ytdApp.onYtActionBoundListener57_) {
  5242. ytdApp.onYtActionBoundListener57_ = ytdApp.onYtActionBoundListener_;
  5243. ytdApp.onYtActionBoundListener_ = ytdApp.onYtAction_.bind(ytdApp);
  5244. mbd++;
  5245. }
  5246. }
  5247.  
  5248. observablePromise(() => {
  5249.  
  5250. if (typeof cProto.created === 'function' && !cProto.created56) {
  5251. cProto.created56 = cProto.created;
  5252. cProto.created = function (...args) {
  5253. const r = this.created56(...args);
  5254. fixer(this);
  5255. return r;
  5256. };
  5257. mbd++;
  5258. }
  5259.  
  5260. if (typeof cProto.onYtAction_ === 'function' && !cProto.onYtAction57_) {
  5261. cProto.onYtAction57_ = cProto.onYtAction_;
  5262. cProto.onYtAction_ = function (...args) {
  5263. Promise.resolve().then(() => this.onYtAction57_(...args));
  5264. };
  5265. mbd++;
  5266. }
  5267.  
  5268. if (ytdApp) fixer(ytdApp);
  5269.  
  5270. /*
  5271. const actionRouter_ = ytdApp ? ytdApp.actionRouter_ : null;
  5272. if (actionRouter_ && typeof actionRouter_.handleAction === 'function' && !actionRouter_.handleAction57) {
  5273. actionRouter_.handleAction57 = actionRouter_.handleAction;
  5274. actionRouter_.handleAction = function (...args) {
  5275. Promise.resolve().then(() => this.handleAction57(...args));
  5276. }
  5277. mbd++;
  5278. }
  5279. */
  5280.  
  5281. // if(mbd === 3) return 1;
  5282. if (mbd >= 3) return 1;
  5283.  
  5284. }, new Promise(r => setTimeout(r, 1000))).obtain();
  5285.  
  5286. })();
  5287.  
  5288.  
  5289.  
  5290. FORCE_NO_REUSEABLE_ELEMENT_POOL && promiseForYtActionCalled.then(async () => {
  5291.  
  5292. const appTag = location.pathname.startsWith('/live_chat') ? 'yt-live-chat-app':'ytd-watch-flexy';
  5293.  
  5294. const app = await observablePromise(() => {
  5295.  
  5296. return document.querySelector(appTag);
  5297.  
  5298. }).obtain();
  5299.  
  5300. if (!app) return;
  5301.  
  5302.  
  5303. const appCnt = insp(app);
  5304.  
  5305. if (typeof appCnt.createComponent_ !== 'function' || appCnt.createComponent_.length != 3) return;
  5306.  
  5307.  
  5308. const mapGet = Map.prototype.get;
  5309.  
  5310.  
  5311. /** @type {Map | null} */
  5312. let qcMap = null;
  5313.  
  5314. Map.prototype.get = function (a) {
  5315. if (a === 'dummy-4718') qcMap = this;
  5316. return mapGet.call(this, a);
  5317. };
  5318. const r = appCnt.createComponent_('dummy-4718', {}, true);
  5319. Map.prototype.get = mapGet;
  5320.  
  5321. if (r && (r.nodeName || '').toLowerCase() === 'dummy-4718') {
  5322.  
  5323.  
  5324. // clearInterval(ckId);
  5325. // ckId = 0;
  5326.  
  5327. if (qcMap !== null && qcMap instanceof Map) {
  5328.  
  5329. console.log('[yt-js-engine-tamer] qcMap', qcMap);
  5330.  
  5331. const setArrayC = (c) => {
  5332. if (c instanceof Array) {
  5333. c.length = 0;
  5334. c.push = function () { };
  5335. c.pop = function () { };
  5336. c.shift = function () { };
  5337. c.unshift = function () { };
  5338. c.splice = function () { };
  5339. c.sort = function () { };
  5340. c.reverse = function () { };
  5341. }
  5342. }
  5343.  
  5344. const cleaning = function () {
  5345. qcMap.forEach(setArrayC);
  5346. qcMap.clear();
  5347. }
  5348.  
  5349. qcMap.set = function (b, c) {
  5350.  
  5351. setArrayC(c);
  5352.  
  5353. // console.log('qcMap.set', b, c);
  5354.  
  5355. if (qcMap.size > 0) {
  5356. // play safe
  5357.  
  5358. console.log('[yt-js-engine-tamer] qcMap', 'clear 01')
  5359. cleaning();
  5360. }
  5361.  
  5362. }
  5363. qcMap.get = function (b) {
  5364.  
  5365. // console.log('qcMap.get', b);
  5366.  
  5367. if (qcMap.size > 0) {
  5368. // play safe
  5369.  
  5370. console.log('[yt-js-engine-tamer] qcMap', 'clear 02')
  5371. cleaning();
  5372. }
  5373.  
  5374. }
  5375.  
  5376.  
  5377. if (qcMap.size > 0) {
  5378.  
  5379. console.log('[yt-js-engine-tamer] qcMap', 'clear 03')
  5380. cleaning();
  5381. }
  5382.  
  5383. }
  5384.  
  5385. }
  5386.  
  5387.  
  5388. });
  5389.  
  5390. const observablePromise = (proc, timeoutPromise) => {
  5391. let promise = null;
  5392. return {
  5393. obtain() {
  5394. if (!promise) {
  5395. promise = new Promise(resolve => {
  5396. let mo = null;
  5397. const f = () => {
  5398. let t = proc();
  5399. if (t) {
  5400. mo.disconnect();
  5401. mo.takeRecords();
  5402. mo = null;
  5403. resolve(t);
  5404. }
  5405. }
  5406. mo = new MutationObserver(f);
  5407. mo.observe(document, { subtree: true, childList: true })
  5408. f();
  5409. timeoutPromise && timeoutPromise.then(() => {
  5410. resolve(null)
  5411. });
  5412. });
  5413. }
  5414. return promise
  5415. }
  5416. }
  5417. }
  5418.  
  5419. // let _yt_player_promise = null;
  5420. /*
  5421. const getYtPlayerPromise = () => {
  5422. if (!_yt_player_promise) {
  5423. _yt_player_promise = new Promise(resolve => {
  5424. let cid = setInterval(() => {
  5425. let t = (((window || 0)._yt_player || 0) || 0);
  5426. if (t) {
  5427. clearInterval(cid);
  5428. resolve(t);
  5429. }
  5430. }, 1);
  5431. promiseForTamerTimeout.then(() => {
  5432. resolve(null)
  5433. });
  5434. });
  5435. }
  5436. return _yt_player_promise;
  5437. }
  5438. */
  5439. const _yt_player_observable = observablePromise(() => {
  5440. const _yt_player = (((window || 0)._yt_player || 0) || 0);
  5441. if (_yt_player) {
  5442. _yt_player[`__is_yt_player__${Date.now()}`] = 1;
  5443. return _yt_player;
  5444. }
  5445. }, promiseForTamerTimeout);
  5446.  
  5447. const polymerObservable = observablePromise(() => {
  5448. const Polymer = window.Polymer;
  5449. if (typeof Polymer !== 'function') return;
  5450. if (!(Polymer.Base || 0).connectedCallback || !(Polymer.Base || 0).disconnectedCallback) return;
  5451. return Polymer;
  5452. }, promiseForTamerTimeout);
  5453.  
  5454. const schedulerInstanceObservable = observablePromise(() => {
  5455. return (((window || 0).ytglobal || 0).schedulerInstanceInstance_ || 0);
  5456. }, promiseForTamerTimeout);
  5457.  
  5458. const timelineObservable = observablePromise(() => {
  5459. let t = (((document || 0).timeline || 0) || 0);
  5460. if (t && typeof t._play === 'function') {
  5461. return t;
  5462. }
  5463. }, promiseForTamerTimeout);
  5464. const animationObservable = observablePromise(() => {
  5465. let t = (((window || 0).Animation || 0) || 0);
  5466. if (t && typeof t === 'function' && t.length === 2 && typeof t.prototype._updatePromises === 'function') {
  5467. return t;
  5468. }
  5469. }, promiseForTamerTimeout);
  5470.  
  5471.  
  5472. const getScreenInfo = {
  5473. screenWidth: 0,
  5474. screenHeight: 0,
  5475. valueReady: false,
  5476. onResize: () => {
  5477. getScreenInfo.valueReady = false;
  5478. },
  5479. sizeProvided: () => {
  5480. if (getScreenInfo.valueReady) return true;
  5481. getScreenInfo.screenWidth = screen.width;
  5482. getScreenInfo.screenHeight = screen.height;
  5483. if (getScreenInfo.screenWidth * getScreenInfo.screenHeight > 1) {
  5484. getScreenInfo.valueReady = true;
  5485. return true;
  5486. }
  5487. return false;
  5488. }
  5489. };
  5490.  
  5491. window.addEventListener('resize', getScreenInfo.onResize, true);
  5492.  
  5493.  
  5494. // const hookLeftPending = new WeakMap();
  5495.  
  5496. const isNaNx = Number.isNaN;
  5497.  
  5498. const hookLeftPD = {
  5499. get() {
  5500. const p = 'left';
  5501. // const o = hookLeftPending.get(this);
  5502. // if (o && o.key) {
  5503. // this.setProperty(p, o.value);
  5504. // o.key = null
  5505. // }
  5506. return this.getPropertyValue(p);
  5507. },
  5508. set(v) {
  5509.  
  5510. const p = 'left';
  5511. const cv = this.getPropertyValue(p);
  5512. const sv = v;
  5513.  
  5514. // const did = Math.floor(Math.random() * 314159265359 + 314159265359).toString(36);
  5515.  
  5516. // console.log(8380,did, cv, sv)
  5517. if (!cv && !sv) return true;
  5518. if (cv === sv) return true;
  5519.  
  5520. // skip 0~9px => L>=4
  5521.  
  5522. const qsv = `${sv}`.length >= 4 && `${sv}`.endsWith('px') ? +sv.slice(0, -2) : NaN;
  5523.  
  5524. if (!isNaNx(qsv)) {
  5525. const qcv = `${cv}`.length >= 4 && `${cv}`.endsWith('px') ? +cv.slice(0, -2) : NaN;
  5526.  
  5527. if (!isNaNx(qcv) && getScreenInfo.sizeProvided()) {
  5528. const { screenWidth, screenHeight } = getScreenInfo;
  5529. let pWidth = screenWidth + 1024;
  5530. let pHeight = screenHeight + 768;
  5531. const minRatio = 0.003;
  5532. const dw = pWidth * 0.0003; // min dw = 0.3072
  5533. const dh = pHeight * 0.0003; // min dh = 0.2304
  5534. // console.log(8381,did, Math.abs(qcv - qsv) < dw)
  5535. if (Math.abs(qcv - qsv) < dw) return true;
  5536. }
  5537.  
  5538. v = `${qsv > -1e-5 && qsv < 1e-5 ? 0 : qsv.toFixed(4)}px`;
  5539. if (`${v}`.length > `${sv}`.length) v = sv;
  5540. // console.log(8382, did, sv, nv, cv, this)
  5541. }
  5542.  
  5543. // Promise.resolve().then(() => {
  5544. // const o = hookLeftPending.get(this);
  5545. // if (o && o.key === did) {
  5546. // this.setProperty(p, o.value);
  5547. // o.key = null;
  5548. // }
  5549. // });
  5550. // hookLeftPending.set(this, {
  5551. // key: did,
  5552. // value: nv
  5553. // });
  5554.  
  5555. // if (nv != v) {
  5556. // console.log(8387, v, nv);
  5557. // }
  5558.  
  5559. this.setProperty(p, v);
  5560. // console.log(8383, did, this.getPropertyValue(p))
  5561. return true;
  5562. },
  5563. enumerable: true,
  5564. configurable: true
  5565. };
  5566.  
  5567.  
  5568. if (HOOK_CSSPD_LEFT) {
  5569.  
  5570.  
  5571. Object.defineProperty(CSSStyleDeclaration.prototype, 'left', hookLeftPD);
  5572.  
  5573. }
  5574.  
  5575.  
  5576.  
  5577.  
  5578.  
  5579. const generalEvtHandler = async (_evKey, _fvKey, _debug) => {
  5580.  
  5581. const evKey = `${_evKey}`;
  5582. const fvKey = `${_fvKey}`;
  5583. const debug = !!_debug;
  5584.  
  5585. const _yt_player = await _yt_player_observable.obtain();
  5586.  
  5587.  
  5588. if (!_yt_player || typeof _yt_player !== 'object') return;
  5589.  
  5590.  
  5591. const getArr = (_yt_player) => {
  5592.  
  5593. let arr = [];
  5594.  
  5595. for (const [k, v] of Object.entries(_yt_player)) {
  5596.  
  5597. const p = typeof v === 'function' ? v.prototype : 0;
  5598. if (p
  5599. && typeof p[evKey] === 'function' && p[evKey].length >= 0 && !p[fvKey]
  5600.  
  5601. ) {
  5602. arr = addProtoToArr(_yt_player, k, arr) || arr;
  5603.  
  5604. }
  5605.  
  5606. }
  5607.  
  5608. if (arr.length === 0) {
  5609.  
  5610. console.warn(`Key prop [${evKey}] does not exist.`);
  5611. } else {
  5612.  
  5613. return arr;
  5614. }
  5615.  
  5616. };
  5617.  
  5618. const arr = getArr(_yt_player);
  5619.  
  5620.  
  5621. if (!arr) return;
  5622.  
  5623. debug && console.log(`FIX_${evKey}`, arr);
  5624.  
  5625. const f = function (...args) {
  5626. Promise.resolve().then(() => this[fvKey](...args));
  5627. };
  5628.  
  5629.  
  5630. for (const k of arr) {
  5631.  
  5632. const g = _yt_player;
  5633. const gk = g[k];
  5634. const gkp = gk.prototype;
  5635.  
  5636. debug && console.log(237, k, gkp)
  5637.  
  5638. if (typeof gkp[evKey] == 'function' && !gkp[fvKey]) {
  5639. gkp[fvKey] = gkp[evKey];
  5640. gkp[evKey] = f;
  5641. }
  5642. }
  5643.  
  5644.  
  5645.  
  5646.  
  5647. }
  5648.  
  5649. FIX_onVideoDataChange && generalEvtHandler('onVideoDataChange', 'onVideoDataChange57');
  5650. // FIX_onClick && generalEvtHandler('onClick', 'onClick57');
  5651. FIX_onStateChange && generalEvtHandler('onStateChange', 'onStateChange57');
  5652. FIX_onLoopRangeChange && generalEvtHandler('onLoopRangeChange', 'onLoopRangeChange57');
  5653. if (FIX_VideoEVENTS_v2) {
  5654. const FIX_VideoEVENTS_DEBUG = 0;
  5655. generalEvtHandler('onVideoProgress', 'onVideoProgress57', FIX_VideoEVENTS_DEBUG); // --
  5656. // generalEvtHandler('onAutoplayBlocked', 'onAutoplayBlocked57', FIX_VideoEVENTS_DEBUG);
  5657. // generalEvtHandler('onLoadProgress', 'onLoadProgress57', FIX_VideoEVENTS_DEBUG); // << CAUSE ISSUE >>
  5658. generalEvtHandler('onFullscreenChange', 'onFullscreenChange57', FIX_VideoEVENTS_DEBUG); // --
  5659. // generalEvtHandler('onLoadedMetadata', 'onLoadedMetadata57', FIX_VideoEVENTS_DEBUG);
  5660. // generalEvtHandler('onDrmOutputRestricted', 'onDrmOutputRestricted57', FIX_VideoEVENTS_DEBUG);
  5661. // generalEvtHandler('onAirPlayActiveChange', 'onAirPlayActiveChange57', FIX_VideoEVENTS_DEBUG);
  5662. // generalEvtHandler('onAirPlayAvailabilityChange', 'onAirPlayAvailabilityChange57', FIX_VideoEVENTS_DEBUG);
  5663. // generalEvtHandler('onApiChange', 'onApiChange57', FIX_VideoEVENTS_DEBUG);
  5664.  
  5665. }
  5666. // onMutedAutoplayChange
  5667. // onVolumeChange
  5668. // onPlaybackRateChange
  5669.  
  5670. // onAirPlayActiveChange
  5671. // onAirPlayAvailabilityChange
  5672. // onApiChange
  5673. // onAutoplayBlocked
  5674. // onDrmOutputRestricted
  5675. // onFullscreenChange
  5676. // onLoadProgress
  5677. // onLoadedMetadata
  5678. // onVideoDataChange
  5679. // onVideoProgress
  5680.  
  5681.  
  5682. (ENABLE_discreteTasking || FIX_Polymer_dom) && (async () => {
  5683.  
  5684. const Polymer = await polymerObservable.obtain();
  5685. if (!Polymer) return;
  5686.  
  5687. if (FIX_Polymer_dom) {
  5688.  
  5689. const checkPDFuncValue = (pd) => {
  5690. return pd && pd.writable && pd.enumerable && pd.configurable && typeof pd.value == 'function'
  5691. }
  5692. const checkPDFuncValue2 = (pd) => {
  5693. return pd && typeof pd.value == 'function'
  5694. }
  5695.  
  5696. const checkPDFuncGet = (pd) => {
  5697. return pd && typeof pd.get == 'function'
  5698. }
  5699.  
  5700. const domX = Polymer.dom(document.createElement('null'));
  5701. const domXP = (((domX || 0).constructor || 0).prototype || 0);
  5702. const pd1 = Object.getOwnPropertyDescriptor(domXP, 'getOwnerRoot');
  5703. const pd2 = Object.getOwnPropertyDescriptor(Node.prototype, 'parentElement');
  5704. const pd3 = Object.getOwnPropertyDescriptor(domXP, 'querySelector'); // undefined
  5705. const pd4 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelector');
  5706. const pd4b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelector');
  5707. const pd5 = Object.getOwnPropertyDescriptor(domXP, 'querySelectorAll'); // undefined
  5708. const pd6 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelectorAll');
  5709. const pd6b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelectorAll');
  5710.  
  5711.  
  5712. // getOwnerRoot - to be reviewed
  5713. if (0 && checkPDFuncValue(pd1) && checkPDFuncGet(pd2) && !domXP.getOwnerRoot15 && typeof domXP.getOwnerRoot === 'function') {
  5714.  
  5715. domXP.getOwnerRoot15 = domXP.getOwnerRoot;
  5716. domXP.getOwnerRoot = function () {
  5717. try {
  5718. const p = this.node;
  5719.  
  5720. if (p instanceof HTMLElement) {
  5721. const pp = pd2.get.call(p);
  5722. if (pp instanceof HTMLElement && pp.isConnected === true) {
  5723. return pp.getRootNode();
  5724. }
  5725.  
  5726. }
  5727. } catch (e) { }
  5728. return this.getOwnerRoot15();
  5729. }
  5730.  
  5731. Polymer.__fixedGetOwnerRoot__ = 1;
  5732. }
  5733.  
  5734.  
  5735.  
  5736.  
  5737. if ((!pd3 || checkPDFuncValue(pd3)) && checkPDFuncValue2(pd4) && checkPDFuncValue2(pd4b) && !('querySelector15' in domXP)) {
  5738.  
  5739. domXP.querySelector15 = domXP.querySelector;
  5740.  
  5741. const querySelectorFn = function (query) {
  5742. try {
  5743. const p = this.node;
  5744.  
  5745. // if (p instanceof HTMLElement && p.isConnected === true) {
  5746. // return pd4.value.call(p, query);
  5747. // }
  5748.  
  5749. if (p instanceof Document && p.isConnected === true) {
  5750. return pd4b.value.call(p, query);
  5751. }
  5752.  
  5753. } catch (e) { }
  5754. return this.querySelector15(query);
  5755. }
  5756.  
  5757. Object.defineProperty(domXP, 'querySelector', {
  5758. get() {
  5759. return querySelectorFn;
  5760. },
  5761. set(nv) {
  5762. if (nv === querySelectorFn) return true;
  5763. this.querySelector15 = nv;
  5764. return true;
  5765. },
  5766.  
  5767. enumerable: false,
  5768. configurable: true
  5769. });
  5770.  
  5771. Polymer.__fixedQuerySelector__ = 1;
  5772. }
  5773.  
  5774. if ((!pd5 || checkPDFuncValue(pd5)) && checkPDFuncValue2(pd6) && checkPDFuncValue2(pd6b) && !('querySelectorAll15' in domXP)) {
  5775.  
  5776. domXP.querySelectorAll15 = domXP.querySelectorAll;
  5777.  
  5778. const querySelectorAllFn = function (query) {
  5779.  
  5780. try {
  5781.  
  5782. const p = this.node;
  5783.  
  5784. // if (p instanceof HTMLElement && p.isConnected === true) {
  5785. // return pd6.value.call(p, query);
  5786. // }
  5787.  
  5788. if (p instanceof Document && p.isConnected === true) {
  5789. return pd6b.value.call(p, query);
  5790. }
  5791.  
  5792. } catch (e) {
  5793.  
  5794. }
  5795. return this.querySelectorAll15(query);
  5796. }
  5797.  
  5798. Object.defineProperty(domXP, 'querySelectorAll', {
  5799. get() {
  5800. return querySelectorAllFn;
  5801. },
  5802. set(nv) {
  5803. if (nv === querySelectorAllFn) return true;
  5804. this.querySelectorAll15 = nv;
  5805. return true;
  5806. },
  5807.  
  5808. enumerable: false,
  5809. configurable: true
  5810. });
  5811.  
  5812. Polymer.__fixedQuerySelectorAll__ = 1;
  5813. }
  5814. }
  5815.  
  5816.  
  5817. if (ENABLE_discreteTasking) {
  5818.  
  5819. Polymer.Base.__connInit__ = function () {
  5820. setupDiscreteTasks(this);
  5821. }
  5822.  
  5823.  
  5824. /** @type {Function} */
  5825. const connectedCallbackK = function (...args) {
  5826. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  5827. const r = this[qm53](...args);
  5828. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  5829. this.mh35 = 1;
  5830. return r;
  5831. };
  5832.  
  5833. connectedCallbackK.m353 = 1;
  5834.  
  5835.  
  5836. const qt53 = Polymer.Base.connectedCallback;
  5837. Polymer.Base[qm53] = dmf.get(qt53) || qt53;
  5838.  
  5839. Polymer.Base.connectedCallback = connectedCallbackK;
  5840.  
  5841.  
  5842. /** @type {Function} */
  5843. const createdK = function (...args) {
  5844. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  5845. const r = this[qn53](...args);
  5846. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  5847. this.mh36 = 1;
  5848. return r;
  5849. };
  5850.  
  5851.  
  5852. createdK.m353 = 1;
  5853. Polymer.Base[qn53] = Polymer.Base.created;
  5854. Polymer.Base.created = createdK;
  5855.  
  5856. }
  5857.  
  5858. })();
  5859.  
  5860.  
  5861. /*
  5862.  
  5863. e.nativeAppendChild = d.prototype.appendChild,
  5864. d.prototype.appendChild = function(h) {
  5865. return function(l) {
  5866. if (l instanceof DocumentFragment) {
  5867. var m = Array.from(l.children);
  5868. l = h.nativeAppendChild.call(this, l);
  5869. if (this.isConnected) {
  5870. m = g(m);
  5871. for (var p = m.next(); !p.done; p = m.next())
  5872. YD(p.value)
  5873. }
  5874. return l
  5875. }
  5876. m = l instanceof Element && l.isConnected;
  5877. p = h.nativeAppendChild.call(this, l);
  5878. m && ZD(l);
  5879. this.isConnected && YD(l);
  5880. return p
  5881. }
  5882. }(e),
  5883.  
  5884. */
  5885.  
  5886. CHANGE_appendChild && !Node.prototype.appendChild73 && Node.prototype.appendChild && (() => {
  5887.  
  5888. const f = Node.prototype.appendChild73 = Node.prototype.appendChild;
  5889. if (f) Node.prototype.appendChild = function (a) {
  5890. if (this instanceof Element) { // exclude DocumentFragment
  5891. try {
  5892. let checkFragmentA = (a instanceof DocumentFragment);
  5893. if (!NO_PRELOAD_GENERATE_204_BYPASS && document.head === this) {
  5894. if (headLinkCollection === null) headLinkCollection = document.head.getElementsByTagName('LINK');
  5895. for (const node of headLinkCollection) {
  5896. if (node.rel === 'preload' && node.as === 'fetch') {
  5897. node.rel = 'prefetch'; // see https://github.com/GoogleChromeLabs/quicklink
  5898. }
  5899. }
  5900. } else if (checkFragmentA && this.nodeName.startsWith('YT-')) { // yt-animated-rolling-number, yt-attributed-string
  5901. checkFragmentA = false;
  5902. }
  5903. if (checkFragmentA && a.firstElementChild === null) {
  5904. // no element in fragmentA
  5905. let doNormal = false;
  5906. for (let child = a.firstChild; child instanceof Node; child = child.nextSibling) {
  5907. if (child.nodeType === 3) { doNormal = true; break; }
  5908. }
  5909. if (!doNormal) return a;
  5910. }
  5911. } catch (e) {
  5912. console.log(e);
  5913. }
  5914. }
  5915. return arguments.length === 1 ? f.call(this, a) : f.apply(this, arguments);
  5916. }
  5917.  
  5918. })();
  5919.  
  5920. if (FIX_Shady) {
  5921.  
  5922. observablePromise(() => {
  5923. const { ShadyDOM, ShadyCSS } = window;
  5924. if (ShadyDOM) {
  5925. ShadyDOM.handlesDynamicScoping = false; // 9 of 10
  5926. ShadyDOM.noPatch = true; // 1 of 10
  5927. ShadyDOM.patchOnDemand = false; // 1 of 10
  5928. ShadyDOM.preferPerformance = true; // 1 of 10
  5929. ShadyDOM.querySelectorImplementation = undefined; // 1 of 10
  5930. }
  5931. if (ShadyCSS) {
  5932. ShadyCSS.nativeCss = true; // 1 of 10
  5933. ShadyCSS.nativeShadow = true; // 6 of 10
  5934. ShadyCSS.cssBuild = undefined; // 1 of 10
  5935. ShadyCSS.disableRuntime = true; // 1 of 10
  5936. }
  5937. if (ShadyDOM && ShadyCSS) return 1;
  5938. }, promiseForTamerTimeout).obtain(); // clear until 1 is return
  5939.  
  5940. }
  5941.  
  5942.  
  5943. // let schedulerInstancePropOfTimerType = '';
  5944. // let schedulerInstancePropOfTimerId = '';
  5945. (FIX_schedulerInstanceInstance & 2) && (async () => {
  5946.  
  5947. const schedulerInstanceInstance_ = await schedulerInstanceObservable.obtain();
  5948.  
  5949. if (!schedulerInstanceInstance_) return;
  5950.  
  5951. const checkOK = typeof schedulerInstanceInstance_.start === 'function' && !schedulerInstanceInstance_.start993 && !schedulerInstanceInstance_.stop && !schedulerInstanceInstance_.cancel && !schedulerInstanceInstance_.terminate && !schedulerInstanceInstance_.interupt;
  5952. if (checkOK) {
  5953.  
  5954. schedulerInstanceInstance_.start993 = schedulerInstanceInstance_.start;
  5955.  
  5956. let requestingFn = null;
  5957. let requestingArgs = null;
  5958.  
  5959. const f = function () {
  5960. requestingFn = this.fn;
  5961. requestingArgs = [...arguments];
  5962. return 12373;
  5963. };
  5964.  
  5965. const fakeFns = [
  5966. f.bind({ fn: requestAnimationFrame }),
  5967. f.bind({ fn: setInterval }),
  5968. f.bind({ fn: setTimeout }),
  5969. f.bind({ fn: requestIdleCallback })
  5970. ];
  5971.  
  5972. let mzt = 0;
  5973.  
  5974. let _fnSelectorProp = null;
  5975. const mkFns = new Array(4);
  5976.  
  5977. /*
  5978. case 1:
  5979. var a = this.K;
  5980. this.g = this.I ? window.requestIdleCallback(a, {
  5981. timeout: 3E3
  5982. }) : window.setTimeout(a, ma);
  5983. break;
  5984. case 2:
  5985. this.g = window.setTimeout(this.M, this.N);
  5986. break;
  5987. case 3:
  5988. this.g = window.requestAnimationFrame(this.L);
  5989. break;
  5990. case 4:
  5991. this.g = window.setTimeout(this.J, 0)
  5992. }
  5993.  
  5994. */
  5995. const startFnHandler = {
  5996. get(target, prop, receiver) {
  5997. if (prop === '$$12377$$') return true;
  5998. if (prop === '$$12378$$') return target;
  5999.  
  6000. // console.log('get',prop)
  6001. return target[prop]
  6002. },
  6003. set(target, prop, value, receiver) {
  6004. // console.log('set', prop, value)
  6005.  
  6006. if (value >= 1 && value <= 4) _fnSelectorProp = prop;
  6007. if (value === 12373 && _fnSelectorProp) {
  6008.  
  6009. const schedulerTypeSelection = target[_fnSelectorProp];
  6010. const timerIdProp = prop;
  6011.  
  6012. // if (schedulerTypeSelection && schedulerTypeSelection >= 1 && schedulerTypeSelection <= 4 && timerIdProp) {
  6013. // schedulerInstancePropOfTimerType = _fnSelectorProp || '';
  6014. // schedulerInstancePropOfTimerId = timerIdProp || '';
  6015. // }
  6016.  
  6017. if (schedulerTypeSelection === 3 && requestingFn === requestAnimationFrame) { // rAF(fn)
  6018. target[timerIdProp] = baseRAF.apply(window, requestingArgs);
  6019. } else if (schedulerTypeSelection === 2 && requestingFn === setTimeout) { // setTimeout(fn, delay)
  6020. // rare
  6021. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  6022. } else if (schedulerTypeSelection === 4 && requestingFn === setTimeout && !requestingArgs[1]) { // setTimeout(fn, 0)
  6023. // often
  6024. if ((FIX_schedulerInstanceInstance & 4) && typeof nextBrowserTick == 'function') {
  6025. const f = requestingArgs[0];
  6026. const tir = ++mzt;
  6027. nextBrowserTick(() => {
  6028. if (target[timerIdProp] === -tir) f();
  6029. });
  6030. target[_fnSelectorProp] = 940;
  6031. target[timerIdProp] = -tir;
  6032. } else {
  6033. const f = requestingArgs[0];
  6034. const tir = ++mzt;
  6035. Promise.resolve().then(() => {
  6036. if (target[timerIdProp] === -tir) f();
  6037. });
  6038. target[_fnSelectorProp] = 930;
  6039. target[timerIdProp] = -tir;
  6040. }
  6041. } else if (schedulerTypeSelection === 1 && (requestingFn === requestIdleCallback || requestingFn === setTimeout)) { // setTimeout(requestIdleCallback)
  6042. // often
  6043. if (requestingFn === requestIdleCallback) {
  6044. target[timerIdProp] = requestIdleCallback.apply(window, requestingArgs);
  6045. } else {
  6046. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  6047. }
  6048. } else {
  6049. target[_fnSelectorProp] = 0;
  6050. target[timerIdProp] = 0;
  6051. }
  6052. } else {
  6053. target[prop] = value;
  6054. }
  6055. return true;
  6056. }
  6057. };
  6058.  
  6059. let startBusy = false;
  6060. schedulerInstanceInstance_.start = function () {
  6061. if (startBusy) return;
  6062. startBusy = true;
  6063. try {
  6064. mkFns[0] = window.requestAnimationFrame;
  6065. mkFns[1] = window.setInterval;
  6066. mkFns[2] = window.setTimeout;
  6067. mkFns[3] = window.requestIdleCallback;
  6068. const tThis = this['$$12378$$'] || this;
  6069. window.requestAnimationFrame = fakeFns[0]
  6070. window.setInterval = fakeFns[1]
  6071. window.setTimeout = fakeFns[2]
  6072. window.requestIdleCallback = fakeFns[3]
  6073. _fnSelectorProp = null;
  6074. tThis.start993.call(new Proxy(tThis, startFnHandler));
  6075. _fnSelectorProp = null;
  6076. window.requestAnimationFrame = mkFns[0];
  6077. window.setInterval = mkFns[1];
  6078. window.setTimeout = mkFns[2];
  6079. window.requestIdleCallback = mkFns[3];
  6080. } catch (e) {
  6081. console.warn(e);
  6082. }
  6083. startBusy = false;
  6084. }
  6085.  
  6086. schedulerInstanceInstance_.start.toString = schedulerInstanceInstance_.start993.toString.bind(schedulerInstanceInstance_.start993);
  6087.  
  6088. }
  6089. })();
  6090.  
  6091. FIX_yt_player && (async () => {
  6092.  
  6093. const fOption = 1 | 2 | 4;
  6094.  
  6095. const _yt_player = await _yt_player_observable.obtain();
  6096.  
  6097. if (!_yt_player || typeof _yt_player !== 'object') return;
  6098.  
  6099. const g = _yt_player;
  6100. let k;
  6101.  
  6102. if (fOption & 1) {
  6103.  
  6104. // rAf scheduling
  6105.  
  6106. const keyZqOu = getZqOu(_yt_player);
  6107. if (!keyZqOu) {
  6108. console.warn('[yt-js-engine-tamer] FIX_yt_player::keyZqOu error');
  6109. return;
  6110. }
  6111. k = keyZqOu
  6112.  
  6113. const gk = g[k];
  6114. if (typeof gk !== 'function') {
  6115. console.warn('[yt-js-engine-tamer] FIX_yt_player::g[keyZqOu] error');
  6116. return;
  6117. }
  6118. const gkp = gk.prototype;
  6119.  
  6120. const dummyObject = new gk;
  6121. const nilFunc = () => { };
  6122.  
  6123. const nilObj = {};
  6124.  
  6125. // console.log(1111111111)
  6126.  
  6127. let keyBoolD = '';
  6128. let keyWindow = '';
  6129. let keyFuncC = '';
  6130. let keyCidj = '';
  6131.  
  6132. for (const [t, y] of Object.entries(dummyObject)) {
  6133. if (y instanceof Window) keyWindow = t;
  6134. }
  6135.  
  6136. const dummyObjectProxyHandler = {
  6137. get(target, prop) {
  6138. let v = target[prop]
  6139. if (v instanceof Window && !keyWindow) {
  6140. keyWindow = t;
  6141. }
  6142. let y = typeof v === 'function' ? nilFunc : typeof v === 'object' ? nilObj : v;
  6143. if (prop === keyWindow) y = {
  6144. requestAnimationFrame(f) {
  6145. return 3;
  6146. },
  6147. cancelAnimationFrame() {
  6148.  
  6149. }
  6150. }
  6151. if (!keyFuncC && typeof v === 'function' && !(prop in target.constructor.prototype)) {
  6152. keyFuncC = prop;
  6153. }
  6154. // console.log('[get]', prop, typeof target[prop])
  6155.  
  6156.  
  6157. return y;
  6158. },
  6159. set(target, prop, value) {
  6160.  
  6161. if (typeof value === 'boolean' && !keyBoolD) {
  6162. keyBoolD = prop;
  6163. }
  6164. if (typeof value === 'number' && !keyCidj && value >= 2) {
  6165. keyCidj = prop;
  6166. }
  6167.  
  6168. // console.log('[set]', prop, value)
  6169. target[prop] = value;
  6170.  
  6171. return true;
  6172. }
  6173. };
  6174.  
  6175. dummyObject.start.call(new Proxy(dummyObject, dummyObjectProxyHandler));
  6176.  
  6177. // console.log('gkp.start',gkp.start);
  6178. // console.log('gkp.stop',gkp.stop);
  6179. gkp._activation = false;
  6180.  
  6181. gkp.start = function () {
  6182. // p59 || console.log(12100)
  6183. if (!this._activation) {
  6184. this._activation = true;
  6185. foregroundPromiseFn().then(() => {
  6186. this._activation = false;
  6187. if (this[keyCidj]) {
  6188. Promise.resolve().then(this[keyFuncC]);
  6189. }
  6190. });
  6191. }
  6192. this[keyCidj] = 1;
  6193. this[keyBoolD] = true;
  6194. };
  6195.  
  6196. gkp.stop = function () {
  6197. this[keyCidj] = null;
  6198. };
  6199.  
  6200.  
  6201. /*
  6202. g[k].start = function() {
  6203. this.stop();
  6204. this.D = true;
  6205. var a = requestAnimationFrame
  6206. , b = cancelAnimationFrame;
  6207. this.j = a.call(this.B, this.C)
  6208. }
  6209. ;
  6210. g[k].stop = function() {
  6211. if (this.isActive()) {
  6212. var a = requestAnimationFrame
  6213. , b = cancelAnimationFrame;
  6214. b.call(this.B, this.j)
  6215. }
  6216. this.j = null
  6217. }
  6218. */
  6219. }
  6220.  
  6221. if (fOption & 2) {
  6222. const keyzo = PERF_471489_ ? getzo(_yt_player) : null;
  6223.  
  6224. if (keyzo) {
  6225.  
  6226. k = keyzo;
  6227.  
  6228. const attrUpdateFn = g[k];
  6229. // console.log(5992, attrUpdateFn)
  6230. g['$$original$$' + k] = attrUpdateFn;
  6231. const zoTransform = async (a, c) => {
  6232.  
  6233. let transformType = '';
  6234. let transformValue = 0;
  6235. let transformUnit = '';
  6236. let transformTypeI = 0;
  6237.  
  6238. const aStyle = a.style;
  6239.  
  6240. let cType = 0;
  6241.  
  6242. const cl = c.length;
  6243.  
  6244. if (cl >= 8) {
  6245. // scale(1)
  6246. if (c.startsWith('scale') && c.charCodeAt(6) === 40 && c.charCodeAt(cl - 1) === 41) {
  6247. cType = 1;
  6248. let t = c.charCodeAt(5);
  6249. if (t === 88 || t === 120) cType = 1 | 4;
  6250. if (t === 89 || t === 121) cType = 1 | 8;
  6251. } else if (c.startsWith('translate') && c.charCodeAt(10) === 40 && c.charCodeAt(cl - 1) === 41) {
  6252. cType = 2;
  6253. let t = c.charCodeAt(9);
  6254. if (t === 88 || t === 120) cType = 2 | 4;
  6255. if (t === 89 || t === 121) cType = 2 | 8;
  6256. }
  6257. let w = 0;
  6258. if (w = (cType === 5) ? 1 : (cType === 9) ? 2 : 0) {
  6259. let p = c.substring(7, cl - 1);
  6260. let q = p.length >= 1 ? parseFloat(p) : NaN;
  6261. if (typeof q === 'number' && !isNaNx(q)) {
  6262. transformType = w === 1 ? 'scaleX' : 'scaleY';
  6263. transformValue = q;
  6264. transformUnit = '';
  6265. transformTypeI = 1;
  6266. } else {
  6267. cType = 256;
  6268. }
  6269. } else if (w = (cType === 6) ? 1 : (cType === 10) ? 2 : 0) {
  6270. if (c.endsWith('px)')) {
  6271. let p = c.substring(11, cl - 3);
  6272. let q = p.length >= 1 ? parseFloat(p) : NaN;
  6273. if (typeof q === 'number' && !isNaNx(q)) {
  6274. transformType = w === 1 ? 'translateX' : 'translateY';
  6275. transformValue = q;
  6276. transformUnit = 'px';
  6277. transformTypeI = 2;
  6278. } else if (p === 'NaN') {
  6279. return;
  6280. }
  6281. } else {
  6282. cType = 256;
  6283. }
  6284. } else if (cType > 0) {
  6285. cType = 256;
  6286. }
  6287. }
  6288.  
  6289.  
  6290. if (cType === 256) {
  6291. console.log('[yt-js-engine-tamer] zoTransform undefined', c);
  6292. }
  6293.  
  6294. if (transformTypeI === 1) {
  6295. const q = Math.round(transformValue * steppingScaleN) / steppingScaleN;
  6296. const vz = toFixed2(q, 3);
  6297. c = `${transformType}(${vz})`;
  6298. const cv = aStyle.transform;
  6299. if (c === cv) return;
  6300. aStyle.transform = c;
  6301. } else if (transformTypeI === 2) {
  6302. const q = transformValue;
  6303. const vz = toFixed2(q, 1);
  6304. c = `${transformType}(${vz}${transformUnit})`;
  6305. const cv = aStyle.transform;
  6306. if (c === cv) return;
  6307. aStyle.transform = c;
  6308. } else { // eg empty
  6309. const cv = aStyle.transform;
  6310. if (!c && !cv) return;
  6311. else if (c === cv) return;
  6312. aStyle.transform = c;
  6313. }
  6314.  
  6315. };
  6316.  
  6317. const elmTransformTemp = new WeakMap();
  6318. const elmPropTemps = {
  6319. 'display': new WeakMap(),
  6320. 'width': new WeakMap(),
  6321. 'height': new WeakMap(),
  6322. 'outlineWidth': new WeakMap(),
  6323. 'position': new WeakMap(),
  6324. 'padding': new WeakMap(),
  6325. "cssText": new WeakMap(),
  6326. "right": new WeakMap(),
  6327. "left": new WeakMap(),
  6328. "top": new WeakMap(),
  6329. "bottom": new WeakMap(),
  6330. "transitionDelay": new WeakMap(),
  6331. "marginLeft": new WeakMap(),
  6332. "marginTop": new WeakMap(),
  6333. "marginRight": new WeakMap(),
  6334. "marginBottom": new WeakMap(),
  6335. }
  6336.  
  6337. const ns5 = Symbol();
  6338. const nextModify = (a, c, m, f, immediate) => {
  6339. const a_ = a;
  6340. const m_ = m;
  6341. const noKey = !m_.has(a_);
  6342. if (immediate || noKey) {
  6343. m_.set(a_, ns5);
  6344. f(a_, c);
  6345. noKey && nextBrowserTick_(() => {
  6346. const d = m_.get(a_);
  6347. if (d === undefined) return;
  6348. m_.delete(a_);
  6349. if (d !== ns5) f(a_, d);
  6350. });
  6351. } else {
  6352. m_.set(a_, c);
  6353. }
  6354. };
  6355.  
  6356. const set66 = new Set();
  6357. const log77 = new Map();
  6358. // const set77 = new Set(['top', 'left', 'bottom', 'right']); // caption positioning - immediate change
  6359.  
  6360. const modifiedFn = function (a, b, c, immediateChange = false) { // arrow function does not have function.prototype
  6361.  
  6362. // console.log(140000, a, b, c);
  6363. if (typeof c === 'number' && typeof b === 'string' && a instanceof HTMLElement) {
  6364. const num = c;
  6365. c = `${num}`;
  6366. if (c.length > 5) c = (num < 10 && num > -10) ? toFixed2(num, 3) : toFixed2(num, 1);
  6367. }
  6368.  
  6369. if (typeof b === 'string' && typeof c === 'string' && a instanceof HTMLElement) {
  6370.  
  6371. let elmPropTemp = null;
  6372.  
  6373. if (b === "transform") {
  6374. // div.ytp-hover-progress.ytp-hover-progress-light
  6375. // div.ytp-play-progress.ytp-swatch-background-color
  6376.  
  6377. nextModify(a, c, elmTransformTemp, zoTransform, immediateChange);
  6378. // let ast = null;
  6379. // if (a instanceof HTMLElement && !('__styleH745__' in a) && (ast = a.style)) {
  6380. // a.__styleH745__ = 1;
  6381. // Object.defineProperty(ast, 'left', hookLeftPD);
  6382. // }
  6383. return;
  6384.  
  6385. } else if (elmPropTemp = elmPropTemps[b]) {
  6386.  
  6387. // if (c.length > 5 && c.includes('.')) {
  6388. // console.log(123213, c)
  6389. // }
  6390.  
  6391. const b_ = b;
  6392. nextModify(a, c, elmPropTemp, (a, c) => {
  6393. const style = a.style;
  6394. const cv = style[b_];
  6395. if (!cv && !c) return;
  6396. if (cv === c) return;
  6397. style[b_] = c;
  6398. }, immediateChange);
  6399. return;
  6400.  
  6401. } else if (b === "outline-width") {
  6402.  
  6403. const b_ = 'outlineWidth';
  6404. elmPropTemp = elmPropTemps[b_];
  6405. nextModify(a, c, elmPropTemp, (a, c) => {
  6406. const style = a.style;
  6407. const cv = style[b_];
  6408. if (!cv && !c) return;
  6409. if (cv === c) return;
  6410. style[b_] = c;
  6411. }, immediateChange);
  6412. return;
  6413.  
  6414. } else if (b === 'maxWidth' || b === 'maxHeight') {
  6415. // I think these can be directly assigned.
  6416.  
  6417. const b_ = b;
  6418. const style = a.style;
  6419. const cv = style[b_];
  6420. if (!cv && !c) return;
  6421. if (cv === c) return;
  6422. style[b_] = c;
  6423. return;
  6424.  
  6425. } else {
  6426. // if(immediate && elmPropTemps[b]){
  6427. // console.log(5191, b)
  6428. // }
  6429. // caption-window
  6430. // margin-left max-height max-width font-family fill color font-size background white-space margin
  6431. // text-align background-color
  6432. // console.log(27304, a, b, c)
  6433. if (!set66.has(b)) {
  6434. set66.add(b);
  6435. nextBrowserTick_(() => {
  6436. if (!a.classList.contains('caption-window') && !a.classList.contains('ytp-caption-segment')) {
  6437. console.log(27304, a, b, c)
  6438. }
  6439. })
  6440. }
  6441. }
  6442.  
  6443. attrUpdateFn.call(this, a, b, c);
  6444. return;
  6445. } else if (typeof (b || 0) === 'object') {
  6446.  
  6447. // this is to fix caption positioning
  6448. // const immediate = (a.id || 0).length > 14 && (('top' in b) || ('left' in b) || ('right' in b) || ('bottom' in b));
  6449. const immediate = (a.id || 0).length > 14;
  6450. for (const [k, v] of Object.entries(b)) {
  6451. modifiedFn.call(this, a, k, v, immediate);
  6452. }
  6453.  
  6454. } else {
  6455.  
  6456. // a = circle, b = stroke-dasharray, c= "1.8422857142857143 32"
  6457. // ytp-ad-timed-pie-countdown-inner
  6458.  
  6459. if (typeof b === 'string') {
  6460.  
  6461. let m = log77.get(b);
  6462. if (!m) {
  6463. m = [];
  6464. console.log(27306, m);
  6465. log77.set(b, m);
  6466. }
  6467. m.push([a, b, c]);
  6468.  
  6469. } else {
  6470. console.log(27306, a, b, c);
  6471. }
  6472.  
  6473. attrUpdateFn.call(this, a, b, c);
  6474. return;
  6475. }
  6476.  
  6477. // console.log(130000, a, b, c);
  6478.  
  6479. };
  6480. g[k] = modifiedFn;
  6481.  
  6482.  
  6483. /*
  6484. g.zo = function(a, b, c) {
  6485. if ("string" === typeof b)
  6486. (b = yo(a, b)) && (a.style[b] = c);
  6487. else
  6488. for (var d in b) {
  6489. c = a;
  6490. var e = b[d]
  6491. , f = yo(c, d);
  6492. f && (c.style[f] = e)
  6493. }
  6494. }
  6495. */
  6496.  
  6497.  
  6498. }
  6499. }
  6500.  
  6501. if (fOption & 4) {
  6502. const keyuG = PERF_471489_ ? getuG(_yt_player) : null;
  6503.  
  6504. if (keyuG) {
  6505.  
  6506. k = keyuG;
  6507.  
  6508. const gk = g[k];
  6509. const gkp = gk.prototype;
  6510.  
  6511.  
  6512. /** @type { Map<string, WeakMap<any, any>> } */
  6513. const ntLogs = new Map();
  6514.  
  6515. if (typeof gkp.updateValue === 'function' && gkp.updateValue.length === 2 && !gkp.updateValue31) {
  6516.  
  6517. gkp.updateValue31 = gkp.updateValue;
  6518. gkp.updateValue = function (a, b) {
  6519. if (typeof a !== 'string') return this.updateValue31(a, b);
  6520.  
  6521. const element = this.element;
  6522. if (!(element instanceof HTMLElement)) return this.updateValue31(a, b);
  6523.  
  6524. let ntLog = ntLogs.get(a);
  6525. if (!ntLog) ntLogs.set(a, (ntLog = new WeakMap()));
  6526.  
  6527. let cache = ntLog.get(element);
  6528. if (cache && cache.value === b) {
  6529. return;
  6530. }
  6531. if (!cache) {
  6532. this.__oldValueByUpdateValue__ = null;
  6533. ntLog.set(element, cache = { value: b });
  6534. } else {
  6535. this.__oldValueByUpdateValue__ = cache.value;
  6536. cache.value = b;
  6537. }
  6538.  
  6539. return this.updateValue31(a, b);
  6540. }
  6541.  
  6542. /*
  6543. g.k.update = function(a) {
  6544. for (var b = g.u(Object.keys(a)), c = b.next(); !c.done; c = b.next())
  6545. c = c.value,
  6546. this.updateValue(c, a[c])
  6547. }
  6548. ;
  6549. g.k.updateValue = function(a, b) {
  6550. (a = this.Td["{{" + a + "}}"]) && wG(this, a[0], a[1], b)
  6551. }
  6552. */
  6553.  
  6554. }
  6555.  
  6556.  
  6557. }
  6558. }
  6559.  
  6560.  
  6561.  
  6562. })();
  6563.  
  6564.  
  6565. FIX_yt_player && FIX_SHORTCUTKEYS > 0 && (async () => {
  6566. // keyboard shortcut keys controller
  6567.  
  6568. const _yt_player = await _yt_player_observable.obtain();
  6569.  
  6570. if (!_yt_player || typeof _yt_player !== 'object') return;
  6571.  
  6572. keyboardController(_yt_player);
  6573.  
  6574. })();
  6575.  
  6576. FIX_yt_player && (async () => {
  6577. // timer scheduling
  6578.  
  6579. const _yt_player = await _yt_player_observable.obtain();
  6580.  
  6581. if (!_yt_player || typeof _yt_player !== 'object') return;
  6582.  
  6583. let keyZqQu = getZqQu(_yt_player);
  6584.  
  6585. if (!keyZqQu) return;
  6586.  
  6587. const g = _yt_player
  6588. let k = keyZqQu
  6589.  
  6590. const gk = g[k];
  6591. if (typeof gk !== 'function') return;
  6592. const gkp = gk.prototype;
  6593.  
  6594. const extractKeysZqQu = () => {
  6595.  
  6596.  
  6597. let _keyeC = '';
  6598. try {
  6599. gkp.stop.call(new Proxy({
  6600. isActive: () => { }
  6601. }, {
  6602. set(target, prop, value) {
  6603. if (value === 0) _keyeC = prop;
  6604. return true;
  6605. }
  6606. }));
  6607. } catch (e) { }
  6608. if (!_keyeC) return;
  6609. const keyeC = _keyeC;
  6610.  
  6611. let keyC = ''; // this.C = this.ST.bind(this)
  6612. let keyhj = ''; // 1000ms
  6613. try {
  6614. gkp.start.call(new Proxy({
  6615. stop: () => { },
  6616. [keyeC]: 0,
  6617. }, {
  6618. get(target, prop) {
  6619. if (prop in target) return target[prop];
  6620. if (!keyC) {
  6621. keyC = prop;
  6622. return null; // throw error
  6623. }
  6624. else if (!keyhj) {
  6625. keyhj = prop;
  6626. }
  6627.  
  6628. }
  6629. }));
  6630. } catch (e) {
  6631. if (!keyC || !keyhj) {
  6632. console.log(e)
  6633. }
  6634. }
  6635.  
  6636. if (!keyC || !keyhj) return;
  6637. let keyST = '';
  6638. let keyj = '';
  6639. let keyB = '';
  6640. let keyxa = '';
  6641.  
  6642. const possibleKs = new Set();
  6643.  
  6644. for (const [k, v] of Object.entries(gkp)) {
  6645. if (k === 'stop' || k === 'start' || k === 'isActive' || k === 'constructor' || k === keyeC || k === keyC || k === keyhj) {
  6646. continue;
  6647. }
  6648. if (typeof v === 'function') {
  6649. const m = /this\.(\w+)\.call\(this\.(\w+)\)/.exec(v + '');
  6650. if (m) {
  6651. keyST = k;
  6652. keyj = m[1];
  6653. keyB = m[2];
  6654. } else {
  6655. possibleKs.add(k);
  6656. }
  6657. }
  6658. }
  6659.  
  6660. if (!keyST || !keyj || !keyB) return;
  6661.  
  6662. for (const k of possibleKs) {
  6663. if (k === keyST || k === keyj || k === keyB) {
  6664. continue;
  6665. }
  6666. const v = gkp[k];
  6667. if (typeof v === 'function' && (v + '').includes(`this.stop();delete this.${keyj};delete this.${keyB}`)) {
  6668. keyxa = k;
  6669. }
  6670. }
  6671.  
  6672. return [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa];
  6673.  
  6674. }
  6675.  
  6676. const keys = extractKeysZqQu();
  6677. if (!keys || !keys.length) return;
  6678. const [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa] = keys; // [timerId, binded executorFn, 1000ms, executorFn, dataJ, objectB, disposeFn]
  6679.  
  6680. if (!keyeC || !keyC || !keyhj || !keyST || !keyj || !keyB || !keyxa) return;
  6681.  
  6682. let disposeKeys = null;
  6683.  
  6684. gkp[keyxa] = function () {
  6685. // dispose
  6686. if (!disposeKeys) {
  6687. disposeKeys = Object.getOwnPropertyNames(this).filter(key => {
  6688. if (key != keyeC && key != keyC && key != keyhj && key != keyST && key != keyj && key != keyB && key != keyxa) {
  6689. const t = typeof this[key];
  6690. return t === 'undefined' || t === 'object'
  6691. }
  6692. return false;
  6693. });
  6694. }
  6695. for (const key of disposeKeys) {
  6696. const v = this[key];
  6697. if ((v || 0).length >= 1) v.length = 0; // function (){if(this.fn)for(;this.fn.length;)this.fn.shift()()}
  6698. }
  6699. if (this[keyeC] > 0) this.stop();
  6700. this[keyj] = null;
  6701. this[keyB] = null;
  6702. };
  6703.  
  6704. gkp.start = function (a) {
  6705. if (this[keyeC] > 0) this.stop();
  6706. const delay = void 0 !== a ? a : this[keyhj];
  6707. this[keyeC] = window.setTimeout(this[keyC], delay);
  6708. };
  6709. gkp.stop = function () {
  6710. if (this[keyeC] > 0) {
  6711. window.clearTimeout(this[keyeC]);
  6712. this[keyeC] = 0;
  6713. }
  6714. };
  6715.  
  6716. gkp.isActive = function () {
  6717. return this[keyeC] > 0;
  6718. };
  6719.  
  6720. gkp[keyST] = function () {
  6721. this.stop(); // this[keyeC] = 0;
  6722. const fn = this[keyj];
  6723. const obj = this[keyB];
  6724. let skip = false;
  6725. if (!fn) skip = true;
  6726. else if (IGNORE_bufferhealth_CHECK && obj) {
  6727. let m;
  6728. if ((m = obj[keyC]) instanceof Map || (m = obj[keyj]) instanceof Map) {
  6729. if (m.has("bufferhealth")) skip = true;
  6730. }
  6731. }
  6732. if (!skip) {
  6733. fn.call(obj);
  6734. }
  6735. };
  6736.  
  6737.  
  6738.  
  6739.  
  6740. /*
  6741.  
  6742. g.k.eC = 0;
  6743. g.k.xa = function() {
  6744. g.Qu.Vf.xa.call(this);
  6745. this.stop();
  6746. delete this.j;
  6747. delete this.B
  6748. }
  6749. ;
  6750. g.k.start = function(a) {
  6751. this.stop();
  6752. this.eC = g.gg(this.C, void 0 !== a ? a : this.hj)
  6753. }
  6754. ;
  6755. g.k.stop = function() {
  6756. this.isActive() && g.Sa.clearTimeout(this.eC);
  6757. this.eC = 0
  6758. }
  6759. ;
  6760. g.k.isActive = function() {
  6761. return 0 != this.eC
  6762. }
  6763. ;
  6764. g.k.ST = function() {
  6765. this.eC = 0;
  6766. this.j && this.j.call(this.B)
  6767. }
  6768. ;
  6769. */
  6770.  
  6771.  
  6772.  
  6773.  
  6774. })();
  6775.  
  6776. FIX_Animation_n_timeline && (async () => {
  6777.  
  6778. const [timeline, Animation] = await Promise.all([timelineObservable.obtain(), animationObservable.obtain()]);
  6779.  
  6780. if (!timeline || !Animation) return;
  6781.  
  6782. const aniProto = Animation.prototype;
  6783. // aniProto.sequenceNumber = 0; // native YouTube engine bug - sequenceNumber is not set
  6784.  
  6785. const getXroto = (x) => {
  6786. try {
  6787. return x.__proto__;
  6788. } catch (e) { }
  6789. return null;
  6790. }
  6791. const timProto = getXroto(timeline);
  6792. if (!timProto) return;
  6793. if (
  6794. (
  6795. typeof timProto.getAnimations === 'function' && typeof timProto.play === 'function' &&
  6796. typeof timProto._discardAnimations === 'function' && typeof timProto._play === 'function' &&
  6797. typeof timProto._updateAnimationsPromises === 'function' && !timProto.nofCQ &&
  6798. typeof aniProto._updatePromises === 'function' && !aniProto.nofYH
  6799. )
  6800.  
  6801. ) {
  6802.  
  6803. timProto.nofCQ = 1;
  6804. aniProto.nofYH = 1;
  6805.  
  6806. const originalAnimationsWithPromises = ((_updateAnimationsPromises) => {
  6807.  
  6808.  
  6809. /*
  6810. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  6811. return c._updatePromises();
  6812. });
  6813. */
  6814.  
  6815. const p = Array.prototype.filter;
  6816.  
  6817. let res = null;
  6818. Array.prototype.filter = function () {
  6819.  
  6820. res = this;
  6821. return this;
  6822.  
  6823. };
  6824.  
  6825. _updateAnimationsPromises.call({});
  6826.  
  6827. Array.prototype.filter = p;
  6828.  
  6829. if (res && typeof res.length === 'number') {
  6830. /** @type {any[]} */
  6831. const _res = res;
  6832. return _res;
  6833. }
  6834.  
  6835.  
  6836. return null;
  6837.  
  6838.  
  6839.  
  6840.  
  6841. })(timProto._updateAnimationsPromises);
  6842.  
  6843. if (!originalAnimationsWithPromises || typeof originalAnimationsWithPromises.length !== 'number') return;
  6844.  
  6845. // console.log('originalAnimationsWithPromises', originalAnimationsWithPromises)
  6846.  
  6847. aniProto._updatePromises31 = aniProto._updatePromises;
  6848.  
  6849. /*
  6850. aniProto._updatePromises = function(){
  6851. console.log('eff',this._oldPlayState, this.playState)
  6852. return this._updatePromises31.apply(this, arguments)
  6853. }
  6854. */
  6855.  
  6856. aniProto._updatePromises = function () {
  6857. var oldPlayState = this._oldPlayState;
  6858. var newPlayState = this.playState;
  6859. // console.log('ett', oldPlayState, newPlayState)
  6860. if (newPlayState !== oldPlayState) {
  6861. this._oldPlayState = newPlayState;
  6862. if (this._readyPromise) {
  6863. if ("idle" == newPlayState) {
  6864. this._rejectReadyPromise();
  6865. this._readyPromise = void 0;
  6866. } else if ("pending" == oldPlayState) {
  6867. this._resolveReadyPromise();
  6868. } else if ("pending" == newPlayState) {
  6869. this._readyPromise = void 0;
  6870. }
  6871. }
  6872. if (this._finishedPromise) {
  6873. if ("idle" == newPlayState) {
  6874. this._rejectFinishedPromise();
  6875. this._finishedPromise = void 0;
  6876. } else if ("finished" == newPlayState) {
  6877. this._resolveFinishedPromise();
  6878. } else if ("finished" == oldPlayState) {
  6879. this._finishedPromise = void 0;
  6880. }
  6881. }
  6882. }
  6883. return this._readyPromise || this._finishedPromise;
  6884. };
  6885.  
  6886.  
  6887. let restartWebAnimationsNextTickFlag = false;
  6888.  
  6889. const looperMethodT = () => {
  6890.  
  6891. const runnerFn = (hRes) => {
  6892. var b = timeline;
  6893. b.currentTime = hRes;
  6894. b._discardAnimations();
  6895. if (0 == b._animations.length) {
  6896. restartWebAnimationsNextTickFlag = false;
  6897. } else {
  6898. getRafPromise().then(runnerFn);
  6899. }
  6900. }
  6901.  
  6902. const restartWebAnimationsNextTick = () => {
  6903. if (!restartWebAnimationsNextTickFlag) {
  6904. restartWebAnimationsNextTickFlag = true;
  6905. getRafPromise().then(runnerFn);
  6906. }
  6907. }
  6908.  
  6909. return { restartWebAnimationsNextTick }
  6910. };
  6911.  
  6912.  
  6913. const looperMethodN = () => {
  6914.  
  6915. const acs = document.createElement('a-f');
  6916. acs.id = 'a-f';
  6917.  
  6918. if (!document.getElementById('afscript')) {
  6919. const style = document.createElement('style');
  6920. style.id = 'afscript';
  6921. style.textContent = `
  6922. @keyFrames aF1 {
  6923. 0% {
  6924. order: 0;
  6925. }
  6926. 100% {
  6927. order: 1;
  6928. }
  6929. }
  6930. #a-f[id] {
  6931. visibility: collapse !important;
  6932. position: fixed !important;
  6933. display: block !important;
  6934. top: -100px !important;
  6935. left: -100px !important;
  6936. margin:0 !important;
  6937. padding:0 !important;
  6938. outline:0 !important;
  6939. border:0 !important;
  6940. z-index:-1 !important;
  6941. width: 0px !important;
  6942. height: 0px !important;
  6943. contain: strict !important;
  6944. pointer-events: none !important;
  6945. animation: 1ms steps(2, jump-none) 0ms infinite alternate forwards running aF1 !important;
  6946. }
  6947. `;
  6948. (document.head || document.documentElement).appendChild(style);
  6949. }
  6950.  
  6951. document.documentElement.insertBefore(acs, document.documentElement.firstChild);
  6952.  
  6953. const _onanimationiteration = function (evt) {
  6954. const hRes = evt.timeStamp;
  6955. var b = timeline;
  6956. b.currentTime = hRes;
  6957. b._discardAnimations();
  6958. if (0 == b._animations.length) {
  6959. restartWebAnimationsNextTickFlag = false;
  6960. acs.onanimationiteration = null;
  6961. } else {
  6962. acs.onanimationiteration = _onanimationiteration;
  6963. }
  6964.  
  6965. }
  6966.  
  6967.  
  6968.  
  6969. const restartWebAnimationsNextTick = () => {
  6970. if (!restartWebAnimationsNextTickFlag) {
  6971. restartWebAnimationsNextTickFlag = true;
  6972. acs.onanimationiteration = _onanimationiteration;
  6973.  
  6974. }
  6975. }
  6976.  
  6977. return { restartWebAnimationsNextTick }
  6978. };
  6979.  
  6980.  
  6981.  
  6982. const { restartWebAnimationsNextTick } = ('onanimationiteration' in document.documentElement) ? looperMethodN() : looperMethodT();
  6983.  
  6984.  
  6985. // console.log(571, timProto);
  6986. timProto._play = function (c) {
  6987. c = new Animation(c, this);
  6988. this._animations.push(c);
  6989. restartWebAnimationsNextTick();
  6990. c._updatePromises();
  6991. c._animation.play();
  6992. c._updatePromises();
  6993. return c
  6994. }
  6995.  
  6996. const animationsWithPromisesMap = new Set(originalAnimationsWithPromises);
  6997. originalAnimationsWithPromises.length = 0;
  6998. originalAnimationsWithPromises.push = null;
  6999. originalAnimationsWithPromises.splice = null;
  7000. originalAnimationsWithPromises.slice = null;
  7001. originalAnimationsWithPromises.indexOf = null;
  7002. originalAnimationsWithPromises.unshift = null;
  7003. originalAnimationsWithPromises.shift = null;
  7004. originalAnimationsWithPromises.pop = null;
  7005. originalAnimationsWithPromises.filter = null;
  7006. originalAnimationsWithPromises.forEach = null;
  7007. originalAnimationsWithPromises.map = null;
  7008.  
  7009.  
  7010. const _updateAnimationsPromises = () => {
  7011. animationsWithPromisesMap.forEach(c => {
  7012. if (!c._updatePromises()) animationsWithPromisesMap.delete(c);
  7013. });
  7014. /*
  7015. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  7016. return c._updatePromises();
  7017. });
  7018. */
  7019. }
  7020.  
  7021. timProto._updateAnimationsPromises31 = timProto._updateAnimationsPromises;
  7022.  
  7023. timProto._updateAnimationsPromises = _updateAnimationsPromises;
  7024.  
  7025. delete timProto._updateAnimationsPromises;
  7026. Object.defineProperty(timProto, '_updateAnimationsPromises', {
  7027. get() {
  7028. if (animationsWithPromisesMap.size === 0) return nilFn;
  7029. return _updateAnimationsPromises;
  7030. },
  7031. set(nv) {
  7032. delete this._updateAnimationsPromises;
  7033. this._updateAnimationsPromises = nv;
  7034. },
  7035. enumerable: true,
  7036. configurable: true,
  7037. });
  7038.  
  7039.  
  7040. let pdFinished = Object.getOwnPropertyDescriptor(aniProto, 'finished');
  7041. aniProto.__finished_native_get__ = pdFinished.get;
  7042. if (typeof pdFinished.get === 'function' && !pdFinished.set && pdFinished.configurable === true && pdFinished.enumerable === true) {
  7043.  
  7044.  
  7045. Object.defineProperty(aniProto, 'finished', {
  7046. get() {
  7047. this._finishedPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  7048. this._finishedPromise = new Promise((resolve, reject) => {
  7049. this._resolveFinishedPromise = function () {
  7050. resolve(this)
  7051. };
  7052. this._rejectFinishedPromise = function () {
  7053. reject({
  7054. type: DOMException.ABORT_ERR,
  7055. name: "AbortError"
  7056. })
  7057. };
  7058. }),
  7059. "finished" == this.playState && this._resolveFinishedPromise());
  7060. return this._finishedPromise
  7061. },
  7062. set: undefined,
  7063. enumerable: true,
  7064. configurable: true
  7065. });
  7066.  
  7067. }
  7068.  
  7069.  
  7070.  
  7071. let pdReady = Object.getOwnPropertyDescriptor(aniProto, 'ready');
  7072. aniProto.__ready_native_get__ = pdReady.get;
  7073. if (typeof pdReady.get === 'function' && !pdReady.set && pdReady.configurable === true && pdReady.enumerable === true) {
  7074.  
  7075. Object.defineProperty(aniProto, 'ready', {
  7076. get() {
  7077. this._readyPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  7078. this._readyPromise = new Promise((resolve, reject) => {
  7079. this._resolveReadyPromise = function () {
  7080. resolve(this)
  7081. };
  7082. this._rejectReadyPromise = function () {
  7083. reject({
  7084. type: DOMException.ABORT_ERR,
  7085. name: "AbortError"
  7086. })
  7087. };
  7088. }),
  7089. "pending" !== this.playState && this._resolveReadyPromise());
  7090. return this._readyPromise
  7091. },
  7092. set: undefined,
  7093. enumerable: true,
  7094. configurable: true
  7095. });
  7096.  
  7097. }
  7098.  
  7099.  
  7100. if (IGNORE_bindAnimationForCustomEffect && typeof aniProto._rebuildUnderlyingAnimation === 'function' && !aniProto._rebuildUnderlyingAnimation21 && aniProto._rebuildUnderlyingAnimation.length === 0) {
  7101.  
  7102. aniProto._rebuildUnderlyingAnimation21 = aniProto._rebuildUnderlyingAnimation;
  7103. const _rebuildUnderlyingAnimation = function () {
  7104. // if (isNaN(this._sequenceNumber)) return; // do not rebuild underlying animation if native animation is used.
  7105. this.effect && this.effect._onsample && (this.effect._onsample = null);
  7106. return this._rebuildUnderlyingAnimation21();
  7107. }
  7108. aniProto._rebuildUnderlyingAnimation = _rebuildUnderlyingAnimation;
  7109. // delete aniProto._rebuildUnderlyingAnimation;
  7110. // Object.defineProperty(aniProto, '_rebuildUnderlyingAnimation', {
  7111. // get() {
  7112. // if (isNaN(this._sequenceNumber)) return nilFn;
  7113. // return this._rebuildUnderlyingAnimation21;
  7114. // },
  7115. // set(nv) {
  7116. // delete this._rebuildUnderlyingAnimation;
  7117. // this._rebuildUnderlyingAnimation = nv;
  7118. // },
  7119. // enumerable: true,
  7120. // configurable: true
  7121. // });
  7122. }
  7123.  
  7124.  
  7125. /*
  7126.  
  7127.  
  7128. function f(c) {
  7129. var b = v.timeline;
  7130. b.currentTime = c;
  7131. b._discardAnimations();
  7132. 0 == b._animations.length ? d = !1 : requestAnimationFrame(f)
  7133. }
  7134. var h = window.requestAnimationFrame;
  7135. window.requestAnimationFrame = function(c) {
  7136. return h(function(b) {
  7137. v.timeline._updateAnimationsPromises();
  7138. c(b);
  7139. v.timeline._updateAnimationsPromises()
  7140. })
  7141. }
  7142. ;
  7143. v.AnimationTimeline = function() {
  7144. this._animations = [];
  7145. this.currentTime = void 0
  7146. }
  7147. ;
  7148. v.AnimationTimeline.prototype = {
  7149. getAnimations: function() {
  7150. this._discardAnimations();
  7151. return this._animations.slice()
  7152. },
  7153. _updateAnimationsPromises: function() {
  7154. v.animationsWithPromises = v.animationsWithPromises.filter(function(c) {
  7155. return c._updatePromises()
  7156. })
  7157. },
  7158. _discardAnimations: function() {
  7159. this._updateAnimationsPromises();
  7160. this._animations = this._animations.filter(function(c) {
  7161. return "finished" != c.playState && "idle" != c.playState
  7162. })
  7163. },
  7164. _play: function(c) {
  7165. c = new v.Animation(c,this);
  7166. this._animations.push(c);
  7167. v.restartWebAnimationsNextTick();
  7168. c._updatePromises();
  7169. c._animation.play();
  7170. c._updatePromises();
  7171. return c
  7172. },
  7173. play: function(c) {
  7174. c && c.remove();
  7175. return this._play(c)
  7176. }
  7177. };
  7178. var d = !1;
  7179. v.restartWebAnimationsNextTick = function() {
  7180. d || (d = !0,
  7181. requestAnimationFrame(f))
  7182. }
  7183. ;
  7184. var a = new v.AnimationTimeline;
  7185. v.timeline = a;
  7186. try {
  7187. Object.defineProperty(window.document, "timeline", {
  7188. configurable: !0,
  7189. get: function() {
  7190. return a
  7191. }
  7192. })
  7193. } catch (c) {}
  7194. try {
  7195. window.document.timeline = a
  7196. } catch (c) {}
  7197.  
  7198. */
  7199.  
  7200.  
  7201.  
  7202. /*
  7203.  
  7204. var g = window.getComputedStyle;
  7205. Object.defineProperty(window, "getComputedStyle", {
  7206. configurable: !0,
  7207. enumerable: !0,
  7208. value: function() {
  7209. v.timeline._updateAnimationsPromises();
  7210. var e = g.apply(this, arguments);
  7211. h() && (e = g.apply(this, arguments));
  7212. v.timeline._updateAnimationsPromises();
  7213. return e
  7214. }
  7215. });
  7216.  
  7217. */
  7218.  
  7219.  
  7220.  
  7221.  
  7222. }
  7223.  
  7224.  
  7225.  
  7226.  
  7227. })();
  7228.  
  7229. !isUrlInEmbed && Promise.resolve().then(() => {
  7230.  
  7231. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  7232.  
  7233.  
  7234.  
  7235. class LimitedSizeSet extends Set {
  7236. constructor(n) {
  7237. super();
  7238. this.limit = n;
  7239. }
  7240.  
  7241. add(key) {
  7242. if (!super.has(key)) {
  7243. super.add(key);
  7244. let n = super.size - this.limit;
  7245. if (n > 0) {
  7246. const iterator = super.values();
  7247. do {
  7248. const firstKey = iterator.next().value; // Get the first (oldest) key
  7249. super.delete(firstKey); // Delete the oldest key
  7250. } while (--n > 0)
  7251. }
  7252. }
  7253. }
  7254.  
  7255. removeAdd(key) {
  7256. super.delete(key);
  7257. this.add(key);
  7258. }
  7259.  
  7260. }
  7261.  
  7262. // const wk3 = new WeakMap();
  7263.  
  7264. // let mtxVideoId = '';
  7265. // let aje3 = [];
  7266. const mfvContinuationRecorded = new LimitedSizeSet(8); // record all success continuation keys
  7267. const mfyContinuationIgnored = new LimitedSizeSet(8); // ignore continuation keys by copying the keys in the past
  7268. let mtzlastAllowedContinuation = ''; // the key stored at the last success; clear when scheduling changes
  7269. let mtzCount = 0; // the key keeps unchanged
  7270. // let mjtNextMainKey = '';
  7271. let mjtRecordedPrevKey = ''; // the key stored at the last success (no clear)
  7272. let mjtLockPreviousKey = ''; // the key before fetch() should be discarded. (uncertain continuation)
  7273. let mbCId322 = 0; // cid for delay fetchUpdatedMetadata
  7274. // let allowNoDelay322=false;
  7275. let mbDelayBelowNCalls = 0; // after N calls, by pass delay; reset when scheduling changes
  7276.  
  7277. let mpKey22 = ''; // last success continutation key & url pair
  7278. let mpUrl22 = ''; // last success continutation key & url pair
  7279. let mpKey21 = ''; // latest requested continutation key & url pair
  7280. let mpUrl21 = ''; // latest requested continutation key & url pair
  7281.  
  7282.  
  7283. async function sha1Hex(message) {
  7284. const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  7285. const hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8); // hash the message
  7286. const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  7287. const hashHex = hashArray
  7288. .map((b) => b.toString(16).padStart(2, "0"))
  7289. .join(""); // convert bytes to hex string
  7290. return hashHex;
  7291. }
  7292.  
  7293. async function continuationLog(a, ...args) {
  7294. let b = a;
  7295. try {
  7296. if (advanceLogging) b = await sha1Hex(a);
  7297. let c = args.map(e => {
  7298. return e === a ? b : e
  7299. });
  7300. console.log(...c)
  7301. } catch (e) { console.warn(e) }
  7302. }
  7303.  
  7304. function copyPreviousContiuationToIgnored374(toClearRecorded) {
  7305.  
  7306.  
  7307. if (mfvContinuationRecorded.length > 0) {
  7308. for (const [e, d] of mfvContinuationRecorded) {
  7309. mfyContinuationIgnored.removeAdd(e);
  7310. }
  7311. toClearRecorded && mfvContinuationRecorded.clear();
  7312. }
  7313.  
  7314. }
  7315.  
  7316. function setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr) {
  7317.  
  7318. const tmProto = taskMgr.constructor.prototype;
  7319. if (tmProto && typeof tmProto.addJob === 'function' && tmProto.addJob.length === 3 && typeof tmProto.cancelJob === 'function' && tmProto.cancelJob.length === 1) {
  7320.  
  7321. if (!tmProto.addJob714) {
  7322.  
  7323. tmProto.addJob714 = tmProto.addJob;
  7324.  
  7325. tmProto.addJob = function (a, b, c) {
  7326. const jobId = this.addJob714(a, b, c);
  7327. if (jobId > 0) {
  7328. // const ez = wk3.get(this);
  7329. // const dz = ez ? ez.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint : null;
  7330. // aje3.push({mtx, jobId, a,b,c, element: this, dz, data: (ez?.data || null) })
  7331.  
  7332. this.__lastJobId863__ = jobId;
  7333. }
  7334. return jobId;
  7335. }
  7336.  
  7337. }
  7338.  
  7339. if (!tmProto.cancelJob714) {
  7340.  
  7341. tmProto.cancelJob714 = tmProto.cancelJob;
  7342.  
  7343. tmProto.cancelJob = function (a) {
  7344. const res = this.cancelJob714(a);
  7345. // if (a > 0) {
  7346. // for (const e of aje3) {
  7347. // if (e.jobId === a) e.cancelled = true;
  7348. // }
  7349. // }
  7350. return res;
  7351. }
  7352.  
  7353. }
  7354.  
  7355. }
  7356. }
  7357.  
  7358.  
  7359. const FIX_avoid_incorrect_video_meta_bool = FIX_avoid_incorrect_video_meta && isPrepareCachedV && check_for_set_key_order;
  7360.  
  7361.  
  7362. FIX_avoid_incorrect_video_meta_bool && whenCEDefined('ytd-video-primary-info-renderer').then(() => {
  7363. let dummy;
  7364. let cProto;
  7365. // let mc = 4;
  7366. // dummy = await observablePromise(() => {
  7367. // const r = document.querySelector('ytd-video-primary-info-renderer');
  7368. // if (!r) return;
  7369. // let cProto = insp(r).constructor.prototype;
  7370. // if (cProto.fetchUpdatedMetadata) return r;
  7371. // if (--mc < 0) return -1;
  7372. // return null;
  7373. // }).obtain();
  7374. dummy = document.createElement('ytd-video-primary-info-renderer');
  7375. if (!(dummy instanceof Element)) return;
  7376. // console.log(5022, dummy)
  7377. cProto = insp(dummy).constructor.prototype;
  7378.  
  7379. cProto.__getEmittorTaskMgr859__ = function () {
  7380. let taskMgr_ = null;
  7381. try {
  7382. taskMgr_ = (this.ytTaskEmitterBehavior || 0).getTaskManager() || null;
  7383. } catch (e) { }
  7384. return taskMgr_;
  7385. }
  7386. if (typeof cProto.fetchUpdatedMetadata === 'function' && cProto.fetchUpdatedMetadata.length === 1 && !cProto.fetchUpdatedMetadata717) {
  7387. // console.log(1234, cProto, cProto.is)
  7388. cProto.fetchUpdatedMetadata717 = cProto.fetchUpdatedMetadata;
  7389.  
  7390. let c_;
  7391. cProto.fetchUpdatedMetadata718 = function (a) {
  7392. // delay or immediate call the actual fetchUpdatedMetadata
  7393.  
  7394. let doImmediately = false;
  7395. if (a && typeof a === 'string' && mjtRecordedPrevKey && mjtRecordedPrevKey === mpKey22 && a === mpKey22 && (!pageSetupVideoId || pageSetupVideoId !== mpUrl22)) {
  7396.  
  7397. if (!pageSetupVideoId && videoPlayingY.videoId === mpUrl22) doImmediately = true;
  7398.  
  7399. } else if (typeof a !== 'string' || mbDelayBelowNCalls > 3 || !mpKey22 || (mpKey22 === a && mpKey22 !== mjtLockPreviousKey) || (mjtLockPreviousKey && mjtLockPreviousKey !== a)) {
  7400.  
  7401. doImmediately = true;
  7402.  
  7403. }
  7404.  
  7405. if (mbCId322) {
  7406. clearTimeout(mbCId322);
  7407. mbCId322 = 0;
  7408. }
  7409.  
  7410. if (doImmediately) return this.fetchUpdatedMetadata717(a);
  7411.  
  7412. let delay = mjtLockPreviousKey === a ? 8000 : 800;
  7413.  
  7414. mbCId322 = setTimeout(() => {
  7415. this.fetchUpdatedMetadata717(a);
  7416. }, delay);
  7417.  
  7418. console.log('[yt-js-engine-tamer]', '5190 delayed fetchUpdatedMetadata', delay);
  7419.  
  7420. }
  7421.  
  7422. cProto.fetchUpdatedMetadata = function (a) {
  7423.  
  7424. if (!pageSetupState) {
  7425. if (c_) clearTimeout(c_);
  7426. c_ = setTimeout(() => {
  7427. this.fetchUpdatedMetadata718(a);
  7428. }, 300);
  7429. return;
  7430. }
  7431.  
  7432. // pageSetupState == 0
  7433.  
  7434. try {
  7435.  
  7436. mbDelayBelowNCalls++;
  7437.  
  7438. if (arguments.length > 1 || !(a === undefined || (typeof a === 'string' && a))) {
  7439. console.warn("CAUTION: fetchUpdatedMetadata coding might have to be updated.");
  7440. }
  7441.  
  7442. // console.log('fum377', a)
  7443. if (typeof a === 'string' && mfyContinuationIgnored.has(a)) {
  7444. console.log('[yt-js-engine-tamer]', '5040 skip fetchUpdatedMetadata', a);
  7445. return;
  7446. }
  7447.  
  7448. if (!a && (this.data || 0).updatedMetadataEndpoint) {
  7449. if (mjtRecordedPrevKey && mjtLockPreviousKey !== mjtRecordedPrevKey) {
  7450. mjtLockPreviousKey = mjtRecordedPrevKey;
  7451. LOG_FETCHMETA_UPDATE && continuationLog(mjtLockPreviousKey, '5150 Lock Key', mjtLockPreviousKey);
  7452. }
  7453. // mjtNextMainKey = true;
  7454. mtzlastAllowedContinuation = '';
  7455. mtzCount = 0;
  7456. // allowNoDelay322 = false;
  7457. // fetch new metadata, cancel all previous continuations
  7458. copyPreviousContiuationToIgnored374(true);
  7459. } else if (typeof a === 'string') {
  7460. const videoPlayingId = videoPlayingY.videoId;
  7461.  
  7462. // if(mjtNextMainKey === true) mjtNextMainKey = a;
  7463.  
  7464. let update21 = !!pageSetupVideoId;
  7465. if (mpKey22 === a && mpUrl22 === videoPlayingId && mpUrl22 && videoPlayingId && (!pageSetupVideoId || pageSetupVideoId === videoPlayingId)) {
  7466. update21 = true;
  7467. } else if (mpKey22 === a && mpUrl22 !== pageSetupVideoId) {
  7468. LOG_FETCHMETA_UPDATE && continuationLog(mpKey22, '5060 mpUrl22 mismatched', mpKey22, mpUrl22, pageSetupVideoId || '(null)', videoPlayingId || '(null)');
  7469. return;
  7470. }
  7471. if (update21) {
  7472. mpKey21 = a;
  7473. mpUrl21 = pageSetupVideoId || videoPlayingId;
  7474. }
  7475.  
  7476. if (!mfvContinuationRecorded.has(a)) mfvContinuationRecorded.add(a);
  7477. }
  7478. LOG_FETCHMETA_UPDATE && continuationLog(a, '5180 fetchUpdatedMetadata\t', a, pageSetupVideoId || '(null)', videoPlayingY.videoId || '(null)');
  7479. // if (!pageSetupVideoId && typeof a === 'string' && a.length > 40) return; // ignore incorrect continuation
  7480. // if(a === mjtNextMainKey) allowNoDelay322 = false;
  7481. return this.fetchUpdatedMetadata718(a);
  7482.  
  7483. } catch (e) {
  7484. console.log('Code Error in fetchUpdatedMetadata', e);
  7485. }
  7486. return this.fetchUpdatedMetadata717(a)
  7487. }
  7488. }
  7489.  
  7490.  
  7491. if (typeof cProto.scheduleInitialUpdatedMetadataRequest === 'function' && cProto.scheduleInitialUpdatedMetadataRequest.length === 0 && !cProto.scheduleInitialUpdatedMetadataRequest717) {
  7492. // console.log(1234, cProto, cProto.is)
  7493. cProto.scheduleInitialUpdatedMetadataRequest717 = cProto.scheduleInitialUpdatedMetadataRequest;
  7494. let mJob = null;
  7495.  
  7496. cProto.scheduleInitialUpdatedMetadataRequest = function () {
  7497.  
  7498. try {
  7499.  
  7500. if (arguments.length > 0) {
  7501. console.warn("CAUTION: scheduleInitialUpdatedMetadataRequest coding might have to be updated.");
  7502. }
  7503. // mfy = mfv;
  7504.  
  7505. // mjtNextMainKey = '';
  7506. mtzlastAllowedContinuation = '';
  7507. mtzCount = 0;
  7508. if (mbCId322) {
  7509. clearTimeout(mbCId322);
  7510. mbCId322 = 0;
  7511. }
  7512. mbDelayBelowNCalls = 0;
  7513. // allowNoDelay322 = false;
  7514. copyPreviousContiuationToIgnored374(true);
  7515.  
  7516. const taskMgr = this.__getEmittorTaskMgr859__();
  7517. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714 && taskMgr.addJob && taskMgr.cancelJob) setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr);
  7518. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714) {
  7519. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 507');
  7520. }
  7521.  
  7522. // prevent depulicated schedule job by clearing previous JobId
  7523. if (taskMgr && typeof taskMgr.addLowPriorityJob === 'function' && taskMgr.addLowPriorityJob.length === 2 && typeof taskMgr.cancelJob === 'function' && taskMgr.cancelJob.length === 1) {
  7524.  
  7525. let res;
  7526.  
  7527. if (mJob) {
  7528. const job = mJob;
  7529. mJob = null;
  7530. console.log('cancelJob', job)
  7531. taskMgr.cancelJob(job); // clear previous [Interval Meta Update] job
  7532. // p.cancelJob(a,b);
  7533. }
  7534.  
  7535. // const updatedMetadataEndpoint = this.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint
  7536.  
  7537. let pza = taskMgr.__lastJobId863__;
  7538. try { res = this.scheduleInitialUpdatedMetadataRequest717(); } catch (e) { }
  7539. let pzb = taskMgr.__lastJobId863__
  7540. if (pza !== pzb) {
  7541. mJob = pzb; // set [Interval Meta Update] jobId
  7542. }
  7543.  
  7544. // if (updatedMetadataEndpoint && updatedMetadataEndpoint.videoId) {
  7545. // mtxVideoId = updatedMetadataEndpoint.videoId || ''; // set the current target VideoId
  7546. // } else {
  7547. // mtxVideoId = ''; // sometimes updatedMetadataEndpoint is not ready
  7548. // }
  7549.  
  7550. return res;
  7551.  
  7552. } else {
  7553. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 601');
  7554. }
  7555.  
  7556. } catch (e) {
  7557. console.log('Code Error in scheduleInitialUpdatedMetadataRequest', e);
  7558. }
  7559.  
  7560.  
  7561. return this.scheduleInitialUpdatedMetadataRequest717();
  7562. }
  7563. }
  7564.  
  7565.  
  7566. });
  7567.  
  7568. FIX_avoid_incorrect_video_meta_bool && promiseForYtActionCalled.then((ytAppDom) => {
  7569. let dummy;
  7570. let cProto;
  7571. dummy = ytAppDom;
  7572. if (!(dummy instanceof Element)) return;
  7573. cProto = insp(dummy).constructor.prototype;
  7574. if (typeof cProto.sendServiceAjax_ === 'function' && cProto.sendServiceAjax_.length === 4 && !cProto.sendServiceAjax717_) {
  7575. // console.log(1234, cProto, cProto.is);
  7576. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  7577. // cProto.handleServiceRequest_ = function (a, b, c, d) {
  7578. // console.log(123401, arguments);
  7579. // return this.handleServiceRequest717_(a, b, c, d);
  7580. // }
  7581.  
  7582. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  7583.  
  7584. // cProto.handleServiceRequest_ = function(a,b,c,d){
  7585. // console.log(59901, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  7586. // if(a?.is === 'ytd-video-primary-info-renderer' && b?.updatedMetadataEndpoint?.videoId && c?.continuation && typeof c?.continuation ==='string'){
  7587. // console.log('mfv', c.continuation);
  7588. // mfv.add( c.continuation);
  7589. // }
  7590. // return this.handleServiceRequest717_(a,b,c,d);
  7591. // }
  7592.  
  7593. function extraArguments322(a, b, c) {
  7594. let is = (a || 0).is;
  7595. let videoId = ((b || 0).updatedMetadataEndpoint || 0).videoId;
  7596. let continuation = (c || 0).continuation;
  7597. if (typeof is !== 'string') is = null;
  7598. if (typeof videoId !== 'string') videoId = null;
  7599. if (typeof continuation !== 'string') continuation = null;
  7600. return { is, videoId, continuation };
  7601. }
  7602.  
  7603. cProto.sendServiceAjax717_ = cProto.sendServiceAjax_;
  7604. cProto.sendServiceAjax_ = function (a, b, c, d) {
  7605.  
  7606. // console.log(8001)
  7607. try {
  7608.  
  7609. const { is, videoId, continuation } = extraArguments322(a, b, c);
  7610.  
  7611. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  7612. console.warn("CAUTION: sendServiceAjax_ coding might have to be updated.");
  7613. }
  7614.  
  7615. if (pageSetupVideoId && videoId && continuation) {
  7616. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  7617. mfyContinuationIgnored.removeAdd(continuation);
  7618. mfvContinuationRecorded.delete(continuation);
  7619. return;
  7620. }
  7621. }
  7622.  
  7623. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  7624. copyPreviousContiuationToIgnored374(false);
  7625. mfyContinuationIgnored.delete(continuation);
  7626. mfvContinuationRecorded.removeAdd(continuation);
  7627. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  7628. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  7629. mjtLockPreviousKey = '';
  7630. }
  7631. // if (mjtNextMainKey === continuation) {
  7632. // copyPreviousContiuationToIgnored(false);
  7633. // mfyContinuationIgnored.delete(continuation);
  7634. // mfvContinuationRecorded.add(continuation);
  7635. // }
  7636.  
  7637.  
  7638. if (mfyContinuationIgnored && continuation) {
  7639. if (mfyContinuationIgnored.has(continuation)) {
  7640. LOG_FETCHMETA_UPDATE && continuationLog(continuation, '5260 matched01', continuation)
  7641. return;
  7642. }
  7643. }
  7644.  
  7645. // console.log(59902, a?.is, b,c,d)
  7646. // console.log(59903, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  7647. if (is === 'ytd-video-primary-info-renderer' && videoId && continuation && !mfvContinuationRecorded.has(continuation)) {
  7648. // console.log('mfv377', continuation);
  7649. mfvContinuationRecorded.add(continuation);
  7650. }
  7651.  
  7652. // if (videoId) {
  7653. // if (!pageSetupVideoId) return; // ignore page not ready
  7654. // // if (mtxVideoId && b.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  7655. // if (videoId !== pageSetupVideoId) {
  7656. // return;
  7657. // }
  7658. // }
  7659.  
  7660. } catch (e) {
  7661. console.log('Coding Error in sendServiceAjax_', e)
  7662. }
  7663. // console.log(8002)
  7664. // console.log(123402, arguments);
  7665. // console.log(5162, 'a',a?.is,'b',b,'c',c,'d',d);
  7666.  
  7667. // console.log(5211, b?.updatedMetadataEndpoint?.kdkw33);
  7668. // if(b &&b.updatedMetadataEndpoint && !b.updatedMetadataEndpoint.kdkw33){
  7669. // b.updatedMetadataEndpoint = new Proxy(b.updatedMetadataEndpoint, {
  7670. // get(target, prop, receiver){
  7671. // console.log('xxs99', target.videoId, mtx)
  7672. // if(prop ==='kdkw33') return 1;
  7673. // console.log(3322, prop, target)
  7674. // if(prop === 'initialDelayMs') {
  7675. // throw new Error("ABCC");
  7676. // }
  7677. // return target[prop];
  7678. // },
  7679. // set(target, prop, value, receiver){
  7680.  
  7681. // if(prop ==='kdkw33') return true;
  7682. // target[prop]=value;
  7683. // return true;
  7684. // }
  7685. // });
  7686. // }
  7687. // console.log(5533, b?.updatedMetadataEndpoint?.kdkw33)
  7688. return this.sendServiceAjax717_(a, b, c, d);
  7689. }
  7690. }
  7691.  
  7692. function delayClearOtherKeys(lztContinuation) {
  7693. // // schedule delayed removal if mfyContinuationIgnored is not empty
  7694. // getRafPromise().then(() => {
  7695. // // assume the repeat continuation could be only for popstate which is triggered by user interaction
  7696. // // foreground page only
  7697.  
  7698. // });
  7699.  
  7700.  
  7701. if (lztContinuation !== mtzlastAllowedContinuation) return;
  7702. if (lztContinuation !== mpKey21 || lztContinuation !== mpKey22) return;
  7703. if (!mfyContinuationIgnored.size) return;
  7704. if (mfyContinuationIgnored.size > 1) {
  7705. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, 'delayClearOtherKeys, current = ', lztContinuation);
  7706. }
  7707. mfyContinuationIgnored.forEach((value, key) => {
  7708. if (key !== lztContinuation) {
  7709. mfyContinuationIgnored.delete(key);
  7710. LOG_FETCHMETA_UPDATE && continuationLog(key, 'previous continuation removed from ignored store', key);
  7711. }
  7712. });
  7713.  
  7714. }
  7715. if (typeof cProto.getCancellableNetworkPromise_ === 'function' && cProto.getCancellableNetworkPromise_.length === 5 && !cProto.getCancellableNetworkPromise717_) {
  7716. cProto.getCancellableNetworkPromise717_ = cProto.getCancellableNetworkPromise_;
  7717. cProto.getCancellableNetworkPromise_ = function (a, b, c, d, e) {
  7718.  
  7719. // console.log(8003)
  7720. try {
  7721.  
  7722.  
  7723. const { is, videoId, continuation } = extraArguments322(b, c, d);
  7724.  
  7725. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  7726. console.warn("CAUTION: getCancellableNetworkPromise_ coding might have to be updated.");
  7727. }
  7728.  
  7729. if (pageSetupVideoId && videoId && continuation) {
  7730. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  7731. mfyContinuationIgnored.removeAdd(continuation);
  7732. mfvContinuationRecorded.delete(continuation);
  7733. return;
  7734. }
  7735. }
  7736.  
  7737. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  7738. copyPreviousContiuationToIgnored374(false);
  7739. mfyContinuationIgnored.delete(continuation);
  7740. mfvContinuationRecorded.removeAdd(continuation);
  7741. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  7742. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  7743. mjtLockPreviousKey = '';
  7744. }
  7745.  
  7746. // if (mjtNextMainKey === continuation) {
  7747. // copyPreviousContiuationToIgnored(false);
  7748. // mfyContinuationIgnored.delete(continuation);
  7749. // mfvContinuationRecorded.add(continuation);
  7750. // }
  7751.  
  7752. const lztContinuation = continuation;
  7753.  
  7754. if (mfyContinuationIgnored && lztContinuation && typeof lztContinuation === 'string') {
  7755. if (mfyContinuationIgnored.has(lztContinuation)) {
  7756. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5360 matched02', lztContinuation)
  7757. return;
  7758. }
  7759. }
  7760.  
  7761. // if (videoId) {
  7762. // if (!pageSetupVideoId) return; // ignore page not ready
  7763. // // if (mtxVideoId && c.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  7764. // if (videoId !== pageSetupVideoId) {
  7765. // return;
  7766. // }
  7767. // }
  7768.  
  7769. if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation !== lztContinuation) {
  7770. mtzlastAllowedContinuation = lztContinuation;
  7771. // console.log(70401, lztContinuation, mfyContinuationIgnored.size)
  7772.  
  7773. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5382 Continuation sets to\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  7774. mjtRecordedPrevKey = lztContinuation;
  7775. if (mjtLockPreviousKey === lztContinuation) mjtLockPreviousKey = '';
  7776. // if (mfyContinuationIgnored.size > 0) {
  7777. // delayClearOtherKeys(lztContinuation);
  7778. // }
  7779. mtzCount = 0;
  7780. // allowNoDelay322 = false;
  7781. } else if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation && mtzlastAllowedContinuation === lztContinuation) {
  7782. // repeated
  7783. if (mtzCount > 1e9) mtzCount = 1e4;
  7784. ++mtzCount;
  7785. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5386 Same Continuation\t\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  7786.  
  7787. // if (mtzCount >= 3) allowNoDelay322 = true;
  7788. if (mtzCount >= 3 && mfyContinuationIgnored.size > 0) {
  7789. Promise.resolve(lztContinuation).then(delayClearOtherKeys).catch(console.warn);
  7790. }
  7791. if (mtzCount === 5) {
  7792. mfvContinuationRecorded.clear();
  7793. mfvContinuationRecorded.add(lztContinuation);
  7794. }
  7795.  
  7796. }
  7797.  
  7798. if (typeof lztContinuation === 'string' && lztContinuation && (pageSetupVideoId || videoPlayingY.videoId)) {
  7799. mpKey22 = lztContinuation;
  7800. mpUrl22 = pageSetupVideoId || videoPlayingY.videoId;
  7801. }
  7802.  
  7803. if (mbCId322) {
  7804. clearTimeout(mbCId322);
  7805. mbCId322 = 0;
  7806. }
  7807. } catch (e) {
  7808. console.log('Coding Error in getCancellableNetworkPromise_', e)
  7809. }
  7810.  
  7811. // console.log(8004)
  7812. // console.log(123403, arguments);
  7813. // if(c.updatedMetadataEndpoint) console.log(123404, pageSetupVideoId, JSON.stringify(c.updatedMetadataEndpoint))
  7814.  
  7815. // console.log(5163, a?.is,b,c,d,e);
  7816. return this.getCancellableNetworkPromise717_(a, b, c, d, e);
  7817. }
  7818. }
  7819. });
  7820.  
  7821. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  7822.  
  7823.  
  7824. FIX_ytdExpander_childrenChanged && whenCEDefined('ytd-expander').then(() => {
  7825.  
  7826. let dummy;
  7827. let cProto;
  7828.  
  7829. dummy = document.createElement('ytd-expander');
  7830. cProto = insp(dummy).constructor.prototype;
  7831.  
  7832. if (fnIntegrity(cProto.initChildrenObserver, '0.48.21') && fnIntegrity(cProto.childrenChanged, '0.40.22')) {
  7833.  
  7834. cProto.initChildrenObserver14 = cProto.initChildrenObserver;
  7835. cProto.childrenChanged14 = cProto.childrenChanged;
  7836.  
  7837. cProto.initChildrenObserver = function () {
  7838. var a = this;
  7839. this.observer = new MutationObserver(function () {
  7840. a.childrenChanged()
  7841. }
  7842. );
  7843. this.observer.observe(this.content, {
  7844. subtree: !0,
  7845. childList: !0,
  7846. attributes: !0,
  7847. characterData: !0
  7848. });
  7849. this.childrenChanged()
  7850. }
  7851. ;
  7852. cProto.childrenChanged = function () {
  7853. if (this.alwaysToggleable) {
  7854. this.canToggle = this.alwaysToggleable;
  7855. } else if (!this.canToggleJobId) {
  7856. this.canToggleJobId = 1;
  7857. foregroundPromiseFn().then(() => {
  7858. this.canToggleJobId = 0;
  7859. this.calculateCanCollapse()
  7860. })
  7861. }
  7862. }
  7863.  
  7864. // console.log(cProto.initChildrenObserver)
  7865. console.debug('ytd-expander-fix-childrenChanged');
  7866.  
  7867. }
  7868.  
  7869. });
  7870.  
  7871.  
  7872. FIX_paper_ripple_animate && whenCEDefined('paper-ripple').then(() => {
  7873.  
  7874. let dummy;
  7875. let cProto;
  7876. dummy = document.createElement('paper-ripple');
  7877. cProto = insp(dummy).constructor.prototype;
  7878.  
  7879. if (fnIntegrity(cProto.animate, '0.74.5')) {
  7880.  
  7881.  
  7882. cProto.animate34 = cProto.animate;
  7883. cProto.animate = function () {
  7884. if (this._animating) {
  7885. var a;
  7886. const ripples = this.ripples;
  7887. for (a = 0; a < ripples.length; ++a) {
  7888. var b = ripples[a];
  7889. b.draw();
  7890. this.$.background.style.opacity = b.outerOpacity;
  7891. b.isOpacityFullyDecayed && !b.isRestingAtMaxRadius && this.removeRipple(b)
  7892. }
  7893. if ((this.shouldKeepAnimating || 0) !== ripples.length) {
  7894. if (!this._boundAnimate38) this._boundAnimate38 = this.animate.bind(this);
  7895. foregroundPromiseFn().then(this._boundAnimate38);
  7896. } else {
  7897. this.onAnimationComplete();
  7898. }
  7899. }
  7900. }
  7901.  
  7902. console.debug('FIX_paper_ripple_animate')
  7903.  
  7904. // console.log(cProto.animate)
  7905.  
  7906. }
  7907.  
  7908. });
  7909.  
  7910. if (FIX_doIdomRender) {
  7911.  
  7912. const xsetTimeout = function (f, d) {
  7913. if (xsetTimeout.m511 === 1 && !d) {
  7914. xsetTimeout.m511 = 2;
  7915. xsetTimeout.m568 = f;
  7916. } else {
  7917. return setTimeout.apply(window, arguments)
  7918. }
  7919.  
  7920. }
  7921.  
  7922. /**
  7923. *
  7924. IGb = function(a) {
  7925. var b, c = null == (b = a.requestAninmationFrameResolver) ? void 0 : b.promise;
  7926. c || (a.requestAninmationFrameResolver = new Vi,
  7927. c = a.requestAninmationFrameResolver.promise,
  7928. Da.requestAnimationFrame(function() {
  7929. var d;
  7930. null == (d = a.requestAninmationFrameResolver) || d.resolve();
  7931. a.requestAninmationFrameResolver = null
  7932. }));
  7933. return c
  7934. }
  7935.  
  7936. */
  7937.  
  7938. const xrequestAnimationFrame = function (f) {
  7939. const h = `${f}`;
  7940. if (h.startsWith("function(){setTimeout(function(){") && h.endsWith("})}")) {
  7941. let t = null;
  7942. xsetTimeout.m511 = 1;
  7943. f();
  7944. if (xsetTimeout.m511 === 2) {
  7945. t = xsetTimeout.m568;
  7946. xsetTimeout.m568 = null;
  7947. }
  7948. xsetTimeout.m511 = 0;
  7949. if (typeof t === 'function') {
  7950. foregroundPromiseFn().then(t);
  7951. }
  7952. } else if (h.includes("requestAninmationFrameResolver")) {
  7953. foregroundPromiseFn().then(f);
  7954. } else {
  7955. return requestAnimationFrame.apply(window, arguments);
  7956. }
  7957. }
  7958.  
  7959. let busy = false;
  7960. const doIdomRender = function () {
  7961.  
  7962. if (!this) return;
  7963. if (busy) {
  7964. return this.doIdomRender13(...arguments);
  7965. }
  7966. busy = true;
  7967. const { requestAnimationFrame, setTimeout } = window;
  7968. window.requestAnimationFrame = xrequestAnimationFrame;
  7969. window.setTimeout = xsetTimeout;
  7970. let r = this.doIdomRender13(...arguments);
  7971. window.requestAnimationFrame = requestAnimationFrame;
  7972. window.setTimeout = setTimeout;
  7973. busy = false;
  7974. return r;
  7975. };
  7976. 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']) {
  7977.  
  7978.  
  7979. whenCEDefined(ytTag).then(() => {
  7980.  
  7981. let dummy;
  7982. let cProto;
  7983. dummy = document.createElement(ytTag);
  7984. cProto = insp(dummy).constructor.prototype;
  7985.  
  7986. cProto.doIdomRender13 = cProto.doIdomRender;
  7987. cProto.doIdomRender = doIdomRender;
  7988.  
  7989. if (cProto.doIdomRender13 === cProto.templatingFn) cProto.templatingFn = doIdomRender;
  7990.  
  7991. console.debug('[yt-js-engine-tamer] FIX_doIdomRender', ytTag)
  7992.  
  7993.  
  7994.  
  7995. });
  7996.  
  7997. }
  7998.  
  7999. }
  8000.  
  8001.  
  8002.  
  8003. FIX_POPUP_UNIQUE_ID && whenCEDefined('ytd-popup-container').then(async () => {
  8004.  
  8005. const sMap = new Map();
  8006.  
  8007. const ZTa = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  8008. const ZT = function () {
  8009. for (var a = Array(36), b = 0, c, d = 0; d < 36; d++)
  8010. d == 8 || d == 13 || d == 18 || d == 23 ? a[d] = "-" : d == 14 ? a[d] = "4" : (b <= 2 && (b = 33554432 + Math.random() * 16777216 | 0),
  8011. c = b & 15,
  8012. b >>= 4,
  8013. a[d] = ZTa[d == 19 ? c & 3 | 8 : c]);
  8014. return a.join("")
  8015. };
  8016.  
  8017.  
  8018. const popupContainerCollection = document.getElementsByTagName('ytd-popup-container');
  8019.  
  8020. const popupContainer = await observablePromise(() => {
  8021. return popupContainerCollection[0];
  8022. }).obtain();
  8023.  
  8024.  
  8025. let cProto;
  8026. cProto = insp(popupContainer).constructor.prototype;
  8027.  
  8028.  
  8029. if (!cProto || typeof cProto.handleOpenPopupAction !== 'function' || cProto.handleOpenPopupAction3868 || cProto.handleOpenPopupAction.length !== 2) {
  8030. console.log('FIX_POPUP_UNIQUE_ID NG')
  8031. return;
  8032. }
  8033. cProto.handleOpenPopupAction3868 = cProto.handleOpenPopupAction;
  8034.  
  8035. cProto.handleOpenPopupAction = function (a, b) {
  8036.  
  8037. if (typeof (a || 0) === 'object' && !a.__jOdQA__) {
  8038.  
  8039. a.__jOdQA__ = true;
  8040.  
  8041. try {
  8042.  
  8043. const h = this.hostElement;
  8044.  
  8045. if (h instanceof HTMLElement) {
  8046.  
  8047. const map = h.__skme44__ = h.__skme44__ || new Map();
  8048.  
  8049. let mKey = '';
  8050. const wKey = firstObjectKey(a);
  8051. const wObj = wKey ? a[wKey] : null;
  8052. if (wKey && wObj && typeof (wObj.popup || 0) === 'object') {
  8053. const pKey = firstObjectKey(wObj.popup)
  8054. const pObj = pKey ? wObj.popup[pKey] : null;
  8055. let contentKey = '';
  8056. let headerKey = '';
  8057.  
  8058. if (pObj && pObj.identifier && pObj.content && pObj.header) {
  8059. contentKey = firstObjectKey(pObj.content)
  8060. headerKey = firstObjectKey(pObj.header)
  8061. }
  8062. if (contentKey && headerKey) {
  8063.  
  8064. mKey = `${wKey}(popupType:${wObj.popupType},popup(${pKey}(content(${contentKey}:...),header(${headerKey}:...),identifer(surface:${pObj.identifier.surface}))))`
  8065.  
  8066. if (mKey) {
  8067.  
  8068. if (!wObj.uniqueId) {
  8069. for (let i = 0; i < 8; i++) {
  8070. wObj.uniqueId = ZT();
  8071. if (!sMap.has(wObj.uniqueId)) break;
  8072. }
  8073. }
  8074. const oId = wObj.uniqueId
  8075.  
  8076. let nId_ = map.get(mKey);
  8077. if (!nId_) {
  8078. map.set(mKey, nId_ = oId);
  8079. }
  8080.  
  8081. wObj.uniqueId = nId_ || wObj.uniqueId;
  8082.  
  8083. const nId = wObj.uniqueId
  8084.  
  8085. sMap.set(oId, nId);
  8086. sMap.set(nId, nId);
  8087.  
  8088. wObj.uniqueId = nId;
  8089. pObj.targetId = nId;
  8090. pObj.identifier.tag = nId;
  8091.  
  8092. if (oId !== nId) {
  8093. console.log('FIX_POPUP_UNIQUE_ID', oId, nId);
  8094. }
  8095.  
  8096. }
  8097.  
  8098. }
  8099. }
  8100.  
  8101. // console.log(12213, mKey, a, b, h)
  8102.  
  8103. }
  8104.  
  8105. } catch (e) {
  8106. console.warn(e)
  8107. }
  8108.  
  8109. try {
  8110.  
  8111. const results = searchNestedObject(a, (x) => {
  8112. if (typeof x === 'string' && x.length === 36) {
  8113. 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;
  8114. }
  8115. return false;
  8116. });
  8117. for (const [obj, key] of results) {
  8118. const oId = obj[key];
  8119. const nId = sMap.get(oId);
  8120. if (nId) obj[key] = nId;
  8121. }
  8122. } catch (e) {
  8123. console.warn(e)
  8124. }
  8125.  
  8126.  
  8127. }
  8128.  
  8129. return this.handleOpenPopupAction3868(...arguments)
  8130. }
  8131.  
  8132. console.log('FIX_POPUP_UNIQUE_ID OK')
  8133.  
  8134.  
  8135. })
  8136.  
  8137.  
  8138. });
  8139.  
  8140. });
  8141.  
  8142.  
  8143.  
  8144.  
  8145. if (isMainWindow) {
  8146.  
  8147. console.groupCollapsed(
  8148. "%cYouTube JS Engine Tamer",
  8149. "background-color: #EDE43B ; color: #000 ; font-weight: bold ; padding: 4px ;"
  8150. );
  8151.  
  8152.  
  8153.  
  8154. console.log("Script is loaded.");
  8155. console.log("This script changes the core mechanisms of the YouTube JS engine.");
  8156.  
  8157. console.log("This script is experimental and subject to further changes.");
  8158.  
  8159. console.log("This might boost your YouTube performance.");
  8160.  
  8161. console.log("CAUTION: This might break your YouTube.");
  8162.  
  8163.  
  8164. if (prepareLogs.length >= 1) {
  8165. console.log(" =========================================================================== ");
  8166.  
  8167. for (const msg of prepareLogs) {
  8168. console.log(msg)
  8169. }
  8170.  
  8171. console.log(" =========================================================================== ");
  8172. }
  8173.  
  8174. console.groupEnd();
  8175.  
  8176. }
  8177.  
  8178.  
  8179.  
  8180. })();