Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

5.2 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from 'fs';
import os from 'os';
import path from 'path';

import { calculateSha1 } from './crypto';

export const existsAsync = (path: string): Promise<boolean> => new Promise(resolve => fs.stat(path, err => resolve(!err)));

export async function mkdirIfNeeded(filePath: string) {
  // This will harmlessly throw on windows if the dirname is the root directory.
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true }).catch(() => {});
}

export async function removeFolders(dirs: string[]): Promise<(Error| undefined)[]> {
  return await Promise.all(dirs.map((dir: string) =>
    fs.promises.rm(dir, { recursive: true, force: true, maxRetries: 10 }).catch(e => e)
  ));
}

export function canAccessFile(file: string) {
  if (!file)
    return false;

  try {
    fs.accessSync(file);
    return true;
  } catch (e) {
    return false;
  }
}

export function isWritable(file: string): boolean {
  try {
    fs.accessSync(file, fs.constants.W_OK);
    return true;
  } catch {
    return false;
  }
}

export function isSystemDirectory(dir: string): boolean {
  const resolved = path.resolve(dir);
  if (process.platform === 'win32') {
    const systemRoot = path.resolve(process.env.SystemRoot || 'C:\\Windows');
    return isPathInside(systemRoot.toLowerCase(), resolved.toLowerCase());
  }
  return resolved === '/';
}

export async function copyFileAndMakeWritable(from: string, to: string) {
  await fs.promises.copyFile(from, to);
  await fs.promises.chmod(to, 0o664);
}

export function addSuffixToFilePath(filePath: string, suffix: string): string {
  const ext = path.extname(filePath);
  const base = filePath.substring(0, filePath.length - ext.length);
  return base + suffix + ext;
}

export function sanitizeForFilePath(s: string) {
  return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, '-');
}

export function trimLongString(s: string, length = 100) {
  if (s.length <= length)
    return s;
  const hash = calculateSha1(s);
  const middle = `-${hash.substring(0, 5)}-`;
  const start = Math.floor((length - middle.length) / 2);
  const end = length - middle.length - start;
  return s.substring(0, start) + middle + s.slice(-end);
}

// Does not follow symlinks, see resolveSymlinks.
export function isPathInside(root: string, candidate: string): boolean {
  const resolvedRoot = path.resolve(root);
  const resolvedCandidate = path.resolve(candidate);
  if (resolvedCandidate === resolvedRoot)
    return true;
  return resolvedCandidate.startsWith(resolvedRoot + path.sep);
}

// Like realpath, but tolerates a non-existent tail.
export async function resolveSymlinks(filePath: string): Promise<string> {
  const resolved = path.resolve(filePath);
  try {
    return await fs.promises.realpath(resolved);
  } catch (e) {
    const parent = path.dirname(resolved);
    if (e.code !== 'ENOENT' || parent === resolved)
      throw e;
    return path.join(await resolveSymlinks(parent), path.basename(resolved));
  }
}

export function resolveWithinRoot(root: string, fileName: string): string | null {
  if (path.isAbsolute(fileName))
    return null;
  const resolvedFile = path.resolve(root, fileName);
  return isPathInside(root, resolvedFile) ? resolvedFile : null;
}

export function throwingResolveWithinRoot(root: string, fileName: string): string {
  const resolved = resolveWithinRoot(root, fileName);
  if (!resolved)
    throw new Error(`Path '${fileName}' escapes root directory`);
  return resolved;
}

export function toPosixPath(aPath: string): string {
  return aPath.split(path.sep).join(path.posix.sep);
}

// macOS sun_path is 104 bytes (Linux is 108) including the NUL terminator. Use the lower bound.
const UNIX_SOCKET_PATH_MAX = 103;

export function makeSocketPath(domain: string, name: string): string {
  const userNameHash = calculateSha1(process.env.USERNAME || process.env.USER || 'default').slice(0, 8);
  if (process.platform === 'win32') {
    const socketsDir = process.env.PWTEST_SOCKETS_DIR;
    const suffix = socketsDir ? `-${calculateSha1(socketsDir).slice(0, 8)}` : '';
    return `\\\\.\\pipe\\pw-${userNameHash}-${domain}-${name}${suffix}`;
  }
  const baseDir = process.env.PWTEST_SOCKETS_DIR || path.join(os.tmpdir(), `pw-${userNameHash}`);
  const dir = path.join(baseDir, domain);
  let result = path.join(dir, sanitizeForFilePath(name) + '.sock');
  if (Buffer.byteLength(result) > UNIX_SOCKET_PATH_MAX)
    result = path.join(dir, calculateSha1(name).slice(0, 16) + '.sock');
  if (Buffer.byteLength(result) > UNIX_SOCKET_PATH_MAX)
    throw new Error(`Socket directory path is too long (${Buffer.byteLength(dir)} bytes); set PWTEST_SOCKETS_DIR to a shorter location.`);
  fs.mkdirSync(dir, { recursive: true });
  return result;
}