YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

当前为 2024-04-24 提交的版本,查看 最新版本

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