YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址