All files / src/node-resolve index.js

71.42% Statements 110/154
55.24% Branches 79/143
68.75% Functions 11/16
72.18% Lines 109/151

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382  1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 6x   6x 14x 5x       6x     1x 1x 1x 1x                           1x   1x 4x   4x             4x 4x       4x       4x 4x 4x 4x   4x 4x 4x 4x     4x           4x 4x 12x         4x 4x             4x 4x         4x       4x     4x   16x 16x 16x   16x     16x 16x                             16x 16x 16x   16x     16x   12x 12x       16x             16x   16x                     16x 12x             60x                     16x   16x 16x   16x 4x   16x                                         16x   16x               16x                 16x 16x 16x                     16x 16x 16x 16x       16x   16x 16x                     16x         16x                   16x           4x             4x   4x       4x                   32x       32x   32x 32x 32x 16x     16x     16x   16x             16x           16x               16x   16x         16x       16x               16x     16x                 1x  
/* eslint-disable no-param-reassign, no-shadow, no-undefined */
import { dirname, normalize, resolve, sep } from "path";
import isBuiltinModule from "../is-builtin-module";
import deepMerge from "deepmerge";
import isModule from "is-module";
import handleDeprecatedOptions from "./deprecated-options";
import resolveImportSpecifiers from "./resolveImportSpecifiers";
import { getMainFields, getPackageName, normalizeInput } from "./util";
import { fileExists } from "./fs";
import nodeFsAdapter from "../node-fs-adapter";
 
const ES6_BROWSER_EMPTY = "\0node-resolve:empty.js";
const deepFreeze = (object) => {
  Object.freeze(object);
 
  for (const value of Object.values(object)) {
    if (typeof value === "object" && !Object.isFrozen(value)) {
      deepFreeze(value);
    }
  }
 
  return object;
};
 
const baseConditions = ["default", "module"];
const baseConditionsEsm = [...baseConditions, "import"];
const baseConditionsCjs = [...baseConditions, "require"];
const defaults = {
  dedupe: [],
  // It's important that .mjs is listed before .js so that Rollup will interpret npm modules
  // which deploy both ESM .mjs and CommonJS .js files as ESM.
  extensions: [".mjs", ".js", ".json", ".node"],
  resolveOnly: [],
  moduleDirectories: ["node_modules"],
  modulePaths: [],
  ignoreSideEffectsForRoot: false,
  // TODO: set to false in next major release or remove
  allowExportsFolderMapping: true,
  validateImportsExports: true,
  ignoreExports: false,
};
export const DEFAULTS = deepFreeze(deepMerge({}, defaults));
 
