11// @ts -check
22"use strict" ;
33
4+ /** @import { ProjectConfig, ProjectParams } from "./types.js"; */
5+
46/**
57 * This script (and its dependencies) currently cannot be converted to ESM
68 * because it is consumed in `react-native.config.js`.
@@ -19,7 +21,61 @@ const {
1921 v,
2022} = require ( "./helpers" ) ;
2123
22- /** @import { ProjectConfig, ProjectParams } from "./types.js"; */
24+ /**
25+ * Finds `react-native.config.[ts,mjs,cjs,js]`.
26+ *
27+ * @note A naive search on disk might yield false positives so we also try to
28+ * use the stack trace to find it. This currently works in Node (V8) and Bun
29+ * (JSC).
30+ *
31+ * @returns {string } Path to `react-native.config.[ts,mjs,cjs,js]`
32+ */
33+ function findReactNativeConfig ( fs = nodefs ) {
34+ // stack[0] holds this file
35+ // stack[1] holds where this function was called
36+ // stack[2] holds the file we're interested in
37+ const position = 2 ;
38+ if ( position < Error . stackTraceLimit ) {
39+ const orig_prepareStackTrace = Error . prepareStackTrace ;
40+ let stack ;
41+ try {
42+ Error . prepareStackTrace = ( _ , stack ) => stack ;
43+ stack = new Error ( ) . stack ;
44+ } finally {
45+ Error . prepareStackTrace = orig_prepareStackTrace ;
46+ }
47+
48+ if ( Array . isArray ( stack ) ) {
49+ const callsite = stack [ position ] ;
50+ if (
51+ callsite &&
52+ typeof callsite === "object" &&
53+ "getFileName" in callsite
54+ ) {
55+ const file = callsite . getFileName ( ) ;
56+ if ( path . basename ( file ) . startsWith ( "react-native.config." ) ) {
57+ return file ;
58+ }
59+ }
60+ }
61+ }
62+
63+ const configFiles = [
64+ "react-native.config.ts" ,
65+ "react-native.config.mjs" ,
66+ "react-native.config.cjs" ,
67+ "react-native.config.js" ,
68+ ] ;
69+
70+ for ( const file of configFiles ) {
71+ const reactNativeConfig = findNearest ( file , undefined , fs ) ;
72+ if ( reactNativeConfig ) {
73+ return reactNativeConfig ;
74+ }
75+ }
76+
77+ throw new Error ( "Failed to find `react-native.config.[ts,mjs,cjs,js]`" ) ;
78+ }
2379
2480/**
2581 * Returns the version number of a React Native dependency.
@@ -94,14 +150,7 @@ function windowsProjectPath(solutionFile, fs = nodefs) {
94150 * @returns {Partial<ProjectParams> }
95151 */
96152function configureProjects ( { android, ios, windows } , fs = nodefs ) {
97- const reactNativeConfig = findNearest (
98- "react-native.config.js" ,
99- undefined ,
100- fs
101- ) ;
102- if ( ! reactNativeConfig ) {
103- throw new Error ( "Failed to find `react-native.config.js`" ) ;
104- }
153+ const reactNativeConfig = findReactNativeConfig ( fs ) ;
105154
106155 /** @type {Partial<ProjectParams> } */
107156 const config = { } ;
@@ -154,5 +203,6 @@ function configureProjects({ android, ios, windows }, fs = nodefs) {
154203
155204exports . configureProjects = configureProjects ;
156205exports . internalForTestingPurposesOnly = {
206+ findReactNativeConfig,
157207 getAndroidPackageName,
158208} ;
0 commit comments