From 3c8cab74be23a35b0bfd5f693a7d661b0ace3e16 Mon Sep 17 00:00:00 2001 From: Drew Powers Date: Mon, 23 Aug 2021 11:48:25 -0600 Subject: [PATCH] PR feedback --- snowpack/src/sources/local.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/snowpack/src/sources/local.ts b/snowpack/src/sources/local.ts index 6b00b7ab2f..0f99e7e7ae 100644 --- a/snowpack/src/sources/local.ts +++ b/snowpack/src/sources/local.ts @@ -499,9 +499,19 @@ export class PackageSourceLocal implements PackageSource { let packageFormatted = spec + colors.dim('@' + packageVersion); const existingImportMapLoc = path.join(installDest, 'import-map.json'); let existingImportMap: ImportMap | undefined = memoizedImportMap[packageName]; - if (!existingImportMap && existsSync(existingImportMapLoc)) { - existingImportMap = JSON.parse(await fs.readFile(existingImportMapLoc, 'utf8')); - memoizedImportMap[packageName] = existingImportMap as ImportMap; + if (!existingImportMap) { + // note: this must happen BEFORE the check on disk to prevent a race condition. + // If two lookups occur at once from different sources, then we mark this as “taken” immediately and finish the lookup async + memoizedImportMap[packageName] = {imports: {}}; // TODO: this may not exist; should we throw an error? + const importMapHandle = await fs.open(existingImportMapLoc, 'r+').catch(() => { + delete memoizedResolve[packageName]; // if there was trouble reading this, free up memoization + }); + if (importMapHandle) { + const importMapData = await importMapHandle.readFile('utf8'); + existingImportMap = importMapData ? JSON.parse(importMapData) : null; + memoizedImportMap[packageName] = existingImportMap as ImportMap; + await importMapHandle.close(); + } } // Kick off a build, if needed.