export function nodeResolve(opts = {}) {
  const { warnings } = handleDeprecatedOptions(opts);
 
  const options = { ...defaults, ...opts };
  const {
    extensions,
    jail,
    moduleDirectories,
    modulePaths,
    ignoreSideEffectsForRoot,
  } = options;
  const conditionsEsm = [
    ...baseConditionsEsm,
    ...(options.exportConditions || []),
  ];
  const conditionsCjs = [
    ...baseConditionsCjs,
    ...(options.exportConditions || []),
  ];
  const packageInfoCache = new Map();
  const idToPackageInfo = new Map();
  const mainFields = getMainFields(options);
  const useBrowserOverrides = mainFields.indexOf("browser") !== -1;
  const isPreferBuiltinsSet =
    options.preferBuiltins === true || options.preferBuiltins === false;
  const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
  const rootDir = resolve(options.rootDir || process.cwd());
  let { dedupe } = options;
  let rollupOptions;
 
  Iif (moduleDirectories.some((name) => name.includes("/"))) {
    throw new Error(
      "`moduleDirectories` option must only contain directory names. If you want to load modules from somewhere not supported by the default module resolution algorithm, see `modulePaths`.",
    );
  }
 
  Eif (typeof dedupe !== "function") {
    dedupe = (importee) =>
      options.dedupe.includes(importee) ||
      options.dedupe.includes(getPackageName(importee));
  }
 
  // creates a function from the patterns to test if a particular module should be bundled.
  const allowPatterns = (patterns) => {
    const regexPatterns = patterns.map((pattern) => {
      if (pattern instanceof RegExp) {
        return pattern;
      }
      const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&");
      return new RegExp(`^${normalized}$`);
    });
    return (id) =>
      !regexPatterns.length ||
      regexPatterns.some((pattern) => pattern.test(id));
  };
 
  const resolveOnly =
    typeof options.resolveOnly === "function"
      ? options.resolveOnly
      : allowPatterns(options.resolveOnly);
 
  const browserMapCache = new Map();
  let preserveSymlinks;
 
  const resolveLikeNode = async (context, importee, importer, custom, fs) => {
    // strip query params from import
    const [importPath, params] = importee.split("?");
    const importSuffix = `${params ? `?${params}` : ""}`;
    importee = importPath;
 
    const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);
 
    // https://github.com/defunctzombie/package-browser-field-spec
    const browser = browserMapCache.get(importer);
    Iif (useBrowserOverrides && browser) {
      const resolvedImportee = resolve(baseDir, importee);
      if (browser[importee] === false || browser[resolvedImportee] === false) {
        return { id: ES6_BROWSER_EMPTY };
      }
      const browserImportee =
        (importee[0] !== "." && browser[importee]) ||
        browser[resolvedImportee] ||
        browser[`${resolvedImportee}.js`] ||
        browser[`${resolvedImportee}.json`];
      if (browserImportee) {
        importee = browserImportee;
      }
    }
 
    const parts = importee.split(/[/\\]/);
    let id = parts.shift();
    let isRelativeImport = false;
 
    Iif (id[0] === "@" && parts.length > 0) {
      // scoped packages
      id += `/${parts.shift()}`;
    } else if (id[0] === ".") {
      // an import relative to the parent dir of the importer
      id = resolve(baseDir, importee);
      isRelativeImport = true;
    }
 
    // if it's not a relative import, and it's not requested, reject it.
    Iif (!isRelativeImport && !resolveOnly(id)) {
      if (normalizeInput(rollupOptions.input).includes(importee)) {
        return null;
      }
      return false;
    }
 
    const importSpecifierList = [importee];
 
    Iif (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
      // For module graph roots (i.e. when importer is undefined), we
      // need to handle 'path fragments` like `foo/bar` that are commonly
      // found in rollup config files. If importee doesn't look like a
      // relative or absolute path, we make it relative and attempt to
      // resolve it.
      importSpecifierList.push(`./${importee}`);
    }
 
    // TypeScript files may import '.mjs' or '.cjs' to refer to either '.mts' or '.cts'.
    // They may also import .js to refer to either .ts or .tsx, and .jsx to refer to .tsx.
    if (importer && /\.(ts|mts|cts|tsx)$/.test(importer)) {
      for (const [importeeExt, resolvedExt] of [
        [".js", ".ts"],
        [".js", ".tsx"],
        [".jsx", ".tsx"],
        [".mjs", ".mts"],
        [".cjs", ".cts"],
      ]) {
        Iif (
          importee.endsWith(importeeExt) &&
          extensions.includes(resolvedExt)
        ) {
          importSpecifierList.push(
            importee.slice(0, -importeeExt.length) + resolvedExt,
          );
        }
      }
    }
 
    const warn = (...args) => context.warn(...args);
    const isRequire =
      custom && custom["node-resolve"] && custom["node-resolve"].isRequire;
    const exportConditions = isRequire ? conditionsCjs : conditionsEsm;
 
    if (useBrowserOverrides && !exportConditions.includes("browser"))
      exportConditions.push("browser");
 
    const resolvedWithoutBuiltins = await resolveImportSpecifiers({
      importer,
      importSpecifierList,
      exportConditions,
      warn,
      packageInfoCache,
      extensions,
      mainFields,
      preserveSymlinks,
      useBrowserOverrides,
      baseDir,
      moduleDirectories,
      modulePaths,
      rootDir,
      ignoreSideEffectsForRoot,
      allowExportsFolderMapping: options.allowExportsFolderMapping,
      fs,
      validateImportsExports: options.validateImportsExports,
      ignoreExports: options.ignoreExports,
    });
 
    const importeeIsBuiltin = isBuiltinModule(importee);
    const resolved =
      importeeIsBuiltin && preferBuiltins
        ? {
            packageInfo: undefined,
            hasModuleSideEffects: () => null,
            hasPackageEntry: true,
            packageBrowserField: false,
          }
        : resolvedWithoutBuiltins;
    Iif (!resolved) {
      return null;
    }
 
    const {
      packageInfo,
      hasModuleSideEffects,
      hasPackageEntry,
      packageBrowserField,
    } = resolved;
    let { location } = resolved;
    Iif (packageBrowserField) {
      if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
        if (!packageBrowserField[location]) {
          browserMapCache.set(location, packageBrowserField);
          return { id: ES6_BROWSER_EMPTY };
        }
        location = packageBrowserField[location];
      }
      browserMapCache.set(location, packageBrowserField);
    }
 
    Eif (hasPackageEntry && !preserveSymlinks) {
      const exists = await fileExists(location, fs);
      Eif (exists) {
        location = await fs.realpath(location);
      }
    }
 
    idToPackageInfo.set(location, packageInfo);
 
    Eif (hasPackageEntry) {
      Iif (importeeIsBuiltin && preferBuiltins) {
        if (
          !isPreferBuiltinsSet &&
          resolvedWithoutBuiltins &&
          resolved !== importee
        ) {
          context.warn(
            `preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`,
          );
        }
        return false;
      } else Iif (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
        return null;
      }
    }
 
    Iif (options.modulesOnly && (await fileExists(location, fs))) {
      const code = await fs.readFile(location, "utf8");
      if (isModule(code)) {
        return {
          id: `${location}${importSuffix}`,
          moduleSideEffects: hasModuleSideEffects(location),
        };
      }
      return null;
    }
    return {
      id: `${location}${importSuffix}`,
      moduleSideEffects: hasModuleSideEffects(location),
    };
  };
 
  return {
    name: "node-resolve",
 
    version: "1.0.0",
 
    buildStart(buildOptions) {
      // validateVersion(this.meta.rollupVersion, peerDependencies.rollup);
      rollupOptions = buildOptions;
 
      for (const warning of warnings) {
        this.warn(warning);
      }
 
      ({ preserveSymlinks } = buildOptions);
    },
 
    generateBundle() {
      // Cleanup tasks
    },
 
    resolveId: {
      order: "post",
      async handler(importee, importer, resolveOptions) {
        Iif (importee === ES6_BROWSER_EMPTY) {
          return importee;
        }
        // ignore IDs with null character, these belong to other plugins
        Iif (/\0/.test(importee)) return null;
 
        const { custom = {} } = resolveOptions;
        const { "node-resolve": { resolved: alreadyResolved } = {} } = custom;
        if (alreadyResolved) {
          return alreadyResolved;
        }
 
        Iif (/\0/.test(importer)) {
          importer = undefined;
        }
        const fs = options.fs || globalThis.__rollupFs || nodeFsAdapter;
 
        const resolved = await resolveLikeNode(
          this,
          importee,
          importer,
          custom,
          fs,
        );
        Eif (resolved) {
          // This way, plugins may attach additional meta information to the
          // resolved id or make it external. We do not skip node-resolve here
          // because another plugin might again use `this.resolve` in its
          // `resolveId` hook, in which case we want to add the correct
          // `moduleSideEffects` information.
          const resolvedResolved = await this.resolve(resolved.id, importer, {
            ...resolveOptions,
            skipSelf: false,
            custom: {
              ...custom,
              "node-resolve": { ...custom["node-resolve"], resolved, importee },
            },
          });
          Eif (resolvedResolved) {
            // Handle plugins that manually make the result external
            Iif (resolvedResolved.external) {
              return false;
            }
            // Allow other plugins to take over resolution. Rollup core will not
            // change the id if it corresponds to an existing file
            Iif (resolvedResolved.id !== resolved.id) {
              return resolvedResolved;
            }
            // Pass on meta information added by other plugins
            return { ...resolved, meta: resolvedResolved.meta };
          }
        }
        return resolved;
      },
    },
 
    load(importee) {
      Iif (importee === ES6_BROWSER_EMPTY) {
        return "export default {};";
      }
      return null;
    },
 
    getPackageInfoForId(id) {
      return idToPackageInfo.get(id);
    },
  };
}
 
export default nodeResolve;