All files plugin.ts

60.82% Statements 59/97
56.45% Branches 35/62
73.68% Functions 14/19
60.42% Lines 58/96

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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 4321x 1x 1x 1x 1x                                                                                                                                                                                                                                       1x   1x 2x 2x                 2x 2x   2x       2x         2x 2x   2x 2x     2x     2x 2x     2x               1x 4x             4x   4x                     4x                   4x 4x                                                     1x                 4x 4x 4x         26x   26x               26x           26x       26x 14x     12x                 12x   12x                 12x         12x       12x                                                                                                                                                                 24x 24x                                                 4x 24x   24x 18x 18x   6x               4x       114x   114x 92x 92x   22x        
import * as chalk from "chalk";
import * as TsconfigPaths from "tsconfig-paths";
import * as path from "path";
import * as Options from "./options";
import * as Logger from "./logger";
import * as fs from "fs";
import { ResolvePluginInstance, Resolver } from "webpack";
import { ResolveRequest, ResolveContext } from "enhanced-resolve";
 
type FileSystem = Resolver["fileSystem"];
type TapAsyncCallback = (
  request: ResolveRequest,
  context: ResolveContext,
  callback: TapAsyncInnerCallback
) => void;
type TapAsyncInnerCallback = (
  error?: Error | null | false,
  result?: null | ResolveRequest
) => void;
 
export interface LegacyResolverPlugin {
  readonly apply: (resolver: LegacyResolver) => void;
}
 
export interface LegacyResolver {
  readonly apply: (plugin: LegacyResolverPlugin) => void;
  readonly plugin: (source: string, cb: ResolverCallbackLegacy) => void;
  readonly doResolve: doResolveLegacy | doResolve;
  readonly join: (relativePath: string, innerRequest: Request) => Request;
  readonly fileSystem: LegacyResolverFileSystem;
  readonly getHook: (hook: string) => Tapable;
}
 
export type doResolveLegacy = (
  target: string,
  req: Request,
  desc: string,
  callback: Callback
) => void;
 
export type doResolve = (
  hook: Tapable,
  req: Request,
  message: string,
  resolveContext: LegacyResolveContext,
  callback: Callback
) => void;
 
export type ReadJsonCallback = (error: Error | undefined, result?: {}) => void;
 
export type ReadJson = (path2: string, callback: ReadJsonCallback) => void;
 
export type LegacyResolverFileSystem = typeof fs & { readJson?: ReadJson };
 
export interface LegacyResolveContext {
  log?: string;
  stack?: string;
  missing?: string;
}
 
export interface Tapable {
  readonly tapAsync: (
    options: TapableOptions,
    callback: TapAsyncCallback
  ) => void;
}
 
export interface TapableOptions {
  readonly name: string;
}
 
export type ResolverCallbackLegacy = (
  request: Request,
  callback: Callback
) => void;
export type ResolverCallback = (
  request: Request,
  resolveContext: LegacyResolveContext,
  callback: Callback
) => void;
 
type CreateInnerCallback = (
  callback: Callback,
  options: Callback,
  message?: string,
  messageOptional?: string
) => Callback;
 
type CreateInnerContext = (
  options: {
    log?: string;
    stack?: string;
    missing?: string;
  },
  message?: string,
  messageOptional?: string
) => ResolveContext;
 
type getInnerRequest = (
  resolver: Resolver | LegacyResolver,
  request: ResolveRequest | Request
) => string;
 
export interface Request {
  readonly request?: Request | string;
  readonly relativePath: string;
  readonly path: string;
  readonly context: {
    readonly issuer: string;
  };
}
 
export interface Callback {
  (err?: Error, result?: string): void;
  log?: string;
  stack?: string;
  missing?: string;
}
 
// eslint-disable-next-line no-redeclare
const getInnerRequest: getInnerRequest = require("enhanced-resolve/lib/getInnerRequest");
 
export class TsconfigPathsPlugin implements ResolvePluginInstance {
  source: string = "described-resolve";
  target: string = "resolve";
 
  log: Logger.Logger;
  baseUrl: string | undefined;
  absoluteBaseUrl: string;
  extensions: ReadonlyArray<string>;
 
  matchPath: TsconfigPaths.MatchPathAsync;
 
