YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

当前为 2024-12-10 提交的版本,查看 最新版本

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