|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @flow |
| 8 | + * @format |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict'; |
| 12 | + |
| 13 | +// $FlowFixMe it exists! |
| 14 | +const Module = require('module'); |
| 15 | + |
| 16 | +const path = require('path'); |
| 17 | + |
| 18 | +import type {ResolutionContext} from './types'; |
| 19 | + |
| 20 | +const builtinModules = new Set( |
| 21 | + // $FlowFixMe "process.binding" exists |
| 22 | + Module.builtinModules || Object.keys(process.binding('natives')), |
| 23 | +); |
| 24 | + |
| 25 | +module.exports = (pnp: any) => ( |
| 26 | + context: ResolutionContext, |
| 27 | + request: string, |
| 28 | + platform: string | null, |
| 29 | +) => { |
| 30 | + // We don't support builtin modules, so we force pnp to resolve those |
| 31 | + // modules as regular npm packages by appending a `/` character |
| 32 | + if (builtinModules.has(request)) { |
| 33 | + request += '/'; |
| 34 | + } |
| 35 | + |
| 36 | + const unqualifiedPath = pnp.resolveToUnqualified( |
| 37 | + request, |
| 38 | + context.originModulePath, |
| 39 | + ); |
| 40 | + |
| 41 | + const baseExtensions = context.sourceExts.map(extension => `.${extension}`); |
| 42 | + let finalExtensions = [...baseExtensions]; |
| 43 | + |
| 44 | + if (context.preferNativePlatform) { |
| 45 | + finalExtensions = [ |
| 46 | + ...baseExtensions.map(extension => `.native${extension}`), |
| 47 | + ...finalExtensions, |
| 48 | + ]; |
| 49 | + } |
| 50 | + |
| 51 | + if (platform) { |
| 52 | + // We must keep a const reference to make Flow happy |
| 53 | + const p = platform; |
| 54 | + |
| 55 | + finalExtensions = [ |
| 56 | + ...baseExtensions.map(extension => `.${p}${extension}`), |
| 57 | + ...finalExtensions, |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | + try { |
| 62 | + return { |
| 63 | + type: 'sourceFile', |
| 64 | + filePath: pnp.resolveUnqualified(unqualifiedPath, { |
| 65 | + extensions: finalExtensions, |
| 66 | + }), |
| 67 | + }; |
| 68 | + } catch (error) { |
| 69 | + // Only catch the error if it was caused by the resolution process |
| 70 | + if (error.code !== 'QUALIFIED_PATH_RESOLUTION_FAILED') { |
| 71 | + throw error; |
| 72 | + } |
| 73 | + |
| 74 | + const dirname = path.dirname(unqualifiedPath); |
| 75 | + const basename = path.basename(unqualifiedPath); |
| 76 | + |
| 77 | + const assetResolutions = context.resolveAsset(dirname, basename, platform); |
| 78 | + |
| 79 | + if (assetResolutions) { |
| 80 | + return { |
| 81 | + type: 'assetFiles', |
| 82 | + filePaths: assetResolutions.map<string>(name => `${dirname}/${name}`), |
| 83 | + }; |
| 84 | + } else { |
| 85 | + throw error; |
| 86 | + } |
| 87 | + } |
| 88 | +}; |
0 commit comments