From ebf5981903e65a6a6852285b6e13b30cef115606 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Wed, 9 Dec 2020 02:14:53 +0000 Subject: [PATCH] Warn on relative and non-normalized paths --- packages/react-fs/package.json | 3 +++ packages/react-fs/src/ReactFilesystem.js | 31 ++++++++++++++++++++---- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/packages/react-fs/package.json b/packages/react-fs/package.json index 72250aa1b5f0d..d3f9586725e0a 100644 --- a/packages/react-fs/package.json +++ b/packages/react-fs/package.json @@ -17,6 +17,9 @@ "index.browser.js", "cjs/" ], + "peerDependencies": { + "react": "^17.0.0" + }, "browser": { "./index.js": "./index.browser.js" } diff --git a/packages/react-fs/src/ReactFilesystem.js b/packages/react-fs/src/ReactFilesystem.js index 462086c1add54..cfc74bdfd219b 100644 --- a/packages/react-fs/src/ReactFilesystem.js +++ b/packages/react-fs/src/ReactFilesystem.js @@ -11,7 +11,7 @@ import type {Wakeable, Thenable} from 'shared/ReactTypes'; import {unstable_getCacheForType} from 'react'; import * as fs from 'fs/promises'; -import {resolve} from 'path'; +import {isAbsolute, normalize} from 'path'; const Pending = 0; const Resolved = 1; @@ -70,6 +70,27 @@ function readResult(result: Result): T { } } +// We don't want to normalize every path ourselves in production. +// However, relative or non-normalized paths will lead to cache misses. +// So we encourage the developer to fix it in DEV and normalize on their end. +function checkPathInDev(path: string) { + if (__DEV__) { + if (!isAbsolute(path)) { + console.error( + 'The provided path was not absolute: "%s". ' + + 'Convert it to an absolute path first.', + path, + ); + } else if (path !== normalize(path)) { + console.error( + 'The provided path was not normalized: "%s". ' + + 'Convert it to a normalized path first.', + path, + ); + } + } +} + function createReadFileCache(): Map> { return new Map(); } @@ -86,12 +107,12 @@ export function readFile( }, ): string | Buffer { const map = unstable_getCacheForType(createReadFileCache); - const resolvedPath = resolve(path); - let entry = map.get(resolvedPath); + checkPathInDev(path); + let entry = map.get(path); if (!entry) { - const thenable = fs.readFile(resolvedPath); + const thenable = fs.readFile(path); entry = toResult(thenable); - map.set(resolvedPath, entry); + map.set(path, entry); } const result: Buffer = readResult(entry); if (!options) {