All files index.ts

100% Statements 49/49
100% Branches 15/15
100% Functions 15/15
100% Lines 49/49

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                  1x 1x 1x 1x                                             36x     36x 36x       37x       36x                     1x       7x 2x   5x       6x       8x       4x 4x       5x   5x 1x 1x         4x                 4x           10x 2x   10x 10x 3x   7x 8x 1x 1x   7x 7x   7x 7x 7x 6x   1x           3x 3x 2x 2x 2x   3x       3x 3x 2x           36x    
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import util from 'node:util';
import type { PluginRequirements } from '@zorilla/puppeteer-extra-plugin';
import { PuppeteerExtraPlugin } from '@zorilla/puppeteer-extra-plugin';
import debugLib from 'debug';
import type { LaunchOptions } from 'puppeteer';
 
const debug = debugLib('puppeteer-extra-plugin:user-data-dir');
const mkdtempAsync = util.promisify(fs.mkdtemp);
const mkdirAsync = util.promisify(fs.mkdir);
const writeFileAsync = util.promisify(fs.writeFile);
 
interface FileToWrite {
  target: string;
  file: string;
  contents: string;
}
 
interface PluginOptions {
  deleteTemporary?: boolean;
  deleteExisting?: boolean;
  files?: FileToWrite[];
  folderPath?: string;
  folderPrefix?: string;
}
 
/**
 *
 * Further reading:
 * https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md
 */
class Plugin extends PuppeteerExtraPlugin {
  private _userDataDir: string | undefined;
  private _isTemporary = false;
 
  constructor(opts: PluginOptions = {}) {
    super(opts);
    debug('initialized', this.opts);
  }
 
  override get name(): string {
    return 'user-data-dir';
  }
 
  override get defaults(): Required<PluginOptions> {
    return {
      deleteTemporary: true,
      deleteExisting: false,
      files: [],
      // Follow Puppeteers temporary user data dir naming convention by default
      folderPath: os.tmpdir(),
      folderPrefix: 'puppeteer_dev_profile-',
    };
  }
 
  override get requirements(): PluginRequirements {
    return new Set(['runLast', 'dataFromPlugins']);
  }
 
  get shouldDeleteDirectory(): boolean {
    if (this._isTemporary && this.opts.deleteTemporary) {
      return true;
    }
    return this.opts.deleteExisting;
  }
 
  get temporaryDirectoryPath(): string {
    return path.join(this.opts.folderPath, this.opts.folderPrefix);
  }
 
  get defaultProfilePath(): string {
    return path.join(this._userDataDir!, 'Default');
  }
 
  async makeTemporaryDirectory(): Promise<void> {
    this._userDataDir = await mkdtempAsync(this.temporaryDirectoryPath);
    this._isTemporary = true;
  }
 
  deleteUserDataDir(): void {
    debug('removeUserDataDir', this._userDataDir);
 
    if (!this._userDataDir) {
      debug('No userDataDir, not running rm');
      return;
    }
 
    // We're using fs.rm with retry logic here to handle busy resources
    // If resources busy or locked by chrome try again 4 times, then give up
    fs.rm(
      this._userDataDir,
      {
        recursive: true,
        force: true,
        maxRetries: 4,
        retryDelay: 100,
      },
      err => {
        debug(err);
      }
    );
  }
 
  async writeFilesToProfile(): Promise<void> {
    const filesFromPlugins = this.getDataFromPlugins('userDataDirFile').map(
      d => d.value
    ) as FileToWrite[];
    const files: FileToWrite[] = [...filesFromPlugins, ...this.opts.files];
    if (!files.length) {
      return;
    }
    for (const file of files) {
      if (file.target !== 'Profile') {
        console.warn(`Warning: Ignoring file with invalid target`, file);
        continue;
      }
      const filePath = path.join(this.defaultProfilePath, file.file);
      try {
        // Create directory structure if it doesn't exist
        const dirPath = path.dirname(filePath);
        await mkdirAsync(dirPath, { recursive: true });
        await writeFileAsync(filePath, file.contents);
        debug(`Wrote file`, filePath);
      } catch (err) {
        console.warn('Warning: Failure writing file', filePath, file, err);
      }
    }
  }
 
  override async beforeLaunch(options: LaunchOptions): Promise<void> {
    this._userDataDir = options.userDataDir;
    if (!this._userDataDir) {
      await this.makeTemporaryDirectory();
      options.userDataDir = this._userDataDir;
      debug('created custom dir', options.userDataDir);
    }
    await this.writeFilesToProfile();
  }
 
  override async onDisconnected(): Promise<void> {
    debug('onDisconnected');
    if (this.shouldDeleteDirectory) {
      this.deleteUserDataDir();
    }
  }
}
 
export default function (pluginConfig?: PluginOptions): Plugin {
  return new Plugin(pluginConfig);
}