{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n );\n }\n const stream = await ReactDOMFizzServer.renderToReadableStream();\n const result = await readResult(stream);\n // need to wait a macrotask to let the scheduled work from the preconnect to execute\n await new Promise(resolve => {\n setTimeout(resolve, 1);\n });\n\n expect(result).toMatchInlineSnapshot(\n `\"
hello
\"`,\n );\n });\n});\n"},"avg_line_length":{"kind":"number","value":24.974683544303797,"string":"24.974684"},"max_line_length":{"kind":"number","value":88,"string":"88"},"alphnanum_fraction":{"kind":"number","value":0.6255485129205266,"string":"0.625549"}}},{"rowIdx":137,"cells":{"repo_name":{"kind":"string","value":"owtf"},"text":{"kind":"string","value":"import React, {PureComponent, startTransition} from 'react';\nimport {createRoot} from 'react-dom/client';\nimport _ from 'lodash';\nimport Charts from './Charts';\nimport Clock from './Clock';\nimport './index.css';\n\nlet cachedData = new Map();\n\nclass App extends PureComponent {\n state = {\n value: '',\n strategy: 'sync',\n showDemo: true,\n showClock: false,\n };\n\n // Random data for the chart\n getStreamData(input) {\n if (cachedData.has(input)) {\n return cachedData.get(input);\n }\n const multiplier = input.length !== 0 ? input.length : 1;\n const complexity =\n (parseInt(window.location.search.slice(1), 10) / 100) * 25 || 25;\n const data = _.range(5).map(t =>\n _.range(complexity * multiplier).map((j, i) => {\n return {\n x: j,\n y: (t + 1) * _.random(0, 255),\n };\n })\n );\n cachedData.set(input, data);\n return data;\n }\n\n componentDidMount() {\n window.addEventListener('keydown', e => {\n if (e.key.toLowerCase() === '?') {\n e.preventDefault();\n this.setState(state => ({\n showClock: !state.showClock,\n }));\n }\n });\n }\n\n handleChartClick = e => {\n if (this.state.showDemo) {\n if (e.shiftKey) {\n this.setState({showDemo: false});\n }\n return;\n }\n if (this.state.strategy !== 'async') {\n this.setState(state => ({\n showDemo: !state.showDemo,\n }));\n return;\n }\n if (this._ignoreClick) {\n return;\n }\n this._ignoreClick = true;\n\n startTransition(() => {\n this.setState({showDemo: true}, () => {\n this._ignoreClick = false;\n });\n });\n };\n\n debouncedHandleChange = _.debounce(value => {\n if (this.state.strategy === 'debounced') {\n this.setState({value: value});\n }\n }, 1000);\n\n renderOption(strategy, label) {\n const {strategy: currentStrategy} = this.state;\n return (\n \n );\n }\n\n handleChange = e => {\n const value = e.target.value;\n const {strategy} = this.state;\n switch (strategy) {\n case 'sync':\n this.setState({value});\n break;\n case 'debounced':\n this.debouncedHandleChange(value);\n break;\n case 'async':\n // TODO: useTransition hook instead.\n startTransition(() => {\n this.setState({value});\n });\n break;\n default:\n break;\n }\n };\n\n render() {\n const {showClock} = this.state;\n const data = this.getStreamData(this.state.value);\n return (\n
\n
\n {this.renderOption('sync', 'Synchronous')}\n {this.renderOption('debounced', 'Debounced')}\n {this.renderOption('async', 'Concurrent')}\n
\n \n
\n {this.state.showDemo && (\n \n )}\n
\n \n
\n
\n
\n );\n }\n}\n\nconst container = document.getElementById('root');\nconst root = createRoot(container);\nroot.render();\n"},"avg_line_length":{"kind":"number","value":23.98639455782313,"string":"23.986395"},"max_line_length":{"kind":"number","value":74,"string":"74"},"alphnanum_fraction":{"kind":"number","value":0.5438453159041394,"string":"0.543845"}}},{"rowIdx":138,"cells":{"repo_name":{"kind":"string","value":"Penetration_Testing"},"text":{"kind":"string","value":"/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @flow\n */\n\nimport type {Fiber} from './ReactInternalTypes';\nimport type {StackCursor} from './ReactFiberStack';\nimport type {SuspenseProps, SuspenseState} from './ReactFiberSuspenseComponent';\nimport type {OffscreenState} from './ReactFiberActivityComponent';\n\nimport {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags';\nimport {createCursor, push, pop} from './ReactFiberStack';\nimport {isCurrentTreeHidden} from './ReactFiberHiddenContext';\nimport {OffscreenComponent} from './ReactWorkTags';\n\n// The Suspense handler is the boundary that should capture if something\n// suspends, i.e. it's the nearest `catch` block on the stack.\nconst suspenseHandlerStackCursor: StackCursor =\n createCursor(null);\n\n// Represents the outermost boundary that is not visible in the current tree.\n// Everything above this is the \"shell\". When this is null, it means we're\n// rendering in the shell of the app. If it's non-null, it means we're rendering\n// deeper than the shell, inside a new tree that wasn't already visible.\n//\n// The main way we use this concept is to determine whether showing a fallback\n// would result in a desirable or undesirable loading state. Activing a fallback\n// in the shell is considered an undersirable loading state, because it would\n// mean hiding visible (albeit stale) content in the current tree — we prefer to\n// show the stale content, rather than switch to a fallback. But showing a\n// fallback in a new tree is fine, because there's no stale content to\n// prefer instead.\nlet shellBoundary: Fiber | null = null;\n\nexport function getShellBoundary(): Fiber | null {\n return shellBoundary;\n}\n\nexport function pushPrimaryTreeSuspenseHandler(handler: Fiber): void {\n // TODO: Pass as argument\n const current = handler.alternate;\n const props: SuspenseProps = handler.pendingProps;\n\n // Shallow Suspense context fields, like ForceSuspenseFallback, should only be\n // propagated a single level. For example, when ForceSuspenseFallback is set,\n // it should only force the nearest Suspense boundary into fallback mode.\n pushSuspenseListContext(\n handler,\n setDefaultShallowSuspenseListContext(suspenseStackCursor.current),\n );\n\n // Experimental feature: Some Suspense boundaries are marked as having an\n // undesirable fallback state. These have special behavior where we only\n // activate the fallback if there's no other boundary on the stack that we can\n // use instead.\n if (\n enableSuspenseAvoidThisFallback &&\n props.unstable_avoidThisFallback === true &&\n // If an avoided boundary is already visible, it behaves identically to\n // a regular Suspense boundary.\n (current === null || isCurrentTreeHidden())\n ) {\n if (shellBoundary === null) {\n // We're rendering in the shell. There's no parent Suspense boundary that\n // can provide a desirable fallback state. We'll use this boundary.\n push(suspenseHandlerStackCursor, handler, handler);\n\n // However, because this is not a desirable fallback, the children are\n // still considered part of the shell. So we intentionally don't assign\n // to `shellBoundary`.\n } else {\n // There's already a parent Suspense boundary that can provide a desirable\n // fallback state. Prefer that one.\n const handlerOnStack = suspenseHandlerStackCursor.current;\n push(suspenseHandlerStackCursor, handlerOnStack, handler);\n }\n return;\n }\n\n // TODO: If the parent Suspense handler already suspended, there's no reason\n // to push a nested Suspense handler, because it will get replaced by the\n // outer fallback, anyway. Consider this as a future optimization.\n push(suspenseHandlerStackCursor, handler, handler);\n if (shellBoundary === null) {\n if (current === null || isCurrentTreeHidden()) {\n // This boundary is not visible in the current UI.\n shellBoundary = handler;\n } else {\n const prevState: SuspenseState = current.memoizedState;\n if (prevState !== null) {\n // This boundary is showing a fallback in the current UI.\n shellBoundary = handler;\n }\n }\n }\n}\n\nexport function pushFallbackTreeSuspenseHandler(fiber: Fiber): void {\n // We're about to render the fallback. If something in the fallback suspends,\n // it's akin to throwing inside of a `catch` block. This boundary should not\n // capture. Reuse the existing handler on the stack.\n reuseSuspenseHandlerOnStack(fiber);\n}\n\nexport function pushOffscreenSuspenseHandler(fiber: Fiber): void {\n if (fiber.tag === OffscreenComponent) {\n // A SuspenseList context is only pushed here to avoid a push/pop mismatch.\n // Reuse the current value on the stack.\n // TODO: We can avoid needing to push here by by forking popSuspenseHandler\n // into separate functions for Suspense and Offscreen.\n pushSuspenseListContext(fiber, suspenseStackCursor.current);\n push(suspenseHandlerStackCursor, fiber, fiber);\n if (shellBoundary !== null) {\n // A parent boundary is showing a fallback, so we've already rendered\n // deeper than the shell.\n } else {\n const current = fiber.alternate;\n if (current !== null) {\n const prevState: OffscreenState = current.memoizedState;\n if (prevState !== null) {\n // This is the first boundary in the stack that's already showing\n // a fallback. So everything outside is considered the shell.\n shellBoundary = fiber;\n }\n }\n }\n } else {\n // This is a LegacyHidden component.\n reuseSuspenseHandlerOnStack(fiber);\n }\n}\n\nexport function reuseSuspenseHandlerOnStack(fiber: Fiber) {\n pushSuspenseListContext(fiber, suspenseStackCursor.current);\n push(suspenseHandlerStackCursor, getSuspenseHandler(), fiber);\n}\n\nexport function getSuspenseHandler(): Fiber | null {\n return suspenseHandlerStackCursor.current;\n}\n\nexport function popSuspenseHandler(fiber: Fiber): void {\n pop(suspenseHandlerStackCursor, fiber);\n if (shellBoundary === fiber) {\n // Popping back into the shell.\n shellBoundary = null;\n }\n popSuspenseListContext(fiber);\n}\n\n// SuspenseList context\n// TODO: Move to a separate module? We may change the SuspenseList\n// implementation to hide/show in the commit phase, anyway.\nexport opaque type SuspenseContext = number;\nexport opaque type SubtreeSuspenseContext: SuspenseContext = number;\nexport opaque type ShallowSuspenseContext: SuspenseContext = number;\n\nconst DefaultSuspenseContext: SuspenseContext = 0b00;\n\nconst SubtreeSuspenseContextMask: SuspenseContext = 0b01;\n\n// ForceSuspenseFallback can be used by SuspenseList to force newly added\n// items into their fallback state during one of the render passes.\nexport const ForceSuspenseFallback: ShallowSuspenseContext = 0b10;\n\nexport const suspenseStackCursor: StackCursor = createCursor(\n DefaultSuspenseContext,\n);\n\nexport function hasSuspenseListContext(\n parentContext: SuspenseContext,\n flag: SuspenseContext,\n): boolean {\n return (parentContext & flag) !== 0;\n}\n\nexport function setDefaultShallowSuspenseListContext(\n parentContext: SuspenseContext,\n): SuspenseContext {\n return parentContext & SubtreeSuspenseContextMask;\n}\n\nexport function setShallowSuspenseListContext(\n parentContext: SuspenseContext,\n shallowContext: ShallowSuspenseContext,\n): SuspenseContext {\n return (parentContext & SubtreeSuspenseContextMask) | shallowContext;\n}\n\nexport function pushSuspenseListContext(\n fiber: Fiber,\n newContext: SuspenseContext,\n): void {\n push(suspenseStackCursor, newContext, fiber);\n}\n\nexport function popSuspenseListContext(fiber: Fiber): void {\n pop(suspenseStackCursor, fiber);\n}\n"},"avg_line_length":{"kind":"number","value":37.294117647058826,"string":"37.294118"},"max_line_length":{"kind":"number","value":80,"string":"80"},"alphnanum_fraction":{"kind":"number","value":0.7421584944309307,"string":"0.742158"}}},{"rowIdx":139,"cells":{"repo_name":{"kind":"string","value":"PenetrationTestingScripts"},"text":{"kind":"string","value":"const semver = require('semver');\nconst fs = require('fs');\nconst ReactVersionSrc = fs.readFileSync(require.resolve('shared/ReactVersion'));\nconst reactVersion = /export default '([^']+)';/.exec(ReactVersionSrc)[1];\n\nconst config = {\n use: {\n headless: true,\n browserName: 'chromium',\n launchOptions: {\n // This bit of delay gives async React time to render\n // and DevTools operations to be sent across the bridge.\n slowMo: 100,\n },\n url: process.env.REACT_VERSION\n ? 'http://localhost:8080/e2e-regression.html'\n : 'http://localhost:8080/e2e.html',\n react_version: process.env.REACT_VERSION\n ? semver.coerce(process.env.REACT_VERSION).version\n : reactVersion,\n trace: 'retain-on-failure',\n },\n // Some of our e2e tests can be flaky. Retry tests to make sure the error isn't transient\n retries: 3,\n};\n\nmodule.exports = config;\n"},"avg_line_length":{"kind":"number","value":30.714285714285715,"string":"30.714286"},"max_line_length":{"kind":"number","value":91,"string":"91"},"alphnanum_fraction":{"kind":"number","value":0.6685456595264938,"string":"0.668546"}}},{"rowIdx":140,"cells":{"repo_name":{"kind":"string","value":"cybersecurity-penetration-testing"},"text":{"kind":"string","value":"/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @flow\n */\n\n/**\n * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary\n */\nconst supportedInputTypes: {[key: string]: true | void, ...} = {\n color: true,\n date: true,\n datetime: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n password: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n};\n\nfunction isTextInputElement(elem: ?HTMLElement): boolean {\n const nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n\n if (nodeName === 'input') {\n return !!supportedInputTypes[((elem: any): HTMLInputElement).type];\n }\n\n if (nodeName === 'textarea') {\n return true;\n }\n\n return false;\n}\n\nexport default isTextInputElement;\n"},"avg_line_length":{"kind":"number","value":20.347826086956523,"string":"20.347826"},"max_line_length":{"kind":"number","value":114,"string":"114"},"alphnanum_fraction":{"kind":"number","value":0.6636085626911316,"string":"0.663609"}}},{"rowIdx":141,"cells":{"repo_name":{"kind":"string","value":"PenetrationTestingScripts"},"text":{"kind":"string","value":"/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @flow\n */\n\nimport typeof ReactTestRenderer from 'react-test-renderer';\nimport type {FrontendBridge} from 'react-devtools-shared/src/bridge';\nimport type {Context} from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext';\nimport type {DispatcherContext} from 'react-devtools-shared/src/devtools/views/Components/TreeContext';\nimport type Store from 'react-devtools-shared/src/devtools/store';\n\ndescribe('ProfilerContext', () => {\n let React;\n let ReactDOM;\n let TestRenderer: ReactTestRenderer;\n let bridge: FrontendBridge;\n let legacyRender;\n let store: Store;\n let utils;\n\n let BridgeContext;\n let ProfilerContext;\n let ProfilerContextController;\n let StoreContext;\n let TreeContextController;\n let TreeDispatcherContext;\n let TreeStateContext;\n\n beforeEach(() => {\n utils = require('./utils');\n utils.beforeEachProfiling();\n\n legacyRender = utils.legacyRender;\n\n bridge = global.bridge;\n store = global.store;\n store.collapseNodesByDefault = false;\n store.recordChangeDescriptions = true;\n\n React = require('react');\n ReactDOM = require('react-dom');\n TestRenderer = utils.requireTestRenderer();\n\n BridgeContext =\n require('react-devtools-shared/src/devtools/views/context').BridgeContext;\n ProfilerContext =\n require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContext;\n ProfilerContextController =\n require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContextController;\n StoreContext =\n require('react-devtools-shared/src/devtools/views/context').StoreContext;\n TreeContextController =\n require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController;\n TreeDispatcherContext =\n require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeDispatcherContext;\n TreeStateContext =\n require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeStateContext;\n });\n\n const Contexts = ({\n children = null,\n defaultSelectedElementID = null,\n defaultSelectedElementIndex = null,\n }: any) => (\n \n \n \n {children}\n \n \n \n );\n\n it('updates updates profiling support based on the attached roots', async () => {\n const Component = () => null;\n\n let context: Context = ((null: any): Context);\n\n function ContextReader() {\n context = React.useContext(ProfilerContext);\n return null;\n }\n await utils.actAsync(() => {\n TestRenderer.create(\n \n \n ,\n );\n });\n\n expect(context.supportsProfiling).toBe(false);\n\n const containerA = document.createElement('div');\n const containerB = document.createElement('div');\n\n await utils.actAsync(() => legacyRender(, containerA));\n expect(context.supportsProfiling).toBe(true);\n\n await utils.actAsync(() => legacyRender(, containerB));\n await utils.actAsync(() => ReactDOM.unmountComponentAtNode(containerA));\n expect(context.supportsProfiling).toBe(true);\n\n await utils.actAsync(() => ReactDOM.unmountComponentAtNode(containerB));\n expect(context.supportsProfiling).toBe(false);\n });\n\n it('should gracefully handle an empty profiling session (with no recorded commits)', async () => {\n const Example = () => null;\n\n utils.act(() => legacyRender(, document.createElement('div')));\n\n let context: Context = ((null: any): Context);\n\n function ContextReader() {\n context = React.useContext(ProfilerContext);\n return null;\n }\n\n // Profile but don't record any updates.\n await utils.actAsync(() => store.profilerStore.startProfiling());\n await utils.actAsync(() => {\n TestRenderer.create(\n \n \n ,\n );\n });\n expect(context).not.toBeNull();\n expect(context.didRecordCommits).toBe(false);\n expect(context.isProcessingData).toBe(false);\n expect(context.isProfiling).toBe(true);\n expect(context.profilingData).toBe(null);\n await utils.actAsync(() => store.profilerStore.stopProfiling());\n\n expect(context).not.toBeNull();\n expect(context.didRecordCommits).toBe(false);\n expect(context.isProcessingData).toBe(false);\n expect(context.isProfiling).toBe(false);\n expect(context.profilingData).toBe(null);\n });\n\n it('should auto-select the root ID matching the Components tab selection if it has profiling data', async () => {\n const Parent = () => ;\n const Child = () => null;\n\n const containerOne = document.createElement('div');\n const containerTwo = document.createElement('div');\n utils.act(() => legacyRender(, containerOne));\n utils.act(() => legacyRender(, containerTwo));\n expect(store).toMatchInlineSnapshot(`\n [root]\n ▾ \n \n [root]\n ▾ \n \n `);\n\n // Profile and record updates to both roots.\n await utils.actAsync(() => store.profilerStore.startProfiling());\n await utils.actAsync(() => legacyRender(, containerOne));\n await utils.actAsync(() => legacyRender(, containerTwo));\n await utils.actAsync(() => store.profilerStore.stopProfiling());\n\n let context: Context = ((null: any): Context);\n function ContextReader() {\n context = React.useContext(ProfilerContext);\n return null;\n }\n\n // Select an element within the second root.\n await utils.actAsync(() =>\n TestRenderer.create(\n \n \n ,\n ),\n );\n\n expect(context).not.toBeNull();\n expect(context.rootID).toBe(\n store.getRootIDForElement(((store.getElementIDAtIndex(3): any): number)),\n );\n });\n\n it('should not select the root ID matching the Components tab selection if it has no profiling data', async () => {\n const Parent = () => ;\n const Child = () => null;\n\n const containerOne = document.createElement('div');\n const containerTwo = document.createElement('div');\n utils.act(() => legacyRender(, containerOne));\n utils.act(() => legacyRender(, containerTwo));\n expect(store).toMatchInlineSnapshot(`\n [root]\n ▾ \n \n [root]\n ▾ \n \n `);\n\n // Profile and record updates to only the first root.\n await utils.actAsync(() => store.profilerStore.startProfiling());\n await utils.actAsync(() => legacyRender(, containerOne));\n await utils.actAsync(() => store.profilerStore.stopProfiling());\n\n let context: Context = ((null: any): Context);\n function ContextReader() {\n context = React.useContext(ProfilerContext);\n return null;\n }\n\n // Select an element within the second root.\n await utils.actAsync(() =>\n TestRenderer.create(\n \n \n ,\n ),\n );\n\n // Verify the default profiling root is the first one.\n expect(context).not.toBeNull();\n expect(context.rootID).toBe(\n store.getRootIDForElement(((store.getElementIDAtIndex(0): any): number)),\n );\n });\n\n it('should maintain root selection between profiling sessions so long as there is data for that root', async () => {\n const Parent = () => ;\n const Child = () => null;\n\n const containerA = document.createElement('div');\n const containerB = document.createElement('div');\n utils.act(() => legacyRender(, containerA));\n utils.act(() => legacyRender(, containerB));\n expect(store).toMatchInlineSnapshot(`\n [root]\n ▾ \n \n [root]\n ▾ \n \n `);\n\n // Profile and record updates.\n await utils.actAsync(() => store.profilerStore.startProfiling());\n await utils.actAsync(() => legacyRender(, containerA));\n await utils.actAsync(() => legacyRender(, containerB));\n await utils.actAsync(() => store.profilerStore.stopProfiling());\n\n let context: Context = ((null: any): Context);\n let dispatch: DispatcherContext = ((null: any): DispatcherContext);\n let selectedElementID = null;\n function ContextReader() {\n context = React.useContext(ProfilerContext);\n dispatch = React.useContext(TreeDispatcherContext);\n selectedElementID = React.useContext(TreeStateContext).selectedElementID;\n return null;\n }\n\n const id = ((store.getElementIDAtIndex(3): any): number);\n\n // Select an element within the second root.\n await utils.actAsync(() =>\n TestRenderer.create(\n \n \n ,\n ),\n );\n\n expect(selectedElementID).toBe(id);\n\n // Profile and record more updates to both roots\n await utils.actAsync(() => store.profilerStore.startProfiling());\n await utils.actAsync(() => legacyRender(, containerA));\n await utils.actAsync(() => legacyRender(, containerB));\n await utils.actAsync(() => store.profilerStore.stopProfiling());\n\n const otherID = ((store.getElementIDAtIndex(0): any): number);\n\n // Change the selected element within a the Components tab.\n utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 0}));\n\n // Verify that the initial Profiler root selection is maintained.\n expect(selectedElementID).toBe(otherID);\n expect(context).not.toBeNull();\n expect(context.rootID).toBe(store.getRootIDForElement(id));\n });\n\n it('should sync selected element in the Components tab too, provided the element is a match', async () => {\n const GrandParent = ({includeChild}) => (\n \n );\n const Parent = ({includeChild}) => (includeChild ? : null);\n const Child = () => null;\n\n const container = document.createElement('div');\n utils.act(() =>\n legacyRender(, container),\n );\n expect(store).toMatchInlineSnapshot(`\n [root]\n ▾ \n ▾ \n \n `);\n\n const parentID = ((store.getElementIDAtIndex(1): any): number);\n const childID = ((store.getElementIDAtIndex(2): any): number);\n\n // Profile and record updates.\n await utils.actAsync(() => store.profilerStore.startProfiling());\n await utils.actAsync(() =>\n legacyRender(, container),\n );\n await utils.actAsync(() =>\n legacyRender(, container),\n );\n await utils.actAsync(() => store.profilerStore.stopProfiling());\n\n expect(store).toMatchInlineSnapshot(`\n [root]\n ▾ \n \n `);\n\n let context: Context = ((null: any): Context);\n let selectedElementID = null;\n function ContextReader() {\n context = React.useContext(ProfilerContext);\n selectedElementID = React.useContext(TreeStateContext).selectedElementID;\n return null;\n }\n\n await utils.actAsync(() =>\n TestRenderer.create(\n \n \n ,\n ),\n );\n expect(selectedElementID).toBeNull();\n\n // Select an element in the Profiler tab and verify that the selection is synced to the Components tab.\n await utils.actAsync(() => context.selectFiber(parentID, 'Parent'));\n expect(selectedElementID).toBe(parentID);\n\n // Select an unmounted element and verify no Components tab selection doesn't change.\n await utils.actAsync(() => context.selectFiber(childID, 'Child'));\n expect(selectedElementID).toBe(parentID);\n });\n});\n"},"avg_line_length":{"kind":"number","value":33.34426229508197,"string":"33.344262"},"max_line_length":{"kind":"number","value":118,"string":"118"},"alphnanum_fraction":{"kind":"number","value":0.6626621051794097,"string":"0.662662"}}},{"rowIdx":142,"cells":{"repo_name":{"kind":"null"},"text":{"kind":"string","value":"/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nconst {\n __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,\n} = require('ReactDOM');\n\nmodule.exports =\n __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactBrowserEventEmitter;\n"},"avg_line_length":{"kind":"number","value":23.5,"string":"23.5"},"max_line_length":{"kind":"number","value":78,"string":"78"},"alphnanum_fraction":{"kind":"number","value":0.7161125319693095,"string":"0.716113"}}},{"rowIdx":143,"cells":{"repo_name":{"kind":"null"},"text":{"kind":"string","value":"/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * @flow\n */\nimport {AsyncLocalStorage} from 'async_hooks';\n\nimport type {Request} from 'react-server/src/ReactFlightServer';\n\nexport * from 'react-server-dom-esm/src/ReactFlightServerConfigESMBundler';\nexport * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';\n\nexport const supportsRequestStorage = true;\nexport const requestStorage: AsyncLocalStorage =\n new AsyncLocalStorage();\n\nexport * from '../ReactFlightServerConfigDebugNoop';\n"},"avg_line_length":{"kind":"number","value":30.047619047619047,"string":"30.047619"},"max_line_length":{"kind":"number","value":75,"string":"75"},"alphnanum_fraction":{"kind":"number","value":0.7695852534562212,"string":"0.769585"}}},{"rowIdx":144,"cells":{"repo_name":{"kind":"null"},"text":{"kind":"string","value":"'use strict';\n\nconst Lighthouse = require('lighthouse');\nconst chromeLauncher = require('chrome-launcher');\n\nconst stats = require('stats-analysis');\nconst config = require('lighthouse/lighthouse-core/config/perf-config');\nconst spawn = require('child_process').spawn;\nconst os = require('os');\n\nconst timesToRun = 10;\n\nfunction wait(val) {\n return new Promise(resolve => setTimeout(resolve, val));\n}\n\nasync function runScenario(benchmark, chrome) {\n const port = chrome.port;\n const results = await Lighthouse(\n `http://localhost:8080/${benchmark}/`,\n {\n output: 'json',\n port,\n },\n config\n );\n\n const perfMarkings = results.lhr.audits['user-timings'].details.items;\n const entries = perfMarkings\n .filter(({timingType}) => timingType !== 'Mark')\n .map(({duration, name}) => ({\n entry: name,\n time: duration,\n }));\n entries.push({\n entry: 'First Meaningful Paint',\n time: results.lhr.audits['first-meaningful-paint'].rawValue,\n });\n\n return entries;\n}\n\nfunction bootstrap(data) {\n const len = data.length;\n const arr = Array(len);\n for (let j = 0; j < len; j++) {\n arr[j] = data[(Math.random() * len) | 0];\n }\n return arr;\n}\n\nfunction calculateStandardErrorOfMean(data) {\n const means = [];\n for (let i = 0; i < 10000; i++) {\n means.push(stats.mean(bootstrap(data)));\n }\n return stats.stdev(means);\n}\n\nfunction calculateAverages(runs) {\n const data = [];\n const averages = [];\n\n runs.forEach((entries, x) => {\n entries.forEach(({entry, time}, i) => {\n if (i >= averages.length) {\n data.push([time]);\n averages.push({\n entry,\n mean: 0,\n sem: 0,\n });\n } else {\n data[i].push(time);\n if (x === runs.length - 1) {\n const dataWithoutOutliers = stats.filterMADoutliers(data[i]);\n averages[i].mean = stats.mean(dataWithoutOutliers);\n averages[i].sem = calculateStandardErrorOfMean(data[i]);\n }\n }\n });\n });\n\n return averages;\n}\n\nasync function initChrome() {\n const platform = os.platform();\n\n if (platform === 'linux') {\n process.env.XVFBARGS = '-screen 0, 1024x768x16';\n process.env.LIGHTHOUSE_CHROMIUM_PATH = 'chromium-browser';\n const child = spawn('xvfb start', [{detached: true, stdio: ['ignore']}]);\n child.unref();\n // wait for chrome to load then continue\n await wait(3000);\n return child;\n }\n}\n\nasync function launchChrome(headless) {\n return await chromeLauncher.launch({\n chromeFlags: [headless ? '--headless' : ''],\n });\n}\n\nasync function runBenchmark(benchmark, headless) {\n const results = {\n runs: [],\n averages: [],\n };\n\n await initChrome();\n\n for (let i = 0; i < timesToRun; i++) {\n let chrome = await launchChrome(headless);\n\n results.runs.push(await runScenario(benchmark, chrome));\n // add a delay or sometimes it confuses lighthouse and it hangs\n await wait(500);\n try {\n await chrome.kill();\n } catch (e) {}\n }\n\n results.averages = calculateAverages(results.runs);\n return results;\n}\n\nmodule.exports = runBenchmark;\n"},"avg_line_length":{"kind":"number","value":22.603053435114504,"string":"22.603053"},"max_line_length":{"kind":"number","value":77,"string":"77"},"alphnanum_fraction":{"kind":"number","value":0.6179230022646393,"string":"0.617923"}}},{"rowIdx":145,"cells":{"repo_name":{"kind":"string","value":"Python-Penetration-Testing-for-Developers"},"text":{"kind":"string","value":"let React;\nlet ReactNoop;\nlet Cache;\nlet getCacheSignal;\nlet Scheduler;\nlet assertLog;\nlet act;\nlet Suspense;\nlet Activity;\nlet useCacheRefresh;\nlet startTransition;\nlet useState;\nlet cache;\n\nlet getTextCache;\nlet textCaches;\nlet seededCache;\n\ndescribe('ReactCache', () => {\n beforeEach(() => {\n jest.resetModules();\n\n React = require('react');\n ReactNoop = require('react-noop-renderer');\n Cache = React.unstable_Cache;\n Scheduler = require('scheduler');\n act = require('internal-test-utils').act;\n Suspense = React.Suspense;\n cache = React.cache;\n Activity = React.unstable_Activity;\n getCacheSignal = React.unstable_getCacheSignal;\n useCacheRefresh = React.unstable_useCacheRefresh;\n startTransition = React.startTransition;\n useState = React.useState;\n\n const InternalTestUtils = require('internal-test-utils');\n assertLog = InternalTestUtils.assertLog;\n\n textCaches = [];\n seededCache = null;\n\n if (gate(flags => flags.enableCache)) {\n getTextCache = cache(() => {\n if (seededCache !== null) {\n // Trick to seed a cache before it exists.\n // TODO: Need a built-in API to seed data before the initial render (i.e.\n // not a refresh because nothing has mounted yet).\n const textCache = seededCache;\n seededCache = null;\n return textCache;\n }\n\n const data = new Map();\n const version = textCaches.length + 1;\n const textCache = {\n version,\n data,\n resolve(text) {\n const record = data.get(text);\n if (record === undefined) {\n const newRecord = {\n status: 'resolved',\n value: text,\n cleanupScheduled: false,\n };\n data.set(text, newRecord);\n } else if (record.status === 'pending') {\n record.value.resolve();\n }\n },\n reject(text, error) {\n const record = data.get(text);\n if (record === undefined) {\n const newRecord = {\n status: 'rejected',\n value: error,\n cleanupScheduled: false,\n };\n data.set(text, newRecord);\n } else if (record.status === 'pending') {\n record.value.reject();\n }\n },\n };\n textCaches.push(textCache);\n return textCache;\n });\n }\n });\n\n function readText(text) {\n const signal = getCacheSignal ? getCacheSignal() : null;\n const textCache = getTextCache();\n const record = textCache.data.get(text);\n if (record !== undefined) {\n if (!record.cleanupScheduled) {\n // This record was seeded prior to the abort signal being available:\n // schedule a cleanup function for it.\n // TODO: Add ability to cleanup entries seeded w useCacheRefresh()\n record.cleanupScheduled = true;\n if (getCacheSignal) {\n signal.addEventListener('abort', () => {\n Scheduler.log(`Cache cleanup: ${text} [v${textCache.version}]`);\n });\n }\n }\n switch (record.status) {\n case 'pending':\n throw record.value;\n case 'rejected':\n throw record.value;\n case 'resolved':\n return textCache.version;\n }\n } else {\n Scheduler.log(`Cache miss! [${text}]`);\n\n let resolve;\n let reject;\n const thenable = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n }).then(\n value => {\n if (newRecord.status === 'pending') {\n newRecord.status = 'resolved';\n newRecord.value = value;\n }\n },\n error => {\n if (newRecord.status === 'pending') {\n newRecord.status = 'rejected';\n newRecord.value = error;\n }\n },\n );\n thenable.resolve = resolve;\n thenable.reject = reject;\n\n const newRecord = {\n status: 'pending',\n value: thenable,\n cleanupScheduled: true,\n };\n textCache.data.set(text, newRecord);\n\n if (getCacheSignal) {\n signal.addEventListener('abort', () => {\n Scheduler.log(`Cache cleanup: ${text} [v${textCache.version}]`);\n });\n }\n throw thenable;\n }\n }\n\n function Text({text}) {\n Scheduler.log(text);\n return text;\n }\n\n function AsyncText({text, showVersion}) {\n const version = readText(text);\n const fullText = showVersion ? `${text} [v${version}]` : text;\n Scheduler.log(fullText);\n return fullText;\n }\n\n function seedNextTextCache(text) {\n if (seededCache === null) {\n seededCache = getTextCache();\n }\n seededCache.resolve(text);\n }\n\n function resolveMostRecentTextCache(text) {\n if (textCaches.length === 0) {\n throw Error('Cache does not exist.');\n } else {\n // Resolve the most recently created cache. An older cache can by\n // resolved with `textCaches[index].resolve(text)`.\n textCaches[textCaches.length - 1].resolve(text);\n }\n }\n\n // @gate enableCacheElement && enableCache\n test('render Cache component', async () => {\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(Hi);\n });\n expect(root).toMatchRenderedOutput('Hi');\n });\n\n // @gate enableCacheElement && enableCache\n test('mount new data', async () => {\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n \n }>\n \n \n ,\n );\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A']);\n expect(root).toMatchRenderedOutput('A');\n\n await act(() => {\n root.render('Bye');\n });\n // no cleanup: cache is still retained at the root\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCache\n test('root acts as implicit cache boundary', async () => {\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n }>\n \n ,\n );\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A']);\n expect(root).toMatchRenderedOutput('A');\n\n await act(() => {\n root.render('Bye');\n });\n // no cleanup: cache is still retained at the root\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('multiple new Cache boundaries in the same mount share the same, fresh root cache', async () => {\n function App() {\n return (\n <>\n \n }>\n \n \n \n \n }>\n \n \n \n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n\n // Even though there are two new trees, they should share the same\n // data cache. So there should be only a single cache miss for A.\n assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A', 'A']);\n expect(root).toMatchRenderedOutput('AA');\n\n await act(() => {\n root.render('Bye');\n });\n // no cleanup: cache is still retained at the root\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('multiple new Cache boundaries in the same update share the same, fresh cache', async () => {\n function App({showMore}) {\n return showMore ? (\n <>\n \n }>\n \n \n \n \n }>\n \n \n \n \n ) : (\n '(empty)'\n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n assertLog([]);\n expect(root).toMatchRenderedOutput('(empty)');\n\n await act(() => {\n root.render();\n });\n // Even though there are two new trees, they should share the same\n // data cache. So there should be only a single cache miss for A.\n assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A', 'A']);\n expect(root).toMatchRenderedOutput('AA');\n\n await act(() => {\n root.render('Bye');\n });\n // cleanup occurs for the cache shared by the inner cache boundaries (which\n // are not shared w the root because they were added in an update)\n // note that no cache is created for the root since the cache is never accessed\n assertLog(['Cache cleanup: A [v1]']);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test(\n 'nested cache boundaries share the same cache as the root during ' +\n 'the initial render',\n async () => {\n function App() {\n return (\n }>\n \n \n \n \n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n // Even though there is a nested boundary, it should share the same\n // data cache as the root. So there should be only a single cache miss for A.\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A', 'A']);\n expect(root).toMatchRenderedOutput('AA');\n\n await act(() => {\n root.render('Bye');\n });\n // no cleanup: cache is still retained at the root\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n },\n );\n\n // @gate enableCacheElement && enableCache\n test('new content inside an existing Cache boundary should re-use already cached data', async () => {\n function App({showMore}) {\n return (\n \n }>\n \n \n {showMore ? (\n }>\n \n \n ) : null}\n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n seedNextTextCache('A');\n root.render();\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Add a new cache boundary\n await act(() => {\n root.render();\n });\n assertLog([\n 'A [v1]',\n // New tree should use already cached data\n 'A [v1]',\n ]);\n expect(root).toMatchRenderedOutput('A [v1]A [v1]');\n\n await act(() => {\n root.render('Bye');\n });\n // no cleanup: cache is still retained at the root\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('a new Cache boundary uses fresh cache', async () => {\n // The only difference from the previous test is that the \"Show More\"\n // content is wrapped in a nested boundary\n function App({showMore}) {\n return (\n \n }>\n \n \n {showMore ? (\n \n }>\n \n \n \n ) : null}\n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n seedNextTextCache('A');\n root.render();\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Add a new cache boundary\n await act(() => {\n root.render();\n });\n assertLog([\n 'A [v1]',\n // New tree should load fresh data.\n 'Cache miss! [A]',\n 'Loading...',\n ]);\n expect(root).toMatchRenderedOutput('A [v1]Loading...');\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v2]']);\n expect(root).toMatchRenderedOutput('A [v1]A [v2]');\n\n // Replace all the children: this should retain the root Cache instance,\n // but cleanup the separate cache instance created for the fresh cache\n // boundary\n await act(() => {\n root.render('Bye!');\n });\n // Cleanup occurs for the *second* cache instance: the first is still\n // referenced by the root\n assertLog(['Cache cleanup: A [v2]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test('inner/outer cache boundaries uses the same cache instance on initial render', async () => {\n const root = ReactNoop.createRoot();\n\n function App() {\n return (\n \n }>\n {/* The shell reads A */}\n \n {/* The inner content reads both A and B */}\n }>\n \n \n \n \n \n \n \n );\n }\n\n function Shell({children}) {\n readText('A');\n return (\n <>\n
\n \n
\n
{children}
\n \n );\n }\n\n function Content() {\n readText('A');\n readText('B');\n return ;\n }\n\n await act(() => {\n root.render();\n });\n assertLog(['Cache miss! [A]', 'Loading shell...']);\n expect(root).toMatchRenderedOutput('Loading shell...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog([\n 'Shell',\n // There's a cache miss for B, because it hasn't been read yet. But not\n // A, because it was cached when we rendered the shell.\n 'Cache miss! [B]',\n 'Loading content...',\n ]);\n expect(root).toMatchRenderedOutput(\n <>\n
Shell
\n
Loading content...
\n ,\n );\n\n await act(() => {\n resolveMostRecentTextCache('B');\n });\n assertLog(['Content']);\n expect(root).toMatchRenderedOutput(\n <>\n
Shell
\n
Content
\n ,\n );\n\n await act(() => {\n root.render('Bye');\n });\n // no cleanup: cache is still retained at the root\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('inner/ outer cache boundaries added in the same update use the same cache instance', async () => {\n const root = ReactNoop.createRoot();\n\n function App({showMore}) {\n return showMore ? (\n \n }>\n {/* The shell reads A */}\n \n {/* The inner content reads both A and B */}\n }>\n \n \n \n \n \n \n \n ) : (\n '(empty)'\n );\n }\n\n function Shell({children}) {\n readText('A');\n return (\n <>\n
\n \n
\n
{children}
\n \n );\n }\n\n function Content() {\n readText('A');\n readText('B');\n return ;\n }\n\n await act(() => {\n root.render();\n });\n assertLog([]);\n expect(root).toMatchRenderedOutput('(empty)');\n\n await act(() => {\n root.render();\n });\n assertLog(['Cache miss! [A]', 'Loading shell...']);\n expect(root).toMatchRenderedOutput('Loading shell...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog([\n 'Shell',\n // There's a cache miss for B, because it hasn't been read yet. But not\n // A, because it was cached when we rendered the shell.\n 'Cache miss! [B]',\n 'Loading content...',\n ]);\n expect(root).toMatchRenderedOutput(\n <>\n
Shell
\n
Loading content...
\n ,\n );\n\n await act(() => {\n resolveMostRecentTextCache('B');\n });\n assertLog(['Content']);\n expect(root).toMatchRenderedOutput(\n <>\n
Shell
\n
Content
\n ,\n );\n\n await act(() => {\n root.render('Bye');\n });\n assertLog(['Cache cleanup: A [v1]', 'Cache cleanup: B [v1]']);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCache\n test('refresh a cache boundary', async () => {\n let refresh;\n function App() {\n refresh = useCacheRefresh();\n return ;\n }\n\n // Mount initial data\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n }>\n \n ,\n );\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Refresh for new data.\n await act(() => {\n startTransition(() => refresh());\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n // Note that the version has updated\n if (getCacheSignal) {\n assertLog(['A [v2]', 'Cache cleanup: A [v1]']);\n } else {\n assertLog(['A [v2]']);\n }\n expect(root).toMatchRenderedOutput('A [v2]');\n\n await act(() => {\n root.render('Bye');\n });\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('refresh the root cache', async () => {\n let refresh;\n function App() {\n refresh = useCacheRefresh();\n return ;\n }\n\n // Mount initial data\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n }>\n \n ,\n );\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Refresh for new data.\n await act(() => {\n startTransition(() => refresh());\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n // Note that the version has updated, and the previous cache is cleared\n assertLog(['A [v2]', 'Cache cleanup: A [v1]']);\n expect(root).toMatchRenderedOutput('A [v2]');\n\n await act(() => {\n root.render('Bye');\n });\n // the original root cache already cleaned up when the refresh completed\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('refresh the root cache without a transition', async () => {\n let refresh;\n function App() {\n refresh = useCacheRefresh();\n return ;\n }\n\n // Mount initial data\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n }>\n \n ,\n );\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Refresh for new data.\n await act(() => {\n refresh();\n });\n assertLog([\n 'Cache miss! [A]',\n 'Loading...',\n // The v1 cache can be cleaned up since everything that references it has\n // been replaced by a fallback. When the boundary switches back to visible\n // it will use the v2 cache.\n 'Cache cleanup: A [v1]',\n ]);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n // Note that the version has updated, and the previous cache is cleared\n assertLog(['A [v2]']);\n expect(root).toMatchRenderedOutput('A [v2]');\n\n await act(() => {\n root.render('Bye');\n });\n // the original root cache already cleaned up when the refresh completed\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('refresh a cache with seed data', async () => {\n let refreshWithSeed;\n function App() {\n const refresh = useCacheRefresh();\n const [seed, setSeed] = useState({fn: null});\n if (seed.fn) {\n seed.fn();\n seed.fn = null;\n }\n refreshWithSeed = fn => {\n setSeed({fn});\n refresh();\n };\n return ;\n }\n\n // Mount initial data\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n \n }>\n \n \n ,\n );\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Refresh for new data.\n await act(() => {\n // Refresh the cache with seeded data, like you would receive from a\n // server mutation.\n // TODO: Seeding multiple typed textCaches. Should work by calling `refresh`\n // multiple times with different key/value pairs\n startTransition(() =>\n refreshWithSeed(() => {\n const textCache = getTextCache();\n textCache.resolve('A');\n }),\n );\n });\n // The root should re-render without a cache miss.\n // The cache is not cleared up yet, since it's still reference by the root\n assertLog(['A [v2]']);\n expect(root).toMatchRenderedOutput('A [v2]');\n\n await act(() => {\n root.render('Bye');\n });\n // the refreshed cache boundary is unmounted and cleans up\n assertLog(['Cache cleanup: A [v2]']);\n expect(root).toMatchRenderedOutput('Bye');\n });\n\n // @gate enableCacheElement && enableCache\n test('refreshing a parent cache also refreshes its children', async () => {\n let refreshShell;\n function RefreshShell() {\n refreshShell = useCacheRefresh();\n return null;\n }\n\n function App({showMore}) {\n return (\n \n \n }>\n \n \n {showMore ? (\n \n }>\n \n \n \n ) : null}\n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n seedNextTextCache('A');\n root.render();\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Add a new cache boundary\n await act(() => {\n seedNextTextCache('A');\n root.render();\n });\n assertLog([\n 'A [v1]',\n // New tree should load fresh data.\n 'A [v2]',\n ]);\n expect(root).toMatchRenderedOutput('A [v1]A [v2]');\n\n // Now refresh the shell. This should also cause the \"Show More\" contents to\n // refresh, since its cache is nested inside the outer one.\n await act(() => {\n startTransition(() => refreshShell());\n });\n assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']);\n expect(root).toMatchRenderedOutput('A [v1]A [v2]');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog([\n 'A [v3]',\n 'A [v3]',\n // once the refresh completes the inner showMore boundary frees its previous\n // cache instance, since it is now using the refreshed parent instance.\n 'Cache cleanup: A [v2]',\n ]);\n expect(root).toMatchRenderedOutput('A [v3]A [v3]');\n\n await act(() => {\n root.render('Bye!');\n });\n // Unmounting children releases the refreshed cache instance only; the root\n // still retains the original cache instance used for the first render\n assertLog(['Cache cleanup: A [v3]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test(\n 'refreshing a cache boundary does not refresh the other boundaries ' +\n 'that mounted at the same time (i.e. the ones that share the same cache)',\n async () => {\n let refreshFirstBoundary;\n function RefreshFirstBoundary() {\n refreshFirstBoundary = useCacheRefresh();\n return null;\n }\n\n function App({showMore}) {\n return showMore ? (\n <>\n \n }>\n \n \n \n \n \n }>\n \n \n \n \n ) : null;\n }\n\n // First mount the initial shell without the nested boundaries. This is\n // necessary for this test because we want the two inner boundaries to be\n // treated like sibling providers that happen to share an underlying\n // cache, as opposed to consumers of the root-level cache.\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n\n // Now reveal the boundaries. In a real app this would be a navigation.\n await act(() => {\n root.render();\n });\n\n // Even though there are two new trees, they should share the same\n // data cache. So there should be only a single cache miss for A.\n assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]', 'A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]A [v1]');\n\n // Refresh the first boundary. It should not refresh the second boundary,\n // even though they previously shared the same underlying cache.\n await act(async () => {\n await refreshFirstBoundary();\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v2]']);\n expect(root).toMatchRenderedOutput('A [v2]A [v1]');\n\n // Unmount children: this should clear *both* cache instances:\n // the root doesn't have a cache instance (since it wasn't accessed\n // during the initial render, and all subsequent cache accesses were within\n // a fresh boundary). Therefore this causes cleanup for both the fresh cache\n // instance in the refreshed first boundary and cleanup for the non-refreshed\n // sibling boundary.\n await act(() => {\n root.render('Bye!');\n });\n assertLog(['Cache cleanup: A [v2]', 'Cache cleanup: A [v1]']);\n expect(root).toMatchRenderedOutput('Bye!');\n },\n );\n\n // @gate enableCacheElement && enableCache\n test(\n 'mount a new Cache boundary in a sibling while simultaneously ' +\n 'resolving a Suspense boundary',\n async () => {\n function App({showMore}) {\n return (\n <>\n {showMore ? (\n }>\n \n \n \n \n ) : null}\n }>\n \n {' '}\n {' '}\n \n \n \n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n // This will resolve the content in the first cache\n resolveMostRecentTextCache('A');\n resolveMostRecentTextCache('B');\n // And mount the second tree, which includes new content\n root.render();\n });\n assertLog([\n // The new tree should use a fresh cache\n 'Cache miss! [A]',\n 'Loading...',\n // The other tree uses the cached responses. This demonstrates that the\n // requests are not dropped.\n 'A [v1]',\n 'B [v1]',\n ]);\n expect(root).toMatchRenderedOutput('Loading... A [v1] B [v1]');\n\n // Now resolve the second tree\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v2]']);\n expect(root).toMatchRenderedOutput('A [v2] A [v1] B [v1]');\n\n await act(() => {\n root.render('Bye!');\n });\n // Unmounting children releases both cache boundaries, but the original\n // cache instance (used by second boundary) is still referenced by the root.\n // only the second cache instance is freed.\n assertLog(['Cache cleanup: A [v2]']);\n expect(root).toMatchRenderedOutput('Bye!');\n },\n );\n\n // @gate enableCacheElement && enableCache\n test('cache pool is cleared once transitions that depend on it commit their shell', async () => {\n function Child({text}) {\n return (\n \n \n \n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n }>(empty),\n );\n });\n assertLog([]);\n expect(root).toMatchRenderedOutput('(empty)');\n\n await act(() => {\n startTransition(() => {\n root.render(\n }>\n \n ,\n );\n });\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('(empty)');\n\n await act(() => {\n startTransition(() => {\n root.render(\n }>\n \n \n ,\n );\n });\n });\n assertLog([\n // No cache miss, because it uses the pooled cache\n 'Loading...',\n ]);\n expect(root).toMatchRenderedOutput('(empty)');\n\n // Resolve the request\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]', 'A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]A [v1]');\n\n // Now do another transition\n await act(() => {\n startTransition(() => {\n root.render(\n }>\n \n \n \n ,\n );\n });\n });\n assertLog([\n // First two children use the old cache because they already finished\n 'A [v1]',\n 'A [v1]',\n // The new child uses a fresh cache\n 'Cache miss! [A]',\n 'Loading...',\n ]);\n expect(root).toMatchRenderedOutput('A [v1]A [v1]');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]', 'A [v1]', 'A [v2]']);\n expect(root).toMatchRenderedOutput('A [v1]A [v1]A [v2]');\n\n // Unmount children: the first text cache instance is created only after the root\n // commits, so both fresh cache instances are released by their cache boundaries,\n // cleaning up v1 (used for the first two children which render together) and\n // v2 (used for the third boundary added later).\n await act(() => {\n root.render('Bye!');\n });\n assertLog(['Cache cleanup: A [v1]', 'Cache cleanup: A [v2]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test('cache pool is not cleared by arbitrary commits', async () => {\n function App() {\n return (\n <>\n \n \n \n );\n }\n\n let showMore;\n function ShowMore() {\n const [shouldShow, _showMore] = useState(false);\n showMore = () => _showMore(true);\n return (\n <>\n }>\n {shouldShow ? (\n \n \n \n ) : null}\n \n \n );\n }\n\n let updateUnrelated;\n function Unrelated() {\n const [count, _updateUnrelated] = useState(0);\n updateUnrelated = _updateUnrelated;\n return ;\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n assertLog(['0']);\n expect(root).toMatchRenderedOutput('0');\n\n await act(() => {\n startTransition(() => {\n showMore();\n });\n });\n assertLog(['Cache miss! [A]', 'Loading...']);\n expect(root).toMatchRenderedOutput('0');\n\n await act(() => {\n updateUnrelated(1);\n });\n assertLog([\n '1',\n\n // Happens to re-render the fallback. Doesn't need to, but not relevant\n // to this test.\n 'Loading...',\n ]);\n expect(root).toMatchRenderedOutput('1');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]1');\n\n // Unmount children: the first text cache instance is created only after initial\n // render after calling showMore(). This instance is cleaned up when that boundary\n // is unmounted. Bc root cache instance is never accessed, the inner cache\n // boundary ends up at v1.\n await act(() => {\n root.render('Bye!');\n });\n assertLog(['Cache cleanup: A [v1]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test('cache boundary uses a fresh cache when its key changes', async () => {\n const root = ReactNoop.createRoot();\n seedNextTextCache('A');\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n seedNextTextCache('B');\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['B [v2]']);\n expect(root).toMatchRenderedOutput('B [v2]');\n\n // Unmount children: the fresh cache instance for B cleans up since the cache boundary\n // is the only owner, while the original cache instance (for A) is still retained by\n // the root.\n await act(() => {\n root.render('Bye!');\n });\n assertLog(['Cache cleanup: B [v2]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test('overlapping transitions after an initial mount use the same fresh cache', async () => {\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['Cache miss! [A]']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // After a mount, subsequent transitions use a fresh cache\n await act(() => {\n startTransition(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n });\n assertLog(['Cache miss! [B]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Update to a different text and with a different key for the cache\n // boundary: this should still use the fresh cache instance created\n // for the earlier transition\n await act(() => {\n startTransition(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n });\n assertLog(['Cache miss! [C]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n await act(() => {\n resolveMostRecentTextCache('C');\n });\n assertLog(['C [v2]']);\n expect(root).toMatchRenderedOutput('C [v2]');\n\n // Unmount children: the fresh cache used for the updates is freed, while the\n // original cache (with A) is still retained at the root.\n await act(() => {\n root.render('Bye!');\n });\n assertLog(['Cache cleanup: B [v2]', 'Cache cleanup: C [v2]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test('overlapping updates after an initial mount use the same fresh cache', async () => {\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['Cache miss! [A]']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('A');\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // After a mount, subsequent updates use a fresh cache\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['Cache miss! [B]']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n // A second update uses the same fresh cache: even though this is a new\n // Cache boundary, the render uses the fresh cache from the pending update.\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['Cache miss! [C]']);\n expect(root).toMatchRenderedOutput('Loading...');\n\n await act(() => {\n resolveMostRecentTextCache('C');\n });\n assertLog(['C [v2]']);\n expect(root).toMatchRenderedOutput('C [v2]');\n\n // Unmount children: the fresh cache used for the updates is freed, while the\n // original cache (with A) is still retained at the root.\n await act(() => {\n root.render('Bye!');\n });\n assertLog(['Cache cleanup: B [v2]', 'Cache cleanup: C [v2]']);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test('cleans up cache only used in an aborted transition', async () => {\n const root = ReactNoop.createRoot();\n seedNextTextCache('A');\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Start a transition from A -> B..., which should create a fresh cache\n // for the new cache boundary (bc of the different key)\n await act(() => {\n startTransition(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n });\n assertLog(['Cache miss! [B]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // ...but cancel by transitioning \"back\" to A (which we never really left)\n await act(() => {\n startTransition(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n });\n assertLog(['A [v1]', 'Cache cleanup: B [v2]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Unmount children: ...\n await act(() => {\n root.render('Bye!');\n });\n assertLog([]);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test.skip('if a root cache refresh never commits its fresh cache is released', async () => {\n const root = ReactNoop.createRoot();\n let refresh;\n function Example({text}) {\n refresh = useCacheRefresh();\n return ;\n }\n seedNextTextCache('A');\n await act(() => {\n root.render(\n \n \n ,\n );\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n await act(() => {\n startTransition(() => {\n refresh();\n });\n });\n assertLog(['Cache miss! [A]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n await act(() => {\n root.render('Bye!');\n });\n assertLog([\n // TODO: the v1 cache should *not* be cleaned up, it is still retained by the root\n // The following line is presently yielded but should not be:\n // 'Cache cleanup: A [v1]',\n\n // TODO: the v2 cache *should* be cleaned up, it was created for the abandoned refresh\n // The following line is presently not yielded but should be:\n 'Cache cleanup: A [v2]',\n ]);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableCacheElement && enableCache\n test.skip('if a cache boundary refresh never commits its fresh cache is released', async () => {\n const root = ReactNoop.createRoot();\n let refresh;\n function Example({text}) {\n refresh = useCacheRefresh();\n return ;\n }\n seedNextTextCache('A');\n await act(() => {\n root.render(\n \n \n \n \n ,\n );\n });\n assertLog(['A [v1]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n await act(() => {\n startTransition(() => {\n refresh();\n });\n });\n assertLog(['Cache miss! [A]']);\n expect(root).toMatchRenderedOutput('A [v1]');\n\n // Unmount the boundary before the refresh can complete\n await act(() => {\n root.render('Bye!');\n });\n assertLog([\n // TODO: the v2 cache *should* be cleaned up, it was created for the abandoned refresh\n // The following line is presently not yielded but should be:\n 'Cache cleanup: A [v2]',\n ]);\n expect(root).toMatchRenderedOutput('Bye!');\n });\n\n // @gate enableActivity\n // @gate enableCache\n test('prerender a new cache boundary inside an Activity tree', async () => {\n function App({prerenderMore}) {\n return (\n \n
\n {prerenderMore ? (\n \n \n \n ) : null}\n
\n
\n );\n }\n\n const root = ReactNoop.createRoot();\n await act(() => {\n root.render();\n });\n assertLog([]);\n expect(root).toMatchRenderedOutput(