Greasy Fork is available in English.

YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

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