  constructor(IrawOptions: Partial<Options.Options> = {}) {
    const options = Options.getOptions(rawOptions);
 
    this.extensions = options.extensions;
 
    // const colors = new chalk.constructor({ enabled: options.colors });
 
    this.log = Logger.makeLogger(
      options,
      new chalk.Instance({ level: options.colors ? undefined : 0 })
    );
 
    const context = options.context || process.cwd();
    const loadFrom = options.configFile || context;
 
    const loadResult = TsconfigPaths.loadConfig(loadFrom);
    Iif (loadResult.resultType === "failed") {
      this.log.logError(`Failed to load ${loadFrom}: ${loadResult.message}`);
    } else {
      this.log.logInfo(
        `tsconfig-paths-webpack-plugin: Using config file at ${loadResult.configFileAbsolutePath}`
      );
      this.baseUrl = options.baseUrl || loadResult.baseUrl;
      this.absoluteBaseUrl = options.baseUrl
        ? path.resolve(options.baseUrl)
        : loadResult.absoluteBaseUrl;
      this.matchPath = TsconfigPaths.createMatchPathAsync(
        this.absoluteBaseUrl,
        loadResult.paths,
        options.mainFields
      );
    }
  }
 
  apply(resolver: Resolver): void {
    Iif (!resolver) {
      this.log.logWarning(
        "tsconfig-paths-webpack-plugin: Found no resolver, not applying tsconfig-paths-webpack-plugin"
      );
      return;
    }
 
    const { baseUrl } = this;
 
    Iif (!baseUrl) {
      // Nothing to do if there is no baseUrl
      this.log.logWarning(
        "tsconfig-paths-webpack-plugin: Found no baseUrl in tsconfig.json, not applying tsconfig-paths-webpack-plugin"
      );
      return;
    }
 
    // The file system only exists when the plugin is in the resolve context. This means it's also properly placed in the resolve.plugins array.
    // If not, we should warn the user that this plugin should be placed in resolve.plugins and not the plugins array of the root config for example.
    // This should hopefully prevent issues like: https://github.com/dividab/tsconfig-paths-webpack-plugin/issues/9
    Iif (!("fileSystem" in resolver)) {
      this.log.logWarning(
        "tsconfig-paths-webpack-plugin: No file system found on resolver." +
          " Please make sure you've placed the plugin in the correct part of the configuration." +
          " This plugin is a resolver plugin and should be placed in the resolve part of the Webpack configuration."
      );
      return;
    }
 
    // getHook will only exist in Webpack 4 & 5, if so we should comply to the Webpack 4 plugin system.
    if ("getHook" in resolver && typeof resolver.getHook === "function") {
      resolver
        .getHook(this.source)
        .tapAsync(
          { name: "TsconfigPathsPlugin" },
          createPluginCallback(
            this.matchPath,
            resolver,
            this.absoluteBaseUrl,
            resolver.getHook(this.target),
            this.extensions
          )
        );
    } else IEif ("plugin" in resolver) {
      // This is the legacy (Webpack < 4.0.0) way of using the plugin system.
      const legacyResolver = (resolver as unknown) as LegacyResolver;
      legacyResolver.plugin(
        this.source,
        createPluginLegacy(
          this.matchPath,
          (resolver as unknown) as LegacyResolver,
          this.absoluteBaseUrl,
          this.target,
          this.extensions
        )
      );
    }
  }
}
 
function createPluginCallback(
  matchPath: TsconfigPaths.MatchPathAsync,
  resolver: Resolver,
  absoluteBaseUrl: string,
  hook: Tapable,
  extensions: ReadonlyArray<string>
): TapAsyncCallback {
  const fileExistAsync = createFileExistAsync(resolver.fileSystem);
  const readJsonAsync = createReadJsonAsync(resolver.fileSystem);
  return (
    request: ResolveRequest,
    resolveContext: ResolveContext,
    callback: TapAsyncInnerCallback
  ) => {
    const innerRequest = getInnerRequest(resolver, request);
 
    Iif (
      !innerRequest ||
      request?.request?.startsWith(".") ||
      request?.request?.startsWith("..")
    ) {
      return callback();
    }
 
    matchPath(
      innerRequest,
      readJsonAsync,
      fileExistAsync,
      extensions,
      (err, foundMatch) => {
        Iif (err) {
          return callback(err);
        }
 
        if (!foundMatch) {
          return callback();
        }
 
        const newRequest = {
          ...request,
          request: foundMatch,
          path: absoluteBaseUrl,
        };
 
        // Only at this point we are sure we are dealing with the latest Webpack version (>= 4.0.0)
        // So only now can we require the createInnerContext function.
        // (It doesn't exist in legacy versions)
        const createInnerContext: CreateInnerContext = require("enhanced-resolve/lib/createInnerContext");
 
        return resolver.doResolve(
          hook,
          newRequest as never,
          `Resolved request '${innerRequest}' to '${foundMatch}' using tsconfig.json paths mapping`,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          createInnerContext({ ...(resolveContext as any) }),
          (err2: Error, result2: ResolveRequest): void => {
            // Pattern taken from:
            // https://github.com/webpack/enhanced-resolve/blob/42ff594140582c3f8f86811f95dea7bf6774a1c8/lib/AliasPlugin.js#L44
            Iif (err2) {
              return callback(err2);
            }
 
            // Don't allow other aliasing or raw request
            Iif (result2 === undefined) {
              return callback(undefined, undefined);
            }
 
            callback(undefined, result2);
          }
        );
      }
    );
  };
}
 
