prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
>isDataProvider());
$this->assertFalse($metadata->isDataProviderClosure());
$this->assertFalse($metadata->isDependsOnClass());
$this->assertFalse($metadata->isDependsOnMethod());
$this->assertFalse($metadata->isDisableReturnValueGenerationForTestDoubles());
$this->assertFalse($me... | HPUnitWarnings());
$this->assertFalse($metadata->isRunInSeparateProcess());
$this->assertFalse($metadata->isRunTestsInSeparateProcesses());
$this->assertFalse($metadata->isTest());
$this->assertFalse($metadata->isPreConditio | $this->assertFalse($metadata->isGroup());
$this->assertFalse($metadata->isIgnoreDeprecations());
$this->assertFalse($metadata->isIgnorePhpunitDeprecations());
$this->assertFalse($metadata->isIgnoreP | {
"filepath": "tests/unit/Metadata/MetadataTest.php",
"language": "php",
"file_size": 299810,
"cut_index": 13624,
"middle_length": 229
} |
tian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Event\Test;
use const PHP_EOL;
use PHPUnit\Event\AbstractEventTestCase;
use PHPUnit\Event\Code\IssueTrigger\IssueTrigger;
use PHPUnit\Framework\Attrib... | this->testValueObject();
$message = 'message';
$file = 'file';
$line = 1;
$suppressed = false;
$ignoredByBaseline = false;
$ignoredByTest = false;
$trigg | system/events')]
final class DeprecationTriggeredTest extends AbstractEventTestCase
{
public function testConstructorSetsValues(): void
{
$telemetryInfo = $this->telemetryInfo();
$test = $ | {
"filepath": "tests/unit/Event/Events/Test/Issue/DeprecationTriggeredTest.php",
"language": "php",
"file_size": 4254,
"cut_index": 614,
"middle_length": 229
} |
tian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Metadata\Api;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use... | Test extends TestCase
{
/**
* @return non-empty-list<array{list<string>, class-string, string, bool}>
*/
public static function provider(): array
{
return [
[
[
],
No | e\NoGroupsMetadataTest;
use PHPUnit\TestFixture\SmallGroupAnnotationsTest;
use PHPUnit\TestFixture\SmallGroupAttributesTest;
#[CoversClass(Groups::class)]
#[Small]
#[Group('metadata')]
#[Group('metadata/api')]
final class Groups | {
"filepath": "tests/unit/Metadata/Api/GroupsTest.php",
"language": "php",
"file_size": 4007,
"cut_index": 614,
"middle_length": 229
} |
art of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Logging\TestDox;
use PHPUnit\Event\Code\TestDoxBuilder;
use PHPUnit\Event\Code\TestMethod;
use PHPU... | ase
{
public function test_Test_method_status_and_throwable_are_exposed_when_a_throwable_is_present(): void
{
$testMethod = $this->testMethod();
$status = TestStatus::error('boom');
$throwable = new Throwable(
| Small;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestStatus\TestStatus;
use PHPUnit\Metadata\MetadataCollection;
#[CoversClass(TestResult::class)]
#[Group('testdox')]
#[Small]
final class TestResultTest extends TestC | {
"filepath": "tests/unit/Logging/TestDox/TestResult/TestResultTest.php",
"language": "php",
"file_size": 2098,
"cut_index": 563,
"middle_length": 229
} |
e(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Event\Test;
use const PHP_EOL;
use PHPUnit\Event\AbstractEve... | s->telemetryInfo();
$test = $this->testValueObject();
$message = 'message';
$event = new PhpunitDeprecationTriggered(
$telemetryInfo,
$test,
$message,
);
$this->as | Small]
#[Group('event-system')]
#[Group('event-system/events')]
final class PhpunitDeprecationTriggeredTest extends AbstractEventTestCase
{
public function testConstructorSetsValues(): void
{
$telemetryInfo = $thi | {
"filepath": "tests/unit/Event/Events/Test/Issue/PhpunitDeprecationTriggeredTest.php",
"language": "php",
"file_size": 1300,
"cut_index": 524,
"middle_length": 229
} |
nValueGenerationForTestDoublesTest;
use PHPUnit\TestFixture\Metadata\Attribute\DoesNotPerformAssertionsTest;
use PHPUnit\TestFixture\Metadata\Attribute\DuplicateSmallAttributeTest;
use PHPUnit\TestFixture\Metadata\Attribute\DuplicateTestAttributeTest;
use PHPUnit\TestFixture\Metadata\Attribute\Example;
use PHPUnit\Test... | e\Metadata\Attribute\IgnorePhpunitWarningsTest;
use PHPUnit\TestFixture\Metadata\Attribute\LargeTest;
use PHPUnit\TestFixture\Metadata\Attribute\MediumTest;
use PHPUnit\TestFixture\Metadata\Attribute\NonPhpunitAttributeTest;
use PHPUnit\TestFixture\Metadat | etadata\Attribute\IgnoreDeprecationsMethodTest;
use PHPUnit\TestFixture\Metadata\Attribute\IgnorePhpunitDeprecationsClassTest;
use PHPUnit\TestFixture\Metadata\Attribute\IgnorePhpunitDeprecationsMethodTest;
use PHPUnit\TestFixtur | {
"filepath": "tests/unit/Metadata/Parser/AttributeParserTestCase.php",
"language": "php",
"file_size": 55016,
"cut_index": 2151,
"middle_length": 229
} |
ules: {
'ft-flow/array-style-complex-type': [OFF, 'verbose'],
'ft-flow/array-style-simple-type': [OFF, 'verbose'], // TODO should be WARNING
'ft-flow/boolean-style': ERROR,
'ft-flow/no-dupe-keys': ERROR,
'ft-flow/no-primitive-constructor-types': ERROR,
'ft-flow/no-types-missing-file-annotation':... | mpty-character-class': WARNING,
'no-empty': OFF,
'no-ex-assign': WARNING,
'no-extra-boolean-cast': WARNING,
'no-func-assign': ERROR,
'no-invalid-regexp': WARNING,
'no-irregular-whitespace': WARNING,
'no-negated-in-lhs': ERROR,
| aining': ERROR,
'no-cond-assign': OFF,
'no-constant-condition': OFF,
'no-control-regex': OFF,
'no-debugger': ERROR,
'no-dupe-args': ERROR,
'no-dupe-keys': ERROR,
'no-duplicate-case': WARNING,
'no-e | {
"filepath": ".eslintrc.js",
"language": "javascript",
"file_size": 21080,
"cut_index": 1331,
"middle_length": 229
} |
ax-jsx',
'@babel/plugin-transform-flow-strip-types',
['@babel/plugin-proposal-class-properties', {loose: true}],
'syntax-trailing-function-commas',
[
'@babel/plugin-proposal-object-rest-spread',
{loose: true, useBuiltIns: true},
],
['@babel/plugin-transform-template-literals', {loose... | ',
'@babel/plugin-transform-for-of',
['@babel/plugin-transform-spread', {loose: true, useBuiltIns: true}],
'@babel/plugin-transform-parameters',
['@babel/plugin-transform-destructuring', {loose: true, useBuiltIns: true}],
['@babel/plugi | ',
'@babel/plugin-transform-shorthand-properties | {
"filepath": "babel.config.js",
"language": "javascript",
"file_size": 959,
"cut_index": 582,
"middle_length": 52
} |
d,
debug(...data: Array<any>): void,
dir(...data: Array<any>): void,
dirxml(...data: Array<any>): void,
error(...data: Array<any>): void,
_exception(...data: Array<any>): void,
group(...data: Array<any>): void,
groupCollapsed(...data: Array<any>): void,
groupEnd(): void,
info(...data: Array<any>): voi... | trackGroup?: string,
color?: string,
): void,
timeLog(label?: string, ...data?: Array<any>): void,
trace(...data: Array<any>): void,
warn(...data: Array<any>): void,
createTask(label: string): ConsoleTask,
...
};
type ScrollTimelineOption | : any, ...}>
| Array<Array<any>>,
): void,
time(label?: string): void,
timeEnd(label: string): void,
timeStamp(
label?: string,
start?: string | number,
end?: string | number,
trackName?: string,
| {
"filepath": "scripts/flow/environment.js",
"language": "javascript",
"file_size": 18883,
"cut_index": 1331,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Based on similar script in Jest
// https://github.com/facebook/jest/blob/a7acc5ae519613647ff2c253dd21933d6f94b47f/scripts/prettier.js
const chalk = require('chalk');
const glob = require('glob');
const prettier =... | d ? listChangedFiles() : null;
const prettierIgnoreFilePath = path.join(
__dirname,
'..',
'..',
'.prettierignore'
);
const prettierIgnore = fs.readFileSync(prettierIgnoreFilePath, {
encoding: 'utf8',
});
const ignoredPathsListedInPrettierIgnore | .prettierrc');
const mode = process.argv[2] || 'check';
const shouldWrite = mode === 'write' || mode === 'write-changed';
const onlyChanged = mode === 'check-changed' || mode === 'write-changed';
const changedFiles = onlyChange | {
"filepath": "scripts/prettier/index.js",
"language": "javascript",
"file_size": 3417,
"cut_index": 614,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const fs = require('fs');
const path = require('path');
const existingErrorMap = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '../error-codes/codes.json'))
);
const messages = new S... | ) {
return node.value;
} else if (node.type === 'BinaryExpression' && node.operator === '+') {
const l = getLiteralString(node.left);
const r = getLiteralString(node.right);
if (l !== null && r !== null) {
re | {
meta: {
schema: [],
},
create(context) {
// we also allow literal strings and concatenated literal strings
function getLiteralString(node) {
if (node.type === 'Literal' && typeof node.value === 'string' | {
"filepath": "scripts/eslint-rules/warning-args.js",
"language": "javascript",
"file_size": 3213,
"cut_index": 614,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const minimatch = require('minimatch');
const {ESLint} = require('eslint');
const listChangedFiles = require('../shared/listChangedFiles');
const allPaths = ['**/*... | erns;
const results = await eslint.lintFiles(finalFilePatterns);
if (options != null && options.fix === true) {
await ESLint.outputFixes(results);
}
// When using `ignorePattern`, eslint will show `File ignored...` warnings for any ignores.
| rmatter();
if (onlyChanged && changedFiles === null) {
// Calculate lazily.
changedFiles = [...listChangedFiles()];
}
const finalFilePatterns = onlyChanged
? intersect(changedFiles, filePatterns)
: filePatt | {
"filepath": "scripts/eslint/index.js",
"language": "javascript",
"file_size": 2808,
"cut_index": 563,
"middle_length": 229
} |
poRoot} = require('./utils');
async function fetchNpmInfo(packageName, {log}) {
const npmArgs = ['view', `${packageName}@latest`, '--json'];
const options = {cwd: repoRoot, maxBuffer: 10 * 1024 * 1024};
log(`Fetching npm info for ${packageName}...`);
const {stdout} = await execFileAsync('npm', npmArgs, options... | packageName}@${version}`, 'gitHead'],
{cwd: repoRoot, maxBuffer: 1024 * 1024}
);
const possibleGitHead = gitHeadResult.stdout.trim();
if (
possibleGitHead &&
possibleGitHead !== 'undefined' &&
possibleGitHead !== 'null'
| fo = info[info.length - 1];
}
const version = info.version || info['dist-tags']?.latest;
let gitHead = info.gitHead || null;
if (!gitHead) {
const gitHeadResult = await execFileAsync(
'npm',
['view', `${ | {
"filepath": "scripts/tasks/generate-changelog/data.js",
"language": "javascript",
"file_size": 4969,
"cut_index": 614,
"middle_length": 229
} |
ent',
'react-dom/profiling',
'react-dom/server.browser',
'react-dom/static.browser',
'react-dom/unstable_testing',
'react-dom/src/server/react-dom-server.browser',
'react-dom/src/server/ReactDOMFizzServerBrowser.js', // react-dom/server.browser
'react-dom/src/server/ReactDOMFiz... | server-dom-webpack/static.browser',
'react-server-dom-webpack/src/client/ReactFlightDOMClientBrowser.js', // react-server-dom-webpack/client.browser
'react-server-dom-webpack/src/client/ReactFlightClientConfigBundlerWebpack.js',
'react-se | src/shared/ReactFlightClientConfigDOM.js',
'react-server-dom-webpack',
'react-server-dom-webpack/client',
'react-server-dom-webpack/client.browser',
'react-server-dom-webpack/server.browser',
'react- | {
"filepath": "scripts/shared/inlinedHostConfigs.js",
"language": "javascript",
"file_size": 31532,
"cut_index": 1331,
"middle_length": 229
} |
strict';
const {join, relative} = require('path');
const {handleError} = require('./utils');
const yargs = require('yargs');
const clear = require('clear');
const theme = require('./theme');
const {
downloadBuildArtifacts,
} = require('./shared-commands/download-build-artifacts');
const argv = yargs.wrap(yargs.ter... |
requiresArg: false,
type: 'boolean',
default: false,
},
}).argv;
function printSummary(commit) {
const commandPath = relative(
process.env.PWD,
join(__dirname, '../download-experimental-build.js')
);
clear();
const message | e'],
default: 'experimental',
},
commit: {
alias: 'c',
describe: 'Commit hash to download.',
requiresArg: true,
demandOption: true,
type: 'string',
},
noVerify: {
describe: 'Skip verification', | {
"filepath": "scripts/release/download-experimental-build.js",
"language": "javascript",
"file_size": 1531,
"cut_index": 537,
"middle_length": 229
} |
strict';
// IMPORTANT:
// Changes below should be mirrored in ../ci-add-build-info-json.js
const {existsSync} = require('fs');
const {writeJson, readJson} = require('fs-extra');
const {join} = require('path');
const {getPublicPackages, logPromise} = require('../utils');
const theme = require('../theme');
const run ... | i++) {
const packageName = packages[i];
const packagePath = join(packagesDir, packageName);
const packageJSON = await readJson(join(packagePath, 'package.json'));
// Verify all public packages include "build-info.json" in the files array.
| onst packagesDir = join(tempDirectory, 'packages');
const buildInfoJSON = {
branch,
buildNumber: null,
checksum,
commit,
environment: 'local',
reactVersion,
};
for (let i = 0; i < packages.length; | {
"filepath": "scripts/release/build-release-locally-commands/add-build-info-json.js",
"language": "javascript",
"file_size": 1582,
"cut_index": 537,
"middle_length": 229
} |
2Server = require('http2');
const httpServer = require('http-server');
const {existsSync, statSync, createReadStream} = require('fs');
const {join} = require('path');
const argv = require('minimist')(process.argv.slice(2));
const mime = require('mime');
function sendFile(filename, response) {
response.setHeader('Con... | ;
if (existsSync(filename) && statSync(filename).isFile()) {
sendFile(filename, response);
} else {
const indexHtmlPath = join(filename, 'index.html');
if (existsSync(indexHtmlPath)) {
sendFile(indexHtmlPath, response);
| n createHTTP2Server(benchmark) {
const server = http2Server.createServer({}, (request, response) => {
const filename = join(
__dirname,
'benchmarks',
benchmark,
request.url
).replace(/\?.*/g, '') | {
"filepath": "scripts/bench/server.js",
"language": "javascript",
"file_size": 1920,
"cut_index": 537,
"middle_length": 229
} |
';
const REACT_VERSION_ENV = process.env.REACT_VERSION;
function transform(babel) {
const {types: t} = babel;
// Runs tests conditionally based on the version of react (semver range) we are running
// Input:
// @reactVersion >= 17.0
// test('some test', () => {/*...*/})
//
// Output:
// @reactV... | if (!commentStr.startsWith(GATE_VERSION_STR)) {
return accumulatedCondition;
}
const condition = commentStr.slice(GATE_VERSION_STR.length);
if (accumulatedCondition === null) {
return condition;
}
| ersionCondition(comments) {
if (!comments) {
return null;
}
const resultingCondition = comments.reduce(
(accumulatedCondition, commentLine) => {
const commentStr = commentLine.value.trim();
| {
"filepath": "scripts/babel/transform-react-version-pragma.js",
"language": "javascript",
"file_size": 3509,
"cut_index": 614,
"middle_length": 229
} |
dule is the single source of truth for versioning packages that we
// publish to npm.
//
// Packages will not be published unless they are added here.
//
// The @latest channel uses the version as-is, e.g.:
//
// 19.3.0
//
// The @canary channel appends additional information, with the scheme
// <version>-<label>-<co... | .
//
// It only affects the label used in the version string. To customize the
// npm dist tags used during publish, refer to .github/workflows/runtime_prereleases_*.yml.
const canaryChannelLabel = 'canary';
// If the canaryChannelLabel is "rc", the build | ctVersion = '19.3.0';
// The label used by the @canary channel. Represents the upcoming release's
// stability. Most of the time, this will be "canary", but we may temporarily
// choose to change it to "alpha", "beta", "rc", etc | {
"filepath": "ReactVersions.js",
"language": "javascript",
"file_size": 1994,
"cut_index": 537,
"middle_length": 229
} |
;
/* eslint-disable no-for-of-loops/no-for-of-loops */
// Hi, if this is your first time editing/reading a Dangerfile, here's a summary:
// It's a JS runtime which helps you provide continuous feedback inside GitHub.
//
// You can see the docs here: http://danger.systems/js/
//
// If you want to test changes Danger, ... | = require('util');
const glob = promisify(require('glob'));
const gzipSize = require('gzip-size');
const {writeFileSync} = require('fs');
const {readFileSync, statSync} = require('fs');
const BASE_DIR = 'base-build';
const HEAD_DIR = 'build';
const CRI | f7
//
// (Just remove the space)
//
// So, for example:
//
// `DANGER_GITHUB_API_TOKEN=[ENV_ABOVE] yarn danger pr https://github.com/facebook/react/pull/11865
const {markdown, danger, warn} = require('danger');
const {promisify} | {
"filepath": "dangerfile.js",
"language": "javascript",
"file_size": 8470,
"cut_index": 716,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const inlinedHostConfigs = require('../shared/inlinedHostConfigs');
const flowVersion = requi... | orksPath = path.join(basePath, 'forks');
const forks = fs.readdirSync(path.join('packages', forksPath));
forks.forEach(f => allForks.add('forks/' + f));
forkedFiles.set(file, basePath);
return basePath;
}
function addFork(forks, renderer, file) {
| generation
const allForks = new Set();
// maps forked file to the base path containing it and it's forks (it's parent)
const forkedFiles = new Map();
function findForks(file) {
const basePath = path.join(file, '..');
const f | {
"filepath": "scripts/flow/createFlowConfigs.js",
"language": "javascript",
"file_size": 4498,
"cut_index": 614,
"middle_length": 229
} |
/* eslint-disable no-unused-vars */
declare const __EXTENSION__: boolean;
declare const __TEST__: boolean;
declare const __IS_FIREFOX__: boolean;
declare const __IS_CHROME__: boolean;
declare const __IS_EDGE__: boolean;
declare const __IS_NATIVE__: boolean;
interface ExtensionAction {
/** @see {@link https://devel... | er.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow} */
inspectedWindow: $FlowFixMe;
/** @see {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools/network} */
network: $FlowFixMe; | e {@link https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/action/setPopup} */
setPopup(details: {tabId: number, popup: string}): void;
}
interface ExtensionDevtools {
/** @see {@link https://develop | {
"filepath": "scripts/flow/react-devtools.js",
"language": "javascript",
"file_size": 5095,
"cut_index": 716,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
const {spawn} = require('child_process');
const fs = require('fs');
// TODO: This generates all the renderer configs at once. Originally this was
// to allow the possibility of runni... | ow';
if (process.platform === 'win32') {
cmd = cmd.replace(/\//g, '\\') + '.cmd';
}
// Copy renderer flowconfig file to the root of the project so that it
// works with editor integrations. This means that the Flow config used by
| e step and
// generate only the config for the specified renderer.
require('./createFlowConfigs');
async function runFlow(renderer, args) {
return new Promise(resolve => {
let cmd = __dirname + '/../../node_modules/.bin/fl | {
"filepath": "scripts/flow/runFlow.js",
"language": "javascript",
"file_size": 3108,
"cut_index": 614,
"middle_length": 229
} |
// libdefs cannot actually import. These are supposed to be the types imported
// from 'react-native-renderer/src/ReactNativeTypes'
type __MeasureOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number,
) => void;
type __MeasureInWindowOnSuccessCallback = (
... | t-native-renderer/src/legacy-events/TopLevelEventTypes';
type __RNTopLevelEventType = any;
// libdefs cannot actually import. This is supposed to be the type imported
// from 'react-reconciler/src/ReactCapturedValue'
type __CapturedError = any;
type RawE | e __ReactNativeBaseComponentViewConfig = any;
type __ViewConfigGetter = any;
type __ViewConfig = any;
type __AttributeConfiguration = any;
// libdefs cannot actually import. This is supposed to be the type imported
// from 'reac | {
"filepath": "scripts/flow/react-native-host-hooks.js",
"language": "javascript",
"file_size": 7201,
"cut_index": 716,
"middle_length": 229
} |
Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
module.exports = {
meta: {
schema: [],
},
create(context) {
function report(node... | ression') {
context.report(
node,
"Do not use `new String()`. Use String() without new (or '' + value for perf-sensitive code)."
);
}
break;
case 'Number':
report(
| se 'Boolean':
report(
node,
name,
'To cast a value to a boolean, use double negation: !!value'
);
break;
case 'String':
if (node.type === 'NewExp | {
"filepath": "scripts/eslint-rules/no-primitive-constructors.js",
"language": "javascript",
"file_size": 1240,
"cut_index": 518,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
module.exports = {
meta: {
fixable: 'code',
schema: [],
},
create: function (context) {
function isInDEVBlock(node) {
... | ) {
return true;
}
node = parent;
}
}
function reportWrapInDEV(node) {
context.report({
node: node,
message: `Wrap console.{{identifier}}() in an "if (__DEV__) {}" check`,
data: | node === parent.consequent &&
parent.test.type === 'Identifier' &&
// This is intentionally strict so we can
// see blocks of DEV-only code at once.
parent.test.name === '__DEV__'
| {
"filepath": "scripts/eslint-rules/no-production-logging.js",
"language": "javascript",
"file_size": 2056,
"cut_index": 563,
"middle_length": 229
} |
return (
// TaggedTemplateExpressions can return non-strings
(node.type === 'TemplateLiteral' &&
node.parent.type !== 'TaggedTemplateExpression') ||
(node.type === 'Literal' && typeof node.value === 'string')
);
}
// Symbols and Temporal.* objects will throw when using `'' + value`, but that
// pat... | tests, devtools extension, build tools, etc.)
// should use `String(value)` because it will never crash and the (small) perf
// difference doesn't matter enough for non-prod use cases.
//
// This rule assists enforcing these guidelines:
// * `'' + value` i | ng coercion. The only exception is prod
// error handling code, because it's bad to crash while assembling an error
// message or call stack! Also, error-handling code isn't usually perf-critical.
//
// Non-production codepaths ( | {
"filepath": "scripts/eslint-rules/safe-string-coercion.js",
"language": "javascript",
"file_size": 11687,
"cut_index": 921,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const fs = require('fs');
const path = require('path');
const errorMap = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '../error-co... | return l + r;
} else if (node.type === 'TemplateLiteral') {
let elements = [];
for (let i = 0; i < node.quasis.length; i++) {
const elementNode = node.quasis[i];
if (elementNode.type !== 'TemplateElement') {
throw new Erro | ' && typeof node.value === 'string') {
return node.value;
} else if (node.type === 'BinaryExpression' && node.operator === '+') {
const l = nodeToErrorTemplate(node.left);
const r = nodeToErrorTemplate(node.right);
| {
"filepath": "scripts/eslint-rules/prod-error-codes.js",
"language": "javascript",
"file_size": 2376,
"cut_index": 563,
"middle_length": 229
} |
Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const rule = require('../no-primitive-constructors');
const {RuleTester} = require('eslint');
... | {
message:
"Do not use `new String()`. Use String() without new (or '' + value for perf-sensitive code).",
},
],
},
{
code: 'Number(string)',
errors: [
{
message:
'Do | s: [
{
message:
'Do not use the Boolean constructor. To cast a value to a boolean, use double negation: !!value',
},
],
},
{
code: 'new String(obj)',
errors: [
| {
"filepath": "scripts/eslint-rules/__tests__/no-primitive-constructors-test.internal.js",
"language": "javascript",
"file_size": 1132,
"cut_index": 518,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const rule = require('../prod-error-codes');
const {RuleTester} = require('eslint');
const ruleTester = new RuleTester({
parserOptions: {... | {
message:
'Error message does not have a corresponding production error ' +
'code. Add the following message to codes.json so it can be stripped from ' +
'the production builds:\n\n' +
'Not | }`)',
"Error('Expected ' + foo + ' target to be an array; got ' + bar)",
'Error(`Expected ${foo} target to ` + `be an array; got ${bar}`)',
],
invalid: [
{
code: "Error('Not in error map')",
errors: [
| {
"filepath": "scripts/eslint-rules/__tests__/prod-error-codes-test.internal.js",
"language": "javascript",
"file_size": 2198,
"cut_index": 563,
"middle_length": 229
} |
ct-core
*/
'use strict';
const rule = require('../safe-string-coercion');
const {RuleTester} = require('eslint');
RuleTester.setDefaultConfig({
parser: require.resolve('babel-eslint'),
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
},
});
const ruleTester = new RuleTester();
const missingDev... | e` or `value + ''` is fast to coerce strings, but may throw." +
' For prod code, add a DEV check from shared/CheckStringCoercion immediately' +
' before this coercion.' +
' For non-prod code and prod error handling, use `String(value)` instead.';
ru | t prevStatementNotDevCheckMessage =
'The statement before this coercion must be a DEV check in this format:\n' +
' if (__DEV__) {\n' +
' checkXxxxxStringCoercion(value);\n' +
' }';
const message =
"Using `'' + valu | {
"filepath": "scripts/eslint-rules/__tests__/safe-string-coercion-test.internal.js",
"language": "javascript",
"file_size": 7545,
"cut_index": 716,
"middle_length": 229
} |
ct-core
*/
'use strict';
const rule = require('../no-production-logging');
const {RuleTester} = require('eslint');
const ruleTester = new RuleTester();
ruleTester.run('no-production-logging', rule, {
valid: [
{
code: `
if (__DEV__) {
console.error('Oh no');
}
`,
},
... | ,
},
// This is OK too because it's wrapped outside:
{
code: `
if (__DEV__) {
if (potato) {
while (true) {
console.error('Oh no');
}
}
}`,
},
{
code: | o, bar)
}
`,
},
{
code: `
if (__DEV__) {
console.warn('Oh no');
}
`,
},
{
code: `
if (__DEV__) {
console.warn('Oh no');
}
` | {
"filepath": "scripts/eslint-rules/__tests__/no-production-logging-test.internal.js",
"language": "javascript",
"file_size": 5865,
"cut_index": 716,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const rule = require('../warning-args');
const {RuleTester} = require('eslint');
const ruleTester = new RuleTester();
ruleTester.run('esli... | rrors: [
{
message:
'The first argument to console.warn must be a string literal',
},
],
},
{
code: 'var g = 5; console.error(g);',
errors: [
{
message:
'The firs | code: 'console.error(null);',
errors: [
{
message:
'The first argument to console.error must be a string literal',
},
],
},
{
code: 'console.warn(null);',
e | {
"filepath": "scripts/eslint-rules/__tests__/warning-args-test.internal.js",
"language": "javascript",
"file_size": 2303,
"cut_index": 563,
"middle_length": 229
} |
abel/plugin-transform-modules-commonjs'],
});
const yargs = require('yargs');
const argv = yargs
.parserConfiguration({
// Important: This option tells yargs to move all other options not
// specified here into the `_` key. We use this to send all of the
// Jest options that we don't use through to Jest ... | ',
'rn',
'rn-fb',
'rn-next',
'canary',
'next',
'experimental',
null,
],
default: null,
},
sort: {
alias: 's',
describe: 'sort diff by one or more flags.',
require | type: 'boolean',
default: false,
},
diff: {
alias: 'd',
describe: 'output diff of two or more flags.',
requiresArg: false,
type: 'array',
choices: [
'www',
'www-modern | {
"filepath": "scripts/flags/flags.js",
"language": "javascript",
"file_size": 16034,
"cut_index": 921,
"middle_length": 229
} |
right (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
process.on('unhandledRejection', err => {
throw err;
});
const runFlow = require('../flow/runFlow');
const inlinedHostCon... | ig.shortName === shortName
);
if (rendererInfo == null) {
throw new Error(`Could not find inlinedHostConfig for ${shortName}`);
}
if (rendererInfo.isFlowTyped) {
await runFlow(rendererInfo.shortName, ['check']);
}
}
check(process.argv[2] | erInfo = inlinedHostConfigs.find(
config => conf | {
"filepath": "scripts/tasks/flow-ci.js",
"language": "javascript",
"file_size": 834,
"cut_index": 523,
"middle_length": 52
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
process.on('unhandledRejection', err => {
throw err;
});
const chalk = require('chalk');
const runFlow = require('../flow/... | pick a primary renderer:'
);
console.log();
inlinedHostConfigs.forEach(rendererInfo => {
if (rendererInfo.isFlowTyped) {
console.log(' * ' + chalk.cyan('yarn flow ' + rendererInfo.shortName));
}
});
console.log();
console.log(
| rimaryRenderer = inlinedHostConfigs.find(
info => info.isFlowTyped && info.shortName === process.argv[2]
);
if (!primaryRenderer) {
console.log(
'The ' +
chalk.red('yarn flow') +
' command now requires you to | {
"filepath": "scripts/tasks/flow.js",
"language": "javascript",
"file_size": 1482,
"cut_index": 524,
"middle_length": 229
} |
ackages} = require('../../../ReactVersions');
const {isCommandAvailable} = require('./utils');
function parseArgs(argv) {
const parser = yargs(argv)
.usage(
'Usage: yarn generate-changelog [--codex|--claude] [--debug] [--format <text|csv|json>] [<pkg@version> ...]'
)
.example(
'$0 --codex esl... | dex for commit summarization.',
})
.option('claude', {
type: 'boolean',
describe: 'Use Claude for commit summarization.',
})
.option('debug', {
type: 'boolean',
describe: 'Enable verbose debug logging.',
defaul | for multiple packages using Claude.'
)
.example(
'$0 --codex',
'Generate changelog for all stable packages using recorded versions.'
)
.option('codex', {
type: 'boolean',
describe: 'Use Co | {
"filepath": "scripts/tasks/generate-changelog/args.js",
"language": "javascript",
"file_size": 3435,
"cut_index": 614,
"middle_length": 229
} |
Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const fs = require('fs');
const ReactVersionSrc = fs.readFileSync(
require.resolve('../../packages/shared/ReactVersio... | es/shared/ReactVersion.js': reactVersion,
};
let allVersionsMatch = true;
Object.keys(versions).forEach(function (name) {
const version = versions[name];
if (version !== reactVersion) {
allVersionsMatch = false;
console.log(
'%s version | ,
'packages/react-dom/package.json':
require('../../packages/react-dom/package.json').version,
'packages/react-test-renderer/package.json':
require('../../packages/react-test-renderer/package.json').version,
'packag | {
"filepath": "scripts/tasks/version-check.js",
"language": "javascript",
"file_size": 1163,
"cut_index": 518,
"middle_length": 229
} |
ource code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const path = require('path');
const spawn = require('child_process').spawn;
const extension = process.platform === 'win32' ? '.cmd' : '';
// sizebot public_repo token (this is publi... | table',
],
{
// Allow colors to pass through
stdio: 'inherit',
env: {
...process.env,
DANGER_GITHUB_API_TOKEN: token,
},
}
).on('close', function (code) {
if (code !== 0) {
console.error('Danger failed');
} else {
| ASE_CHANNEL === 'experimental' ? 'experimental' : 's | {
"filepath": "scripts/tasks/danger.js",
"language": "javascript",
"file_size": 955,
"cut_index": 582,
"middle_length": 52
} |
ackage,
prMetadata,
}) {
const entries = [];
for (let i = 0; i < packageSpecs.length; i++) {
const spec = packageSpecs[i];
const version = spec.displayVersion || spec.version;
const commitsForPackage = commitsByPackage.get(spec.name) || [];
if (commitsForPackage.length === 0) {
entries.pus... | egExp(`\\s*\\(#${commit.prNumber}\\)$`);
summary = summary.replace(prPattern, '').trim();
}
const commitSha = commit.sha;
const commitUrl = `https://github.com/facebook/react/commit/${commitSha}`;
const prNumber = commit.pr | riesByPackage.get(spec.name) || new Map();
const commitEntries = commitsForPackage.map(commit => {
let summary = summaryMap.get(commit.sha) || commit.subject;
if (commit.prNumber) {
const prPattern = new R | {
"filepath": "scripts/tasks/generate-changelog/formatters.js",
"language": "javascript",
"file_size": 5918,
"cut_index": 716,
"middle_length": 229
} |
y =
preferredPackage === 'eslint-plugin-react-hooks'
? preferredPackage
: 'root';
if (!readChangelogSnippet.cache) {
readChangelogSnippet.cache = new Map();
}
const cache = readChangelogSnippet.cache;
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
const targetPath =
pr... | urn snippet;
}
function sanitizeSummary(text) {
if (!text) {
return '';
}
const trimmed = text.trim();
const withoutBullet = trimmed.replace(/^([-*]\s+|\d+\s*[\.)]\s+)/, '');
return withoutBullet.replace(/\s+/g, ' ').trim();
}
async funct | th.join(repoRoot, 'CHANGELOG.md');
let content = '';
try {
content = fs.readFileSync(targetPath, 'utf8');
} catch {
content = '';
}
const snippet = content.slice(0, 4000);
cache.set(cacheKey, snippet);
ret | {
"filepath": "scripts/tasks/generate-changelog/summaries.js",
"language": "javascript",
"file_size": 7832,
"cut_index": 716,
"middle_length": 229
} |
Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function evalStringConcat(ast) {
switch (ast.type) {
case 'StringLiteral':
case 'Literal': // ESLint
return ast.value;
... | ringLiteral':
return ast.value;
case 'BinaryExpression': // `+`
if (ast.operator !== '+') {
throw new Error('Unsupported binary operator ' + ast.operator);
}
return (
evalStringAndTemplateConcat(ast.left, args) + | StringConcat(ast.right);
default:
throw new Error('Unsupported type ' + ast.type);
}
}
exports.evalStringConcat = evalStringConcat;
function evalStringAndTemplateConcat(ast, args) {
switch (ast.type) {
case 'St | {
"filepath": "scripts/shared/evalToString.js",
"language": "javascript",
"file_size": 1688,
"cut_index": 537,
"middle_length": 229
} |
('./args');
const {
fetchNpmInfo,
collectCommitsSince,
loadCommitDetails,
extractPrNumber,
fetchPullRequestMetadata,
} = require('./data');
const {summarizePackages} = require('./summaries');
const {buildChangelogEntries, renderChangelog} = require('./formatters');
const {noopLogger} = require('./utils');
as... | s.includes(spec.name)) {
throw new Error(
`Package "${spec.name}" is not listed in stablePackages.`
);
}
if (packageTargets.has(spec.name)) {
throw new Error(`Package "${spec.name}" was specified more than once.`);
}
| ..args)
: noopLogger;
const allStablePackages = Object.keys(stablePackages);
const packageTargets = new Map();
for (let i = 0; i < packageSpecs.length; i++) {
const spec = packageSpecs[i];
if (!allStablePackage | {
"filepath": "scripts/tasks/generate-changelog/index.js",
"language": "javascript",
"file_size": 4737,
"cut_index": 614,
"middle_length": 229
} |
;
const fs = require('fs');
const path = require('path');
const {execFile} = require('child_process');
const {promisify} = require('util');
const execFileAsync = promisify(execFile);
const repoRoot = path.resolve(__dirname, '..', '..', '..');
function isCommandAvailable(command) {
const paths = (process.env.PATH |... | fs.accessSync(fullPath, fs.constants.X_OK);
return true;
} catch {
// Keep searching.
}
}
}
return false;
}
function noopLogger() {}
function escapeCsvValue(value) {
if (value == null) {
return '';
}
| th; i++) {
const dir = paths[i];
if (!dir) {
continue;
}
for (let j = 0; j < extensions.length; j++) {
const ext = extensions[j];
const fullPath = path.join(dir, `${command}${ext}`);
try {
| {
"filepath": "scripts/tasks/generate-changelog/utils.js",
"language": "javascript",
"file_size": 1410,
"cut_index": 524,
"middle_length": 229
} |
Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const execFileSync = require('child_process').execFileSync;
const exec = (command, args) => {
console.log('> ' + [command].concat(args).... | return true;
} catch (_e) {
return false;
}
};
const execGitCmd = args => exec('git', args).trim().toString().split('\n');
const execSlCmd = args => exec('sl', args).trim().toString().split('\n');
const listChangedFiles = () => {
if (isGit() | => {
try {
const wt = execGitCmd(['rev-parse', '--is-inside-work-tree']);
return wt.length > 0 && wt[0] === 'true';
} catch (_e) {
return false;
}
};
const isSl = () => {
try {
execSlCmd(['whereami']);
| {
"filepath": "scripts/shared/listChangedFiles.js",
"language": "javascript",
"file_size": 1612,
"cut_index": 537,
"middle_length": 229
} |
Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const {evalStringConcat} = require('../evalToString');
const parser = require('@babel/parser');
const parse = source =>... | Eval(`'foo ' + 'bar'`)).toBe('foo bar');
});
it('should throw when it finds other types', () => {
expect(() => parseAndEval(`'foo ' + true`)).toThrowError(
/Unsupported type/
);
expect(() => parseAndEval(`'foo ' + 3`)).toThrowError(/ | t('should support StringLiteral', () => {
expect(parseAndEval(`'foobar'`)).toBe('foobar');
expect(parseAndEval(`'yowassup'`)).toBe('yowassup');
});
it('should support string concat (`+`)', () => {
expect(parseAnd | {
"filepath": "scripts/shared/__tests__/evalToString-test.js",
"language": "javascript",
"file_size": 1226,
"cut_index": 518,
"middle_length": 229
} |
strict';
const {tmpdir} = require('os');
const {join} = require('path');
const {getBuildInfo, handleError} = require('./utils');
// This script is an escape hatch!
// It exists for special case manual builds.
// The typical suggested release process is to create a "next" build from a CI artifact.
// This build scrip... | nds/confirm-automated-testing');
const copyRepoToTempDirectory = require('./build-release-locally-commands/copy-repo-to-temp-directory');
const npmPackAndUnpack = require('./build-release-locally-commands/npm-pack-and-unpack');
const printPrereleaseSummary | nfoJSON = require('./build-release-locally-commands/add-build-info-json');
const buildArtifacts = require('./build-release-locally-commands/build-artifacts');
const confirmAutomatedTesting = require('./build-release-locally-comma | {
"filepath": "scripts/release/build-release-locally.js",
"language": "javascript",
"file_size": 1888,
"cut_index": 537,
"middle_length": 229
} |
disable no-for-of-loops/no-for-of-loops */
const fs = require('fs');
const semver = require('semver');
const {stablePackages} = require('../../ReactVersions');
function main() {
if (!fs.existsSync('./build/oss-stable-semver')) {
throw new Error('No build artifacts found');
}
const packages = new Map();
... | {
for (const [depName, depRange] of Object.entries(info.dependencies)) {
if (packages.has(depName)) {
const releaseVersion = packages.get(depName).version;
checkDependency(packageName, depName, releaseVersion, depRange);
| nfo = JSON.parse(
fs.readFileSync(`build/oss-stable-semver/${packageName}/package.json`)
);
packages.set(info.name, info);
}
}
for (const [packageName, info] of packages) {
if (info.dependencies) | {
"filepath": "scripts/release/check-release-dependencies.js",
"language": "javascript",
"file_size": 1658,
"cut_index": 537,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const {
parse,
SimpleTraverser: {traverse},
} = require('hermes-parser');
const fs = require('fs');
const through = require('through2');
const gs = require('glob... | se(ast, {
enter() {},
leave(node) {
if (node.type !== 'CallExpression') {
return;
}
const callee = node.callee;
if (
callee.type === 'MemberExpression' &&
callee.object.type === 'Ide | ce) {
if (err) {
cb(err);
return;
}
let ast;
try {
ast = parse(source);
} catch (error) {
console.error('Failed to parse source file:', file.path);
throw error;
}
traver | {
"filepath": "scripts/print-warnings/print-warnings.js",
"language": "javascript",
"file_size": 2465,
"cut_index": 563,
"middle_length": 229
} |
ta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Files that are transformed and can use ES6/Flow/JSX.
const esNextPaths = [
// Internal forwarding modules
'packages/*/*.js',
'pa... | **/*.js',
// Shims and Flow environment
'scripts/flow/*.js',
'scripts/rollup/shims/**/*.js',
];
// Files that we distribute on npm that should be ES5-only.
const es5Paths = ['packages/*/npm/**/*.js'];
module.exports = {
esNextPaths,
es5Paths,
} | -event-testing-library/**/*.js',
'packages/shared/ | {
"filepath": "scripts/shared/pathsByLanguageVersion.js",
"language": "javascript",
"file_size": 845,
"cut_index": 535,
"middle_length": 52
} |
strict';
const {tmpdir} = require('os');
const {join} = require('path');
const {getBuildInfo, handleError} = require('./utils');
// This script is an escape hatch!
// It exists for special case manual builds.
// The typical suggested release process is to create a "next" build from a CI artifact.
// This build scrip... | nds/confirm-automated-testing');
const copyRepoToTempDirectory = require('./build-release-locally-commands/copy-repo-to-temp-directory');
const npmPackAndUnpack = require('./build-release-locally-commands/npm-pack-and-unpack');
const printPrereleaseSummary | nfoJSON = require('./build-release-locally-commands/add-build-info-json');
const buildArtifacts = require('./build-release-locally-commands/build-artifacts');
const confirmAutomatedTesting = require('./build-release-locally-comma | {
"filepath": "scripts/release/build-release.js",
"language": "javascript",
"file_size": 1888,
"cut_index": 537,
"middle_length": 229
} |
!/usr/bin/env node
'use strict';
const {join} = require('path');
const {addDefaultParamValue, handleError} = require('./utils');
const {
downloadBuildArtifacts,
} = require('./shared-commands/download-build-artifacts');
const parseParams = require('./shared-commands/parse-params');
const printPrereleaseSummary = r... | process.env.RELEASE_CHANNEL,
});
if (!params.skipTests) {
await testPackagingFixture(params);
}
const isLatestRelease = params.releaseChannel === 'latest';
await printPrereleaseSummary(params, isLatestRelease);
} catch (error | lue(null, '--commit', 'main');
const params = await parseParams();
params.cwd = join(__dirname, '..', '..');
await downloadBuildArtifacts({
commit: params.commit,
releaseChannel: params.releaseChannel ?? | {
"filepath": "scripts/release/prepare-release-from-ci.js",
"language": "javascript",
"file_size": 1041,
"cut_index": 513,
"middle_length": 229
} |
require('path');
const {getPublicPackages, handleError} = require('./utils');
const theme = require('./theme');
const confirmVersionAndTags = require('./publish-commands/confirm-version-and-tags');
const parseParams = require('./publish-commands/parse-params');
const publishToNPM = require('./publish-commands/publish-... | ages.length > 0 && params.skipPackages.length > 0) {
console.error(
'--onlyPackages and --skipPackages cannot be used together'
);
process.exit(1);
}
if (params.onlyPackages.length > 0) {
params.packages = params.pa | {
const params = parseParams();
const isExperimental = params.tag === 'experimental';
params.cwd = join(__dirname, '..', '..');
params.packages = await getPublicPackages(isExperimental);
if (params.onlyPack | {
"filepath": "scripts/release/publish.js",
"language": "javascript",
"file_size": 2608,
"cut_index": 563,
"middle_length": 229
} |
use strict';
const chalk = require('chalk');
const colors = {
blue: '#0091ea',
gray: '#78909c',
green: '#00c853',
red: '#d50000',
yellow: '#ffd600',
};
const theme = chalk.constructor();
theme.package = theme.hex(colors.green);
theme.version = theme.hex(colors.yellow);
theme.tag = theme.hex(colors.yellow);... | eme.diffHeader = theme.hex(colors.gray);
theme.diffAdded = theme.hex(colors.green);
theme.diffRemoved = theme.hex(colors.red);
theme.spinnerInProgress = theme.hex(colors.yellow);
theme.spinnerError = theme.hex(colors.red);
theme.spinnerSuccess = theme.hex | ors.red).bold;
theme.link = theme.hex(colors.blue).underline.italic;
theme.header = theme.hex(colors.green).bold;
theme.path = theme.hex(colors.gray).italic;
theme.command = theme.hex(colors.gray);
theme.quote = theme.italic;
th | {
"filepath": "scripts/release/theme.js",
"language": "javascript",
"file_size": 1039,
"cut_index": 513,
"middle_length": 229
} |
Promise} = require('../utils');
const os = require('os');
if (process.env.GH_TOKEN == null) {
console.log(
theme`{error Expected GH_TOKEN to be provided as an env variable}`
);
process.exit(1);
}
const REPO = process.env.GITHUB_REPOSITORY || 'facebook/react';
const WORKFLOW_ID = 'runtime_build_and_test.yml'... | orkflowId() {
if (
existsSync(join(__dirname, `../../../.github/workflows/${WORKFLOW_ID}`))
) {
return WORKFLOW_ID;
} else {
throw new Error(
`Incorrect workflow ID: .github/workflows/${WORKFLOW_ID} does not exist. Please check the | executableIsAvailable(name) {
try {
await exec(`which ${name}`);
return true;
} catch (_error) {
return false;
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getW | {
"filepath": "scripts/release/shared-commands/download-build-artifacts.js",
"language": "javascript",
"file_size": 6458,
"cut_index": 716,
"middle_length": 229
} |
strict';
const commandLineArgs = require('command-line-args');
const theme = require('../theme');
const paramDefinitions = [
{
name: 'build',
type: String,
description:
'CI build ID corresponding to the "process_artifacts_combined" task.',
defaultValue: null,
},
{
name: 'commit',
... | name: 'allowBrokenCI',
type: Boolean,
description:
'Continue even if CI is failing. Useful if you need to debug a broken build.',
defaultValue: false,
},
];
module.exports = async () => {
const params = commandLineArgs(paramDefiniti |
description: 'Skip automated fixture tests.',
defaultValue: false,
},
{
name: 'releaseChannel',
alias: 'r',
type: String,
description: 'Release channel (stable, experimental, or latest)',
},
{
| {
"filepath": "scripts/release/shared-commands/parse-params.js",
"language": "javascript",
"file_size": 1508,
"cut_index": 537,
"middle_length": 229
} |
strict';
const {exec} = require('child-process-promise');
const {join} = require('path');
const puppeteer = require('puppeteer');
const server = require('pushstate-server');
const theme = require('../theme');
const {logPromise} = require('../utils');
const validate = async () => {
const browser = await puppeteer.l... | ript> Babel tag
const container =
iframe.contentDocument.body.getElementsByTagName('div')[0];
if (container.textContent !== 'Hello World!') {
return `Unexpected fixture content, "${container.textContent}"`;
}
| querySelectorAll('iframe');
if (iframes.length === 0) {
return 'No iframes were found.';
}
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i];
// Don't include the <sc | {
"filepath": "scripts/release/shared-commands/test-packaging-fixture.js",
"language": "javascript",
"file_size": 1777,
"cut_index": 537,
"middle_length": 229
} |
n} = require('path');
const {readFileSync} = require('fs');
const theme = require('./theme');
const {getDateStringForCommit, logPromise, printDiff} = require('./utils');
const cwd = join(__dirname, '..', '..');
const CIRCLE_CI_BUILD = 12707;
const COMMIT = 'b3d1a81a9';
const VERSION = '1.2.3';
const run = async () =... | sion ${CIRCLE_CI_BUILD}}`
);
await promise;
const dateString = await getDateStringForCommit(COMMIT);
// Upgrade the above build top a known React version.
// Note that using the --local flag skips NPM checkout.
// This isn't total | n(
'node',
[
'./scripts/release/prepare-release-from-ci.js',
`--build=${CIRCLE_CI_BUILD}`,
],
defaultOptions
);
logPromise(
promise,
theme`Checking out "next" build {ver | {
"filepath": "scripts/release/snapshot-test.js",
"language": "javascript",
"file_size": 3079,
"cut_index": 614,
"middle_length": 229
} |
#!/usr/bin/env node
'use strict';
const clear = require('clear');
const {join, relative} = require('path');
const theme = require('../theme');
module.exports = ({cwd}, isStableRelease) => {
const publishPath = relative(
process.env.PWD,
join(__dirname, '../publish.js')
);
clear();
let message;
if... | release candidate has been prepared!}
You can review the contents of this release in {path build/node_modules/}
You can publish this release by running:
{path ${publishPath}}
`;
}
console.log(message.replace(/\n +/g, '\n').t | {header Before publishing, consider testing this release locally with create-react-app!}
You can publish this release by running:
{path ${publishPath}}
`;
} else {
message = theme`
{caution A "next" | {
"filepath": "scripts/release/shared-commands/print-prerelease-summary.js",
"language": "javascript",
"file_size": 1008,
"cut_index": 512,
"middle_length": 229
} |
re('fs');
const {readJson, writeJson} = require('fs-extra');
const logUpdate = require('log-update');
const {join} = require('path');
const createLogger = require('progress-estimator');
const prompt = require('prompt-promise');
const theme = require('./theme');
const {stablePackages, experimentalPackages} = require('..... | th(`${longName}=`)) {
found = true;
break;
}
}
if (!found) {
process.argv.push(`${longName}=${defaultValue}`);
}
};
const confirm = async message => {
const confirmation = await prompt(theme`\n{caution ${message}} (y/N) `);
| ltParamValue = (optionalShortName, longName, defaultValue) => {
let found = false;
for (let i = 0; i < process.argv.length; i++) {
const current = process.argv[i];
if (current === optionalShortName || current.startsWi | {
"filepath": "scripts/release/utils.js",
"language": "javascript",
"file_size": 8902,
"cut_index": 716,
"middle_length": 229
} |
const {exec} = require('child-process-promise');
const {join} = require('path');
const {tmpdir} = require('os');
const {logPromise} = require('../utils');
const theme = require('../theme');
const run = async ({commit, cwd, tempDirectory}) => {
const directory = `react-${commit}`;
const temp = tmpdir();
if (tem... | `, {
cwd,
});
await exec(`mkdir ${directory}`, {cwd: temp});
await exec(`tar -xf ./react.tgz -C ./${directory}`, {cwd: temp});
};
module.exports = async params => {
return logPromise(
run(params),
theme`Copying React repo to temporary | ve --format=tar --output=${temp}/react.tgz ${commit} | {
"filepath": "scripts/release/build-release-locally-commands/copy-repo-to-temp-directory.js",
"language": "javascript",
"file_size": 907,
"cut_index": 547,
"middle_length": 52
} |
strict';
const {spawnSync} = require('child_process');
const {readJsonSync} = require('fs-extra');
const {join} = require('path');
const theme = require('../theme');
const run = async ({cwd, dry, tag}, packageName) => {
const packagePath = join(cwd, 'build/node_modules', packageName);
const {version} = readJsonS... | published.`
);
return;
}
console.log(
`::group::${theme`{spinnerSuccess ✓} Publishing {package ${packageName}}${dry ? ' (--dry-run)' : ''}`}`
);
// OIDC trusted publishing authorizes exactly one publish per call, and
// can't add/rem | pawnSync('npm', [
'view',
`${packageName}@${version}`,
]);
const packageExists = npmViewStatus === 0;
if (packageExists) {
console.log(
theme`{package ${packageName}} {version ${version}} has already been | {
"filepath": "scripts/release/publish-commands/publish-to-npm.js",
"language": "javascript",
"file_size": 1726,
"cut_index": 537,
"middle_length": 229
} |
strict';
const {readJson} = require('fs-extra');
const {join} = require('path');
const theme = require('../theme');
const run = async ({cwd, packages, tag}) => {
// All canaries share a version number, so it's okay to check any of them.
const arbitraryPackageName = packages[0];
const packageJSONPath = join(
... | rror cannot be tagged as} {tag ${tag}}`
);
process.exit(1);
}
if (tag === 'experimental' && !isExperimentalVersion) {
console.log(
theme`{error Canary release} {version ${version}} {error cannot be tagged as} {tag experime | 'experimental') !== -1;
if (version.indexOf('-') !== -1) {
// Prerelease: canary or experimental.
if (tag === 'latest' || tag === 'backport') {
console.log(
theme`{error Prerelease} {version ${version}} {e | {
"filepath": "scripts/release/publish-commands/validate-tags.js",
"language": "javascript",
"file_size": 1618,
"cut_index": 537,
"middle_length": 229
} |
ncp').ncp;
const {existsSync} = require('fs');
const exec = require('child_process').exec;
const {join} = require('path');
const reactUrl = 'https://github.com/facebook/react.git';
function cleanDir() {
return new Promise(_resolve => rimraf('remote-repo', _resolve));
}
function executeCommand(command) {
return n... | ctPath() {
return join(__dirname, 'remote-repo');
}
async function buildBenchmark(reactPath = getDefaultReactPath(), benchmark) {
// get the build.js from the benchmark directory and execute it
await require(join(__dirname, 'benchmarks', benchmark, | n asyncCopyTo(from, to) {
return new Promise(_resolve => {
ncp(from, to, error => {
if (error) {
console.error(error);
process.exit(1);
}
_resolve();
});
});
}
function getDefaultRea | {
"filepath": "scripts/bench/build.js",
"language": "javascript",
"file_size": 3217,
"cut_index": 614,
"middle_length": 229
} |
strict';
const {join} = require('path');
const {exec} = require('child-process-promise');
const {readdirSync} = require('fs');
const {readJsonSync} = require('fs-extra');
const {logPromise} = require('../utils');
const run = async ({cwd, dry, tempDirectory}) => {
// Cleanup from previous build.
await exec(`rm -r... | c('mkdir build/node_modules', {cwd});
await exec(
`cp -r ${tempDirectory}/build/node_modules/*.tgz ./build/node_modules/`,
{cwd}
);
// Unpack packages and prepare to publish.
const compressedPackages = readdirSync(join(cwd, 'build/node_mod | de_modules/'));
for (let i = 0; i < builtPackages.length; i++) {
await exec(`npm pack ./${builtPackages[i]}`, {
cwd: `${tempDirectory}/build/node_modules/`,
});
}
await exec('mkdir build', {cwd});
await exe | {
"filepath": "scripts/release/build-release-locally-commands/npm-pack-and-unpack.js",
"language": "javascript",
"file_size": 1606,
"cut_index": 537,
"middle_length": 229
} |
neArgs = require('command-line-args');
const {splitCommaParams} = require('../utils');
const paramDefinitions = [
{
name: 'dry',
type: Boolean,
description: 'Dry run command without actually publishing to NPM.',
defaultValue: false,
},
{
name: 'tag',
type: String,
description:
'... | multiple: true,
description: 'Packages to exclude from publishing',
defaultValue: [],
},
];
module.exports = () => {
const params = commandLineArgs(paramDefinitions);
splitCommaParams(params.skipPackages);
splitCommaParams(params.onlyPa | ting --tag is rejected.',
},
{
name: 'onlyPackages',
type: String,
multiple: true,
description: 'Packages to include in publishing',
defaultValue: [],
},
{
name: 'skipPackages',
type: String,
| {
"filepath": "scripts/release/publish-commands/parse-params.js",
"language": "javascript",
"file_size": 2038,
"cut_index": 563,
"middle_length": 229
} |
er');
const stats = require('stats-analysis');
const config = require('lighthouse/lighthouse-core/config/perf-config');
const spawn = require('child_process').spawn;
const os = require('os');
const timesToRun = 10;
function wait(val) {
return new Promise(resolve => setTimeout(resolve, val));
}
async function runS... | duration,
}));
entries.push({
entry: 'First Meaningful Paint',
time: results.lhr.audits['first-meaningful-paint'].rawValue,
});
return entries;
}
function bootstrap(data) {
const len = data.length;
const arr = Array(len);
for (le | g
);
const perfMarkings = results.lhr.audits['user-timings'].details.items;
const entries = perfMarkings
.filter(({timingType}) => timingType !== 'Mark')
.map(({duration, name}) => ({
entry: name,
time: | {
"filepath": "scripts/bench/benchmark.js",
"language": "javascript",
"file_size": 3091,
"cut_index": 614,
"middle_length": 229
} |
nBenchmark = require('./benchmark');
const {
buildReactBundles,
buildBenchmark,
buildBenchmarkBundlesFromGitRepo,
getMergeBaseFromLocalGitRepo,
} = require('./build');
const argv = require('minimist')(process.argv.slice(2));
const chalk = require('chalk');
const printResults = require('./stats');
const serveBen... | skipBuild = argv['skip-build'];
async function runBenchmarks(reactPath) {
const benchmarkNames = getBenchmarkNames();
const results = {};
const server = serveBenchmark();
await wait(1000);
for (let i = 0; i < benchmarkNames.length; i++) {
|
);
}
function wait(val) {
return new Promise(resolve => setTimeout(resolve, val));
}
const runRemote = argv.remote;
const runLocal = argv.local;
const benchmarkFilter = argv.benchmark;
const headless = argv.headless;
const | {
"filepath": "scripts/bench/runner.js",
"language": "javascript",
"file_size": 3918,
"cut_index": 614,
"middle_length": 229
} |
strict';
const {readJson} = require('fs-extra');
const {join} = require('path');
const theme = require('../theme');
const {execRead} = require('../utils');
const readPackageJSON = async (cwd, name) => {
const packageJSONPath = join(
cwd,
'build',
'node_modules',
name,
'package.json'
);
retu... | sion = dependencies[dependency];
// Do we depend on a version of the package that has not been published to NPM?
const info = await execRead(`npm view ${dependency}@${version}`);
if (!info) {
console.log(
theme | ependencies) => {
if (!dependencies) {
return;
}
for (let dependency in dependencies) {
// Do we depend on a package that has been skipped?
if (skipPackages.includes(dependency)) {
const ver | {
"filepath": "scripts/release/publish-commands/validate-skip-packages.js",
"language": "javascript",
"file_size": 1658,
"cut_index": 537,
"middle_length": 229
} |
ange(prev, current, prevSem, currentSem) {
const [mean, sd] = calculateMeanAndSdOfRatioFromDeltaMethod(
prev,
current,
prevSem,
currentSem
);
const pctChange = +(mean * 100).toFixed(1);
const ci95 = +(100 * 1.96 * sd).toFixed(1);
const ciInfo = ci95 > 0 ? ` +- ${ci95} %` : '';
const text = ... | Math.pow(semControl, 2) * meanTest) / Math.pow(meanControl, 3);
const variance =
Math.pow(semTest / meanControl, 2) +
Math.pow(semControl * meanTest, 2) / Math.pow(meanControl, 4);
return [mean, Math.sqrt(variance)];
}
function addBenchmarkRes | // Statistically insignificant.
return text;
}
}
function calculateMeanAndSdOfRatioFromDeltaMethod(
meanControl,
meanTest,
semControl,
semTest
) {
const mean =
(meanTest - meanControl) / meanControl -
( | {
"filepath": "scripts/bench/stats.js",
"language": "javascript",
"file_size": 3456,
"cut_index": 614,
"middle_length": 229
} |
4r85sjIn sx_538591',
src: null,
});
}
if (x === 148) {
return React.createElement('i', {
className: '_3yz6 _5whs img sp_i534r85sjIn sx_896996',
src: null,
alt: '',
});
}
if (x === 152) {
return React.createElement('i', {
className: '_5b5p _... |
if (x === 177) {
return React.createElement('i', {
alt: '',
className: '_3-99 img sp_i534r85sjIn sx_2c18b7',
src: null,
});
}
if (x === 186) {
return React.createElement('i', {
src: null,
| n sx_2f396a',
src: null,
alt: '',
});
}
if (x === 160) {
return React.createElement('i', {
src: null,
alt: '',
className: 'img sp_i534r85sjIn sx_31d9b0',
});
} | {
"filepath": "scripts/bench/benchmarks/pe-no-components/benchmark.js",
"language": "javascript",
"file_size": 119464,
"cut_index": 3790,
"middle_length": 229
} |
274, 14200711, 14201147, 14201365, 14201499, 14200618, 14201169,
14200911, 14200734, 14201083, 14200706, 14200785, 14201032,
],
score: 178,
time: 1493183234,
title: 'My Hackintosh Hardware Spec – clean, based on a 2013 iMac',
type: 'story',
url: 'https://infinitediaries.net/my-exact-hackin... | 99813, 14197259, 14197503,
],
score: 562,
time: 1493145853,
title: "Evidence-based advice we've found on how to be successful in a job",
type: 'story',
url: 'https://80000hours.org/career-guide/how-to-be-successful/',
},
{
b | 198224, 14200614, 14201983, 14200697, 14199252, 14201214,
14198923, 14200224, 14197509, 14200859, 14200064, 14200114, 14197256,
14197220, 14200653, 14197186, 14199258, 14197155, 14197344, 14198361,
14197969, 141 | {
"filepath": "scripts/bench/benchmarks/hacker-news/top-stories.js",
"language": "javascript",
"file_size": 22792,
"cut_index": 1331,
"middle_length": 229
} |
);
}
if (props.x === 43) {
return React.createElement(
'a',
{
className: '_585q _50zy _50-0 _50z- _5upp _42ft',
size: 'medium',
type: null,
title: 'Remove',
'data-hover': undefined,
'data-tooltip-alignh': undefined,
... | 08',
rel: undefined,
onClick: function () {},
},
React.createElement(XUIText29, {x: 48})
);
}
if (props.x === 128) {
return React.createElement(
'a',
{
className: ' _5bbf _55 | fined,
'Remove',
undefined
);
}
if (props.x === 49) {
return React.createElement(
'a',
{
target: '_blank',
href: '/ads/manage/billing.php?act=101499990736434 | {
"filepath": "scripts/bench/benchmarks/pe-functional-components/benchmark.js",
"language": "javascript",
"file_size": 139770,
"cut_index": 7068,
"middle_length": 229
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Most of our tests call jest.resetModules in a beforeEach and the
// re-require all the React modules. However, the JSX runtime is injected by
// the compiler, so those bindings don't get updated. This causes warni... | resetModules, and use import syntax instead so this kind of thing doesn't
// happen.
module.exports = function replaceJSXImportWithLazy(babel) {
const {types: t} = babel;
function getInlineRequire(moduleName) {
return t.callExpression(t.identifie | etModules call is longer the same one.
//
// To workaround this issue, use a transform that calls require() again before
// every JSX invocation.
//
// Longer term we should migrate all our tests away from using require() and
// | {
"filepath": "scripts/babel/transform-lazy-jsx-import.js",
"language": "javascript",
"file_size": 3292,
"cut_index": 614,
"middle_length": 229
} |
iates.
* Copyright (c) 2017, Amjad Masad
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// Based on https://repl.it/site/blog/infinite-loops.
// This should be reasonable for all loops in the source.
// Note that if ... | the error ends up being caught by the code.
const buildGuard = template(`
if (%%iterator%%++ > %%maxIterations%%) {
global.infiniteLoopError = new RangeError(
'Potential infinite loop: exceeded ' +
%%maxIterations%% +
' | tests themselves is permitted to run longer.
// For example, in the fuzz tester.
const MAX_TEST_ITERATIONS = 5000;
module.exports = ({types: t, template}) => {
// We set a global so that we can later fail the test
// even if | {
"filepath": "scripts/babel/transform-prevent-infinite-loops.js",
"language": "javascript",
"file_size": 2427,
"cut_index": 563,
"middle_length": 229
} |
className: '_387r _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft',
style: {width: 250, maxWidth: '250px'},
disabled: null,
label: null,
href: '#',
rel: undefined,
onClick: function () {},
},
null,
React.createEleme... |
if (this.props.x === 43) {
return React.createElement(
'a',
{
className: '_585q _50zy _50-0 _50z- _5upp _42ft',
size: 'medium',
type: null,
title: 'Remove',
'dat | React.createElement('span', {className: '_48u-'}, 'Account:'),
' ',
'Dick Madanson (10149999073643408)'
)
),
React.createElement(ReactImage0, {x: 0})
);
} | {
"filepath": "scripts/bench/benchmarks/pe-class-components/benchmark.js",
"language": "javascript",
"file_size": 157015,
"cut_index": 7068,
"middle_length": 229
} |
right (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function getComments(path) {
const allComments = path.hub.file.ast.comments;
if (path.node.leadingComments) {
// Bab... | Comments[i].loc.end.line >= line) {
i--;
}
while (i >= 0 && allComments[i].loc.end.line === line - 1) {
line = allComments[i].loc.start.line;
comments.unshift(allComments[i]);
i--;
}
return comments;
}
module.exports = getComments; | t i = allComments.length - 1;
while (i >= 0 && all | {
"filepath": "scripts/babel/getComments.js",
"language": "javascript",
"file_size": 832,
"cut_index": 523,
"middle_length": 52
} |
return Math.round(minutes) + ' minutes ago';
}
return Math.round(minutes / 60) + ' hours ago';
}
function getHostUrl(url) {
return (url + '')
.replace('https://', '')
.replace('http://', '')
.split('/')[0];
}
function HeaderBar() {
return e(
'tr',
{
st... | width: 18,
paddingRight: 4,
},
},
e(
'a',
{
href: '#',
},
e('img', {
src: 'logo.png' | lSpacing: 0,
cellPadding: 0,
},
e(
'tbody',
null,
e(
'tr',
null,
e(
'td',
{
style: {
| {
"filepath": "scripts/bench/benchmarks/hacker-news/benchmark.js",
"language": "javascript",
"file_size": 6169,
"cut_index": 716,
"middle_length": 229
} |
Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const helperModuleImports = require('@babel/helper-module-imports');
module.exports = function autoImporter(babel) {
function getAssign... | ile.filename)) {
// Don't replace Object.assign if we're transforming shared/assign
return;
}
if (path.get('callee').matchesPattern('Object.assign')) {
// generate identifier and require if it hasn't been alrea | state.id;
}
return {
pre: function () {
// map from module to generated identifier
this.id = null;
},
visitor: {
CallExpression: function (path, file) {
if (/shared(\/|\\)assign/.test(f | {
"filepath": "scripts/babel/transform-object-assign.js",
"language": "javascript",
"file_size": 1516,
"cut_index": 537,
"middle_length": 229
} |
V = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
global.__EXTENSION__ = false;
global.__TEST__ = NODE_ENV === 'test';
global.__PROFILE__ = NODE_ENV === '... | typeof RELEASE_CHANNEL === 'string'
? RELEASE_CHANNEL === 'experimental'
: true;
global.__VARIANT__ = !!process.env.VARIANT;
if (typeof window !== 'undefined') {
} else {
global.AbortController =
require('abortcontroller-polyfill/dist/cjs-p | if it's "experimental".
global.__EXPERIMENTAL__ =
| {
"filepath": "scripts/jest/setupEnvironment.js",
"language": "javascript",
"file_size": 884,
"cut_index": 547,
"middle_length": 52
} |
} = require('fs-extra');
const inquirer = require('inquirer');
const {join, relative} = require('path');
const semver = require('semver');
const {
CHANGELOG_PATH,
DRY_RUN,
MANIFEST_PATHS,
PACKAGE_PATHS,
PULL_REQUEST_BASE_URL,
RELEASE_SCRIPT_TOKEN,
ROOT_PATH,
} = require('./configuration');
const {
check... | ay(shortCommitLog)
);
console.log('');
const releaseType = await getReleaseType();
const path = join(ROOT_PATH, PACKAGE_PATHS[0]);
const previousVersion = readJsonSync(path).version;
const {major, minor, patch} = semver(previousVersion);
co | rmissions();
const sha = await getPreviousCommitSha();
const [shortCommitLog, formattedCommitLog] = await getCommitLog(sha);
console.log('');
console.log(
'This release includes the following commits:',
chalk.gr | {
"filepath": "scripts/devtools/prepare-release.js",
"language": "javascript",
"file_size": 7611,
"cut_index": 716,
"middle_length": 229
} |
onjs: true,
browser: true,
},
globals: {
// ES 6
BigInt: 'readonly',
Map: 'readonly',
Set: 'readonly',
Proxy: 'readonly',
Symbol: 'readonly',
WeakMap: 'readonly',
WeakSet: 'readonly',
WeakRef: 'readonly',
Int8Array: 'readonly',
Uint8Array: 'readonly',
Uint8Clampe... | e: 'readonly',
navigation: 'readonly',
// Vendor specific
MSApp: 'readonly',
__REACT_DEVTOOLS_GLOBAL_HOOK__: 'readonly',
// CommonJS / Node
process: 'readonly',
setImmediate: 'readonly',
Buffer: 'readonly',
// Trusted Ty | ,
BigInt64Array: 'readonly',
BigUint64Array: 'readonly',
DataView: 'readonly',
ArrayBuffer: 'readonly',
Reflect: 'readonly',
globalThis: 'readonly',
FinalizationRegistry: 'readonly',
ScrollTimelin | {
"filepath": "scripts/rollup/validate/eslintrc.cjs2015.js",
"language": "javascript",
"file_size": 2670,
"cut_index": 563,
"middle_length": 229
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const invertObject = require('../invertObject');
const objectValues = target => Object.keys(target).map(key => target[key]);
... | vertObject({
a: '3',
b: '4',
c: '3',
})
).toEqual({
4: 'b',
3: 'c',
});
});
it('should preserve the original order', () => {
expect(
Object.keys(
invertObject({
a: '3',
| expect(
invertObject({
a: '3',
b: '4',
})
).toEqual({
3: 'a',
4: 'b',
});
});
it('should take the last value when there are duplications in vals', () => {
expect(
in | {
"filepath": "scripts/error-codes/__tests__/invertObject-test.js",
"language": "javascript",
"file_size": 1253,
"cut_index": 524,
"middle_length": 229
} |
**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
describe('transform-lazy-jsx-import', () => {
it('should use the mocked version of the "react" runtime in jsx', (... | ('react/jsx-runtime', () => ({
jsx: mock,
jsxs: mock,
}));
}
// eslint-disable-next-line react/react-in-jsx-scope
const x = <div />;
expect(x).toBe('fakejsx: div');
expect(mock).toHaveBeenCalledTimes(1);
});
});
| k,
};
});
} else {
jest.mock | {
"filepath": "scripts/babel/__tests__/transform-lazy-jsx-import-test.js",
"language": "javascript",
"file_size": 821,
"cut_index": 513,
"middle_length": 52
} |
eudo-JavaScript, used to run tests conditionally
// based on the environment.
//
// Input:
// @gate a && (b || c)
// test('some test', () => {/*...*/})
//
// Output:
// @gate a && (b || c)
// _test_gate(ctx => ctx.a && (ctx.b || ctx.c), 'some test', () => {/*...*/});
//
// expression →... | gs
if (char === '"') {
let string = '';
i++;
do {
if (i > code.length) {
throw Error('Missing a closing quote');
}
char = code[i++];
if (char === '"') {
break;
| → NAME | STRING | BOOLEAN
// | "(" expression ")" ;
function tokenize(code) {
const tokens = [];
let i = 0;
while (i < code.length) {
let char = code[i];
// Double quoted strin | {
"filepath": "scripts/babel/transform-test-gate-pragma.js",
"language": "javascript",
"file_size": 9000,
"cut_index": 716,
"middle_length": 229
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
describe('transform-prevent-infinite-loops', () => {
// Note: instead of testing the transform by applying it,
// we assum... | flag since otherwise *this* test would fail.
global.infiniteLoopError = null;
});
it('fails the test for `for` loops', () => {
expect(global.infiniteLoopError).toBe(null);
expect(() => {
for (;;) {
// do nothing
}
} | xpect(() => {
while (true) {
// do nothing
}
}).toThrow(RangeError);
// Make sure this gets set so the test would fail regardless.
expect(global.infiniteLoopError).not.toBe(null);
// Clear the | {
"filepath": "scripts/babel/__tests__/transform-prevent-infinite-loops-test.js",
"language": "javascript",
"file_size": 1260,
"cut_index": 524,
"middle_length": 229
} |
uire('chalk');
const {join} = require('path');
const semver = require('semver');
const yargs = require('yargs');
const fs = require('fs');
const REGRESSION_FOLDER = 'build-regression';
const ROOT_PATH = join(__dirname, '..', '..');
const buildPath = join(ROOT_PATH, `build`, 'oss-experimental');
const regressionBuild... | -is');
}
console.log(chalk.bold.white(`Downloading React v${version}\n`));
// Make build directory for temporary modules we're going to download
// from NPM
console.log(
chalk.white(
`Make Build directory at ${chalk.underline.blue(reg | wnloadRegressionBuild() {
const reactVersion = semver.coerce(version).version;
const installPackages = ['react-dom', 'react', 'react-test-renderer'];
if (semver.gte(reactVersion, '16.3.0')) {
installPackages.push('react | {
"filepath": "scripts/ci/download_devtools_regression_build.js",
"language": "javascript",
"file_size": 4781,
"cut_index": 614,
"middle_length": 229
} |
e strict';
const ReactJSDOMEnvironment = require('./ReactJSDOMEnvironment');
const {TestEnvironment: NodeEnvironment} = require('jest-environment-node');
/**
* Test environment for testing integration of react-dom (browser) with react-dom/server (node)
*/
class ReactDOMServerIntegrationEnvironment extends NodeEnvir... | ntListener;
this.global.MutationObserver = this.global.window.MutationObserver;
}
async setup() {
await super.setup();
await this.domEnvironment.setup();
}
async teardown() {
await this.domEnvironment.teardown();
await super.t | indow;
this.global.document = this.global.window.document;
this.global.navigator = this.global.window.navigator;
this.global.Node = this.global.window.Node;
this.global.addEventListener = this.global.window.addEve | {
"filepath": "scripts/jest/ReactDOMServerIntegrationEnvironment.js",
"language": "javascript",
"file_size": 1073,
"cut_index": 515,
"middle_length": 229
} |
;
module.exports = {
globalSetup: require.resolve('./setupGlobal.js'),
testSequencer: require.resolve('./sizeBalancedSequencer.js'),
modulePathIgnorePatterns: [
'<rootDir>/scripts/rollup/shims/',
'<rootDir>/scripts/bench/',
'<rootDir>/packages/eslint-plugin-react-hooks/',
],
transform: {
'^.+... | tupEnvironment.js')],
setupFilesAfterEnv: [require.resolve('./setupTests.js')],
// Only include files directly in __tests__, not in nested folders.
testRegex: '/__tests__/[^/]*(\\.js|\\.coffee|[^d]\\.ts)$',
moduleFileExtensions: ['js', 'json', 'nod | 'babel-jest',
{configFile: require.resolve('../../babel.config-ts.js')},
],
'.(?!ts$)': require.resolve('./preprocessor.js'),
},
prettierPath: require.resolve('prettier-2'),
setupFiles: [require.resolve('./se | {
"filepath": "scripts/jest/config.base.js",
"language": "javascript",
"file_size": 1412,
"cut_index": 524,
"middle_length": 229
} |
ire('fs');
const {join} = require('path');
const baseConfig = require('./config.base');
process.env.IS_BUILD = true;
const NODE_MODULES_DIR =
process.env.RELEASE_CHANNEL === 'stable' ? 'oss-stable' : 'oss-experimental';
// Find all folders in packages/* with package.json
const packagesRoot = join(__dirname, '..', ... | y {
stat = statSync(packagePath);
} catch (err) {
return false;
}
return stat.isFile();
});
// Create a module map to point React packages to the build output
const moduleNameMapper = {};
// Allow bundle tests to read (but not write!) defau | // from source.
// TODO: Maybe let's have some convention for this?
return false;
}
if (dir.charAt(0) === '.') {
return false;
}
const packagePath = join(packagesRoot, dir, 'package.json');
let stat;
tr | {
"filepath": "scripts/jest/config.build.js",
"language": "javascript",
"file_size": 2485,
"cut_index": 563,
"middle_length": 229
} |
scripts/jest/config.build-devtools.js';
// TODO: These configs are separate but should be rolled into the configs above
// so that the CLI can provide them as options for any of the configs.
const persistentConfig = './scripts/jest/config.source-persistent.js';
const buildConfig = './scripts/jest/config.build.js';
co... | ',
requiresArg: false,
type: 'boolean',
default: false,
},
project: {
alias: 'p',
describe: 'Run the given project.',
requiresArg: true,
type: 'string',
default: 'default',
choices: ['default', | Jest options that we don't use through to Jest (like --watch).
'unknown-options-as-args': true,
})
.wrap(yargs.terminalWidth())
.options({
debug: {
alias: 'd',
describe: 'Run with node debugger attached. | {
"filepath": "scripts/jest/jest-cli.js",
"language": "javascript",
"file_size": 11031,
"cut_index": 921,
"middle_length": 229
} |
describe('transform-test-gate-pragma', () => {
// Fake runtime
// eslint-disable-next-line no-unused-vars
const _test_gate = (gateFn, testName, cb) => {
// eslint-disable-next-line jest/no-done-callback, jest/valid-title
it(testName, (...args) => {
shouldPass = gateFn(context);
return cb(...... | itle
it(testName, (...args) => {
shouldPass = gateFn(context);
isFocused = true;
return cb(...args);
});
};
// Feature flags, environment variables, etc. We can configure this in
// our test set up.
const context = {
| lls to
// `test.only` and `fit` are compiled to `_test_gate_focus`. So if you want
// to focus something, swap the following `test` call for `test.only`.
// eslint-disable-next-line jest/no-done-callback, jest/valid-t | {
"filepath": "scripts/babel/__tests__/transform-test-gate-pragma-test.js",
"language": "javascript",
"file_size": 5559,
"cut_index": 716,
"middle_length": 229
} |
path');
const ROOT_PATH = join(__dirname, '..', '..');
const reactVersion = process.argv[2];
const inlinePackagePath = join(ROOT_PATH, 'packages', 'react-devtools-inline');
const shellPackagePath = join(ROOT_PATH, 'packages', 'react-devtools-shell');
const playwrightArtifactsPath = join(ROOT_PATH, 'tmp', 'playwright-a... | ggable}\x1b[0m`);
}
function logDim(loggable) {
const formatted = format(loggable, 2);
if (formatted !== '') {
console.log(`\x1b[2m${formatted}\x1b[0m`);
}
}
function logError(loggable) {
const formatted = format(loggable, 2);
if (formatted | format(loggable) {
return `${loggable}`
.split('\n')
.filter(line => {
return line.trim() !== '';
})
.map(line => ` ${line}`)
.join('\n');
}
function logBright(loggable) {
console.log(`\x1b[1m${lo | {
"filepath": "scripts/ci/run_devtools_e2e_tests.js",
"language": "javascript",
"file_size": 4818,
"cut_index": 614,
"middle_length": 229
} |
seConfig = require('./config.base');
const devtoolsRegressionConfig = require('./devtools/config.build-devtools-regression');
const NODE_MODULES_DIR =
process.env.RELEASE_CHANNEL === 'stable' ? 'oss-stable' : 'oss-experimental';
// Find all folders in packages/* with package.json
const packagesRoot = join(__dirname... | ackagePath = join(packagesRoot, dir, 'package.json');
let stat;
try {
stat = statSync(packagePath);
} catch (err) {
return false;
}
return stat.isFile();
});
// Create a module map to point React packages to the build output
const module | lse;
}
if (dir === 'internal-test-utils') {
// This is an internal package used only for testing. It's OK to read
// from source.
// TODO: Maybe let's have some convention for this?
return false;
}
const p | {
"filepath": "scripts/jest/config.build-devtools.js",
"language": "javascript",
"file_size": 3762,
"cut_index": 614,
"middle_length": 229
} |
uire('coffee-script');
const hermesParser = require('hermes-parser');
const tsPreprocessor = require('./typescript/preprocessor');
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const {ReactVersion} = require('../../ReactVersions');
const semver = require('semver');
const pathToBa... | rt = require.resolve(
'../babel/transform-lazy-jsx-import'
);
const pathToBabelrc = path.join(__dirname, '..', '..', 'babel.config.js');
const pathToErrorCodes = require.resolve('../error-codes/codes.json');
const ReactVersionTestingAgainst = process.en | athToTransformTestGatePragma = require.resolve(
'../babel/transform-test-gate-pragma'
);
const pathToTransformReactVersionPragma = require.resolve(
'../babel/transform-react-version-pragma'
);
const pathToTransformLazyJSXImpo | {
"filepath": "scripts/jest/preprocessor.js",
"language": "javascript",
"file_size": 4744,
"cut_index": 614,
"middle_length": 229
} |
nditions. They're like GKs.
//
// Examples:
// // @gate enableSomeAPI
// test('uses an unstable API', () => {/*...*/})
//
// // @gate __DEV__
// test('only passes in development', () => {/*...*/})
//
// Most flags are defined in ReactFeatureFlags. If it's defined there, you don't
// have to do anything extra he... | ation also works:
// // @gate !deprecateLegacyContext
// test('uses a deprecated feature', () => {/*...*/})
// These flags are based on the environment and don't change for the entire
// test run.
const environmentFlags = {
__DEV__,
build: __DEV__ | enableSomeAPI
// // @gate __DEV__
// test('both conditions must pass', () => {/*...*/})
//
// Or using logical operators
// // @gate enableSomeAPI && __DEV__
// test('both conditions must pass', () => {/*...*/})
//
// Neg | {
"filepath": "scripts/jest/TestFlags.js",
"language": "javascript",
"file_size": 4130,
"cut_index": 614,
"middle_length": 229
} |
equire('./config.base');
module.exports = Object.assign({}, baseConfig, {
modulePathIgnorePatterns: [
...baseConfig.modulePathIgnorePatterns,
'packages/react-devtools-extensions',
'packages/react-devtools-shared',
'ReactIncrementalPerf',
'ReactIncrementalUpdatesMinimalism',
'ReactIncrementalT... | be migrated to Noop renderer.
testPathIgnorePatterns: [
'node_modules',
'packages/react-dom',
'packages/react-server-dom-webpack',
],
setupFiles: [
...baseConfig.setupFiles,
require.resolve('./setupTests.xplat.js'),
require.r | use the www entrypoint,
// but those tests should | {
"filepath": "scripts/jest/config.source-xplat.js",
"language": "javascript",
"file_size": 897,
"cut_index": 547,
"middle_length": 52
} |
Pick which entry point fork to use:
// .modern.fb.js
// .classic.fb.js
// .fb.js
// .stable.js
// .experimental.js
// .js
// or any of those plus .development.js
if (isFBBundle) {
// FB builds for react-dom need to alias both react-dom and react-dom/client to the same
// entrypoint since there ... |
: 'src/ReactDOMFB.js';
} else if (resolvedEntry.endsWith('client.js')) {
specifier = 'react-dom/client';
entrypoint = __EXPERIMENTAL__
? 'src/ReactDOMFB.modern.js'
: 'src/ReactDOMFB.js';
} else {
| nstable_testing.js')
) {
let specifier;
let entrypoint;
if (resolvedEntry.endsWith('index.js')) {
specifier = 'react-dom';
entrypoint = __EXPERIMENTAL__
? 'src/ReactDOMFB.modern.js' | {
"filepath": "scripts/jest/setupHostConfigs.js",
"language": "javascript",
"file_size": 8811,
"cut_index": 716,
"middle_length": 229
} |
;
jest.mock('shared/ReactFeatureFlags', () => {
jest.mock(
'ReactFeatureFlags',
() => jest.requireActual('shared/forks/ReactFeatureFlags.www-dynamic'),
{virtual: true}
);
const actual = jest.requireActual('shared/forks/ReactFeatureFlags.www');
// Flags that aren't currently used, but we still want... | heduler/src/SchedulerFeatureFlags', () => {
const schedulerSrcPath = process.cwd() + '/packages/scheduler';
jest.mock(
'SchedulerFeatureFlags',
() =>
jest.requireActual(
schedulerSrcPath + '/src/forks/SchedulerFeatureFlags.www-dyn | both variants until
// we remove the flag.
actual.disableClientCache = __VARIANT__;
// Some value that doesn't impact existing tests
actual.ownerStackLimit = __VARIANT__ ? 500 : 1e4;
return actual;
});
jest.mock('sc | {
"filepath": "scripts/jest/setupTests.www.js",
"language": "javascript",
"file_size": 1331,
"cut_index": 524,
"middle_length": 229
} |
= require('path');
const ts = require('typescript');
const tsOptions = {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.React,
};
function formatErrorMessage(error) {
if (error.file) {
const message = ts.flattenDiagnosticMessageText(error.messageText, '\n');
return (
error.file.fileName +
... |
},
getCurrentDirectory() {
return '';
},
getDefaultLibFileName: () => 'lib.d.ts',
getNewLine: () => ts.sys.newLine,
getSourceFile(filename, languageVersion) {
let source;
const libRegex = /lib\.(.+\.)?d\.ts$/;
| }
function compile(content, contentFilename) {
let output = null;
const compilerHost = {
fileExists(filename) {
return ts.sys.fileExists(filename);
},
getCanonicalFileName(filename) {
return filename; | {
"filepath": "scripts/jest/typescript/preprocessor.js",
"language": "javascript",
"file_size": 3042,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.