YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

目前為 2024-04-27 提交的版本,檢視 最新版本

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