function createPluginLegacy(
  matchPath: TsconfigPaths.MatchPathAsync,
  resolver: LegacyResolver,
  absoluteBaseUrl: string,
  target: string,
  extensions: ReadonlyArray<string>
): ResolverCallbackLegacy {
  const fileExistAsync = createFileExistAsync(resolver.fileSystem);
  const readJsonAsync = createReadJsonAsync(resolver.fileSystem);
  return (request, callback) => {
    const innerRequest = getInnerRequest(resolver, request);
 
    Iif (
      !innerRequest ||
      innerRequest.startsWith(".") ||
      innerRequest.startsWith("..")
    ) {
      return callback();
    }
 
    matchPath(
      innerRequest,
      readJsonAsync,
      fileExistAsync,
      extensions,
      (err, foundMatch) => {
        Iif (err) {
          return callback(err);
        }
 
        Iif (!foundMatch) {
          return callback();
        }
 
        const newRequest = {
          ...request,
          request: foundMatch,
          path: absoluteBaseUrl,
        };
 
        // Only at this point we are sure we are dealing with a legacy Webpack version (< 4.0.0)
        // So only now can we require the createInnerCallback function.
        // (It's already deprecated and might be removed down the line).
        const createInnerCallback: CreateInnerCallback = require("enhanced-resolve/lib/createInnerCallback");
 
        return (resolver.doResolve as doResolveLegacy)(
          target,
          newRequest,
          `Resolved request '${innerRequest}' to '${foundMatch}' using tsconfig.json paths mapping`,
          createInnerCallback(function (err2: Error, result2: string): void {
            // Note:
            //  *NOT* using an arrow function here because arguments.length implies we have "this"
            //  That means "this" has to be in the current function scope, and not the scope above.
            //  Pattern taken from:
            //  https://github.com/s-panferov/awesome-typescript-loader/blob/10653beff85f555f1f3b5d4bfd7d21513d0e54a4/src/paths-plugin.ts#L169
            Iif (arguments.length > 0) {
              return callback(err2, result2);
            }
 
            // don't allow other aliasing or raw request
            callback(undefined, undefined);
          }, callback)
        );
      }
    );
  };
}
 
function readJson(
  fileSystem: FileSystem,
  path2: string,
  callback: ReadJsonCallback
): void {
  if ("readJson" in fileSystem && fileSystem.readJson) {
    return fileSystem.readJson(path2, callback);
  }
 
  fileSystem.readFile(path2, (err, buf) => {
    Iif (err) {
      return callback(err);
    }
 
    let data;
 
    try {
      // @ts-ignore  This will crash if buf is undefined, which I guess it can be...
      data = JSON.parse(buf.toString("utf-8"));
    } catch (e) {
      return callback(e);
    }
 
    return callback(undefined, data);
  });
}
 
function createReadJsonAsync(
  filesystem: FileSystem
): TsconfigPaths.ReadJsonAsync {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return (path2: string, callback2: (err?: Error, content?: any) => void) => {
    readJson(filesystem, path2, (err, json) => {
      // If error assume file does not exist
      if (err || !json) {
        callback2();
        return;
      }
      callback2(undefined, json);
    });
  };
}
 
function createFileExistAsync(
  filesystem: FileSystem
): TsconfigPaths.FileExistsAsync {
  return (
    path2: string,
    callback2: (err?: Error, exists?: boolean) => void
  ) => {
    filesystem.stat(path2, (err: Error, stats: fs.Stats) => {
      // If error assume file does not exist
      if (err) {
        callback2(undefined, false);
        return;
      }
      callback2(undefined, stats ? stats.isFile() : false);
    });
  };
}