diff --git a/.gitignore b/.gitignore index 6bb51dcda8..fda9414aae 100644 --- a/.gitignore +++ b/.gitignore @@ -51,3 +51,6 @@ tmp-*/ .env.local .env* .env*.local +# the vendored fs-extra corpus package: its lib/output module and jsonfile's own universalify +!tests/corpus/fs-extra-package/node_modules/fs-extra/lib/output/ +!tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/ diff --git a/docs/content/docs/dependencies.mdx b/docs/content/docs/dependencies.mdx index 1a08b324ee..de35d169ca 100644 --- a/docs/content/docs/dependencies.mdx +++ b/docs/content/docs/dependencies.mdx @@ -71,7 +71,7 @@ Some packages your program imports directly ship no declarations, so their types $ scriptc build app.ts --npm-static=three -o app >/dev/null ``` -Naming a package skips the declaration requirement above, but the package still has to compile. Add a trailing `...` to select a package together with every package it depends on, for example `--npm-static=fs-extra...`. `--npm-static=auto` uses the default automatic selection. The option accepts a comma-separated list and can be repeated. +Naming a package skips the declaration requirement above, but the package still has to compile. Add a trailing `...` to select a package together with every package it depends on, for example `--npm-static=semver...`. `--npm-static=auto` uses the default automatic selection. The option accepts a comma-separated list and can be repeated. ## Built-in packages @@ -84,6 +84,12 @@ scriptc implements a few packages itself and compiles that implementation in pla - `fetch` with a dispatcher returns a response whose `url` is empty and whose `redirected` is `false`, offers only `gzip, deflate` encodings, and sends string and byte bodies. Without a dispatcher it is the built-in `fetch`. - Request bodies are strings and bytes; stream, iterable and form-data bodies, `pipelining` above 1, `CONNECT` requests and Unix socket paths aren't supported. +`fs-extra` 8.x through 11.x is built in, and its declarations replace `@types/fs-extra`. The default import, a namespace import and named imports all read the same exports. fs's members are re-exported, and fs-extra's wrapped methods follow its rule: with a callback as the last argument they call back, otherwise they return a promise. The extra methods cover `copy`, `copySync`, `move`, `moveSync`, `remove`, `removeSync`, `emptyDir`, `ensureDir`, `mkdirs`, `mkdirp`, `ensureFile`, `pathExists`, `outputFile`, `readJson`, `readJsonSync`, `writeJson`, `writeJsonSync`, `outputJson` and their aliases, with fs-extra's error messages. Known differences: + +- `ensureLink`, `ensureSymlink`, `createLink`, `createSymlink`, `gracefulify`, the promise forms of the descriptor-based methods, and the callback forms of `stat`, `lstat`, `readdir`, `mkdtemp`, `realpath` and `readJson` aren't declared, so using one is a type error at build time. Paths are strings, text is UTF-8, and write flags, string modes and `copyFile` mode flags aren't accepted. +- graceful-fs's retry queue, which fs-extra uses under Node.js, isn't part of the implementation, so a program that runs out of file descriptors fails at the first `EMFILE` error instead of retrying. +- An ES module that imports fs-extra can use any of its exports by name. Node.js only exposes the names its CommonJS lexer finds in fs-extra's source, so a name like `readFile` throws a `SyntaxError` there. + Small polyfill packages whose module is exactly a Node.js built-in on Node.js 24 compile as that built-in, at the `require()` that loads them, from your program's CommonJS files, from compiled packages, and from esbuild bundles whose module paths name the package and its version (as pnpm installs do). The package's own files aren't compiled. diff --git a/packages/compiler/shims/fs-extra/core/api.ts b/packages/compiler/shims/fs-extra/core/api.ts new file mode 100644 index 0000000000..a17a5f9a79 --- /dev/null +++ b/packages/compiler/shims/fs-extra/core/api.ts @@ -0,0 +1,1185 @@ +// fs-extra's exports over node:fs. +// +// fs-extra re-exports every fs member and wraps the asynchronous ones with +// universalify: a call whose last argument is a function takes the callback +// form, any other call returns a promise. The wrapped methods below follow +// that rule over fs.promises (callback forms settle through the promise); +// fs's other members are fs's own. The extra methods (copy, remove, mkdirs, +// the JSON helpers, ...) restate fs-extra's behavior and error messages. +// graceful-fs's EMFILE retry queue, which fs-extra loads under Node, has no +// counterpart: on Node 24 it only changes behavior when the process runs +// out of file descriptors. +// +// What is not declared here is a compile-time error: ensureLink, +// ensureSymlink, createLink, createSymlink and their sync forms, +// gracefulify, the descriptor-based methods' promise forms (fstat, read, +// write, ...), the callback forms of the methods that answer stats, +// listings or paths (stat, lstat, readdir, mkdtemp, realpath, readJson), +// Buffer and URL paths, and option shapes fs.promises does not compile +// natively (copyFile mode flags, append options, write flags, string modes, +// numeric utimes times). A readFile callback that fails receives an empty +// value beside the error, where Node passes undefined. +import * as fs from "node:fs"; +import * as fsp from "node:fs/promises"; +import * as path from "node:path"; +import type { Stats } from "node:fs"; + +// fs's other members, as fs-extra re-exports them (fs-extra's own versions +// of the wrapped methods below take their place). +export { + appendFileSync, + accessSync, + chownSync, + chmodSync, + close, + closeSync, + copyFileSync, + cp, + cpSync, + createReadStream, + createWriteStream, + exists, + existsSync, + fchown, + fchownSync, + fchmod, + fchmodSync, + fdatasync, + fdatasyncSync, + fstat, + fstatSync, + fsync, + fsyncSync, + ftruncate, + ftruncateSync, + futimes, + futimesSync, + lchownSync, + linkSync, + lstatSync, + lutimes, + lutimesSync, + mkdirSync, + mkdtempSync, + open, + openSync, + readdirSync, + read, + readSync, + readv, + readvSync, + readFileSync, + readlinkSync, + realpathSync, + renameSync, + rmSync, + rmdirSync, + statfs, + statSync, + statfsSync, + symlinkSync, + truncateSync, + unwatchFile, + unlinkSync, + utimesSync, + watch, + watchFile, + writeFileSync, + write, + writeSync, + writev, + writevSync, + Dirent, + Stats, + ReadStream, + WriteStream, + Dir, + opendir, + opendirSync, + constants, + promises, +} from "node:fs"; + +/** A Node-style callback with a result. */ +export type Callback = (err: NodeJS.ErrnoException | null, value: T) => void; +/** A Node-style callback without a result. */ +export type VoidCallback = (err: NodeJS.ErrnoException | null) => void; + +export type SymlinkType = "dir" | "file" | "junction"; +export type Utf8 = "utf8" | "utf-8"; + +export interface WriteFileOptions { + encoding?: Utf8 | undefined; + mode?: number | undefined; +} + +export interface ReadOptions { + throws?: boolean | undefined; + encoding?: Utf8 | undefined; +} + +export interface WriteOptions { + encoding?: Utf8 | undefined; + mode?: number | undefined; + spaces?: number | undefined; + EOL?: string | undefined; + finalEOL?: boolean | undefined; +} + +/** A copy filter: fs-extra accepts a boolean or a promise of one. */ +export type CopyFilter = (src: string, dest: string) => boolean | Promise; + +export interface CopyOptions { + dereference?: boolean | undefined; + overwrite?: boolean | undefined; + preserveTimestamps?: boolean | undefined; + errorOnExist?: boolean | undefined; + filter?: CopyFilter | undefined; +} + +export interface CopyOptionsSync { + dereference?: boolean | undefined; + overwrite?: boolean | undefined; + preserveTimestamps?: boolean | undefined; + errorOnExist?: boolean | undefined; + filter?: ((src: string, dest: string) => boolean) | undefined; +} + +export interface MoveOptions { + overwrite?: boolean | undefined; +} + +export interface EnsureOptions { + mode?: number | undefined; +} + +export interface MakeDirectoryOptions { + recursive?: boolean | undefined; + mode?: number | undefined; +} + +export interface RmOptions { + force?: boolean | undefined; + recursive?: boolean | undefined; +} + +function settleVoid(promise: Promise, callback: VoidCallback | undefined): Promise { + if (callback === undefined) return promise; + // The callback form's promise settles only through the callback (it + // never rejects); fs-extra answers undefined there. + return promise.then( + () => callback(null), + (err: NodeJS.ErrnoException) => callback(err), + ); +} + +/** The result of a callback-form call that settles through fs's own + * callback: callers ignore it (fs-extra answers undefined). */ +function idle(): Promise { + return new Promise(() => undefined); +} + +function codeOf(err: unknown): string | undefined { + return err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined; +} + +/* ── fs methods in universalify's wrapper ─────────────────────────────── */ + +export function access(path: string, mode?: number): Promise; +export function access(path: string, callback: VoidCallback): void; +export function access(path: string, mode: number, callback: VoidCallback): void; +export function access( + path: string, + mode?: number | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof mode === "function") return settleVoid(fsp.access(path), mode); + return settleVoid(fsp.access(path, mode ?? fs.constants.F_OK), callback); +} + +export function appendFile(path: string, data: string | Uint8Array): Promise; +export function appendFile(path: string, data: string | Uint8Array, callback: VoidCallback): void; +export function appendFile( + path: string, + data: string | Uint8Array, + callback?: VoidCallback, +): Promise { + return settleVoid(fsp.appendFile(path, data), callback); +} + +/** fs.writeFileSync(file, bytes, { mode }) as Node runs it: open with + * O_WRONLY | O_CREAT | O_TRUNC and the mode, write every byte, close. */ +function writeBytesSync(file: string, data: Uint8Array, mode: number): void { + const fd = fs.openSync( + file, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC, + mode, + ); + try { + let offset = 0; + while (offset < data.length) offset += fs.writeSync(fd, data, offset, data.length - offset); + } finally { + fs.closeSync(fd); + } +} + +async function writeData( + file: string, + data: string | Uint8Array, + options: WriteFileOptions | Utf8 | undefined, +): Promise { + if (typeof data !== "string") { + // fs.promises.writeFile compiles string data; bytes take the + // synchronous write after the same microtask boundary. + await Promise.resolve(); + if (options === undefined || typeof options === "string") fs.writeFileSync(file, data); + else writeBytesSync(file, data, options.mode ?? 0o666); + return; + } + if (options === undefined || typeof options === "string") + return fsp.writeFile(file, data, "utf8"); + return fsp.writeFile(file, data, { encoding: "utf8", mode: options.mode ?? 0o666 }); +} + +export function writeFile( + file: string, + data: string | Uint8Array, + options?: WriteFileOptions | Utf8, +): Promise; +export function writeFile(file: string, data: string | Uint8Array, callback: VoidCallback): void; +export function writeFile( + file: string, + data: string | Uint8Array, + options: WriteFileOptions | Utf8, + callback: VoidCallback, +): void; +export function writeFile( + file: string, + data: string | Uint8Array, + options?: WriteFileOptions | Utf8 | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(writeData(file, data, undefined), options); + return settleVoid(writeData(file, data, options), callback); +} + +export function chmod(path: string, mode: number): Promise; +export function chmod(path: string, mode: number, callback: VoidCallback): void; +export function chmod(path: string, mode: number, callback?: VoidCallback): Promise { + return settleVoid(fsp.chmod(path, mode), callback); +} + +export function chown(path: string, uid: number, gid: number): Promise; +export function chown(path: string, uid: number, gid: number, callback: VoidCallback): void; +export function chown( + path: string, + uid: number, + gid: number, + callback?: VoidCallback, +): Promise { + return settleVoid(fsp.chown(path, uid, gid), callback); +} + +export function lchown(path: string, uid: number, gid: number): Promise; +export function lchown(path: string, uid: number, gid: number, callback: VoidCallback): void; +export function lchown( + path: string, + uid: number, + gid: number, + callback?: VoidCallback, +): Promise { + return settleVoid(fsp.lchown(path, uid, gid), callback); +} + +export function copyFile(src: string, dest: string): Promise; +export function copyFile(src: string, dest: string, callback: VoidCallback): void; +export function copyFile(src: string, dest: string, callback?: VoidCallback): Promise { + return settleVoid(fsp.copyFile(src, dest), callback); +} + +export function link(existingPath: string, newPath: string): Promise; +export function link(existingPath: string, newPath: string, callback: VoidCallback): void; +export function link( + existingPath: string, + newPath: string, + callback?: VoidCallback, +): Promise { + return settleVoid(fsp.link(existingPath, newPath), callback); +} + +export function lstat(path: string): Promise { + return fsp.lstat(path); +} + +export function stat(path: string): Promise { + return fsp.stat(path); +} + +async function makeDirectory( + path: string, + options: number | MakeDirectoryOptions | undefined, +): Promise { + if (options === undefined) return fsp.mkdir(path); + if (typeof options === "number") return fsp.mkdir(path, { mode: options }); + const mode = options.mode ?? 0o777; + if (options.recursive === true) return fsp.mkdir(path, { recursive: true, mode }); + return fsp.mkdir(path, { mode }); +} + +export function mkdir(path: string, options?: number | MakeDirectoryOptions): Promise; +export function mkdir(path: string, callback: VoidCallback): void; +export function mkdir( + path: string, + options: number | MakeDirectoryOptions, + callback: VoidCallback, +): void; +export function mkdir( + path: string, + options?: number | MakeDirectoryOptions | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(makeDirectory(path, undefined), options); + return settleVoid(makeDirectory(path, options), callback); +} + +export function mkdtemp(prefix: string): Promise { + return fsp.mkdtemp(prefix); +} + +export function readdir(path: string): Promise { + return fsp.readdir(path); +} + +export type ReadFileOptions = Utf8 | { encoding: Utf8 }; + +export function readFile(file: string): Promise; +export function readFile(file: string, options: ReadFileOptions): Promise; +export function readFile(file: string, callback: Callback): void; +export function readFile(file: string, options: ReadFileOptions, callback: Callback): void; +export function readFile( + file: string, + options?: ReadFileOptions | Callback, + callback?: Callback, +): Promise { + if (typeof options === "function") { + fsp.readFile(file).then( + (data) => options(null, data), + (err: NodeJS.ErrnoException) => options(err, Buffer.alloc(0)), + ); + return idle(); + } + if (options === undefined) return fsp.readFile(file); + if (callback !== undefined) { + fsp.readFile(file, "utf8").then( + (text) => callback(null, text), + (err: NodeJS.ErrnoException) => callback(err, ""), + ); + return idle(); + } + return fsp.readFile(file, "utf8"); +} + +export function readlink(path: string): Promise; +export function readlink(path: string, callback: Callback): void; +export function readlink(path: string, callback?: Callback): Promise { + if (callback !== undefined) { + fs.readlink(path, (err, target) => callback(err, target)); + return idle(); + } + return fsp.readlink(path); +} + +export function realpath(path: string): Promise { + return fsp.realpath(path); +} + +export function rename(oldPath: string, newPath: string): Promise; +export function rename(oldPath: string, newPath: string, callback: VoidCallback): void; +export function rename(oldPath: string, newPath: string, callback?: VoidCallback): Promise { + return settleVoid(fsp.rename(oldPath, newPath), callback); +} + +/** Removes a file or directory tree; a missing path is not an error + * (fs-extra's rimraf and fs.rm's force). */ +async function removeTree(target: string): Promise { + let entry: Stats; + try { + entry = await fsp.lstat(target); + } catch (err) { + if (codeOf(err) === "ENOENT") return; + throw err; + } + if (entry.isDirectory()) { + for (const item of await fsp.readdir(target)) await removeTree(path.join(target, item)); + await fsp.rmdir(target); + return; + } + await fsp.unlink(target); +} + +async function rmPath(target: string, options: RmOptions | undefined): Promise { + const recursive = options === undefined ? false : (options.recursive ?? false); + const force = options === undefined ? false : (options.force ?? false); + if (recursive && force) return removeTree(target); + if (!recursive && !force) return fsp.rm(target); + // The mixed forms: fs.rm's own checks, then the walk. + if (force && !fs.existsSync(target)) return; + const entry = await fsp.lstat(target); + if (entry.isDirectory() && !recursive) return fsp.rm(target); + return removeTree(target); +} + +export function rm(path: string, options?: RmOptions): Promise; +export function rm(path: string, callback: VoidCallback): void; +export function rm(path: string, options: RmOptions, callback: VoidCallback): void; +export function rm( + path: string, + options?: RmOptions | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(rmPath(path, undefined), options); + return settleVoid(rmPath(path, options), callback); +} + +export function rmdir(path: string): Promise; +export function rmdir(path: string, callback: VoidCallback): void; +export function rmdir(path: string, callback?: VoidCallback): Promise { + return settleVoid(fsp.rmdir(path), callback); +} + +export function symlink(target: string, path: string, type?: SymlinkType): Promise; +export function symlink(target: string, path: string, callback: VoidCallback): void; +export function symlink( + target: string, + path: string, + type: SymlinkType | undefined, + callback: VoidCallback, +): void; +export function symlink( + target: string, + path: string, + type?: SymlinkType | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof type === "function") return settleVoid(fsp.symlink(target, path), type); + return settleVoid(fsp.symlink(target, path, type ?? null), callback); +} + +export function truncate(path: string, len?: number): Promise; +export function truncate(path: string, callback: VoidCallback): void; +export function truncate(path: string, len: number, callback: VoidCallback): void; +export function truncate( + path: string, + len?: number | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof len === "function") return settleVoid(fsp.truncate(path, 0), len); + return settleVoid(fsp.truncate(path, len ?? 0), callback); +} + +export function unlink(path: string): Promise; +export function unlink(path: string, callback: VoidCallback): void; +export function unlink(path: string, callback?: VoidCallback): Promise { + return settleVoid(fsp.unlink(path), callback); +} + +export function utimes(path: string, atime: Date, mtime: Date): Promise; +export function utimes(path: string, atime: Date, mtime: Date, callback: VoidCallback): void; +export function utimes( + path: string, + atime: Date, + mtime: Date, + callback?: VoidCallback, +): Promise { + return settleVoid(fsp.utimes(path, atime, mtime), callback); +} + +/* ── mkdirs, ensureDir, mkdirp ────────────────────────────────────────── */ + +function dirMode(options: EnsureOptions | number | undefined): number { + if (options === undefined) return 0o777; + if (typeof options === "number") return options; + return options.mode ?? 0o777; +} + +function makeDir(dir: string, mode: number): Promise { + return fsp.mkdir(path.resolve(dir), { recursive: true, mode }); +} + +function makeDirSync(dir: string, mode: number): void { + fs.mkdirSync(path.resolve(dir), { recursive: true, mode }); +} + +export function ensureDir(dir: string, options?: EnsureOptions | number): Promise; +export function ensureDir(dir: string, callback: VoidCallback): void; +export function ensureDir( + dir: string, + options: EnsureOptions | number, + callback: VoidCallback, +): void; +export function ensureDir( + dir: string, + options?: EnsureOptions | number | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(makeDir(dir, 0o777), options); + return settleVoid(makeDir(dir, dirMode(options)), callback); +} + +export function mkdirs(dir: string, options?: EnsureOptions | number): Promise; +export function mkdirs(dir: string, callback: VoidCallback): void; +export function mkdirs( + dir: string, + options?: EnsureOptions | number | VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(makeDir(dir, 0o777), options); + return makeDir(dir, dirMode(options)); +} + +export function mkdirp(dir: string, options?: EnsureOptions | number): Promise; +export function mkdirp(dir: string, callback: VoidCallback): void; +export function mkdirp( + dir: string, + options?: EnsureOptions | number | VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(makeDir(dir, 0o777), options); + return makeDir(dir, dirMode(options)); +} + +export function ensureDirSync(dir: string, options?: EnsureOptions | number): void { + makeDirSync(dir, dirMode(options)); +} + +export function mkdirsSync(dir: string, options?: EnsureOptions | number): void { + makeDirSync(dir, dirMode(options)); +} + +export function mkdirpSync(dir: string, options?: EnsureOptions | number): void { + makeDirSync(dir, dirMode(options)); +} + +/* ── remove, emptyDir ─────────────────────────────────────────────────── */ + +export function remove(dir: string): Promise; +export function remove(dir: string, callback: VoidCallback): void; +export function remove(dir: string, callback?: VoidCallback): Promise { + return settleVoid(removeTree(dir), callback); +} + +export function removeSync(dir: string): void { + fs.rmSync(dir, { recursive: true, force: true }); +} + +async function emptyDirAsync(dir: string): Promise { + let items: string[]; + try { + items = await fsp.readdir(dir); + } catch { + await makeDir(dir, 0o777); + return; + } + while (items.length > 0) { + const item = items.pop(); + if (item !== undefined) await removeTree(path.join(dir, item)); + } +} + +export function emptyDir(dir: string): Promise; +export function emptyDir(dir: string, callback: VoidCallback): void; +export function emptyDir(dir: string, callback?: VoidCallback): Promise { + return settleVoid(emptyDirAsync(dir), callback); +} + +export function emptyDirSync(dir: string): void { + let items: string[]; + try { + items = fs.readdirSync(dir); + } catch { + makeDirSync(dir, 0o777); + return; + } + for (const item of items) fs.rmSync(path.join(dir, item), { recursive: true, force: true }); +} + +/* ── pathExists, ensureFile, outputFile ───────────────────────────────── */ + +async function pathExistsAsync(file: string): Promise { + try { + await fsp.access(file); + return true; + } catch { + return false; + } +} + +export function pathExists(file: string): Promise; +export function pathExists(file: string, callback: Callback): void; +export function pathExists(file: string, callback?: Callback): Promise { + const found = pathExistsAsync(file); + if (callback === undefined) return found; + return found.then((exists) => { + callback(null, exists); + return exists; + }); +} + +export function pathExistsSync(file: string): boolean { + return fs.existsSync(file); +} + +async function createFileAsync(file: string): Promise { + try { + if ((await fsp.stat(file)).isFile()) return; + } catch { + // Missing: created below. + } + const dir = path.dirname(file); + let dirIsDirectory = true; + try { + dirIsDirectory = (await fsp.stat(dir)).isDirectory(); + } catch (err) { + if (codeOf(err) !== "ENOENT") throw err; + await makeDir(dir, 0o777); + } + // A parent that is not a directory fails with readdir's ENOTDIR. + if (!dirIsDirectory) await fsp.readdir(dir); + await fsp.writeFile(file, "", "utf8"); +} + +export function ensureFile(file: string): Promise; +export function ensureFile(file: string, callback: VoidCallback): void; +export function ensureFile(file: string, callback?: VoidCallback): Promise { + return settleVoid(createFileAsync(file), callback); +} + +export function ensureFileSync(file: string): void { + try { + if (fs.statSync(file).isFile()) return; + } catch { + // Missing: created below. + } + const dir = path.dirname(file); + if (!fs.existsSync(dir)) makeDirSync(dir, 0o777); + fs.writeFileSync(file, ""); +} + +async function outputFileAsync( + file: string, + data: string | Uint8Array, + options: WriteFileOptions | Utf8 | undefined, +): Promise { + const dir = path.dirname(file); + if (!(await pathExistsAsync(dir))) await makeDir(dir, 0o777); + await writeData(file, data, options); +} + +export function outputFile( + file: string, + data: string | Uint8Array, + options?: WriteFileOptions | Utf8, +): Promise; +export function outputFile(file: string, data: string | Uint8Array, callback: VoidCallback): void; +export function outputFile( + file: string, + data: string | Uint8Array, + options: WriteFileOptions | Utf8, + callback: VoidCallback, +): void; +export function outputFile( + file: string, + data: string | Uint8Array, + options?: WriteFileOptions | Utf8 | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") + return settleVoid(outputFileAsync(file, data, undefined), options); + return settleVoid(outputFileAsync(file, data, options), callback); +} + +export function outputFileSync(file: string, data: string | Uint8Array): void { + const dir = path.dirname(file); + if (!fs.existsSync(dir)) makeDirSync(dir, 0o777); + fs.writeFileSync(file, data); +} + +/* ── JSON (jsonfile) ──────────────────────────────────────────────────── */ + +function jsonText(value: unknown, options: WriteOptions | Utf8 | undefined): string { + const opts = options === undefined || typeof options === "string" ? undefined : options; + const eol = opts === undefined ? "\n" : (opts.EOL ?? "\n"); + const finalEol = opts === undefined ? true : (opts.finalEOL ?? true); + const spaces = opts === undefined ? 0 : (opts.spaces ?? 0); + const text = JSON.stringify(value, null, spaces) ?? "undefined"; + return text.replace(/\n/g, eol) + (finalEol ? eol : ""); +} + +function jsonWriteOptions(options: WriteOptions | Utf8 | undefined): WriteFileOptions | undefined { + if (options === undefined || typeof options === "string") return undefined; + return { mode: options.mode }; +} + +function jsonThrows(options: ReadOptions | Utf8 | undefined): boolean { + if (options === undefined || typeof options === "string") return true; + return options.throws ?? true; +} + +function prefixed(file: string, err: unknown): Error { + const error = err instanceof Error ? err : new Error(String(err)); + error.message = `${file}: ${error.message}`; + return error; +} + +function parseJson(file: string, text: string, throws: boolean): any { + try { + return JSON.parse(text.replace(/^\uFEFF/, "")); + } catch (err) { + if (!throws) return null; + throw prefixed(file, err); + } +} + +async function readJsonAsync(file: string, options: ReadOptions | Utf8 | undefined): Promise { + const text = await fsp.readFile(file, "utf8"); + return parseJson(file, text, jsonThrows(options)); +} + +// readJson's callback form is not declared. +export function readJson(file: string, options?: ReadOptions | Utf8): Promise { + return readJsonAsync(file, options); +} + +export function readJsonSync(file: string, options?: ReadOptions | Utf8): any { + const throws = jsonThrows(options); + let text: string; + try { + text = fs.readFileSync(file, "utf8"); + } catch (err) { + // jsonfile reads inside the same try as the parse. + if (!throws) return null; + throw prefixed(file, err); + } + return parseJson(file, text, throws); +} + +async function writeJsonAsync( + file: string, + value: unknown, + options: WriteOptions | Utf8 | undefined, +): Promise { + await writeData(file, jsonText(value, options), jsonWriteOptions(options)); +} + +export function writeJson(file: string, value: any, options?: WriteOptions | Utf8): Promise; +export function writeJson(file: string, value: any, callback: VoidCallback): void; +export function writeJson( + file: string, + value: any, + options: WriteOptions | Utf8, + callback: VoidCallback, +): void; +export function writeJson( + file: string, + value: any, + options?: WriteOptions | Utf8 | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") + return settleVoid(writeJsonAsync(file, value, undefined), options); + return settleVoid(writeJsonAsync(file, value, options), callback); +} + +export function writeJsonSync(file: string, value: any, options?: WriteOptions | Utf8): void { + const text = jsonText(value, options); + if (options === undefined || typeof options === "string") fs.writeFileSync(file, text, "utf8"); + else fs.writeFileSync(file, text, { encoding: "utf8", mode: options.mode ?? 0o666 }); +} + +async function outputJsonAsync( + file: string, + value: unknown, + options: WriteOptions | Utf8 | undefined, +): Promise { + const dir = path.dirname(file); + if (!(await pathExistsAsync(dir))) await makeDir(dir, 0o777); + await writeJsonAsync(file, value, options); +} + +export function outputJson(file: string, value: any, options?: WriteOptions | Utf8): Promise; +export function outputJson(file: string, value: any, callback: VoidCallback): void; +export function outputJson( + file: string, + value: any, + options: WriteOptions | Utf8, + callback: VoidCallback, +): void; +export function outputJson( + file: string, + value: any, + options?: WriteOptions | Utf8 | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") + return settleVoid(outputJsonAsync(file, value, undefined), options); + return settleVoid(outputJsonAsync(file, value, options), callback); +} + +export function outputJsonSync(file: string, value: any, options?: WriteOptions | Utf8): void { + const dir = path.dirname(file); + if (!fs.existsSync(dir)) makeDirSync(dir, 0o777); + writeJsonSync(file, value, options); +} + +/* ── copy, move ───────────────────────────────────────────────────────── */ + +function isSrcSubdir(src: string, dest: string): boolean { + const srcParts = path + .resolve(src) + .split(path.sep) + .filter((part) => part !== ""); + const destParts = path + .resolve(dest) + .split(path.sep) + .filter((part) => part !== ""); + for (let i = 0; i < srcParts.length; i++) if (destParts[i] !== srcParts[i]) return false; + return true; +} + +function subdirMessage(src: string, dest: string, verb: string): string { + return `Cannot ${verb} '${src}' to a subdirectory of itself, '${dest}'.`; +} + +function sameNode(a: Stats, b: Stats): boolean { + return b.ino !== 0 && b.dev !== 0 && a.ino === b.ino && a.dev === b.dev; +} + +async function statOrNull(file: string): Promise { + try { + return await fsp.stat(file); + } catch (err) { + if (codeOf(err) === "ENOENT") return null; + throw err; + } +} + +/** fs-extra's checkPaths and checkParentPaths: the source exists, is not + * the destination, and a directory never copies or moves into itself. + * Answers whether the destination exists. */ +async function checkPaths(src: string, dest: string, verb: string): Promise { + const srcStat = await fsp.stat(src); + const destStat = await statOrNull(dest); + if (destStat !== null && sameNode(srcStat, destStat)) + throw new Error("Source and destination must not be the same."); + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) + throw new Error(subdirMessage(src, dest, verb)); + const srcParent = path.resolve(path.dirname(src)); + let destParent = path.resolve(path.dirname(dest)); + while (destParent !== srcParent && destParent !== path.parse(destParent).root) { + const parentStat = await statOrNull(destParent); + if (parentStat === null) break; + if (sameNode(srcStat, parentStat)) throw new Error(subdirMessage(src, dest, verb)); + destParent = path.resolve(path.dirname(destParent)); + } + return destStat !== null; +} + +function statOrNullSync(file: string): Stats | null { + try { + return fs.statSync(file); + } catch (err) { + if (codeOf(err) === "ENOENT") return null; + throw err; + } +} + +/** checkPaths for copySync and moveSync. Answers the destination's stats, + * or null when it does not exist. */ +function checkPathsSync(src: string, dest: string, verb: string): Stats | null { + const srcStat = fs.statSync(src); + const destStat = statOrNullSync(dest); + if (destStat !== null && sameNode(srcStat, destStat)) + throw new Error("Source and destination must not be the same."); + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) + throw new Error(subdirMessage(src, dest, verb)); + const srcParent = path.resolve(path.dirname(src)); + let destParent = path.resolve(path.dirname(dest)); + while (destParent !== srcParent && destParent !== path.parse(destParent).root) { + const parentStat = statOrNullSync(destParent); + if (parentStat === null) break; + if (sameNode(srcStat, parentStat)) throw new Error(subdirMessage(src, dest, verb)); + destParent = path.resolve(path.dirname(destParent)); + } + return destStat; +} + +interface CopyState { + overwrite: boolean; + errorOnExist: boolean; + dereference: boolean; + preserveTimestamps: boolean; + filter: CopyFilter | undefined; +} + +async function included(state: CopyState, src: string, dest: string): Promise { + const filter = state.filter; + if (filter === undefined) return true; + return await filter(src, dest); +} + +/** fs-extra's onLink: a symlink source creates a symlink at `dest`. Only + * a destination that is itself a symlink is replaced; over a regular file + * or a directory, symlink fails with EEXIST, whatever `overwrite` says. */ +async function copyLink( + target: string, + dest: string, + destExists: boolean, + dereference: boolean, +): Promise { + if (!destExists) return fsp.symlink(target, dest); + let destLinked: string; + try { + destLinked = await fsp.readlink(dest); + } catch (err) { + const code = codeOf(err); + if (code === "EINVAL" || code === "UNKNOWN") return fsp.symlink(target, dest); + throw err; + } + const destTarget = dereference ? path.resolve(process.cwd(), destLinked) : destLinked; + checkLinkTargets(target, destTarget, (await fsp.stat(dest)).isDirectory()); + await fsp.unlink(dest); + await fsp.symlink(target, dest); +} + +function copyLinkSync( + target: string, + dest: string, + destExists: boolean, + dereference: boolean, +): void { + if (!destExists) { + fs.symlinkSync(target, dest); + return; + } + let destLinked: string; + try { + destLinked = fs.readlinkSync(dest); + } catch (err) { + const code = codeOf(err); + if (code !== "EINVAL" && code !== "UNKNOWN") throw err; + fs.symlinkSync(target, dest); + return; + } + const destTarget = dereference ? path.resolve(process.cwd(), destLinked) : destLinked; + checkLinkTargets(target, destTarget, fs.statSync(dest).isDirectory()); + fs.unlinkSync(dest); + fs.symlinkSync(target, dest); +} + +/** Replacing a destination symlink never points it into its own target, + * nor removes a directory link the source lives under. */ +function checkLinkTargets(target: string, destTarget: string, destIsDirectory: boolean): void { + if (isSrcSubdir(target, destTarget)) + throw new Error(`Cannot copy '${target}' to a subdirectory of itself, '${destTarget}'.`); + if (destIsDirectory && isSrcSubdir(destTarget, target)) + throw new Error(`Cannot overwrite '${destTarget}' with '${target}'.`); +} + +async function copyEntry( + state: CopyState, + src: string, + dest: string, + destExists: boolean, + filtered: boolean, +): Promise { + if (!filtered && !(await included(state, src, dest))) return; + const srcStat = state.dereference ? await fsp.stat(src) : await fsp.lstat(src); + if (srcStat.isDirectory()) { + if (destExists && !(await fsp.stat(dest)).isDirectory()) + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); + if (!destExists) await fsp.mkdir(dest); + const items = await fsp.readdir(src); + while (items.length > 0) { + const item = items.pop(); + if (item === undefined) break; + const srcItem = path.join(src, item); + const destItem = path.join(dest, item); + const destItemStat = await statOrNull(destItem); + if (destItemStat !== null && sameNode(await fsp.stat(srcItem), destItemStat)) + throw new Error("Source and destination must not be the same."); + await copyEntry(state, srcItem, destItem, destItemStat !== null, false); + } + if (!destExists) await fsp.chmod(dest, srcStat.mode); + return; + } + if (srcStat.isSymbolicLink()) { + const linked = await fsp.readlink(src); + await copyLink( + state.dereference ? path.resolve(process.cwd(), linked) : linked, + dest, + destExists, + state.dereference, + ); + return; + } + if (destExists) { + if (state.overwrite) await fsp.unlink(dest); + else if (state.errorOnExist) throw new Error(`'${dest}' already exists`); + else return; + } + await fsp.copyFile(src, dest); + if (state.preserveTimestamps) { + const updated = await fsp.stat(src); + if ((srcStat.mode & 0o200) === 0) await fsp.chmod(dest, srcStat.mode | 0o200); + await fsp.utimes(dest, updated.atime, updated.mtime); + } + await fsp.chmod(dest, srcStat.mode); +} + +async function copyAsync( + src: string, + dest: string, + options: CopyOptions | undefined, +): Promise { + const state: CopyState = { + overwrite: options === undefined ? true : (options.overwrite ?? true), + errorOnExist: options === undefined ? false : (options.errorOnExist ?? false), + dereference: options === undefined ? false : (options.dereference ?? false), + preserveTimestamps: options === undefined ? false : (options.preserveTimestamps ?? false), + filter: options === undefined ? undefined : options.filter, + }; + const destExists = await checkPaths(src, dest, "copy"); + if (!(await included(state, src, dest))) return; + const parent = path.dirname(dest); + if (!(await pathExistsAsync(parent))) await makeDir(parent, 0o777); + await copyEntry(state, src, dest, destExists, true); +} + +export function copy(src: string, dest: string, options?: CopyOptions): Promise; +export function copy(src: string, dest: string, callback: VoidCallback): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: VoidCallback): void; +export function copy( + src: string, + dest: string, + options?: CopyOptions | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(copyAsync(src, dest, undefined), options); + return settleVoid(copyAsync(src, dest, options), callback); +} + +function copyEntrySync( + state: CopyOptionsSync, + src: string, + dest: string, + destExists: boolean, + filtered: boolean, +): void { + const filter = state.filter; + if (!filtered && filter !== undefined && !filter(src, dest)) return; + const srcStat = state.dereference === true ? fs.statSync(src) : fs.lstatSync(src); + if (srcStat.isDirectory()) { + if (destExists && !fs.statSync(dest).isDirectory()) + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); + if (!destExists) fs.mkdirSync(dest); + for (const item of fs.readdirSync(src)) { + const destItem = path.join(dest, item); + copyEntrySync(state, path.join(src, item), destItem, fs.existsSync(destItem), false); + } + if (!destExists) fs.chmodSync(dest, srcStat.mode); + return; + } + if (srcStat.isSymbolicLink()) { + const dereference = state.dereference === true; + const linked = fs.readlinkSync(src); + copyLinkSync( + dereference ? path.resolve(process.cwd(), linked) : linked, + dest, + destExists, + dereference, + ); + return; + } + if (destExists) { + if (state.overwrite ?? true) fs.unlinkSync(dest); + else if (state.errorOnExist === true) throw new Error(`'${dest}' already exists`); + else return; + } + fs.copyFileSync(src, dest); + if (state.preserveTimestamps === true) { + const updated = fs.statSync(src); + if ((srcStat.mode & 0o200) === 0) fs.chmodSync(dest, srcStat.mode | 0o200); + fs.utimesSync(dest, updated.atime, updated.mtime); + } + fs.chmodSync(dest, srcStat.mode); +} + +export function copySync(src: string, dest: string, options?: CopyOptionsSync): void { + const opts: CopyOptionsSync = options ?? {}; + const destStat = checkPathsSync(src, dest, "copy"); + const filter = opts.filter; + if (filter !== undefined && !filter(src, dest)) return; + const parent = path.dirname(dest); + if (!fs.existsSync(parent)) makeDirSync(parent, 0o777); + copyEntrySync(opts, src, dest, destStat !== null, true); +} + +async function moveAsync( + src: string, + dest: string, + options: MoveOptions | undefined, +): Promise { + const overwrite = options === undefined ? false : (options.overwrite ?? false); + await checkPaths(src, dest, "move"); + await makeDir(path.dirname(dest), 0o777); + if (overwrite) await removeTree(dest); + else if (await pathExistsAsync(dest)) throw new Error("dest already exists."); + try { + await fsp.rename(src, dest); + } catch (err) { + if (codeOf(err) !== "EXDEV") throw err; + await copyAsync(src, dest, { overwrite, errorOnExist: true }); + await removeTree(src); + } +} + +export function move(src: string, dest: string, options?: MoveOptions): Promise; +export function move(src: string, dest: string, callback: VoidCallback): void; +export function move(src: string, dest: string, options: MoveOptions, callback: VoidCallback): void; +export function move( + src: string, + dest: string, + options?: MoveOptions | VoidCallback, + callback?: VoidCallback, +): Promise { + if (typeof options === "function") return settleVoid(moveAsync(src, dest, undefined), options); + return settleVoid(moveAsync(src, dest, options), callback); +} + +export function moveSync(src: string, dest: string, options?: MoveOptions): void { + const overwrite = options === undefined ? false : (options.overwrite ?? false); + checkPathsSync(src, dest, "move"); + makeDirSync(path.dirname(dest), 0o777); + if (overwrite) fs.rmSync(dest, { recursive: true, force: true }); + else if (fs.existsSync(dest)) throw new Error("dest already exists."); + try { + fs.renameSync(src, dest); + } catch (err) { + if (codeOf(err) !== "EXDEV") throw err; + copySync(src, dest, { overwrite, errorOnExist: true }); + fs.rmSync(src, { recursive: true, force: true }); + } +} + +/* ── fs-extra's aliases ───────────────────────────────────────────────── */ + +export { + emptyDir as emptydir, + emptyDirSync as emptydirSync, + ensureFile as createFile, + ensureFileSync as createFileSync, + readJson as readJSON, + readJsonSync as readJSONSync, + writeJson as writeJSON, + writeJsonSync as writeJSONSync, + outputJson as outputJSON, + outputJsonSync as outputJSONSync, +}; diff --git a/packages/compiler/shims/fs-extra/index.ts b/packages/compiler/shims/fs-extra/index.ts new file mode 100644 index 0000000000..43debf2d43 --- /dev/null +++ b/packages/compiler/shims/fs-extra/index.ts @@ -0,0 +1,9 @@ +// scriptc's built-in implementation of the `fs-extra` package, 8.x-11.x API. +// +// Programs whose installed fs-extra is 8.x through 11.x compile this module +// in its place (see packages/compiler/src/frontend/package-shims.ts), and its +// declarations stand in for @types/fs-extra. The default import, the +// namespace import and named imports all read the same exports, as they read +// fs-extra's single CommonJS export object under Node. +export * from "./core/api.ts"; +export * as default from "./core/api.ts"; diff --git a/packages/compiler/src/frontend/lowering/cjs-exports-object.ts b/packages/compiler/src/frontend/lowering/cjs-exports-object.ts index 5ea4001fc9..dfe2f4b4d0 100644 --- a/packages/compiler/src/frontend/lowering/cjs-exports-object.ts +++ b/packages/compiler/src/frontend/lowering/cjs-exports-object.ts @@ -24,9 +24,11 @@ import { cjsExportAssignmentOf, cjsExportTargetLiteral, isCjsJsFile, + isJsSourceFile, isModuleExportsAccess, isRequireStatement, locOf, + resolveImport, } from "../program.js"; import { isCjsModuleGlobal } from "./lower-node-module.js"; import { DYN, type IrExpr, type IrGlobal } from "../../ir/ir.js"; @@ -362,6 +364,50 @@ function symbolIsThisFreeFunction(lowerer: Lowerer, sym: ts.Symbol | undefined): ); } +/** The ES-module half (a TypeScript module required from JavaScript, such + * as a package shim): require() answers its namespace, so a call through + * it binds `this` to the namespace. True when the export is a function + * that never reads `this` (every declaration of an overload set), a + * builtin module's member re-exported from its declarations, or reached + * through an `export *` of a module where that holds. */ +function esModuleExportIgnoresThis( + lowerer: Lowerer, + sf: ts.SourceFile, + name: string, + depth: number, +): boolean { + const moduleSym = lowerer.checker.getSymbolAtLocation(sf); + const exported = moduleSym?.getExports().get(name as ts.__String); + if (exported !== undefined) { + const target = + exported.flags & ts.SymbolFlags.Alias ? lowerer.checker.getAliasedSymbol(exported) : exported; + const decls = target.declarations; + if (decls.length === 0) return false; + return decls.every( + (d) => + (ts.isFunctionDeclaration(d) && !functionUsesThis(d)) || + (d.getSourceFile().isDeclarationFile && ts.isFunctionDeclaration(d)), + ); + } + for (const stmt of sf.statements.nodes) { + if ( + !ts.isExportDeclaration(stmt) || + stmt.exportClause !== undefined || + stmt.moduleSpecifier === undefined || + !ts.isStringLiteral(stmt.moduleSpecifier) + ) + continue; + const dep = resolveImport(lowerer.program, sf, stmt.moduleSpecifier.text); + if ( + dep !== null && + !dep.isDeclarationFile && + esModuleExportIgnoresThis(lowerer, dep, name, depth + 1) + ) + return true; + } + return false; +} + /** True when every value the module assigns to its export `name` is a * function that never reads `this`. A call through the exports object * (`exports.f(x)`) binds `this` to that object, which the static export @@ -373,6 +419,7 @@ export function cjsExportCallIgnoresThis( depth = 0, ): boolean { if (depth > 16) return false; + if (!isJsSourceFile(sf)) return esModuleExportIgnoresThis(lowerer, sf, name, depth); const values: ts.Expression[] = []; ts.walkPreorder(sf, (node) => { if ( diff --git a/packages/compiler/src/frontend/lowering/lower-namespaces.ts b/packages/compiler/src/frontend/lowering/lower-namespaces.ts index 23b7d0f57d..227b981eea 100644 --- a/packages/compiler/src/frontend/lowering/lower-namespaces.ts +++ b/packages/compiler/src/frontend/lowering/lower-namespaces.ts @@ -37,6 +37,7 @@ * statement is not modeled — same as top-level const reads through early * calls). */ import * as ts from "../ts7/adapter.js"; +import { packageShimFor } from "../package-shims.js"; import type { Lowerer } from "./lowerer.js"; import { boundIdentifiersOf } from "./lowerer.js"; import type { FileParts } from "./lower-modules.js"; @@ -252,6 +253,10 @@ function moduleNsSourceFileOf(lowerer: Lowerer, e: ts.Expression): ts.SourceFile sym = lowerer.checker.getSymbolAtLocation(e.name); } if (!sym) return null; + // The import binding's own declaration stays in view: a package scriptc + // implements itself (package-shims.ts) types through a declaration + // file the alias resolves to, while the import compiles the shim. + const bindingDecls = sym.declarations; if (sym.flags & ts.SymbolFlags.Alias) sym = lowerer.checker.getAliasedSymbol(sym); for (const d of sym.declarations) { if ( @@ -279,6 +284,20 @@ function moduleNsSourceFileOf(lowerer: Lowerer, e: ts.Expression): ts.SourceFile } } } + for (const d of bindingDecls) { + if (!ts.isNamespaceImport(d)) continue; + const stmt = d.parent?.parent; + if ( + stmt === undefined || + !ts.isImportDeclaration(stmt) || + !ts.isStringLiteral(stmt.moduleSpecifier) + ) + continue; + const from = d.getSourceFile(); + if (packageShimFor(from.fileName, stmt.moduleSpecifier.text) === null) continue; + const dep = resolveImport(lowerer.program, from, stmt.moduleSpecifier.text); + if (dep && !dep.isDeclarationFile && lowerer.fileTag.has(dep)) return dep; + } return null; } diff --git a/packages/compiler/src/frontend/lowering/lowerer.ts b/packages/compiler/src/frontend/lowering/lowerer.ts index 8ae3771f7b..d4ffa343ad 100644 --- a/packages/compiler/src/frontend/lowering/lowerer.ts +++ b/packages/compiler/src/frontend/lowering/lowerer.ts @@ -150,6 +150,7 @@ import { resolve } from "node:path"; import { bindingSource } from "../binding-source.js"; import { tsgoPath } from "../dts-paths.js"; import * as ts from "../ts7/adapter.js"; +import { isBundledShimForwarder } from "../package-shims.js"; import { erasedTypeOnlyImport } from "../type-only-imports.js"; import { literalValues } from "../literal-values.js"; import { discriminantOwners, literalUnionArm, type UnionLiteral } from "../union-discriminants.js"; @@ -11520,7 +11521,9 @@ export class Lowerer { readonly isNpmFile = (sf: ts.SourceFile): boolean => sf.isDeclarationFile && (sf.fileName.includes("/node_modules/") || workspacePackageOfPath(sf.fileName) !== null) && - !this.isStdlibFile(sf); + !this.isStdlibFile(sf) && + // A bundled copy's forwarder to a package shim types compiled code. + !isBundledShimForwarder(sf.fileName); npmPackageOf(type: ts.Type): string | null { return npmPackageOf(this, type); diff --git a/packages/compiler/src/frontend/npm-static-bundled-chunks.test.ts b/packages/compiler/src/frontend/npm-static-bundled-chunks.test.ts index a54b865ed2..219b62482a 100644 --- a/packages/compiler/src/frontend/npm-static-bundled-chunks.test.ts +++ b/packages/compiler/src/frontend/npm-static-bundled-chunks.test.ts @@ -391,3 +391,27 @@ console.log(mixed.Readable, mixed.from); expect(mixed.text).toContain('var members = require("./index.js.require_readable.cjs");'); expect(mixed.text).toContain('var mixed = require("./index.js.require_readable.cjs");'); }); + +test("a bundled copy of a shimmed package's main file requires the package shim", () => { + const key = (version: string, file: string) => + `node_modules/.pnpm/fs-extra@${version}/node_modules/fs-extra/${file}`; + const result = split(`${keyedHelper}var require_lib = __commonJS({ + "${key("9.0.0", "lib/index.js")}"(exports2, module2) { + module2.exports = { readFile() { return "bundled"; } }; + } +}); +var require_old = __commonJS({ + "${key("7.0.1", "lib/index.js")}"(exports2, module2) { + module2.exports = { readFile() { return "old"; } }; + } +}); +console.log(require_lib().readFile(), require_old().readFile()); +`) as BundledChunkSplit; + const forwarder = result.chunks.find((c) => c.path.endsWith(".shim.d.ts")); + expect(forwarder?.path).toBe("/pkg/dist/index.js.require_lib.shim.d.ts"); + expect(forwarder?.source).toMatch(/export \* from ".*shims\/fs-extra\/index\.ts";/); + expect(forwarder?.source).toMatch(/export \{ default \} from ".*shims\/fs-extra\/index\.ts";/); + expect(result.text).toContain('require("./index.js.require_lib.shim").readFile()'); + // fs-extra 7 has no shim: its chunk stays a module. + expect(result.chunks.map((c) => basename(c.path))).toContain("index.js.require_old.cjs"); +}); diff --git a/packages/compiler/src/frontend/npm-static-bundled-chunks.ts b/packages/compiler/src/frontend/npm-static-bundled-chunks.ts index 6888589859..b8cac2436c 100644 --- a/packages/compiler/src/frontend/npm-static-bundled-chunks.ts +++ b/packages/compiler/src/frontend/npm-static-bundled-chunks.ts @@ -24,6 +24,7 @@ import * as ts from "./ts7/syntax.js"; import { helperTokens } from "./helper-tokens.js"; import { canonicalBuiltinModule } from "./builtin-modules.js"; +import { bundledShimForwarder, packageShimForBundledFile } from "./package-shims.js"; import { builtinAliasOf, versionedPackageOfKey, @@ -598,7 +599,8 @@ export function splitBundledChunks( const alias = builtinAliasOfChunk(chunk); const aliased = alias === null ? null : aliasReplacement(call, alias); if (alias !== null && aliased === null) unaliased.add(chunk.name); - const forwarded = forwarderSpec(chunk); + const forwarded = + forwarderSpec(chunk) ?? (shimOfChunk(chunk) !== null ? shimSpec(chunk) : null); callEdits.push({ start: call.getStart(sf), end: call.getEnd(), @@ -632,6 +634,18 @@ export function splitBundledChunks( bundleEdits.push({ start: chunk.stmt.getStart(sf), end: chunk.stmt.getEnd(), text: "" }); continue; } + const shim = shimOfChunk(chunk); + if (shim !== null) { + // A bundled copy of a package scriptc implements itself is the + // package's shim (package-shims.ts), reached through a forwarder + // declaration the checker follows. + out.push({ + path: shimDeclPath(chunk), + source: bundledShimForwarder(shimDeclPath(chunk), shim), + }); + bundleEdits.push({ start: chunk.stmt.getStart(sf), end: chunk.stmt.getEnd(), text: "" }); + continue; + } if (forwarderSpec(chunk) !== null) { // A chunk that only re-exports a builtin module is that module. bundleEdits.push({ start: chunk.stmt.getStart(sf), end: chunk.stmt.getEnd(), text: "" }); @@ -801,6 +815,24 @@ function builtinAliasOfChunk(chunk: Chunk): BuiltinAlias | null { return pkg === null ? null : builtinAliasOf(pkg.name, pkg.version, pkg.subpath); } +/** The shim module standing in for a chunk that is a bundled copy of a + * shimmed package's main file at a supported version, or null. */ +function shimOfChunk(chunk: Chunk): string | null { + if (chunk.key === null) return null; + const pkg = versionedPackageOfKey(chunk.key); + return pkg === null ? null : packageShimForBundledFile(pkg.name, pkg.version, pkg.subpath); +} + +/** The forwarder declaration beside the bundle for a shimmed chunk, and + * the specifier its call sites require. */ +function shimDeclPath(chunk: Chunk): string { + return chunk.path.replace(/\.cjs$/, ".shim.d.ts"); +} + +function shimSpec(chunk: Chunk): string { + return chunk.spec.replace(/\.cjs$/, ".shim"); +} + /** The builtin module a chunk forwards, or null: a body that is exactly * `module.exports = require("")` (readable-stream's * internal/streams/stream.js). Requiring the chunk is then requiring the diff --git a/packages/compiler/src/frontend/npm-static-bundled-esm.test.ts b/packages/compiler/src/frontend/npm-static-bundled-esm.test.ts index caea3c3663..b3185cf477 100644 --- a/packages/compiler/src/frontend/npm-static-bundled-esm.test.ts +++ b/packages/compiler/src/frontend/npm-static-bundled-esm.test.ts @@ -257,7 +257,7 @@ test("classes whose definition or binding is observable stay assignments", () => var init_m = __esm({ "src/m.ts"() { A = class { static made = console.log("static field runs at definition") }; - B = class extends Array {}; + B = class extends globalThis.Array {}; console.log(typeof D); D = class {}; C = class {}; @@ -289,9 +289,65 @@ console.log(typeof make().on); expect(lowered).toContain('new (require("events")).EventEmitter()'); }); +test("a hoisted class may extend a global constructor, past esbuild's export annotation", () => { + const lowered = expectSameBehavior(`${helpers}var AppError; +var init_errors = __esm({ + "src/errors.ts"() { + AppError = class extends Error { + code; + constructor(message, code) { + super(message); + this.code = code; + } + }; + } +}); +function fail() { + init_errors(); + throw new AppError("failed", "E1"); +} +function main() { + try { + fail(); + } catch (err) { + console.log(err instanceof AppError, err instanceof Error, err.code, err.message); + } +} +main(); +0 && (module.exports = { AppError }); +`); + expect(lowered).toContain("class AppError extends Error"); +}); + +test("an initializer declared last in a shared var statement still hoists its classes", () => { + const lowered = expectSameBehavior(`"use strict"; +${helpers}var BuildError, hints, init_errors = __esm({ + "src/errors.ts"() { + "use strict"; + BuildError = class extends Error { + constructor(code) { + super("failed: " + code); + this.code = code; + } + }, hints = { retry: "try again" }; + } +}); +function run() { + init_errors(); + try { + throw new BuildError("E2"); + } catch (err) { + console.log(err instanceof BuildError, err.code, err.message, hints.retry); + } +} +run(); +`); + expect(lowered).toContain("class BuildError extends Error"); +}); + test("a minified initializer that ends with its class still hoists it", () => { const lowered = expectSameBehavior( - `${helpers}var Counter;var init_counter=__esm({"src/counter.ts"(){console.log("counter init"),Counter=class{n=0;next(){return++this.n}}}});function run(){init_counter();const c=new Counter;c.next();console.log(c.next())}run();`, + `${helpers}var Counter,init_counter=__esm({"src/counter.ts"(){console.log("counter init"),Counter=class{n=0;next(){return++this.n}}}});function run(){init_counter();const c=new Counter;c.next();console.log(c.next())}run();`, ); expect(lowered).toContain("class Counter{"); }); diff --git a/packages/compiler/src/frontend/npm-static-bundled-esm.ts b/packages/compiler/src/frontend/npm-static-bundled-esm.ts index d5635bc2e3..5fe8105df6 100644 --- a/packages/compiler/src/frontend/npm-static-bundled-esm.ts +++ b/packages/compiler/src/frontend/npm-static-bundled-esm.ts @@ -854,6 +854,24 @@ export function lowerBundledEsmInits( return applyEdits(source, 0, source.length, edits); } +/** Global constructors a hoisted class may extend: reading one runs no + * code. */ +const GLOBAL_BASES: ReadonlySet = new Set([ + "Error", + "TypeError", + "RangeError", + "SyntaxError", + "ReferenceError", + "EvalError", + "URIError", + "AggregateError", + "Array", + "Map", + "Set", + "Promise", + "Object", +]); + /** The run-once closure's closing text after the initializer function. */ const RUN_ONCE_TAIL = "return function () { if (__scriptc_done) return; __scriptc_done = true; __scriptc_init(); }; })()"; @@ -891,6 +909,21 @@ function hoistInitClasses( ): Map { const out = new Map(); const hoistedNames = new Set(); + /** esbuild's `0 && (module.exports = { … })` annotation for Node's + * CommonJS lexer: code that never runs. */ + const inDeadAnnotation = (n: ts.Node): boolean => { + for (let child: ts.Node = n, p = n.parent; p !== undefined; child = p, p = p.parent) { + if ( + ts.isBinaryExpression(p) && + p.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken && + p.right === child && + ts.isNumericLiteral(unparen(p.left)) && + (unparen(p.left) as ts.NumericLiteral).text === "0" + ) + return true; + } + return false; + }; const insideFunction = (n: ts.Node): boolean => { for (let p = n.parent; p !== undefined && !ts.isSourceFile(p); p = p.parent) if (ts.isFunctionLike(p)) return true; @@ -905,7 +938,13 @@ function hoistInitClasses( let root: ts.Expression = type.expression; while (ts.isPropertyAccessExpression(root) && !root.questionDotToken) root = root.expression; if (ts.isIdentifier(root)) { - if (root === type.expression) return hoistedNames.has(root.text); + if (root === type.expression) + return ( + hoistedNames.has(root.text) || + // A standard global constructor the bundle never rebinds + // (`class extends Error`, an error base class). + (GLOBAL_BASES.has(root.text) && countDeclarations(sf, root.text) === 0) + ); const spec = interopSpecs.get(root.text); return spec !== undefined && canonicalBuiltinModule(spec) !== null; } @@ -925,7 +964,7 @@ function hoistInitClasses( for (const init of inits.values()) { const stmts = init.body.statements.nodes; if (stmts.some((st) => !ts.isExpressionStatement(st) && !ts.isEmptyStatement(st))) continue; - // The initializer's declaration is a statement of its own. + // The initializer's declarator is its statement's last one. const declarator = init.call.parent; const list = declarator?.parent; if ( @@ -933,7 +972,9 @@ function hoistInitClasses( !ts.isVariableDeclaration(declarator) || list === undefined || !ts.isVariableDeclarationList(list) || - list.declarations.nodes.length !== 1 || + // The initializer ends its statement: the split pieces follow it + // (`var A, B, init_x = __esm(…)` keeps A and B declared before). + list.declarations.nodes[list.declarations.nodes.length - 1] !== declarator || unparen(declarator.initializer!) !== init.call ) continue; @@ -974,6 +1015,7 @@ function hoistInitClasses( r === target || // The class's own methods name the class itself. (r.getStart(sf) >= cls.getStart(sf) && r.getEnd() <= cls.getEnd()) || + inDeadAnnotation(r) || (insideFunction(r) && // The initializer's own earlier code reads the unassigned binding. !(r.getStart(sf) >= init.body.getStart(sf) && r.getStart(sf) < el.getEnd())), diff --git a/packages/compiler/src/frontend/npm-static.ts b/packages/compiler/src/frontend/npm-static.ts index bcff89633d..bc8eeaa38c 100644 --- a/packages/compiler/src/frontend/npm-static.ts +++ b/packages/compiler/src/frontend/npm-static.ts @@ -4,6 +4,7 @@ * Eligibility failures and package preflight errors become explicit refusals. */ import { dirname } from "node:path"; import type { FrontendServices } from "./services.js"; +import { isBundledShimForwarder } from "./package-shims.js"; import type { NpmStaticDeclarationOverloads, NpmStaticDeclarationProperties, @@ -514,6 +515,7 @@ export function npmStaticFsShadow(services: FrontendServices): NpmStaticFsShadow hideFile: (path) => { const target = shadowTargetOf(path); if (!target) return false; + if (isBundledShimForwarder(path)) return false; if (target.viaTypes) return true; // the @types twin hides whole return isDeclarationFileName(path) || isUnloadableInstalledTsSource(path); }, diff --git a/packages/compiler/src/frontend/package-shims.ts b/packages/compiler/src/frontend/package-shims.ts index d08a7a9efd..86a41d3a68 100644 --- a/packages/compiler/src/frontend/package-shims.ts +++ b/packages/compiler/src/frontend/package-shims.ts @@ -55,13 +55,35 @@ interface ImplementationShim { /** Supported major versions and their entry modules, relative to the * shim root. */ versions: ReadonlyMap; + /** The entry has a default export (a CommonJS package's whole export + * object, which a default import reads). */ + defaultExport?: boolean; + /** The package's main file in every supported version: a bundler's copy + * of it (a __commonJS chunk whose key names the package, its version + * and this file) is the package itself. */ + mainFile: string; } const IMPLEMENTATION_SHIMS: ReadonlyMap = new Map([ + [ + "fs-extra", + { + name: "fs-extra", + defaultExport: true, + mainFile: "lib/index.js", + versions: new Map([ + [8, "fs-extra/index.ts"], + [9, "fs-extra/index.ts"], + [10, "fs-extra/index.ts"], + [11, "fs-extra/index.ts"], + ]), + }, + ], [ "undici", { name: "undici", + mainFile: "index.js", versions: new Map([ [5, "undici/v5.ts"], [7, "undici/v7.ts"], @@ -70,6 +92,60 @@ const IMPLEMENTATION_SHIMS: ReadonlyMap = new Map([ ], ]); +/** The shim module that stands in for a bundled copy of a package's main + * file (a __commonJS chunk keyed `…/@/…//`), or + * null when the package, version or file is not one the registry serves. */ +export function packageShimForBundledFile( + name: string, + version: string, + file: string, +): string | null { + const shim = IMPLEMENTATION_SHIMS.get(name); + if (shim === undefined || file.replace(/^\.\//, "") !== shim.mainFile) return null; + const major = Number(/^(\d+)\./.exec(version)?.[1] ?? NaN); + const entry = shim.versions.get(major); + return entry === undefined ? null : join(packageShimRoot(), entry); +} + +/** Bundled-copy forwarders: a virtual declaration module beside a bundle + * (`..shim.d.ts`) that re-exports the shim standing in + * for a bundled package, so the checker loads the shim through it, and + * module resolution answers the shim itself for its path. */ +const bundledForwarders = new Map(); + +/** The forwarder declaration text for a bundled copy of a shimmed package + * and records its path; the bundle's call sites require the forwarder's + * extensionless path. */ +export function bundledShimForwarder(declPath: string, shimPath: string): string { + bundledForwarders.set(declPath.split("\\").join("/"), shimPath); + const target = JSON.stringify(tsgoPath(shimPath)); + const shim = [...IMPLEMENTATION_SHIMS.values()].find((entry) => + [...entry.versions.values()].some((v) => join(packageShimRoot(), v) === shimPath), + ); + const defaultLine = shim?.defaultExport === true ? `export { default } from ${target};\n` : ""; + return `// scriptc: this bundled package compiles from its built-in implementation.\nexport * from ${target};\n${defaultLine}`; +} + +/** True for a bundled-copy forwarder's path (the --npm-static shadow keeps + * it visible where it hides the package's other declaration files). */ +export function isBundledShimForwarder(path: string): boolean { + return bundledForwarders.has(path.split("\\").join("/")); +} + +/** The shim a resolved module path forwards to, or the path itself. */ +export function throughBundledShimForwarder(resolved: string): string { + return bundledForwarders.get(resolved.split("\\").join("/")) ?? resolved; +} + +/** Every implementation module the registry ships (absolute paths), for + * the guard test that compiles each one. */ +export function packageShimEntries(): string[] { + const entries = new Set(); + for (const shim of IMPLEMENTATION_SHIMS.values()) + for (const entry of shim.versions.values()) entries.add(join(packageShimRoot(), entry)); + return [...entries].sort(); +} + /** Package names the project marks never loaded. */ let unloadedPackages: ReadonlySet = new Set(); @@ -212,11 +288,23 @@ export function packageShimDeclarationText(path: string): string | undefined { if (!path.endsWith("/index.d.ts")) return undefined; const pkgDir = dirname(path); const name = pkgDir.slice(pkgDir.lastIndexOf("/") + 1); - if (!IMPLEMENTATION_SHIMS.has(name)) return undefined; - const entry = shimEntryForPackageDir(pkgDir, name); + const shim = IMPLEMENTATION_SHIMS.get(name); + if (shim === undefined) return undefined; + // A DefinitelyTyped twin (`@types/fs-extra`) types a package that ships no + // declarations. Nothing at its path names the installed runtime version, + // so it reads as the shim only when every supported version shares one + // module. + const viaTypes = dirname(pkgDir).endsWith("/@types"); + const entries = new Set(shim.versions.values()); + const entry = viaTypes + ? entries.size === 1 + ? join(packageShimRoot(), [...entries][0]!) + : null + : shimEntryForPackageDir(pkgDir, name); if (entry === null) return undefined; const target = JSON.stringify(tsgoPath(entry)); - return `// scriptc: this package compiles from its built-in implementation.\nexport * from ${target};\n`; + const defaultLine = shim.defaultExport === true ? `export { default } from ${target};\n` : ""; + return `// scriptc: this package compiles from its built-in implementation.\nexport * from ${target};\n${defaultLine}`; } /** True for a file of the shipped package shims. They are compiler-owned @@ -231,4 +319,5 @@ export function isPackageShimFile(fileName: string): boolean { /** Resets per-compile caches. */ export function clearPackageShimCaches(): void { installedCache.clear(); + bundledForwarders.clear(); } diff --git a/packages/compiler/src/frontend/resolve.ts b/packages/compiler/src/frontend/resolve.ts index 3d3d135b48..3b32dad3a2 100644 --- a/packages/compiler/src/frontend/resolve.ts +++ b/packages/compiler/src/frontend/resolve.ts @@ -22,7 +22,11 @@ import { npmStaticPackageOfPath, npmStaticTransformPkgJson, } from "./npm-static.js"; -import { clearPackageShimCaches, packageShimFor } from "./package-shims.js"; +import { + clearPackageShimCaches, + packageShimFor, + throughBundledShimForwarder, +} from "./package-shims.js"; import { provenanceEntryFor } from "./provenance-registry.js"; import { trackedAccessibleEntries, @@ -667,6 +671,11 @@ export function resolveProjectImport(fromFile: string, specifier: string): strin * answer null for their dedicated callers. */ export function resolveProjectModule(fromFile: string, specifier: string): string | null { if (isRelativeSpecifier(specifier) || isAbsolute(specifier)) { + // A bundled copy's forwarder (a virtual declaration module) answers + // the shim it forwards to. + const forwarder = join(dirname(resolve(fromFile)), `${specifier}.d.ts`); + const forwarded = throughBundledShimForwarder(forwarder); + if (forwarded !== forwarder) return forwarded; return resolveRelativeModule(fromFile, specifier); } if (specifier.startsWith("node:")) return null; diff --git a/packages/compiler/test/package-shim-guard.test.ts b/packages/compiler/test/package-shim-guard.test.ts new file mode 100644 index 0000000000..ff01acbb8c --- /dev/null +++ b/packages/compiler/test/package-shim-guard.test.ts @@ -0,0 +1,64 @@ +/* Every package shim (packages/compiler/shims, registered in + * src/frontend/package-shims.ts) compiles without a lowering refusal or a + * runtime fence anywhere in its own files. + * + * Shim files suppress TypeScript errors (like library declarations under + * skipLibCheck), but never lowering diagnostics: a refusal in code the + * program reaches fails its build, located in the shim, and one in code it + * does not reach would fail a later program. This test reaches all of it: + * the analysis lowers the unreached remainder too, so every function body + * of every shim module is checked, under both type worlds a project can + * bring (scriptc's bundled Node declarations, and @types/node). + */ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, test } from "vitest"; +import { analyze } from "../src/index.js"; +import { packageShimEntries } from "../src/frontend/package-shims.js"; +import type { ScrDiagnostic } from "../src/diagnostics/diagnostic.js"; + +const repoRoot = join(import.meta.dirname, "../../.."); +const shimRoot = join(repoRoot, "packages/compiler/shims"); +const scratch = mkdtempSync(join(tmpdir(), "scriptc-shim-guard-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +function shimFindings(entry: string, world: "bundled" | "types-node"): string[] { + const dir = join(scratch, `${world}-${entry.slice(shimRoot.length + 1).replace(/[/.]/g, "_")}`); + mkdirSync(dir, { recursive: true }); + if (world === "types-node") { + mkdirSync(join(dir, "node_modules/@types"), { recursive: true }); + symlinkSync(join(repoRoot, "node_modules/@types/node"), join(dir, "node_modules/@types/node")); + } + const main = join(dir, "main.ts"); + writeFileSync(main, `import ${JSON.stringify(entry)};\nconsole.log("loaded");\n`); + const { coverage } = analyze(main); + expect(coverage.preflightFailed, "the shim type-checks for the analysis").toBe(false); + const all: ScrDiagnostic[] = [ + ...coverage.diagnostics, + ...(coverage.runtimeFences ?? []), + ...(coverage.unreached?.diagnostics ?? []), + ...(coverage.unreached?.runtimeFences ?? []), + ]; + return all + .filter((d) => d.loc.file.startsWith(shimRoot)) + .map((d) => `${d.loc.file.slice(shimRoot.length + 1)}: ${d.code} ${d.message}`); +} + +describe("package shims compile without refusals", () => { + const entries = packageShimEntries(); + test("the registry lists its shim modules", () => { + expect(entries.map((e) => e.slice(shimRoot.length + 1))).toEqual([ + "fs-extra/index.ts", + "undici/v5.ts", + "undici/v7.ts", + ]); + }); + for (const entry of entries) { + for (const world of ["bundled", "types-node"] as const) { + test(`${entry.slice(shimRoot.length + 1)} (${world})`, () => { + expect(shimFindings(entry, world)).toEqual([]); + }, 300_000); + } + } +}); diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/fs-extra-package/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/fs-extra-package/main.ts.json new file mode 100644 index 0000000000..d48b63a869 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/fs-extra-package/main.ts.json @@ -0,0 +1,8 @@ +{ + "order": [ + "/packages/compiler/shims/fs-extra/core/api.ts", + "/packages/compiler/shims/fs-extra/index.ts", + "/tests/corpus/fs-extra-package/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts.json new file mode 100644 index 0000000000..0d5592a51c --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts.json new file mode 100644 index 0000000000..7763781d1b --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/resolver-parity.test.ts b/packages/compiler/test/ts7/resolver-parity.test.ts index 5049a55083..61a84baa95 100644 --- a/packages/compiler/test/ts7/resolver-parity.test.ts +++ b/packages/compiler/test/ts7/resolver-parity.test.ts @@ -147,10 +147,13 @@ test("relative and bare specifiers across the whole test tree resolve identicall // PROJECT imports (#alias / self-name): ts5's NON-external answers // for bare specifiers are exactly the package.json-mediated // resolutions inside the project — resolveProjectImport must agree. + // A package scriptc implements itself (package-shims.ts) answers its + // shim module where 5.9.3 answers the installed package, so only the + // external-library answer below is compared for it. const oursProj = resolveProjectImport(file, spec); const theirsProj = reference && !reference.isExternalLibraryImport ? reference.resolvedFileName : null; - if (oursProj !== theirsProj) { + if (oursProj !== theirsProj && packageShimFor(file, spec) === null) { failures.push(`${file} '${spec}' (project): ours=${oursProj} ts5=${theirsProj}`); } const ours = resolveBareModule(file, spec); diff --git a/tests/corpus/fs-extra-package/main.ts b/tests/corpus/fs-extra-package/main.ts new file mode 100644 index 0000000000..e152a287ca --- /dev/null +++ b/tests/corpus/fs-extra-package/main.ts @@ -0,0 +1,163 @@ +// fs-extra compiles from scriptc's built-in implementation; Node runs the +// real package. node_modules vendors fs-extra 9.0.0 with its dependencies +// (graceful-fs, jsonfile, universalify, at-least-node) and @types/fs-extra +// 9.0.13, unmodified (MIT). The program reads fs-extra through its default +// import, a namespace import and named imports: fs's re-exported members in +// promise and callback form, fs.promises, streams, and the extras (mkdirs, +// copy, remove, pathExists, the JSON helpers, outputFile, emptyDir, move), +// the modes of binary and JSON writes, and the sync copy and move checks. +import fs from "fs-extra"; +import * as fsx from "fs-extra"; +// Named imports use the names Node detects in fs-extra's CommonJS source. +import { copy, outputFile, pathExists, remove } from "fs-extra"; +import * as os from "node:os"; +import * as path from "node:path"; + +function shown(root: string, text: string): string { + return text.split(root).join(""); +} + +async function readStream(file: string): Promise { + return new Promise((resolve, reject) => { + let text = ""; + const stream = fs.createReadStream(file, { encoding: "utf8" }); + stream.on("data", (chunk) => { + text += String(chunk); + }); + stream.on("end", () => resolve(text)); + stream.on("error", reject); + }); +} + +async function main(): Promise { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "scriptc-fs-extra-")); + const file = path.join(root, "a.txt"); + + await fs.writeFile(file, "hello\n"); + await fs.appendFile(file, "world\n"); + console.log(JSON.stringify(await fs.readFile(file, "utf8"))); + console.log((await fs.readFile(file)).length, fs.existsSync(file), fs.existsSync(root + "-missing")); + console.log((await fs.stat(file)).size, (await fs.lstat(file)).isFile(), fs.statSync(root).isDirectory()); + await fs.chmod(file, 0o640); + console.log(((await fs.stat(file)).mode & 0o777).toString(8)); + + const link = path.join(root, "link.txt"); + await fs.symlink(file, link); + console.log(shown(root, await fs.readlink(link)), (await fs.lstat(link)).isSymbolicLink()); + + await fs.ensureDir(path.join(root, "deep", "er")); + await fs.mkdirp(path.join(root, "made", "by", "mkdirp")); + await fs.writeFile(path.join(root, "deep", "er", "leaf.txt"), "leaf"); + console.log((await fs.readdir(root)).sort().join(",")); + + const data = path.join(root, "data.json"); + await fs.writeJson(data, { a: 1, list: [true, null, "x"] }, { spaces: 2 }); + console.log(JSON.stringify(await fs.readFile(data, "utf8"))); + console.log(JSON.stringify(await fs.readJson(data))); + await fs.outputJson(path.join(root, "out", "nested", "o.json"), { ok: true }); + console.log(JSON.stringify(fs.readJSONSync(path.join(root, "out", "nested", "o.json")))); + await outputFile(path.join(root, "out2", "z.txt"), "zed"); + console.log(await fs.readFile(path.join(root, "out2", "z.txt"), "utf8")); + console.log(fs.readJsonSync(file, { throws: false })); + fs.writeFileSync(path.join(root, "bom.json"), '\uFEFF{"bom":true}'); + console.log(JSON.stringify(fs.readJsonSync(path.join(root, "bom.json")))); + + await fs.copy(path.join(root, "deep"), path.join(root, "copied")); + await copy(file, path.join(root, "copied", "a-copy.txt")); + await fsx.copy(file, path.join(root, "copied", "b-copy.txt")); + console.log((await fs.readdir(path.join(root, "copied"))).sort().join(",")); + console.log(await fs.readFile(path.join(root, "copied", "er", "leaf.txt"), "utf8")); + console.log(await pathExists(path.join(root, "copied", "er")), await fs.pathExists(root + "-missing")); + try { + await fs.copy(path.join(root, "deep"), path.join(root, "deep", "er", "inner")); + } catch (err) { + console.log(shown(root, (err as Error).message)); + } + try { + await fs.copy(file, file); + } catch (err) { + console.log((err as Error).message); + } + + await fs.move(path.join(root, "out2"), path.join(root, "moved")); + console.log(await fs.pathExists(path.join(root, "out2")), await fs.pathExists(path.join(root, "moved", "z.txt"))); + try { + await fs.move(path.join(root, "moved"), path.join(root, "copied")); + } catch (err) { + console.log((err as Error).message); + } + await fs.emptyDir(path.join(root, "copied")); + console.log((await fs.readdir(path.join(root, "copied"))).length); + + // Modes of binary and JSON writes, and the sync copy and move checks. + await fs.writeFile(path.join(root, "bytes.bin"), Buffer.from([1, 2, 3]), { mode: 0o600 }); + await fs.outputFile(path.join(root, "out3", "bytes.bin"), new Uint8Array([4, 5]), { mode: 0o600 }); + fs.writeJsonSync(path.join(root, "private.json"), { a: 1 }, { mode: 0o600 }); + fs.outputJsonSync(path.join(root, "out4", "private.json"), { b: 2 }, { mode: 0o600 }); + for (const name of ["bytes.bin", "out3/bytes.bin", "private.json", "out4/private.json"]) + console.log(name, (fs.statSync(path.join(root, name)).mode & 0o777).toString(8)); + const selfLink = path.join(root, "self-link"); + fs.symlinkSync(path.join(root, "deep"), selfLink); + try { + fs.copySync(path.join(root, "deep"), path.join(selfLink, "inner")); + } catch (err) { + console.log(shown(root, (err as Error).message)); + } + try { + fs.moveSync(path.join(root, "deep"), path.join(selfLink, "inner")); + } catch (err) { + console.log(shown(root, (err as Error).message)); + } + try { + fs.moveSync(file, file, { overwrite: true }); + } catch (err) { + console.log((err as Error).message); + } + console.log(fs.existsSync(file), fs.existsSync(path.join(root, "deep", "inner"))); + + // A symlink source over an existing destination entry: a regular file is + // kept and the copy fails with EEXIST; a destination symlink is replaced. + const linkSrc = path.join(root, "link-src"); + fs.mkdirSync(linkSrc); + fs.symlinkSync(file, path.join(linkSrc, "entry")); + for (const sync of [true, false]) { + const linkDest = path.join(root, sync ? "link-dest-sync" : "link-dest-async"); + fs.mkdirSync(linkDest); + fs.writeFileSync(path.join(linkDest, "entry"), "kept"); + try { + if (sync) fs.copySync(linkSrc, linkDest, { overwrite: false }); + else await fs.copy(linkSrc, linkDest, { overwrite: false }); + } catch (err) { + console.log((err as NodeJS.ErrnoException).code, shown(root, (err as Error).message)); + } + const entry = path.join(linkDest, "entry"); + console.log(fs.readFileSync(entry, "utf8"), fs.lstatSync(entry).isSymbolicLink()); + } + const relinkDest = path.join(root, "relink-dest"); + fs.mkdirSync(relinkDest); + fs.symlinkSync(data, path.join(relinkDest, "entry")); + fs.copySync(linkSrc, relinkDest); + console.log(shown(root, fs.readlinkSync(path.join(relinkDest, "entry")))); + + console.log(await readStream(file)); + console.log((await fs.promises.readFile(file, "utf8")).length); + console.log(fs.readFileSync(file, "utf8").length); + + try { + await fs.readFile(path.join(root, "missing.txt"), "utf8"); + } catch (err) { + console.log((err as NodeJS.ErrnoException).code); + } + + fs.readFile(file, "utf8", (err, text) => { + console.log("callback", err === null, text.length); + fs.ensureDir(path.join(root, "from-callback"), (dirErr) => { + console.log("callback ensureDir", dirErr === null, fs.existsSync(path.join(root, "from-callback"))); + void remove(root).then(async () => { + console.log("removed", await fs.pathExists(root)); + }); + }); + }); +} + +main(); diff --git a/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/LICENSE b/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/LICENSE new file mode 100755 index 0000000000..9e841e7a26 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/index.d.ts b/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/index.d.ts new file mode 100755 index 0000000000..4daa564823 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/index.d.ts @@ -0,0 +1,563 @@ +// Type definitions for fs-extra 9.0 +// Project: https://github.com/jprichardson/node-fs-extra +// Definitions by: Alan Agius , +// midknight41 , +// Brendan Forster , +// Mees van Dijk , +// Justin Rockwood , +// Sang Dang , +// Florian Keller +// Piotr Błażejewicz +// Tiger Oakes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Minimum TypeScript Version: 3.9 + +/// + +import * as fs from 'fs'; +import Stats = fs.Stats; +import PathLike = fs.PathLike; + +export * from 'fs'; + +export function copy(src: string, dest: string, options?: CopyOptions): Promise; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; +export function copySync(src: string, dest: string, options?: CopyOptionsSync): void; + +export function copyFile(src: string, dest: string, flags?: number): Promise; +export function copyFile(src: string, dest: string, callback: (err: Error) => void): void; +export function copyFile(src: string, dest: string, flags: number, callback: (err: Error) => void): void; + +export function move(src: string, dest: string, options?: MoveOptions): Promise; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; +export function moveSync(src: string, dest: string, options?: MoveOptions): void; + +export function createFile(file: string): Promise; +export function createFile(file: string, callback: (err: Error) => void): void; +export function createFileSync(file: string): void; + +export function createSymlink(src: string, dest: string, type: SymlinkType): Promise; +export function createSymlink(src: string, dest: string, type: SymlinkType, callback?: (err: Error) => void): void; +export function createSymlinkSync(src: string, dest: string, type: SymlinkType): void; + +export function ensureDir(path: string, options?: EnsureOptions | number): Promise; +export function ensureDir(path: string, callback?: (err: Error) => void): void; +export function ensureDir(path: string, options?: EnsureOptions | number, callback?: (err: Error) => void): void; +export function ensureDirSync(path: string, options?: EnsureOptions | number): void; + +export function mkdirs(dir: string): Promise; +export function mkdirs(dir: string, callback: (err: Error) => void): void; +export function mkdirp(dir: string): Promise; +export function mkdirp(dir: string, callback: (err: Error) => void): void; +export function mkdirsSync(dir: string): void; +export function mkdirpSync(dir: string): void; + +export function outputFile( + file: string, + data: any, + options?: WriteFileOptions | BufferEncoding | string, +): Promise; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFile( + file: string, + data: any, + options: WriteFileOptions | string, + callback: (err: Error) => void, +): void; +export function outputFileSync(file: string, data: any, options?: WriteFileOptions | BufferEncoding | string): void; + +export function readJson(file: string, options?: ReadOptions | BufferEncoding | string): Promise; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson( + file: string, + options: ReadOptions | BufferEncoding | string, + callback: (err: Error, jsonObject: any) => void, +): void; +export function readJSON(file: string, options?: ReadOptions | BufferEncoding | string): Promise; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON( + file: string, + options: ReadOptions | BufferEncoding | string, + callback: (err: Error, jsonObject: any) => void, +): void; + +export function readJsonSync(file: string, options?: ReadOptions | BufferEncoding | string): any; +export function readJSONSync(file: string, options?: ReadOptions | BufferEncoding | string): any; + +export function remove(dir: string, callback: (err: Error) => void): void; +export function remove(dir: string, callback?: (err: Error) => void): Promise; +export function removeSync(dir: string): void; + +export function outputJSON(file: string, data: any, options?: WriteOptions | BufferEncoding | string): Promise; +export function outputJSON( + file: string, + data: any, + options: WriteOptions | BufferEncoding | string, + callback: (err: Error) => void, +): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, options?: WriteOptions | BufferEncoding | string): Promise; +export function outputJson( + file: string, + data: any, + options: WriteOptions | BufferEncoding | string, + callback: (err: Error) => void, +): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; +export function outputJsonSync(file: string, data: any, options?: WriteOptions | BufferEncoding | string): void; +export function outputJSONSync(file: string, data: any, options?: WriteOptions | BufferEncoding | string): void; + +export function writeJSON(file: string, object: any, options?: WriteOptions | BufferEncoding | string): Promise; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON( + file: string, + object: any, + options: WriteOptions | BufferEncoding | string, + callback: (err: Error) => void, +): void; +export function writeJson(file: string, object: any, options?: WriteOptions | BufferEncoding | string): Promise; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson( + file: string, + object: any, + options: WriteOptions | BufferEncoding | string, + callback: (err: Error) => void, +): void; + +export function writeJsonSync(file: string, object: any, options?: WriteOptions | BufferEncoding | string): void; +export function writeJSONSync(file: string, object: any, options?: WriteOptions | BufferEncoding | string): void; + +export function ensureFile(path: string): Promise; +export function ensureFile(path: string, callback: (err: Error) => void): void; +export function ensureFileSync(path: string): void; + +export function ensureLink(src: string, dest: string): Promise; +export function ensureLink(src: string, dest: string, callback: (err: Error) => void): void; +// alias for ensureLink +export const createLink: typeof ensureLink; +export function ensureLinkSync(src: string, dest: string): void; +// aliased as +export const createLinkSync: typeof ensureLinkSync; + +export function ensureSymlink(src: string, dest: string, type?: SymlinkType): Promise; +export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error) => void): void; +export function ensureSymlink(src: string, dest: string, callback: (err: Error) => void): void; +export function ensureSymlinkSync(src: string, dest: string, type?: SymlinkType): void; + +export function emptyDir(path: string): Promise; +export function emptyDir(path: string, callback: (err: Error) => void): void; +export const emptydir: typeof emptyDir; + +export function emptyDirSync(path: string): void; +export const emptydirSync: typeof emptyDirSync; + +export function pathExists(path: string): Promise; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; +export function pathExistsSync(path: string): boolean; + +// fs async methods +// copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts + +export function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: PathLike, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: PathLike, mode?: number): Promise; + +export function appendFile( + file: PathLike | number, + data: any, + options: { + encoding?: BufferEncoding | string | undefined; + mode?: number | string | undefined; + flag?: string | undefined; + }, + callback: (err: NodeJS.ErrnoException) => void, +): void; +export function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile( + file: PathLike | number, + data: any, + options?: + | { + encoding?: BufferEncoding | string | undefined; + mode?: number | string | undefined; + flag?: string | undefined; + } + | BufferEncoding + | string, +): Promise; + +export function chmod(path: PathLike, mode: Mode, callback: (err: NodeJS.ErrnoException) => void): void; +export function chmod(path: PathLike, mode: Mode): Promise; + +export function chown(path: PathLike, uid: number, gid: number): Promise; +export function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + +export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function close(fd: number): Promise; + +export function fchmod(fd: number, mode: Mode, callback: (err: NodeJS.ErrnoException) => void): void; +export function fchmod(fd: number, mode: Mode): Promise; + +export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function fchown(fd: number, uid: number, gid: number): Promise; + +export function fdatasync(fd: number, callback: () => void): void; +export function fdatasync(fd: number): Promise; + +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function fstat(fd: number): Promise; + +export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function fsync(fd: number): Promise; + +export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len?: number): Promise; + +export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: number, mtime: number): Promise; +export function futimes(fd: number, atime: Date, mtime: Date): Promise; + +export function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function lchown(path: PathLike, uid: number, gid: number): Promise; + +export function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function link(existingPath: PathLike, newPath: PathLike): Promise; + +export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function lstat(path: PathLike): Promise; + +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir( + path: PathLike, + options: Mode | fs.MakeDirectoryOptions | null, + callback: (err: NodeJS.ErrnoException) => void, +): void; +export function mkdir(path: PathLike, options?: Mode | fs.MakeDirectoryOptions | null): Promise; +export function mkdirSync(path: PathLike, options?: Mode | fs.MakeDirectoryOptions | null): void; + +export function open( + path: PathLike, + flags: string | number, + callback: (err: NodeJS.ErrnoException, fd: number) => void, +): void; +export function open( + path: PathLike, + flags: string | number, + mode: Mode, + callback: (err: NodeJS.ErrnoException, fd: number) => void, +): void; +export function open(path: PathLike, flags: string | number, mode?: Mode | null): Promise; + +export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: fs.Dir) => void): void; +export function opendir( + path: string, + options: fs.OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: fs.Dir) => void, +): void; +export function opendir(path: string, options?: fs.OpenDirOptions): Promise; + +export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, +): void; +export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, +): Promise<{ bytesRead: number; buffer: TBuffer }>; + +export function readFile(file: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile( + file: PathLike | number, + encoding: BufferEncoding | string, + callback: (err: NodeJS.ErrnoException, data: string) => void, +): void; +export function readFile( + file: PathLike | number, + options: { flag?: string | undefined } | { encoding: BufferEncoding | string; flag?: string | undefined }, + callback: (err: NodeJS.ErrnoException, data: Buffer) => void, +): void; +export function readFile( + file: PathLike | number, + options: { flag?: string | undefined } | { encoding: BufferEncoding | string; flag?: string | undefined }, +): Promise; +// tslint:disable-next-line:unified-signatures +export function readFile(file: PathLike | number, encoding: BufferEncoding | string): Promise; +export function readFile(file: PathLike | number): Promise; + +export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; +export function readdir( + path: PathLike, + options: 'buffer' | { encoding: 'buffer'; withFileTypes?: false | undefined }, +): Promise; +export function readdir( + path: PathLike, + options?: + | { encoding: BufferEncoding | string | null; withFileTypes?: false | undefined } + | BufferEncoding + | string + | null, +): Promise; +export function readdir( + path: PathLike, + options?: { encoding?: BufferEncoding | string | null | undefined; withFileTypes?: false | undefined }, +): Promise; +export function readdir( + path: PathLike, + options: { encoding?: BufferEncoding | string | null | undefined; withFileTypes: true }, +): Promise; + +export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; +export function readlink(path: PathLike): Promise; + +export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath( + path: PathLike, + cache: { [path: string]: string }, + callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any, +): void; +export function realpath(path: PathLike, cache?: { [path: string]: string }): Promise; + +/* tslint:disable:unified-signatures */ +export namespace realpath { + const native: { + (path: PathLike, options: { encoding: 'buffer' } | 'buffer'): Promise; + ( + path: PathLike, + options: { encoding: BufferEncoding | string | null } | BufferEncoding | string | undefined | null, + ): Promise; + (path: PathLike, options: { encoding: BufferEncoding | string | null } | string | undefined | null): Promise< + string | Buffer + >; + (path: PathLike): Promise; + } & typeof fs.realpath.native; +} +/* tslint:enable:unified-signatures */ + +export function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function rename(oldPath: PathLike, newPath: PathLike): Promise; + +/** + * Asynchronously removes files and directories (modeled on the standard POSIX + * `rm` utility). + * + * Only available in node >= v14.14.0 + */ +export function rm( + path: PathLike, + options?: { + force?: boolean | undefined; + maxRetries?: number | undefined; + recursive?: boolean | undefined; + retryDelay?: number | undefined; + }, +): Promise; + +/** + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function rmdir(path: PathLike, options?: fs.RmDirOptions): Promise; + +export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function stat(path: PathLike): Promise; + +export function symlink( + target: PathLike, + path: PathLike, + type: SymlinkType | undefined, + callback: (err: NodeJS.ErrnoException) => void, +): void; +export function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function symlink(target: PathLike, path: PathLike, type?: SymlinkType): Promise; + +export function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function truncate(path: PathLike, len: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function truncate(path: PathLike, len?: number): Promise; + +/** + * Asynchronous unlink - deletes the file specified in {path} + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; +export function unlink(path: PathLike): Promise; + +export function utimes( + path: PathLike, + atime: number, + mtime: number, + callback: (err: NodeJS.ErrnoException) => void, +): void; +export function utimes(path: PathLike, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; +export function utimes(path: PathLike, atime: number, mtime: number): Promise; +export function utimes(path: PathLike, atime: Date, mtime: Date): Promise; + +export function write( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, +): void; +export function write( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, +): void; +export function write( + fd: number, + data: any, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, +): void; +export function write( + fd: number, + data: any, + offset: number, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, +): void; +export function write( + fd: number, + data: any, + offset: number, + encoding: BufferEncoding | string, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, +): void; +export function write( + fd: number, + buffer: TBuffer, + offset?: number, + length?: number, + position?: number | null, +): Promise<{ bytesWritten: number; buffer: TBuffer }>; +export function write( + fd: number, + data: any, + offset?: number, + encoding?: BufferEncoding | string, +): Promise<{ bytesWritten: number; buffer: string }>; + +export function writeFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function writeFile( + file: PathLike | number, + data: any, + options?: WriteFileOptions | BufferEncoding | string, +): Promise; +export function writeFile( + file: PathLike | number, + data: any, + options: WriteFileOptions | BufferEncoding | string, + callback: (err: NodeJS.ErrnoException) => void, +): void; + +export function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, +): void; +export function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, +): void; +export function writev(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + +/** + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ +export function mkdtemp(prefix: string): Promise; +export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + +export interface PathEntry { + path: string; + stats: Stats; +} + +export interface PathEntryStream { + read(): PathEntry | null; +} + +export type CopyFilterSync = (src: string, dest: string) => boolean; +export type CopyFilterAsync = (src: string, dest: string) => Promise; + +export type SymlinkType = 'dir' | 'file' | 'junction'; + +export type Mode = string | number; + +export type ArrayBufferView = NodeJS.TypedArray | DataView; + +export interface CopyOptions { + dereference?: boolean | undefined; + overwrite?: boolean | undefined; + preserveTimestamps?: boolean | undefined; + errorOnExist?: boolean | undefined; + filter?: CopyFilterSync | CopyFilterAsync | undefined; + recursive?: boolean | undefined; +} + +export interface CopyOptionsSync extends CopyOptions { + filter?: CopyFilterSync | undefined; +} + +export interface EnsureOptions { + mode?: number | undefined; +} + +export interface MoveOptions { + overwrite?: boolean | undefined; + limit?: number | undefined; +} + +export interface ReadOptions { + throws?: boolean | undefined; + fs?: object | undefined; + reviver?: any; + encoding?: BufferEncoding | string | undefined; + flag?: string | undefined; +} + +export interface WriteFileOptions { + encoding?: BufferEncoding | string | null | undefined; + flag?: string | undefined; + mode?: number | undefined; +} + +export interface WriteOptions extends WriteFileOptions { + fs?: object | undefined; + replacer?: any; + spaces?: number | string | undefined; + EOL?: string | undefined; +} + +export interface WritevResult { + bytesWritten: number; + buffers: ArrayBufferView[]; +} diff --git a/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/package.json b/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/package.json new file mode 100755 index 0000000000..0dc1040896 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/@types/fs-extra/package.json @@ -0,0 +1,67 @@ +{ + "name": "@types/fs-extra", + "version": "9.0.13", + "description": "TypeScript definitions for fs-extra", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra", + "license": "MIT", + "contributors": [ + { + "name": "Alan Agius", + "url": "https://github.com/alan-agius4", + "githubUsername": "alan-agius4" + }, + { + "name": "midknight41", + "url": "https://github.com/midknight41", + "githubUsername": "midknight41" + }, + { + "name": "Brendan Forster", + "url": "https://github.com/shiftkey", + "githubUsername": "shiftkey" + }, + { + "name": "Mees van Dijk", + "url": "https://github.com/mees-", + "githubUsername": "mees-" + }, + { + "name": "Justin Rockwood", + "url": "https://github.com/jrockwood", + "githubUsername": "jrockwood" + }, + { + "name": "Sang Dang", + "url": "https://github.com/sangdth", + "githubUsername": "sangdth" + }, + { + "name": "Florian Keller", + "url": "https://github.com/ffflorian", + "githubUsername": "ffflorian" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz", + "githubUsername": "peterblazejewicz" + }, + { + "name": "Tiger Oakes", + "url": "https://github.com/NotWoods", + "githubUsername": "NotWoods" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/fs-extra" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "typesPublisherContentHash": "75e10d16a18d936a50e54414024604aa9484e8345b37c2027921869f254523ee", + "typeScriptVersion": "3.9" +} \ No newline at end of file diff --git a/tests/corpus/fs-extra-package/node_modules/at-least-node/LICENSE b/tests/corpus/fs-extra-package/node_modules/at-least-node/LICENSE new file mode 100644 index 0000000000..5e29ccc5ee --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/at-least-node/LICENSE @@ -0,0 +1,6 @@ +The ISC License +Copyright (c) 2020 Ryan Zimmerman + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/tests/corpus/fs-extra-package/node_modules/at-least-node/index.js b/tests/corpus/fs-extra-package/node_modules/at-least-node/index.js new file mode 100644 index 0000000000..974a2fa854 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/at-least-node/index.js @@ -0,0 +1,5 @@ +module.exports = r => { + const n = process.versions.node.split('.').map(x => parseInt(x, 10)) + r = r.split('.').map(x => parseInt(x, 10)) + return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2]))) +} diff --git a/tests/corpus/fs-extra-package/node_modules/at-least-node/package.json b/tests/corpus/fs-extra-package/node_modules/at-least-node/package.json new file mode 100644 index 0000000000..2c13641f9c --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/at-least-node/package.json @@ -0,0 +1,32 @@ +{ + "name": "at-least-node", + "version": "1.0.0", + "description": "Lightweight Node.js version sniffing/comparison", + "keywords": [ + "semver", + "feature" + ], + "homepage": "https://github.com/RyanZim/at-least-node#readme", + "bugs": { + "url": "https://github.com/RyanZim/at-least-node/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/RyanZim/at-least-node.git" + }, + "license": "ISC", + "author": "Ryan Zimmerman ", + "main": "index.js", + "files": [], + "scripts": { + "test": "ava" + }, + "devDependencies": { + "ava": "^3.1.0", + "rewire": "^4.0.1", + "semver": "^7.1.2" + }, + "engines": { + "node": ">= 4.0.0" + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/LICENSE b/tests/corpus/fs-extra-package/node_modules/fs-extra/LICENSE new file mode 100644 index 0000000000..93546dfb76 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/LICENSE @@ -0,0 +1,15 @@ +(The MIT License) + +Copyright (c) 2011-2017 JP Richardson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files +(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, + merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy-sync/copy-sync.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy-sync/copy-sync.js new file mode 100644 index 0000000000..31f06e4419 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy-sync/copy-sync.js @@ -0,0 +1,166 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const mkdirsSync = require('../mkdirs').mkdirsSync +const utimesMillisSync = require('../util/utimes').utimesMillisSync +const stat = require('../util/stat') + +function copySync (src, dest, opts) { + if (typeof opts === 'function') { + opts = { filter: opts } + } + + opts = opts || {} + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n + see https://github.com/jprichardson/node-fs-extra/issues/269`) + } + + const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy') + stat.checkParentPathsSync(src, srcStat, dest, 'copy') + return handleFilterAndCopy(destStat, src, dest, opts) +} + +function handleFilterAndCopy (destStat, src, dest, opts) { + if (opts.filter && !opts.filter(src, dest)) return + const destParent = path.dirname(dest) + if (!fs.existsSync(destParent)) mkdirsSync(destParent) + return startCopy(destStat, src, dest, opts) +} + +function startCopy (destStat, src, dest, opts) { + if (opts.filter && !opts.filter(src, dest)) return + return getStats(destStat, src, dest, opts) +} + +function getStats (destStat, src, dest, opts) { + const statSync = opts.dereference ? fs.statSync : fs.lstatSync + const srcStat = statSync(src) + + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) +} + +function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) + return mayCopyFile(srcStat, src, dest, opts) +} + +function mayCopyFile (srcStat, src, dest, opts) { + if (opts.overwrite) { + fs.unlinkSync(dest) + return copyFile(srcStat, src, dest, opts) + } else if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) + } +} + +function copyFile (srcStat, src, dest, opts) { + fs.copyFileSync(src, dest) + if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) + return setDestMode(dest, srcStat.mode) +} + +function handleTimestamps (srcMode, src, dest) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) + return setDestTimestamps(src, dest) +} + +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} + +function makeFileWritable (dest, srcMode) { + return setDestMode(dest, srcMode | 0o200) +} + +function setDestMode (dest, srcMode) { + return fs.chmodSync(dest, srcMode) +} + +function setDestTimestamps (src, dest) { + // The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + const updatedSrcStat = fs.statSync(src) + return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) +} + +function onDir (srcStat, destStat, src, dest, opts) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) + if (destStat && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) + } + return copyDir(src, dest, opts) +} + +function mkDirAndCopy (srcMode, src, dest, opts) { + fs.mkdirSync(dest) + copyDir(src, dest, opts) + return setDestMode(dest, srcMode) +} + +function copyDir (src, dest, opts) { + fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) +} + +function copyDirItem (item, src, dest, opts) { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) + const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy') + return startCopy(destStat, srcItem, destItem, opts) +} + +function onLink (destStat, src, dest, opts) { + let resolvedSrc = fs.readlinkSync(src) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } + + if (!destStat) { + return fs.symlinkSync(resolvedSrc, dest) + } else { + let resolvedDest + try { + resolvedDest = fs.readlinkSync(dest) + } catch (err) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) + throw err + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } + + // prevent copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + } + return copyLink(resolvedSrc, dest) + } +} + +function copyLink (resolvedSrc, dest) { + fs.unlinkSync(dest) + return fs.symlinkSync(resolvedSrc, dest) +} + +module.exports = copySync diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy-sync/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy-sync/index.js new file mode 100644 index 0000000000..65945aedb2 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy-sync/index.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = { + copySync: require('./copy-sync') +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy/copy.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy/copy.js new file mode 100644 index 0000000000..328f1025f9 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy/copy.js @@ -0,0 +1,232 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const mkdirs = require('../mkdirs').mkdirs +const pathExists = require('../path-exists').pathExists +const utimesMillis = require('../util/utimes').utimesMillis +const stat = require('../util/stat') + +function copy (src, dest, opts, cb) { + if (typeof opts === 'function' && !cb) { + cb = opts + opts = {} + } else if (typeof opts === 'function') { + opts = { filter: opts } + } + + cb = cb || function () {} + opts = opts || {} + + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n + see https://github.com/jprichardson/node-fs-extra/issues/269`) + } + + stat.checkPaths(src, dest, 'copy', (err, stats) => { + if (err) return cb(err) + const { srcStat, destStat } = stats + stat.checkParentPaths(src, srcStat, dest, 'copy', err => { + if (err) return cb(err) + if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) + return checkParentDir(destStat, src, dest, opts, cb) + }) + }) +} + +function checkParentDir (destStat, src, dest, opts, cb) { + const destParent = path.dirname(dest) + pathExists(destParent, (err, dirExists) => { + if (err) return cb(err) + if (dirExists) return startCopy(destStat, src, dest, opts, cb) + mkdirs(destParent, err => { + if (err) return cb(err) + return startCopy(destStat, src, dest, opts, cb) + }) + }) +} + +function handleFilter (onInclude, destStat, src, dest, opts, cb) { + Promise.resolve(opts.filter(src, dest)).then(include => { + if (include) return onInclude(destStat, src, dest, opts, cb) + return cb() + }, error => cb(error)) +} + +function startCopy (destStat, src, dest, opts, cb) { + if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) + return getStats(destStat, src, dest, opts, cb) +} + +function getStats (destStat, src, dest, opts, cb) { + const stat = opts.dereference ? fs.stat : fs.lstat + stat(src, (err, srcStat) => { + if (err) return cb(err) + + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) + }) +} + +function onFile (srcStat, destStat, src, dest, opts, cb) { + if (!destStat) return copyFile(srcStat, src, dest, opts, cb) + return mayCopyFile(srcStat, src, dest, opts, cb) +} + +function mayCopyFile (srcStat, src, dest, opts, cb) { + if (opts.overwrite) { + fs.unlink(dest, err => { + if (err) return cb(err) + return copyFile(srcStat, src, dest, opts, cb) + }) + } else if (opts.errorOnExist) { + return cb(new Error(`'${dest}' already exists`)) + } else return cb() +} + +function copyFile (srcStat, src, dest, opts, cb) { + fs.copyFile(src, dest, err => { + if (err) return cb(err) + if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) + return setDestMode(dest, srcStat.mode, cb) + }) +} + +function handleTimestampsAndMode (srcMode, src, dest, cb) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcMode)) { + return makeFileWritable(dest, srcMode, err => { + if (err) return cb(err) + return setDestTimestampsAndMode(srcMode, src, dest, cb) + }) + } + return setDestTimestampsAndMode(srcMode, src, dest, cb) +} + +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} + +function makeFileWritable (dest, srcMode, cb) { + return setDestMode(dest, srcMode | 0o200, cb) +} + +function setDestTimestampsAndMode (srcMode, src, dest, cb) { + setDestTimestamps(src, dest, err => { + if (err) return cb(err) + return setDestMode(dest, srcMode, cb) + }) +} + +function setDestMode (dest, srcMode, cb) { + return fs.chmod(dest, srcMode, cb) +} + +function setDestTimestamps (src, dest, cb) { + // The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + fs.stat(src, (err, updatedSrcStat) => { + if (err) return cb(err) + return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) + }) +} + +function onDir (srcStat, destStat, src, dest, opts, cb) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) + if (destStat && !destStat.isDirectory()) { + return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) + } + return copyDir(src, dest, opts, cb) +} + +function mkDirAndCopy (srcMode, src, dest, opts, cb) { + fs.mkdir(dest, err => { + if (err) return cb(err) + copyDir(src, dest, opts, err => { + if (err) return cb(err) + return setDestMode(dest, srcMode, cb) + }) + }) +} + +function copyDir (src, dest, opts, cb) { + fs.readdir(src, (err, items) => { + if (err) return cb(err) + return copyDirItems(items, src, dest, opts, cb) + }) +} + +function copyDirItems (items, src, dest, opts, cb) { + const item = items.pop() + if (!item) return cb() + return copyDirItem(items, item, src, dest, opts, cb) +} + +function copyDirItem (items, item, src, dest, opts, cb) { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) + stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => { + if (err) return cb(err) + const { destStat } = stats + startCopy(destStat, srcItem, destItem, opts, err => { + if (err) return cb(err) + return copyDirItems(items, src, dest, opts, cb) + }) + }) +} + +function onLink (destStat, src, dest, opts, cb) { + fs.readlink(src, (err, resolvedSrc) => { + if (err) return cb(err) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } + + if (!destStat) { + return fs.symlink(resolvedSrc, dest, cb) + } else { + fs.readlink(dest, (err, resolvedDest) => { + if (err) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) + return cb(err) + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) + } + + // do not copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) + } + return copyLink(resolvedSrc, dest, cb) + }) + } + }) +} + +function copyLink (resolvedSrc, dest, cb) { + fs.unlink(dest, err => { + if (err) return cb(err) + return fs.symlink(resolvedSrc, dest, cb) + }) +} + +module.exports = copy diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy/index.js new file mode 100644 index 0000000000..b7e4f7f8d4 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/copy/index.js @@ -0,0 +1,6 @@ +'use strict' + +const u = require('universalify').fromCallback +module.exports = { + copy: u(require('./copy')) +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/empty/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/empty/index.js new file mode 100644 index 0000000000..90fb46991e --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/empty/index.js @@ -0,0 +1,48 @@ +'use strict' + +const u = require('universalify').fromCallback +const fs = require('graceful-fs') +const path = require('path') +const mkdir = require('../mkdirs') +const remove = require('../remove') + +const emptyDir = u(function emptyDir (dir, callback) { + callback = callback || function () {} + fs.readdir(dir, (err, items) => { + if (err) return mkdir.mkdirs(dir, callback) + + items = items.map(item => path.join(dir, item)) + + deleteItem() + + function deleteItem () { + const item = items.pop() + if (!item) return callback() + remove.remove(item, err => { + if (err) return callback(err) + deleteItem() + }) + } + }) +}) + +function emptyDirSync (dir) { + let items + try { + items = fs.readdirSync(dir) + } catch { + return mkdir.mkdirsSync(dir) + } + + items.forEach(item => { + item = path.join(dir, item) + remove.removeSync(item) + }) +} + +module.exports = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/file.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/file.js new file mode 100644 index 0000000000..15cc473c8a --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/file.js @@ -0,0 +1,69 @@ +'use strict' + +const u = require('universalify').fromCallback +const path = require('path') +const fs = require('graceful-fs') +const mkdir = require('../mkdirs') + +function createFile (file, callback) { + function makeFile () { + fs.writeFile(file, '', err => { + if (err) return callback(err) + callback() + }) + } + + fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err + if (!err && stats.isFile()) return callback() + const dir = path.dirname(file) + fs.stat(dir, (err, stats) => { + if (err) { + // if the directory doesn't exist, make it + if (err.code === 'ENOENT') { + return mkdir.mkdirs(dir, err => { + if (err) return callback(err) + makeFile() + }) + } + return callback(err) + } + + if (stats.isDirectory()) makeFile() + else { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + fs.readdir(dir, err => { + if (err) return callback(err) + }) + } + }) + }) +} + +function createFileSync (file) { + let stats + try { + stats = fs.statSync(file) + } catch {} + if (stats && stats.isFile()) return + + const dir = path.dirname(file) + try { + if (!fs.statSync(dir).isDirectory()) { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + fs.readdirSync(dir) + } + } catch (err) { + // If the stat call above failed because the directory doesn't exist, create it + if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) + else throw err + } + + fs.writeFileSync(file, '') +} + +module.exports = { + createFile: u(createFile), + createFileSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/index.js new file mode 100644 index 0000000000..c1f67b7187 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/index.js @@ -0,0 +1,23 @@ +'use strict' + +const file = require('./file') +const link = require('./link') +const symlink = require('./symlink') + +module.exports = { + // file + createFile: file.createFile, + createFileSync: file.createFileSync, + ensureFile: file.createFile, + ensureFileSync: file.createFileSync, + // link + createLink: link.createLink, + createLinkSync: link.createLinkSync, + ensureLink: link.createLink, + ensureLinkSync: link.createLinkSync, + // symlink + createSymlink: symlink.createSymlink, + createSymlinkSync: symlink.createSymlinkSync, + ensureSymlink: symlink.createSymlink, + ensureSymlinkSync: symlink.createSymlinkSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/link.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/link.js new file mode 100644 index 0000000000..2cd419626a --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/link.js @@ -0,0 +1,61 @@ +'use strict' + +const u = require('universalify').fromCallback +const path = require('path') +const fs = require('graceful-fs') +const mkdir = require('../mkdirs') +const pathExists = require('../path-exists').pathExists + +function createLink (srcpath, dstpath, callback) { + function makeLink (srcpath, dstpath) { + fs.link(srcpath, dstpath, err => { + if (err) return callback(err) + callback(null) + }) + } + + pathExists(dstpath, (err, destinationExists) => { + if (err) return callback(err) + if (destinationExists) return callback(null) + fs.lstat(srcpath, (err) => { + if (err) { + err.message = err.message.replace('lstat', 'ensureLink') + return callback(err) + } + + const dir = path.dirname(dstpath) + pathExists(dir, (err, dirExists) => { + if (err) return callback(err) + if (dirExists) return makeLink(srcpath, dstpath) + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + makeLink(srcpath, dstpath) + }) + }) + }) + }) +} + +function createLinkSync (srcpath, dstpath) { + const destinationExists = fs.existsSync(dstpath) + if (destinationExists) return undefined + + try { + fs.lstatSync(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink') + throw err + } + + const dir = path.dirname(dstpath) + const dirExists = fs.existsSync(dir) + if (dirExists) return fs.linkSync(srcpath, dstpath) + mkdir.mkdirsSync(dir) + + return fs.linkSync(srcpath, dstpath) +} + +module.exports = { + createLink: u(createLink), + createLinkSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink-paths.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink-paths.js new file mode 100644 index 0000000000..33cd76000e --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink-paths.js @@ -0,0 +1,99 @@ +'use strict' + +const path = require('path') +const fs = require('graceful-fs') +const pathExists = require('../path-exists').pathExists + +/** + * Function that returns two types of paths, one relative to symlink, and one + * relative to the current working directory. Checks if path is absolute or + * relative. If the path is relative, this function checks if the path is + * relative to symlink or relative to current working directory. This is an + * initiative to find a smarter `srcpath` to supply when building symlinks. + * This allows you to determine which path to use out of one of three possible + * types of source paths. The first is an absolute path. This is detected by + * `path.isAbsolute()`. When an absolute path is provided, it is checked to + * see if it exists. If it does it's used, if not an error is returned + * (callback)/ thrown (sync). The other two options for `srcpath` are a + * relative url. By default Node's `fs.symlink` works by creating a symlink + * using `dstpath` and expects the `srcpath` to be relative to the newly + * created symlink. If you provide a `srcpath` that does not exist on the file + * system it results in a broken symlink. To minimize this, the function + * checks to see if the 'relative to symlink' source file exists, and if it + * does it will use it. If it does not, it checks if there's a file that + * exists that is relative to the current working directory, if does its used. + * This preserves the expectations of the original fs.symlink spec and adds + * the ability to pass in `relative to current working direcotry` paths. + */ + +function symlinkPaths (srcpath, dstpath, callback) { + if (path.isAbsolute(srcpath)) { + return fs.lstat(srcpath, (err) => { + if (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + return callback(err) + } + return callback(null, { + toCwd: srcpath, + toDst: srcpath + }) + }) + } else { + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) + return pathExists(relativeToDst, (err, exists) => { + if (err) return callback(err) + if (exists) { + return callback(null, { + toCwd: relativeToDst, + toDst: srcpath + }) + } else { + return fs.lstat(srcpath, (err) => { + if (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + return callback(err) + } + return callback(null, { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + }) + }) + } + }) + } +} + +function symlinkPathsSync (srcpath, dstpath) { + let exists + if (path.isAbsolute(srcpath)) { + exists = fs.existsSync(srcpath) + if (!exists) throw new Error('absolute srcpath does not exist') + return { + toCwd: srcpath, + toDst: srcpath + } + } else { + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) + exists = fs.existsSync(relativeToDst) + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath + } + } else { + exists = fs.existsSync(srcpath) + if (!exists) throw new Error('relative srcpath does not exist') + return { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + } + } + } +} + +module.exports = { + symlinkPaths, + symlinkPathsSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink-type.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink-type.js new file mode 100644 index 0000000000..42dc0ce753 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink-type.js @@ -0,0 +1,31 @@ +'use strict' + +const fs = require('graceful-fs') + +function symlinkType (srcpath, type, callback) { + callback = (typeof type === 'function') ? type : callback + type = (typeof type === 'function') ? false : type + if (type) return callback(null, type) + fs.lstat(srcpath, (err, stats) => { + if (err) return callback(null, 'file') + type = (stats && stats.isDirectory()) ? 'dir' : 'file' + callback(null, type) + }) +} + +function symlinkTypeSync (srcpath, type) { + let stats + + if (type) return type + try { + stats = fs.lstatSync(srcpath) + } catch { + return 'file' + } + return (stats && stats.isDirectory()) ? 'dir' : 'file' +} + +module.exports = { + symlinkType, + symlinkTypeSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink.js new file mode 100644 index 0000000000..fe68b79978 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/ensure/symlink.js @@ -0,0 +1,63 @@ +'use strict' + +const u = require('universalify').fromCallback +const path = require('path') +const fs = require('graceful-fs') +const _mkdirs = require('../mkdirs') +const mkdirs = _mkdirs.mkdirs +const mkdirsSync = _mkdirs.mkdirsSync + +const _symlinkPaths = require('./symlink-paths') +const symlinkPaths = _symlinkPaths.symlinkPaths +const symlinkPathsSync = _symlinkPaths.symlinkPathsSync + +const _symlinkType = require('./symlink-type') +const symlinkType = _symlinkType.symlinkType +const symlinkTypeSync = _symlinkType.symlinkTypeSync + +const pathExists = require('../path-exists').pathExists + +function createSymlink (srcpath, dstpath, type, callback) { + callback = (typeof type === 'function') ? type : callback + type = (typeof type === 'function') ? false : type + + pathExists(dstpath, (err, destinationExists) => { + if (err) return callback(err) + if (destinationExists) return callback(null) + symlinkPaths(srcpath, dstpath, (err, relative) => { + if (err) return callback(err) + srcpath = relative.toDst + symlinkType(relative.toCwd, type, (err, type) => { + if (err) return callback(err) + const dir = path.dirname(dstpath) + pathExists(dir, (err, dirExists) => { + if (err) return callback(err) + if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) + mkdirs(dir, err => { + if (err) return callback(err) + fs.symlink(srcpath, dstpath, type, callback) + }) + }) + }) + }) + }) +} + +function createSymlinkSync (srcpath, dstpath, type) { + const destinationExists = fs.existsSync(dstpath) + if (destinationExists) return undefined + + const relative = symlinkPathsSync(srcpath, dstpath) + srcpath = relative.toDst + type = symlinkTypeSync(relative.toCwd, type) + const dir = path.dirname(dstpath) + const exists = fs.existsSync(dir) + if (exists) return fs.symlinkSync(srcpath, dstpath, type) + mkdirsSync(dir) + return fs.symlinkSync(srcpath, dstpath, type) +} + +module.exports = { + createSymlink: u(createSymlink), + createSymlinkSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/fs/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/fs/index.js new file mode 100644 index 0000000000..101aae9b66 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/fs/index.js @@ -0,0 +1,128 @@ +'use strict' +// This is adapted from https://github.com/normalize/mz +// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors +const u = require('universalify').fromCallback +const fs = require('graceful-fs') + +const api = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'close', + 'copyFile', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'lchmod', + 'lchown', + 'link', + 'lstat', + 'mkdir', + 'mkdtemp', + 'open', + 'opendir', + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rmdir', + 'stat', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'writeFile' +].filter(key => { + // Some commands are not available on some systems. Ex: + // fs.opendir was added in Node.js v12.12.0 + // fs.lchown is not available on at least some Linux + return typeof fs[key] === 'function' +}) + +// Export all keys: +Object.keys(fs).forEach(key => { + if (key === 'promises') { + // fs.promises is a getter property that triggers ExperimentalWarning + // Don't re-export it here, the getter is defined in "lib/index.js" + return + } + exports[key] = fs[key] +}) + +// Universalify async methods: +api.forEach(method => { + exports[method] = u(fs[method]) +}) + +// We differ from mz/fs in that we still ship the old, broken, fs.exists() +// since we are a drop-in replacement for the native module +exports.exists = function (filename, callback) { + if (typeof callback === 'function') { + return fs.exists(filename, callback) + } + return new Promise(resolve => { + return fs.exists(filename, resolve) + }) +} + +// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args + +exports.read = function (fd, buffer, offset, length, position, callback) { + if (typeof callback === 'function') { + return fs.read(fd, buffer, offset, length, position, callback) + } + return new Promise((resolve, reject) => { + fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { + if (err) return reject(err) + resolve({ bytesRead, buffer }) + }) + }) +} + +// Function signature can be +// fs.write(fd, buffer[, offset[, length[, position]]], callback) +// OR +// fs.write(fd, string[, position[, encoding]], callback) +// We need to handle both cases, so we use ...args +exports.write = function (fd, buffer, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.write(fd, buffer, ...args) + } + + return new Promise((resolve, reject) => { + fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { + if (err) return reject(err) + resolve({ bytesWritten, buffer }) + }) + }) +} + +// fs.writev only available in Node v12.9.0+ +if (typeof fs.writev === 'function') { + // Function signature is + // s.writev(fd, buffers[, position], callback) + // We need to handle the optional arg, so we use ...args + exports.writev = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.writev(fd, buffers, ...args) + } + + return new Promise((resolve, reject) => { + fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { + if (err) return reject(err) + resolve({ bytesWritten, buffers }) + }) + }) + } +} + +// fs.realpath.native only available in Node v9.2+ +if (typeof fs.realpath.native === 'function') { + exports.realpath.native = u(fs.realpath.native) +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/index.js new file mode 100644 index 0000000000..d9468e699c --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/index.js @@ -0,0 +1,27 @@ +'use strict' + +module.exports = { + // Export promiseified graceful-fs: + ...require('./fs'), + // Export extra methods: + ...require('./copy-sync'), + ...require('./copy'), + ...require('./empty'), + ...require('./ensure'), + ...require('./json'), + ...require('./mkdirs'), + ...require('./move-sync'), + ...require('./move'), + ...require('./output'), + ...require('./path-exists'), + ...require('./remove') +} + +// Export fs.promises as a getter property so that we don't trigger +// ExperimentalWarning before fs.promises is actually accessed. +const fs = require('fs') +if (Object.getOwnPropertyDescriptor(fs, 'promises')) { + Object.defineProperty(module.exports, 'promises', { + get () { return fs.promises } + }) +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/index.js new file mode 100644 index 0000000000..900126ad0b --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/index.js @@ -0,0 +1,16 @@ +'use strict' + +const u = require('universalify').fromPromise +const jsonFile = require('./jsonfile') + +jsonFile.outputJson = u(require('./output-json')) +jsonFile.outputJsonSync = require('./output-json-sync') +// aliases +jsonFile.outputJSON = jsonFile.outputJson +jsonFile.outputJSONSync = jsonFile.outputJsonSync +jsonFile.writeJSON = jsonFile.writeJson +jsonFile.writeJSONSync = jsonFile.writeJsonSync +jsonFile.readJSON = jsonFile.readJson +jsonFile.readJSONSync = jsonFile.readJsonSync + +module.exports = jsonFile diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/jsonfile.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/jsonfile.js new file mode 100644 index 0000000000..f11d34d623 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/jsonfile.js @@ -0,0 +1,11 @@ +'use strict' + +const jsonFile = require('jsonfile') + +module.exports = { + // jsonfile exports + readJson: jsonFile.readFile, + readJsonSync: jsonFile.readFileSync, + writeJson: jsonFile.writeFile, + writeJsonSync: jsonFile.writeFileSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/output-json-sync.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/output-json-sync.js new file mode 100644 index 0000000000..f76b4744ce --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/output-json-sync.js @@ -0,0 +1,12 @@ +'use strict' + +const { stringify } = require('jsonfile/utils') +const { outputFileSync } = require('../output') + +function outputJsonSync (file, data, options) { + const str = stringify(data, options) + + outputFileSync(file, str, options) +} + +module.exports = outputJsonSync diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/output-json.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/output-json.js new file mode 100644 index 0000000000..0fc668977f --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/json/output-json.js @@ -0,0 +1,12 @@ +'use strict' + +const { stringify } = require('jsonfile/utils') +const { outputFile } = require('../output') + +async function outputJson (file, data, options = {}) { + const str = stringify(data, options) + + await outputFile(file, str, options) +} + +module.exports = outputJson diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/mkdirs/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/mkdirs/index.js new file mode 100644 index 0000000000..9edecee08f --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/mkdirs/index.js @@ -0,0 +1,14 @@ +'use strict' +const u = require('universalify').fromPromise +const { makeDir: _makeDir, makeDirSync } = require('./make-dir') +const makeDir = u(_makeDir) + +module.exports = { + mkdirs: makeDir, + mkdirsSync: makeDirSync, + // alias + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/mkdirs/make-dir.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/mkdirs/make-dir.js new file mode 100644 index 0000000000..f17ecffbcc --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/mkdirs/make-dir.js @@ -0,0 +1,142 @@ +// Adapted from https://github.com/sindresorhus/make-dir +// Copyright (c) Sindre Sorhus (sindresorhus.com) +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict' +const fs = require('../fs') +const path = require('path') +const atLeastNode = require('at-least-node') + +const useNativeRecursiveOption = atLeastNode('10.12.0') + +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +const checkPath = pth => { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) + + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`) + error.code = 'EINVAL' + throw error + } + } +} + +const processOptions = options => { + // Must be defined here so we get fresh process.umask() + const defaults = { mode: 0o777 & (~process.umask()) } + if (typeof options === 'number') options = { mode: options } + return { ...defaults, ...options } +} + +const permissionError = pth => { + // This replicates the exception of `fs.mkdir` with native the + // `recusive` option when run on an invalid drive under Windows. + const error = new Error(`operation not permitted, mkdir '${pth}'`) + error.code = 'EPERM' + error.errno = -4048 + error.path = pth + error.syscall = 'mkdir' + return error +} + +module.exports.makeDir = async (input, options) => { + checkPath(input) + options = processOptions(options) + + if (useNativeRecursiveOption) { + const pth = path.resolve(input) + + return fs.mkdir(pth, { + mode: options.mode, + recursive: true + }) + } + + const make = async pth => { + try { + await fs.mkdir(pth, options.mode) + } catch (error) { + if (error.code === 'EPERM') { + throw error + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth) + } + + if (error.message.includes('null bytes')) { + throw error + } + + await make(path.dirname(pth)) + return make(pth) + } + + try { + const stats = await fs.stat(pth) + if (!stats.isDirectory()) { + // This error is never exposed to the user + // it is caught below, and the original error is thrown + throw new Error('The path is not a directory') + } + } catch { + throw error + } + } + } + + return make(path.resolve(input)) +} + +module.exports.makeDirSync = (input, options) => { + checkPath(input) + options = processOptions(options) + + if (useNativeRecursiveOption) { + const pth = path.resolve(input) + + return fs.mkdirSync(pth, { + mode: options.mode, + recursive: true + }) + } + + const make = pth => { + try { + fs.mkdirSync(pth, options.mode) + } catch (error) { + if (error.code === 'EPERM') { + throw error + } + + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth) + } + + if (error.message.includes('null bytes')) { + throw error + } + + make(path.dirname(pth)) + return make(pth) + } + + try { + if (!fs.statSync(pth).isDirectory()) { + // This error is never exposed to the user + // it is caught below, and the original error is thrown + throw new Error('The path is not a directory') + } + } catch { + throw error + } + } + } + + return make(path.resolve(input)) +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move-sync/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move-sync/index.js new file mode 100644 index 0000000000..af90b06b42 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move-sync/index.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = { + moveSync: require('./move-sync') +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move-sync/move-sync.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move-sync/move-sync.js new file mode 100644 index 0000000000..20f910cc25 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move-sync/move-sync.js @@ -0,0 +1,47 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const copySync = require('../copy-sync').copySync +const removeSync = require('../remove').removeSync +const mkdirpSync = require('../mkdirs').mkdirpSync +const stat = require('../util/stat') + +function moveSync (src, dest, opts) { + opts = opts || {} + const overwrite = opts.overwrite || opts.clobber || false + + const { srcStat } = stat.checkPathsSync(src, dest, 'move') + stat.checkParentPathsSync(src, srcStat, dest, 'move') + mkdirpSync(path.dirname(dest)) + return doRename(src, dest, overwrite) +} + +function doRename (src, dest, overwrite) { + if (overwrite) { + removeSync(dest) + return rename(src, dest, overwrite) + } + if (fs.existsSync(dest)) throw new Error('dest already exists.') + return rename(src, dest, overwrite) +} + +function rename (src, dest, overwrite) { + try { + fs.renameSync(src, dest) + } catch (err) { + if (err.code !== 'EXDEV') throw err + return moveAcrossDevice(src, dest, overwrite) + } +} + +function moveAcrossDevice (src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true + } + copySync(src, dest, opts) + return removeSync(src) +} + +module.exports = moveSync diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move/index.js new file mode 100644 index 0000000000..3785345bd2 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move/index.js @@ -0,0 +1,6 @@ +'use strict' + +const u = require('universalify').fromCallback +module.exports = { + move: u(require('./move')) +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move/move.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move/move.js new file mode 100644 index 0000000000..fa3ea618a2 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/move/move.js @@ -0,0 +1,65 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const copy = require('../copy').copy +const remove = require('../remove').remove +const mkdirp = require('../mkdirs').mkdirp +const pathExists = require('../path-exists').pathExists +const stat = require('../util/stat') + +function move (src, dest, opts, cb) { + if (typeof opts === 'function') { + cb = opts + opts = {} + } + + const overwrite = opts.overwrite || opts.clobber || false + + stat.checkPaths(src, dest, 'move', (err, stats) => { + if (err) return cb(err) + const { srcStat } = stats + stat.checkParentPaths(src, srcStat, dest, 'move', err => { + if (err) return cb(err) + mkdirp(path.dirname(dest), err => { + if (err) return cb(err) + return doRename(src, dest, overwrite, cb) + }) + }) + }) +} + +function doRename (src, dest, overwrite, cb) { + if (overwrite) { + return remove(dest, err => { + if (err) return cb(err) + return rename(src, dest, overwrite, cb) + }) + } + pathExists(dest, (err, destExists) => { + if (err) return cb(err) + if (destExists) return cb(new Error('dest already exists.')) + return rename(src, dest, overwrite, cb) + }) +} + +function rename (src, dest, overwrite, cb) { + fs.rename(src, dest, err => { + if (!err) return cb() + if (err.code !== 'EXDEV') return cb(err) + return moveAcrossDevice(src, dest, overwrite, cb) + }) +} + +function moveAcrossDevice (src, dest, overwrite, cb) { + const opts = { + overwrite, + errorOnExist: true + } + copy(src, dest, opts, err => { + if (err) return cb(err) + return remove(src, cb) + }) +} + +module.exports = move diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/output/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/output/index.js new file mode 100644 index 0000000000..92297ca3a6 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/output/index.js @@ -0,0 +1,40 @@ +'use strict' + +const u = require('universalify').fromCallback +const fs = require('graceful-fs') +const path = require('path') +const mkdir = require('../mkdirs') +const pathExists = require('../path-exists').pathExists + +function outputFile (file, data, encoding, callback) { + if (typeof encoding === 'function') { + callback = encoding + encoding = 'utf8' + } + + const dir = path.dirname(file) + pathExists(dir, (err, itDoes) => { + if (err) return callback(err) + if (itDoes) return fs.writeFile(file, data, encoding, callback) + + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + + fs.writeFile(file, data, encoding, callback) + }) + }) +} + +function outputFileSync (file, ...args) { + const dir = path.dirname(file) + if (fs.existsSync(dir)) { + return fs.writeFileSync(file, ...args) + } + mkdir.mkdirsSync(dir) + fs.writeFileSync(file, ...args) +} + +module.exports = { + outputFile: u(outputFile), + outputFileSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/path-exists/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/path-exists/index.js new file mode 100644 index 0000000000..ddd9bc718f --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/path-exists/index.js @@ -0,0 +1,12 @@ +'use strict' +const u = require('universalify').fromPromise +const fs = require('../fs') + +function pathExists (path) { + return fs.access(path).then(() => true).catch(() => false) +} + +module.exports = { + pathExists: u(pathExists), + pathExistsSync: fs.existsSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/remove/index.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/remove/index.js new file mode 100644 index 0000000000..cee5340077 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/remove/index.js @@ -0,0 +1,9 @@ +'use strict' + +const u = require('universalify').fromCallback +const rimraf = require('./rimraf') + +module.exports = { + remove: u(rimraf), + removeSync: rimraf.sync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/remove/rimraf.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/remove/rimraf.js new file mode 100644 index 0000000000..1e44c12887 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/remove/rimraf.js @@ -0,0 +1,314 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const assert = require('assert') + +const isWindows = (process.platform === 'win32') + +function defaults (options) { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(m => { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 +} + +function rimraf (p, options, cb) { + let busyTries = 0 + + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') + assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') + + defaults(options) + + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && + busyTries < options.maxBusyTries) { + busyTries++ + const time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), time) + } + + // already gone + if (er.code === 'ENOENT') er = null + } + + cb(er) + }) +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === 'ENOENT') { + return cb(null) + } + + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === 'EPERM' && isWindows) { + return fixWinEPERM(p, options, er, cb) + } + + if (st && st.isDirectory()) { + return rmdir(p, options, er, cb) + } + + options.unlink(p, er => { + if (er) { + if (er.code === 'ENOENT') { + return cb(null) + } + if (er.code === 'EPERM') { + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + } + if (er.code === 'EISDIR') { + return rmdir(p, options, er, cb) + } + } + return cb(er) + }) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) { + assert(er instanceof Error) + } + + options.chmod(p, 0o666, er2 => { + if (er2) { + cb(er2.code === 'ENOENT' ? null : er) + } else { + options.stat(p, (er3, stats) => { + if (er3) { + cb(er3.code === 'ENOENT' ? null : er) + } else if (stats.isDirectory()) { + rmdir(p, options, er, cb) + } else { + options.unlink(p, cb) + } + }) + } + }) +} + +function fixWinEPERMSync (p, options, er) { + let stats + + assert(p) + assert(options) + if (er) { + assert(er instanceof Error) + } + + try { + options.chmodSync(p, 0o666) + } catch (er2) { + if (er2.code === 'ENOENT') { + return + } else { + throw er + } + } + + try { + stats = options.statSync(p) + } catch (er3) { + if (er3.code === 'ENOENT') { + return + } else { + throw er + } + } + + if (stats.isDirectory()) { + rmdirSync(p, options, er) + } else { + options.unlinkSync(p) + } +} + +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) { + assert(originalEr instanceof Error) + } + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { + rmkids(p, options, cb) + } else if (er && er.code === 'ENOTDIR') { + cb(originalEr) + } else { + cb(er) + } + }) +} + +function rmkids (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, (er, files) => { + if (er) return cb(er) + + let n = files.length + let errState + + if (n === 0) return options.rmdir(p, cb) + + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) { + return + } + if (er) return cb(errState = er) + if (--n === 0) { + options.rmdir(p, cb) + } + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + let st + + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') + + try { + st = options.lstatSync(p) + } catch (er) { + if (er.code === 'ENOENT') { + return + } + + // Windows can EPERM on stat. Life is suffering. + if (er.code === 'EPERM' && isWindows) { + fixWinEPERMSync(p, options, er) + } + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) { + rmdirSync(p, options, null) + } else { + options.unlinkSync(p) + } + } catch (er) { + if (er.code === 'ENOENT') { + return + } else if (er.code === 'EPERM') { + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + } else if (er.code !== 'EISDIR') { + throw er + } + rmdirSync(p, options, er) + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) { + assert(originalEr instanceof Error) + } + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === 'ENOTDIR') { + throw originalEr + } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { + rmkidsSync(p, options) + } else if (er.code !== 'ENOENT') { + throw er + } + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) + + if (isWindows) { + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + const startTime = Date.now() + do { + try { + const ret = options.rmdirSync(p, options) + return ret + } catch {} + } while (Date.now() - startTime < 500) // give up after 500ms + } else { + const ret = options.rmdirSync(p, options) + return ret + } +} + +module.exports = rimraf +rimraf.sync = rimrafSync diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/util/stat.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/util/stat.js new file mode 100644 index 0000000000..0b1c1b0963 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/util/stat.js @@ -0,0 +1,139 @@ +'use strict' + +const fs = require('../fs') +const path = require('path') +const util = require('util') +const atLeastNode = require('at-least-node') + +const nodeSupportsBigInt = atLeastNode('10.5.0') +const stat = (file) => nodeSupportsBigInt ? fs.stat(file, { bigint: true }) : fs.stat(file) +const statSync = (file) => nodeSupportsBigInt ? fs.statSync(file, { bigint: true }) : fs.statSync(file) + +function getStats (src, dest) { + return Promise.all([ + stat(src), + stat(dest).catch(err => { + if (err.code === 'ENOENT') return null + throw err + }) + ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) +} + +function getStatsSync (src, dest) { + let destStat + const srcStat = statSync(src) + try { + destStat = statSync(dest) + } catch (err) { + if (err.code === 'ENOENT') return { srcStat, destStat: null } + throw err + } + return { srcStat, destStat } +} + +function checkPaths (src, dest, funcName, cb) { + util.callbackify(getStats)(src, dest, (err, stats) => { + if (err) return cb(err) + const { srcStat, destStat } = stats + if (destStat && areIdentical(srcStat, destStat)) { + return cb(new Error('Source and destination must not be the same.')) + } + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + return cb(new Error(errMsg(src, dest, funcName))) + } + return cb(null, { srcStat, destStat }) + }) +} + +function checkPathsSync (src, dest, funcName) { + const { srcStat, destStat } = getStatsSync(src, dest) + if (destStat && areIdentical(srcStat, destStat)) { + throw new Error('Source and destination must not be the same.') + } + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) + } + return { srcStat, destStat } +} + +// recursively check if dest parent is a subdirectory of src. +// It works for all file types including symlinks since it +// checks the src and dest inodes. It starts from the deepest +// parent and stops once it reaches the src parent or the root path. +function checkParentPaths (src, srcStat, dest, funcName, cb) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() + const callback = (err, destStat) => { + if (err) { + if (err.code === 'ENOENT') return cb() + return cb(err) + } + if (areIdentical(srcStat, destStat)) { + return cb(new Error(errMsg(src, dest, funcName))) + } + return checkParentPaths(src, srcStat, destParent, funcName, cb) + } + if (nodeSupportsBigInt) fs.stat(destParent, { bigint: true }, callback) + else fs.stat(destParent, callback) +} + +function checkParentPathsSync (src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return + let destStat + try { + destStat = statSync(destParent) + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } + return checkParentPathsSync(src, srcStat, destParent, funcName) +} + +function areIdentical (srcStat, destStat) { + if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { + if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) { + // definitive answer + return true + } + // Use additional heuristics if we can't use 'bigint'. + // Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER + // See issue 657 + if (destStat.size === srcStat.size && + destStat.mode === srcStat.mode && + destStat.nlink === srcStat.nlink && + destStat.atimeMs === srcStat.atimeMs && + destStat.mtimeMs === srcStat.mtimeMs && + destStat.ctimeMs === srcStat.ctimeMs && + destStat.birthtimeMs === srcStat.birthtimeMs) { + // heuristic answer + return true + } + } + return false +} + +// return true if dest is a subdir of src, otherwise false. +// It only checks the path strings. +function isSrcSubdir (src, dest) { + const srcArr = path.resolve(src).split(path.sep).filter(i => i) + const destArr = path.resolve(dest).split(path.sep).filter(i => i) + return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) +} + +function errMsg (src, dest, funcName) { + return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` +} + +module.exports = { + checkPaths, + checkPathsSync, + checkParentPaths, + checkParentPathsSync, + isSrcSubdir +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/util/utimes.js b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/util/utimes.js new file mode 100644 index 0000000000..75395deff4 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/lib/util/utimes.js @@ -0,0 +1,26 @@ +'use strict' + +const fs = require('graceful-fs') + +function utimesMillis (path, atime, mtime, callback) { + // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) + fs.open(path, 'r+', (err, fd) => { + if (err) return callback(err) + fs.futimes(fd, atime, mtime, futimesErr => { + fs.close(fd, closeErr => { + if (callback) callback(futimesErr || closeErr) + }) + }) + }) +} + +function utimesMillisSync (path, atime, mtime) { + const fd = fs.openSync(path, 'r+') + fs.futimesSync(fd, atime, mtime) + return fs.closeSync(fd) +} + +module.exports = { + utimesMillis, + utimesMillisSync +} diff --git a/tests/corpus/fs-extra-package/node_modules/fs-extra/package.json b/tests/corpus/fs-extra-package/node_modules/fs-extra/package.json new file mode 100644 index 0000000000..1f251f183f --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/fs-extra/package.json @@ -0,0 +1,70 @@ +{ + "name": "fs-extra", + "version": "9.0.0", + "description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as mkdir -p, cp -r, and rm -rf.", + "engines": { + "node": ">=10" + }, + "homepage": "https://github.com/jprichardson/node-fs-extra", + "repository": { + "type": "git", + "url": "https://github.com/jprichardson/node-fs-extra" + }, + "keywords": [ + "fs", + "file", + "file system", + "copy", + "directory", + "extra", + "mkdirp", + "mkdir", + "mkdirs", + "recursive", + "json", + "read", + "write", + "extra", + "delete", + "remove", + "touch", + "create", + "text", + "output", + "move", + "promise" + ], + "author": "JP Richardson ", + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^1.0.0" + }, + "devDependencies": { + "coveralls": "^3.0.0", + "klaw": "^2.1.1", + "klaw-sync": "^3.0.2", + "minimist": "^1.1.1", + "mocha": "^5.0.5", + "nyc": "^15.0.0", + "proxyquire": "^2.0.1", + "read-dir-files": "^0.1.1", + "standard": "^14.1.0" + }, + "main": "./lib/index.js", + "files": [ + "lib/", + "!lib/**/__tests__/" + ], + "scripts": { + "full-ci": "npm run lint && npm run coverage", + "coverage": "nyc -r lcovonly npm run unit", + "coveralls": "coveralls < coverage/lcov.info", + "lint": "standard", + "test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha", + "test": "npm run lint && npm run unit", + "unit": "node test.js" + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/graceful-fs/LICENSE b/tests/corpus/fs-extra-package/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000000..e906a25acf --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/tests/corpus/fs-extra-package/node_modules/graceful-fs/clone.js b/tests/corpus/fs-extra-package/node_modules/graceful-fs/clone.js new file mode 100644 index 0000000000..dff3cc8c50 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/graceful-fs/clone.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} diff --git a/tests/corpus/fs-extra-package/node_modules/graceful-fs/graceful-fs.js b/tests/corpus/fs-extra-package/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000000..8d5b89e4fa --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,448 @@ +var fs = require('fs') +var polyfills = require('./polyfills.js') +var legacy = require('./legacy-streams.js') +var clone = require('./clone.js') + +var util = require('util') + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + require('assert').equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } + + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) + } + } + } + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} + +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} + +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + + if (fs[gracefulQueue].length === 0) + return + + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/graceful-fs/legacy-streams.js b/tests/corpus/fs-extra-package/node_modules/graceful-fs/legacy-streams.js new file mode 100644 index 0000000000..d617b50fc0 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/graceful-fs/legacy-streams.js @@ -0,0 +1,118 @@ +var Stream = require('stream').Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/graceful-fs/package.json b/tests/corpus/fs-extra-package/node_modules/graceful-fs/package.json new file mode 100644 index 0000000000..87babf0248 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/graceful-fs/package.json @@ -0,0 +1,53 @@ +{ + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "4.2.11", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/node-graceful-fs" + }, + "main": "graceful-fs.js", + "directories": { + "test": "test" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags", + "test": "nyc --silent node test.js | tap -c -", + "posttest": "nyc report" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "devDependencies": { + "import-fresh": "^2.0.0", + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^16.3.4" + }, + "files": [ + "fs.js", + "graceful-fs.js", + "legacy-streams.js", + "polyfills.js", + "clone.js" + ], + "tap": { + "reporter": "classic" + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/graceful-fs/polyfills.js b/tests/corpus/fs-extra-package/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000000..453f1a9e70 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,355 @@ +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} + +module.exports = patch + +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/LICENSE b/tests/corpus/fs-extra-package/node_modules/jsonfile/LICENSE new file mode 100644 index 0000000000..cb7e807b9b --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/LICENSE @@ -0,0 +1,15 @@ +(The MIT License) + +Copyright (c) 2012-2015, JP Richardson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files +(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, + merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/index.js b/tests/corpus/fs-extra-package/node_modules/jsonfile/index.js new file mode 100644 index 0000000000..0582868f1b --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/index.js @@ -0,0 +1,88 @@ +let _fs +try { + _fs = require('graceful-fs') +} catch (_) { + _fs = require('fs') +} +const universalify = require('universalify') +const { stringify, stripBom } = require('./utils') + +async function _readFile (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } + + const fs = options.fs || _fs + + const shouldThrow = 'throws' in options ? options.throws : true + + let data = await universalify.fromCallback(fs.readFile)(file, options) + + data = stripBom(data) + + let obj + try { + obj = JSON.parse(data, options ? options.reviver : null) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}` + throw err + } else { + return null + } + } + + return obj +} + +const readFile = universalify.fromPromise(_readFile) + +function readFileSync (file, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } + + const fs = options.fs || _fs + + const shouldThrow = 'throws' in options ? options.throws : true + + try { + let content = fs.readFileSync(file, options) + content = stripBom(content) + return JSON.parse(content, options.reviver) + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}` + throw err + } else { + return null + } + } +} + +async function _writeFile (file, obj, options = {}) { + const fs = options.fs || _fs + + const str = stringify(obj, options) + + await universalify.fromCallback(fs.writeFile)(file, str, options) +} + +const writeFile = universalify.fromPromise(_writeFile) + +function writeFileSync (file, obj, options = {}) { + const fs = options.fs || _fs + + const str = stringify(obj, options) + // not sure if fs.writeFileSync returns anything, but just in case + return fs.writeFileSync(file, str, options) +} + +const jsonfile = { + readFile, + readFileSync, + writeFile, + writeFileSync +} + +module.exports = jsonfile diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/LICENSE b/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/LICENSE new file mode 100644 index 0000000000..514e84e648 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2017, Ryan Zimmerman + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the 'Software'), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/index.js b/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/index.js new file mode 100644 index 0000000000..233beac75c --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/index.js @@ -0,0 +1,24 @@ +'use strict' + +exports.fromCallback = function (fn) { + return Object.defineProperty(function (...args) { + if (typeof args[args.length - 1] === 'function') fn.apply(this, args) + else { + return new Promise((resolve, reject) => { + args.push((err, res) => (err != null) ? reject(err) : resolve(res)) + fn.apply(this, args) + }) + } + }, 'name', { value: fn.name }) +} + +exports.fromPromise = function (fn) { + return Object.defineProperty(function (...args) { + const cb = args[args.length - 1] + if (typeof cb !== 'function') return fn.apply(this, args) + else { + args.pop() + fn.apply(this, args).then(r => cb(null, r), cb) + } + }, 'name', { value: fn.name }) +} diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/package.json b/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/package.json new file mode 100644 index 0000000000..d60fccb505 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/node_modules/universalify/package.json @@ -0,0 +1,34 @@ +{ + "name": "universalify", + "version": "2.0.1", + "description": "Make a callback- or promise-based function support both promises and callbacks.", + "keywords": [ + "callback", + "native", + "promise" + ], + "homepage": "https://github.com/RyanZim/universalify#readme", + "bugs": "https://github.com/RyanZim/universalify/issues", + "license": "MIT", + "author": "Ryan Zimmerman ", + "files": [ + "index.js" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/RyanZim/universalify.git" + }, + "scripts": { + "test": "standard && nyc --reporter text --reporter lcovonly tape test/*.js | colortape" + }, + "devDependencies": { + "colortape": "^0.1.2", + "coveralls": "^3.0.1", + "nyc": "^15.0.0", + "standard": "^14.3.1", + "tape": "^5.0.1" + }, + "engines": { + "node": ">= 10.0.0" + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/package.json b/tests/corpus/fs-extra-package/node_modules/jsonfile/package.json new file mode 100644 index 0000000000..4d01eb1d78 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/package.json @@ -0,0 +1,40 @@ +{ + "name": "jsonfile", + "version": "6.1.0", + "description": "Easily read/write JSON files.", + "repository": { + "type": "git", + "url": "git@github.com:jprichardson/node-jsonfile.git" + }, + "keywords": [ + "read", + "write", + "file", + "json", + "fs", + "fs-extra" + ], + "author": "JP Richardson ", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + }, + "devDependencies": { + "mocha": "^8.2.0", + "rimraf": "^2.4.0", + "standard": "^16.0.1" + }, + "main": "index.js", + "files": [ + "index.js", + "utils.js" + ], + "scripts": { + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "mocha" + } +} diff --git a/tests/corpus/fs-extra-package/node_modules/jsonfile/utils.js b/tests/corpus/fs-extra-package/node_modules/jsonfile/utils.js new file mode 100644 index 0000000000..b5ff48e5e0 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/jsonfile/utils.js @@ -0,0 +1,14 @@ +function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) { + const EOF = finalEOL ? EOL : '' + const str = JSON.stringify(obj, replacer, spaces) + + return str.replace(/\n/g, EOL) + EOF +} + +function stripBom (content) { + // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified + if (Buffer.isBuffer(content)) content = content.toString('utf8') + return content.replace(/^\uFEFF/, '') +} + +module.exports = { stringify, stripBom } diff --git a/tests/corpus/fs-extra-package/node_modules/universalify/LICENSE b/tests/corpus/fs-extra-package/node_modules/universalify/LICENSE new file mode 100644 index 0000000000..514e84e648 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/universalify/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2017, Ryan Zimmerman + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the 'Software'), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/corpus/fs-extra-package/node_modules/universalify/index.js b/tests/corpus/fs-extra-package/node_modules/universalify/index.js new file mode 100644 index 0000000000..e7b5712ea2 --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/universalify/index.js @@ -0,0 +1,23 @@ +'use strict' + +exports.fromCallback = function (fn) { + return Object.defineProperty(function (...args) { + if (typeof args[args.length - 1] === 'function') fn.apply(this, args) + else { + return new Promise((resolve, reject) => { + fn.apply( + this, + args.concat([(err, res) => err ? reject(err) : resolve(res)]) + ) + }) + } + }, 'name', { value: fn.name }) +} + +exports.fromPromise = function (fn) { + return Object.defineProperty(function (...args) { + const cb = args[args.length - 1] + if (typeof cb !== 'function') return fn.apply(this, args) + else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb) + }, 'name', { value: fn.name }) +} diff --git a/tests/corpus/fs-extra-package/node_modules/universalify/package.json b/tests/corpus/fs-extra-package/node_modules/universalify/package.json new file mode 100644 index 0000000000..4ac07daf3e --- /dev/null +++ b/tests/corpus/fs-extra-package/node_modules/universalify/package.json @@ -0,0 +1,34 @@ +{ + "name": "universalify", + "version": "1.0.0", + "description": "Make a callback- or promise-based function support both promises and callbacks.", + "keywords": [ + "callback", + "native", + "promise" + ], + "homepage": "https://github.com/RyanZim/universalify#readme", + "bugs": "https://github.com/RyanZim/universalify/issues", + "license": "MIT", + "author": "Ryan Zimmerman ", + "files": [ + "index.js" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/RyanZim/universalify.git" + }, + "scripts": { + "test": "standard && nyc tape test/*.js | colortape" + }, + "devDependencies": { + "colortape": "^0.1.2", + "coveralls": "^3.0.1", + "nyc": "^15.0.0", + "standard": "^14.3.1", + "tape": "^4.6.3" + }, + "engines": { + "node": ">= 10.0.0" + } +} diff --git a/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts b/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts new file mode 100644 index 0000000000..c81d26bb57 --- /dev/null +++ b/tests/fixtures/npm/cases/2589-bundled-error-subclass/main.ts @@ -0,0 +1,24 @@ +// A program class extending an error class that a bundled package defines +// inside a lazy __esm initializer (build-utils' NowBuildError shape): `new` +// on the subclass, `instanceof` against both classes, and errors the +// package itself throws. +import { AppError, fail, lazyCode } from "gtesmerror"; + +class TaggedError extends AppError { + tag: string; + constructor(code: string) { + super({ message: `tagged ${code}`, code }); + this.tag = "t"; + } +} + +const e = new TaggedError("X1"); +console.log(e.message, e.code, e.tag, e.hideStackTrace); +console.log(e instanceof AppError, e instanceof Error, e instanceof TaggedError); +try { + fail("BOOM"); +} catch (err) { + console.log(err instanceof AppError, err instanceof TaggedError); + if (err instanceof AppError) console.log(err.code, err.message); +} +console.log(lazyCode()); diff --git a/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts b/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts new file mode 100644 index 0000000000..6b6772f34d --- /dev/null +++ b/tests/fixtures/npm/cases/2590-bundled-fs-extra/main.ts @@ -0,0 +1,9 @@ +// A bundle that embeds fs-extra 9.0.0 (as build-utils does): its fs-extra +// chunk compiles as scriptc's built-in fs-extra, and the package's own +// chunks (graceful-fs, universalify, jsonfile) are never loaded. +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { demo } from "gtfsxbundle"; + +demo(mkdtempSync(join(tmpdir(), "scriptc-bundled-fs-extra-"))).then((result) => console.log(result)); diff --git a/tests/fixtures/npm/node_modules/gtesmerror/dist/index.js b/tests/fixtures/npm/node_modules/gtesmerror/dist/index.js new file mode 100644 index 0000000000..fafd47da12 --- /dev/null +++ b/tests/fixtures/npm/node_modules/gtesmerror/dist/index.js @@ -0,0 +1,76 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/errors.ts +var AppError; +var init_errors = __esm({ + "src/errors.ts"() { + AppError = class extends Error { + code; + hideStackTrace; + constructor({ message, code }) { + super(message); + this.hideStackTrace = true; + this.code = code; + } + }; + } +}); + +// src/fail.ts +var fail_exports = {}; +__export(fail_exports, { + fail: () => fail +}); +function fail(code) { + throw new AppError({ message: `failed: ${code}`, code }); +} +var init_fail = __esm({ + "src/fail.ts"() { + init_errors(); + } +}); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + AppError: () => AppError, + fail: () => fail, + lazyCode: () => lazyCode +}); +module.exports = __toCommonJS(index_exports); +init_errors(); +init_fail(); +function lazyCode() { + const failing = (init_fail(), __toCommonJS(fail_exports)); + try { + failing.fail("LAZY"); + } catch (err) { + return err.message; + } + return "unreachable"; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AppError, + fail, + lazyCode +}); diff --git a/tests/fixtures/npm/node_modules/gtesmerror/index.d.ts b/tests/fixtures/npm/node_modules/gtesmerror/index.d.ts new file mode 100644 index 0000000000..df2abf95b3 --- /dev/null +++ b/tests/fixtures/npm/node_modules/gtesmerror/index.d.ts @@ -0,0 +1,7 @@ +export declare class AppError extends Error { + code: string; + hideStackTrace: boolean; + constructor(options: { message: string; code: string }); +} +export declare function fail(code: string): never; +export declare function lazyCode(): string; diff --git a/tests/fixtures/npm/node_modules/gtesmerror/package.json b/tests/fixtures/npm/node_modules/gtesmerror/package.json new file mode 100644 index 0000000000..2968a3ab14 --- /dev/null +++ b/tests/fixtures/npm/node_modules/gtesmerror/package.json @@ -0,0 +1,7 @@ +{ + "name": "gtesmerror", + "version": "1.0.0", + "description": "real esbuild 0.27 output (--bundle --platform=node --format=cjs) of a TypeScript package whose error class over Error is defined inside a lazy __esm initializer (one module require()s it)", + "main": "dist/index.js", + "types": "index.d.ts" +} diff --git a/tests/fixtures/npm/node_modules/gtfsxbundle/dist/index.js b/tests/fixtures/npm/node_modules/gtfsxbundle/dist/index.js new file mode 100644 index 0000000000..343f924f55 --- /dev/null +++ b/tests/fixtures/npm/node_modules/gtfsxbundle/dist/index.js @@ -0,0 +1,2630 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/.pnpm/universalify@1.0.0/node_modules/universalify/index.js +var require_universalify = __commonJS({ + "node_modules/.pnpm/universalify@1.0.0/node_modules/universalify/index.js"(exports2) { + "use strict"; + exports2.fromCallback = function(fn) { + return Object.defineProperty(function(...args) { + if (typeof args[args.length - 1] === "function") fn.apply(this, args); + else { + return new Promise((resolve, reject) => { + fn.apply( + this, + args.concat([(err, res) => err ? reject(err) : resolve(res)]) + ); + }); + } + }, "name", { value: fn.name }); + }; + exports2.fromPromise = function(fn) { + return Object.defineProperty(function(...args) { + const cb = args[args.length - 1]; + if (typeof cb !== "function") return fn.apply(this, args); + else fn.apply(this, args.slice(0, -1)).then((r) => cb(null, r), cb); + }, "name", { value: fn.name }); + }; + } +}); + +// node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js +var require_polyfills = __commonJS({ + "node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js"(exports2, module2) { + var constants = require("constants"); + var origCwd = process.cwd; + var cwd = null; + var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform; + process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process); + return cwd; + }; + try { + process.cwd(); + } catch (er) { + } + if (typeof process.chdir === "function") { + chdir = process.chdir; + process.chdir = function(d) { + cwd = null; + chdir.call(process, d); + }; + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir); + } + var chdir; + module2.exports = patch; + function patch(fs2) { + if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs2); + } + if (!fs2.lutimes) { + patchLutimes(fs2); + } + fs2.chown = chownFix(fs2.chown); + fs2.fchown = chownFix(fs2.fchown); + fs2.lchown = chownFix(fs2.lchown); + fs2.chmod = chmodFix(fs2.chmod); + fs2.fchmod = chmodFix(fs2.fchmod); + fs2.lchmod = chmodFix(fs2.lchmod); + fs2.chownSync = chownFixSync(fs2.chownSync); + fs2.fchownSync = chownFixSync(fs2.fchownSync); + fs2.lchownSync = chownFixSync(fs2.lchownSync); + fs2.chmodSync = chmodFixSync(fs2.chmodSync); + fs2.fchmodSync = chmodFixSync(fs2.fchmodSync); + fs2.lchmodSync = chmodFixSync(fs2.lchmodSync); + fs2.stat = statFix(fs2.stat); + fs2.fstat = statFix(fs2.fstat); + fs2.lstat = statFix(fs2.lstat); + fs2.statSync = statFixSync(fs2.statSync); + fs2.fstatSync = statFixSync(fs2.fstatSync); + fs2.lstatSync = statFixSync(fs2.lstatSync); + if (fs2.chmod && !fs2.lchmod) { + fs2.lchmod = function(path, mode, cb) { + if (cb) process.nextTick(cb); + }; + fs2.lchmodSync = function() { + }; + } + if (fs2.chown && !fs2.lchown) { + fs2.lchown = function(path, uid, gid, cb) { + if (cb) process.nextTick(cb); + }; + fs2.lchownSync = function() { + }; + } + if (platform === "win32") { + fs2.rename = typeof fs2.rename !== "function" ? fs2.rename : (function(fs$rename) { + function rename(from, to, cb) { + var start = Date.now(); + var backoff = 0; + fs$rename(from, to, function CB(er) { + if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) { + setTimeout(function() { + fs2.stat(to, function(stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er); + }); + }, backoff); + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er); + }); + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); + return rename; + })(fs2.rename); + } + fs2.read = typeof fs2.read !== "function" ? fs2.read : (function(fs$read) { + function read(fd, buffer, offset, length, position, callback_) { + var callback; + if (callback_ && typeof callback_ === "function") { + var eagCounter = 0; + callback = function(er, _, __) { + if (er && er.code === "EAGAIN" && eagCounter < 10) { + eagCounter++; + return fs$read.call(fs2, fd, buffer, offset, length, position, callback); + } + callback_.apply(this, arguments); + }; + } + return fs$read.call(fs2, fd, buffer, offset, length, position, callback); + } + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); + return read; + })(fs2.read); + fs2.readSync = typeof fs2.readSync !== "function" ? fs2.readSync : /* @__PURE__ */ (function(fs$readSync) { + return function(fd, buffer, offset, length, position) { + var eagCounter = 0; + while (true) { + try { + return fs$readSync.call(fs2, fd, buffer, offset, length, position); + } catch (er) { + if (er.code === "EAGAIN" && eagCounter < 10) { + eagCounter++; + continue; + } + throw er; + } + } + }; + })(fs2.readSync); + function patchLchmod(fs3) { + fs3.lchmod = function(path, mode, callback) { + fs3.open( + path, + constants.O_WRONLY | constants.O_SYMLINK, + mode, + function(err, fd) { + if (err) { + if (callback) callback(err); + return; + } + fs3.fchmod(fd, mode, function(err2) { + fs3.close(fd, function(err22) { + if (callback) callback(err2 || err22); + }); + }); + } + ); + }; + fs3.lchmodSync = function(path, mode) { + var fd = fs3.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode); + var threw = true; + var ret; + try { + ret = fs3.fchmodSync(fd, mode); + threw = false; + } finally { + if (threw) { + try { + fs3.closeSync(fd); + } catch (er) { + } + } else { + fs3.closeSync(fd); + } + } + return ret; + }; + } + function patchLutimes(fs3) { + if (constants.hasOwnProperty("O_SYMLINK") && fs3.futimes) { + fs3.lutimes = function(path, at, mt, cb) { + fs3.open(path, constants.O_SYMLINK, function(er, fd) { + if (er) { + if (cb) cb(er); + return; + } + fs3.futimes(fd, at, mt, function(er2) { + fs3.close(fd, function(er22) { + if (cb) cb(er2 || er22); + }); + }); + }); + }; + fs3.lutimesSync = function(path, at, mt) { + var fd = fs3.openSync(path, constants.O_SYMLINK); + var ret; + var threw = true; + try { + ret = fs3.futimesSync(fd, at, mt); + threw = false; + } finally { + if (threw) { + try { + fs3.closeSync(fd); + } catch (er) { + } + } else { + fs3.closeSync(fd); + } + } + return ret; + }; + } else if (fs3.futimes) { + fs3.lutimes = function(_a, _b, _c, cb) { + if (cb) process.nextTick(cb); + }; + fs3.lutimesSync = function() { + }; + } + } + function chmodFix(orig) { + if (!orig) return orig; + return function(target, mode, cb) { + return orig.call(fs2, target, mode, function(er) { + if (chownErOk(er)) er = null; + if (cb) cb.apply(this, arguments); + }); + }; + } + function chmodFixSync(orig) { + if (!orig) return orig; + return function(target, mode) { + try { + return orig.call(fs2, target, mode); + } catch (er) { + if (!chownErOk(er)) throw er; + } + }; + } + function chownFix(orig) { + if (!orig) return orig; + return function(target, uid, gid, cb) { + return orig.call(fs2, target, uid, gid, function(er) { + if (chownErOk(er)) er = null; + if (cb) cb.apply(this, arguments); + }); + }; + } + function chownFixSync(orig) { + if (!orig) return orig; + return function(target, uid, gid) { + try { + return orig.call(fs2, target, uid, gid); + } catch (er) { + if (!chownErOk(er)) throw er; + } + }; + } + function statFix(orig) { + if (!orig) return orig; + return function(target, options, cb) { + if (typeof options === "function") { + cb = options; + options = null; + } + function callback(er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 4294967296; + if (stats.gid < 0) stats.gid += 4294967296; + } + if (cb) cb.apply(this, arguments); + } + return options ? orig.call(fs2, target, options, callback) : orig.call(fs2, target, callback); + }; + } + function statFixSync(orig) { + if (!orig) return orig; + return function(target, options) { + var stats = options ? orig.call(fs2, target, options) : orig.call(fs2, target); + if (stats) { + if (stats.uid < 0) stats.uid += 4294967296; + if (stats.gid < 0) stats.gid += 4294967296; + } + return stats; + }; + } + function chownErOk(er) { + if (!er) + return true; + if (er.code === "ENOSYS") + return true; + var nonroot = !process.getuid || process.getuid() !== 0; + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true; + } + return false; + } + } + } +}); + +// node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js +var require_legacy_streams = __commonJS({ + "node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js"(exports2, module2) { + var Stream = require("stream").Stream; + module2.exports = legacy; + function legacy(fs2) { + return { + ReadStream, + WriteStream + }; + function ReadStream(path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + Stream.call(this); + var self = this; + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + this.flags = "r"; + this.mode = 438; + this.bufferSize = 64 * 1024; + options = options || {}; + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + if (this.encoding) this.setEncoding(this.encoding); + if (this.start !== void 0) { + if ("number" !== typeof this.start) { + throw TypeError("start must be a Number"); + } + if (this.end === void 0) { + this.end = Infinity; + } else if ("number" !== typeof this.end) { + throw TypeError("end must be a Number"); + } + if (this.start > this.end) { + throw new Error("start must be <= end"); + } + this.pos = this.start; + } + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + fs2.open(this.path, this.flags, this.mode, function(err, fd) { + if (err) { + self.emit("error", err); + self.readable = false; + return; + } + self.fd = fd; + self.emit("open", fd); + self._read(); + }); + } + function WriteStream(path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + Stream.call(this); + this.path = path; + this.fd = null; + this.writable = true; + this.flags = "w"; + this.encoding = "binary"; + this.mode = 438; + this.bytesWritten = 0; + options = options || {}; + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + if (this.start !== void 0) { + if ("number" !== typeof this.start) { + throw TypeError("start must be a Number"); + } + if (this.start < 0) { + throw new Error("start must be >= zero"); + } + this.pos = this.start; + } + this.busy = false; + this._queue = []; + if (this.fd === null) { + this._open = fs2.open; + this._queue.push([this._open, this.path, this.flags, this.mode, void 0]); + this.flush(); + } + } + } + } +}); + +// node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js +var require_clone = __commonJS({ + "node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js"(exports2, module2) { + "use strict"; + module2.exports = clone; + var getPrototypeOf = Object.getPrototypeOf || function(obj) { + return obj.__proto__; + }; + function clone(obj) { + if (obj === null || typeof obj !== "object") + return obj; + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) }; + else + var copy = /* @__PURE__ */ Object.create(null); + Object.getOwnPropertyNames(obj).forEach(function(key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); + }); + return copy; + } + } +}); + +// node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js +var require_graceful_fs = __commonJS({ + "node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js"(exports2, module2) { + var fs2 = require("fs"); + var polyfills = require_polyfills(); + var legacy = require_legacy_streams(); + var clone = require_clone(); + var util = require("util"); + var gracefulQueue; + var previousSymbol; + if (typeof Symbol === "function" && typeof Symbol.for === "function") { + gracefulQueue = Symbol.for("graceful-fs.queue"); + previousSymbol = Symbol.for("graceful-fs.previous"); + } else { + gracefulQueue = "___graceful-fs.queue"; + previousSymbol = "___graceful-fs.previous"; + } + function noop() { + } + function publishQueue(context, queue2) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue2; + } + }); + } + var debug = noop; + if (util.debuglog) + debug = util.debuglog("gfs4"); + else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) + debug = function() { + var m = util.format.apply(util, arguments); + m = "GFS4: " + m.split(/\n/).join("\nGFS4: "); + console.error(m); + }; + if (!fs2[gracefulQueue]) { + queue = global[gracefulQueue] || []; + publishQueue(fs2, queue); + fs2.close = (function(fs$close) { + function close(fd, cb) { + return fs$close.call(fs2, fd, function(err) { + if (!err) { + resetQueue(); + } + if (typeof cb === "function") + cb.apply(this, arguments); + }); + } + Object.defineProperty(close, previousSymbol, { + value: fs$close + }); + return close; + })(fs2.close); + fs2.closeSync = (function(fs$closeSync) { + function closeSync(fd) { + fs$closeSync.apply(fs2, arguments); + resetQueue(); + } + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }); + return closeSync; + })(fs2.closeSync); + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) { + process.on("exit", function() { + debug(fs2[gracefulQueue]); + require("assert").equal(fs2[gracefulQueue].length, 0); + }); + } + } + var queue; + if (!global[gracefulQueue]) { + publishQueue(global, fs2[gracefulQueue]); + } + module2.exports = patch(clone(fs2)); + if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs2.__patched) { + module2.exports = patch(fs2); + fs2.__patched = true; + } + function patch(fs3) { + polyfills(fs3); + fs3.gracefulify = patch; + fs3.createReadStream = createReadStream; + fs3.createWriteStream = createWriteStream; + var fs$readFile = fs3.readFile; + fs3.readFile = readFile; + function readFile(path, options, cb) { + if (typeof options === "function") + cb = options, options = null; + return go$readFile(path, options, cb); + function go$readFile(path2, options2, cb2, startTime) { + return fs$readFile(path2, options2, function(err) { + if (err && (err.code === "EMFILE" || err.code === "ENFILE")) + enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb2 === "function") + cb2.apply(this, arguments); + } + }); + } + } + var fs$writeFile = fs3.writeFile; + fs3.writeFile = writeFile; + function writeFile(path, data, options, cb) { + if (typeof options === "function") + cb = options, options = null; + return go$writeFile(path, data, options, cb); + function go$writeFile(path2, data2, options2, cb2, startTime) { + return fs$writeFile(path2, data2, options2, function(err) { + if (err && (err.code === "EMFILE" || err.code === "ENFILE")) + enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb2 === "function") + cb2.apply(this, arguments); + } + }); + } + } + var fs$appendFile = fs3.appendFile; + if (fs$appendFile) + fs3.appendFile = appendFile; + function appendFile(path, data, options, cb) { + if (typeof options === "function") + cb = options, options = null; + return go$appendFile(path, data, options, cb); + function go$appendFile(path2, data2, options2, cb2, startTime) { + return fs$appendFile(path2, data2, options2, function(err) { + if (err && (err.code === "EMFILE" || err.code === "ENFILE")) + enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb2 === "function") + cb2.apply(this, arguments); + } + }); + } + } + var fs$copyFile = fs3.copyFile; + if (fs$copyFile) + fs3.copyFile = copyFile; + function copyFile(src, dest, flags, cb) { + if (typeof flags === "function") { + cb = flags; + flags = 0; + } + return go$copyFile(src, dest, flags, cb); + function go$copyFile(src2, dest2, flags2, cb2, startTime) { + return fs$copyFile(src2, dest2, flags2, function(err) { + if (err && (err.code === "EMFILE" || err.code === "ENFILE")) + enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb2 === "function") + cb2.apply(this, arguments); + } + }); + } + } + var fs$readdir = fs3.readdir; + fs3.readdir = readdir; + var noReaddirOptionVersions = /^v[0-5]\./; + function readdir(path, options, cb) { + if (typeof options === "function") + cb = options, options = null; + var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) { + return fs$readdir(path2, fs$readdirCallback( + path2, + options2, + cb2, + startTime + )); + } : function go$readdir2(path2, options2, cb2, startTime) { + return fs$readdir(path2, options2, fs$readdirCallback( + path2, + options2, + cb2, + startTime + )); + }; + return go$readdir(path, options, cb); + function fs$readdirCallback(path2, options2, cb2, startTime) { + return function(err, files) { + if (err && (err.code === "EMFILE" || err.code === "ENFILE")) + enqueue([ + go$readdir, + [path2, options2, cb2], + err, + startTime || Date.now(), + Date.now() + ]); + else { + if (files && files.sort) + files.sort(); + if (typeof cb2 === "function") + cb2.call(this, err, files); + } + }; + } + } + if (process.version.substr(0, 4) === "v0.8") { + var legStreams = legacy(fs3); + ReadStream = legStreams.ReadStream; + WriteStream = legStreams.WriteStream; + } + var fs$ReadStream = fs3.ReadStream; + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype); + ReadStream.prototype.open = ReadStream$open; + } + var fs$WriteStream = fs3.WriteStream; + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype); + WriteStream.prototype.open = WriteStream$open; + } + Object.defineProperty(fs3, "ReadStream", { + get: function() { + return ReadStream; + }, + set: function(val) { + ReadStream = val; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(fs3, "WriteStream", { + get: function() { + return WriteStream; + }, + set: function(val) { + WriteStream = val; + }, + enumerable: true, + configurable: true + }); + var FileReadStream = ReadStream; + Object.defineProperty(fs3, "FileReadStream", { + get: function() { + return FileReadStream; + }, + set: function(val) { + FileReadStream = val; + }, + enumerable: true, + configurable: true + }); + var FileWriteStream = WriteStream; + Object.defineProperty(fs3, "FileWriteStream", { + get: function() { + return FileWriteStream; + }, + set: function(val) { + FileWriteStream = val; + }, + enumerable: true, + configurable: true + }); + function ReadStream(path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this; + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments); + } + function ReadStream$open() { + var that = this; + open(that.path, that.flags, that.mode, function(err, fd) { + if (err) { + if (that.autoClose) + that.destroy(); + that.emit("error", err); + } else { + that.fd = fd; + that.emit("open", fd); + that.read(); + } + }); + } + function WriteStream(path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this; + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments); + } + function WriteStream$open() { + var that = this; + open(that.path, that.flags, that.mode, function(err, fd) { + if (err) { + that.destroy(); + that.emit("error", err); + } else { + that.fd = fd; + that.emit("open", fd); + } + }); + } + function createReadStream(path, options) { + return new fs3.ReadStream(path, options); + } + function createWriteStream(path, options) { + return new fs3.WriteStream(path, options); + } + var fs$open = fs3.open; + fs3.open = open; + function open(path, flags, mode, cb) { + if (typeof mode === "function") + cb = mode, mode = null; + return go$open(path, flags, mode, cb); + function go$open(path2, flags2, mode2, cb2, startTime) { + return fs$open(path2, flags2, mode2, function(err, fd) { + if (err && (err.code === "EMFILE" || err.code === "ENFILE")) + enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]); + else { + if (typeof cb2 === "function") + cb2.apply(this, arguments); + } + }); + } + } + return fs3; + } + function enqueue(elem) { + debug("ENQUEUE", elem[0].name, elem[1]); + fs2[gracefulQueue].push(elem); + retry(); + } + var retryTimer; + function resetQueue() { + var now = Date.now(); + for (var i = 0; i < fs2[gracefulQueue].length; ++i) { + if (fs2[gracefulQueue][i].length > 2) { + fs2[gracefulQueue][i][3] = now; + fs2[gracefulQueue][i][4] = now; + } + } + retry(); + } + function retry() { + clearTimeout(retryTimer); + retryTimer = void 0; + if (fs2[gracefulQueue].length === 0) + return; + var elem = fs2[gracefulQueue].shift(); + var fn = elem[0]; + var args = elem[1]; + var err = elem[2]; + var startTime = elem[3]; + var lastTime = elem[4]; + if (startTime === void 0) { + debug("RETRY", fn.name, args); + fn.apply(null, args); + } else if (Date.now() - startTime >= 6e4) { + debug("TIMEOUT", fn.name, args); + var cb = args.pop(); + if (typeof cb === "function") + cb.call(null, err); + } else { + var sinceAttempt = Date.now() - lastTime; + var sinceStart = Math.max(lastTime - startTime, 1); + var desiredDelay = Math.min(sinceStart * 1.2, 100); + if (sinceAttempt >= desiredDelay) { + debug("RETRY", fn.name, args); + fn.apply(null, args.concat([startTime])); + } else { + fs2[gracefulQueue].push(elem); + } + } + if (retryTimer === void 0) { + retryTimer = setTimeout(retry, 0); + } + } + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/fs/index.js +var require_fs = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/fs/index.js"(exports2) { + "use strict"; + var u = require_universalify().fromCallback; + var fs2 = require_graceful_fs(); + var api = [ + "access", + "appendFile", + "chmod", + "chown", + "close", + "copyFile", + "fchmod", + "fchown", + "fdatasync", + "fstat", + "fsync", + "ftruncate", + "futimes", + "lchmod", + "lchown", + "link", + "lstat", + "mkdir", + "mkdtemp", + "open", + "opendir", + "readdir", + "readFile", + "readlink", + "realpath", + "rename", + "rmdir", + "stat", + "symlink", + "truncate", + "unlink", + "utimes", + "writeFile" + ].filter((key) => { + return typeof fs2[key] === "function"; + }); + Object.keys(fs2).forEach((key) => { + if (key === "promises") { + return; + } + exports2[key] = fs2[key]; + }); + api.forEach((method) => { + exports2[method] = u(fs2[method]); + }); + exports2.exists = function(filename, callback) { + if (typeof callback === "function") { + return fs2.exists(filename, callback); + } + return new Promise((resolve) => { + return fs2.exists(filename, resolve); + }); + }; + exports2.read = function(fd, buffer, offset, length, position, callback) { + if (typeof callback === "function") { + return fs2.read(fd, buffer, offset, length, position, callback); + } + return new Promise((resolve, reject) => { + fs2.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => { + if (err) return reject(err); + resolve({ bytesRead, buffer: buffer2 }); + }); + }); + }; + exports2.write = function(fd, buffer, ...args) { + if (typeof args[args.length - 1] === "function") { + return fs2.write(fd, buffer, ...args); + } + return new Promise((resolve, reject) => { + fs2.write(fd, buffer, ...args, (err, bytesWritten, buffer2) => { + if (err) return reject(err); + resolve({ bytesWritten, buffer: buffer2 }); + }); + }); + }; + if (typeof fs2.writev === "function") { + exports2.writev = function(fd, buffers, ...args) { + if (typeof args[args.length - 1] === "function") { + return fs2.writev(fd, buffers, ...args); + } + return new Promise((resolve, reject) => { + fs2.writev(fd, buffers, ...args, (err, bytesWritten, buffers2) => { + if (err) return reject(err); + resolve({ bytesWritten, buffers: buffers2 }); + }); + }); + }; + } + if (typeof fs2.realpath.native === "function") { + exports2.realpath.native = u(fs2.realpath.native); + } + } +}); + +// node_modules/.pnpm/at-least-node@1.0.0/node_modules/at-least-node/index.js +var require_at_least_node = __commonJS({ + "node_modules/.pnpm/at-least-node@1.0.0/node_modules/at-least-node/index.js"(exports2, module2) { + module2.exports = (r) => { + const n = process.versions.node.split(".").map((x) => parseInt(x, 10)); + r = r.split(".").map((x) => parseInt(x, 10)); + return n[0] > r[0] || n[0] === r[0] && (n[1] > r[1] || n[1] === r[1] && n[2] >= r[2]); + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/mkdirs/make-dir.js +var require_make_dir = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/mkdirs/make-dir.js"(exports2, module2) { + "use strict"; + var fs2 = require_fs(); + var path = require("path"); + var atLeastNode = require_at_least_node(); + var useNativeRecursiveOption = atLeastNode("10.12.0"); + var checkPath = (pth) => { + if (process.platform === "win32") { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, "")); + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`); + error.code = "EINVAL"; + throw error; + } + } + }; + var processOptions = (options) => { + const defaults = { mode: 511 & ~process.umask() }; + if (typeof options === "number") options = { mode: options }; + return { ...defaults, ...options }; + }; + var permissionError = (pth) => { + const error = new Error(`operation not permitted, mkdir '${pth}'`); + error.code = "EPERM"; + error.errno = -4048; + error.path = pth; + error.syscall = "mkdir"; + return error; + }; + module2.exports.makeDir = async (input, options) => { + checkPath(input); + options = processOptions(options); + if (useNativeRecursiveOption) { + const pth = path.resolve(input); + return fs2.mkdir(pth, { + mode: options.mode, + recursive: true + }); + } + const make = async (pth) => { + try { + await fs2.mkdir(pth, options.mode); + } catch (error) { + if (error.code === "EPERM") { + throw error; + } + if (error.code === "ENOENT") { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } + if (error.message.includes("null bytes")) { + throw error; + } + await make(path.dirname(pth)); + return make(pth); + } + try { + const stats = await fs2.stat(pth); + if (!stats.isDirectory()) { + throw new Error("The path is not a directory"); + } + } catch { + throw error; + } + } + }; + return make(path.resolve(input)); + }; + module2.exports.makeDirSync = (input, options) => { + checkPath(input); + options = processOptions(options); + if (useNativeRecursiveOption) { + const pth = path.resolve(input); + return fs2.mkdirSync(pth, { + mode: options.mode, + recursive: true + }); + } + const make = (pth) => { + try { + fs2.mkdirSync(pth, options.mode); + } catch (error) { + if (error.code === "EPERM") { + throw error; + } + if (error.code === "ENOENT") { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } + if (error.message.includes("null bytes")) { + throw error; + } + make(path.dirname(pth)); + return make(pth); + } + try { + if (!fs2.statSync(pth).isDirectory()) { + throw new Error("The path is not a directory"); + } + } catch { + throw error; + } + } + }; + return make(path.resolve(input)); + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/mkdirs/index.js +var require_mkdirs = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/mkdirs/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromPromise; + var { makeDir: _makeDir, makeDirSync } = require_make_dir(); + var makeDir = u(_makeDir); + module2.exports = { + mkdirs: makeDir, + mkdirsSync: makeDirSync, + // alias + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/util/utimes.js +var require_utimes = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/util/utimes.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + function utimesMillis(path, atime, mtime, callback) { + fs2.open(path, "r+", (err, fd) => { + if (err) return callback(err); + fs2.futimes(fd, atime, mtime, (futimesErr) => { + fs2.close(fd, (closeErr) => { + if (callback) callback(futimesErr || closeErr); + }); + }); + }); + } + function utimesMillisSync(path, atime, mtime) { + const fd = fs2.openSync(path, "r+"); + fs2.futimesSync(fd, atime, mtime); + return fs2.closeSync(fd); + } + module2.exports = { + utimesMillis, + utimesMillisSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/util/stat.js +var require_stat = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/util/stat.js"(exports2, module2) { + "use strict"; + var fs2 = require_fs(); + var path = require("path"); + var util = require("util"); + var atLeastNode = require_at_least_node(); + var nodeSupportsBigInt = atLeastNode("10.5.0"); + var stat = (file) => nodeSupportsBigInt ? fs2.stat(file, { bigint: true }) : fs2.stat(file); + var statSync = (file) => nodeSupportsBigInt ? fs2.statSync(file, { bigint: true }) : fs2.statSync(file); + function getStats(src, dest) { + return Promise.all([ + stat(src), + stat(dest).catch((err) => { + if (err.code === "ENOENT") return null; + throw err; + }) + ]).then(([srcStat, destStat]) => ({ srcStat, destStat })); + } + function getStatsSync(src, dest) { + let destStat; + const srcStat = statSync(src); + try { + destStat = statSync(dest); + } catch (err) { + if (err.code === "ENOENT") return { srcStat, destStat: null }; + throw err; + } + return { srcStat, destStat }; + } + function checkPaths(src, dest, funcName, cb) { + util.callbackify(getStats)(src, dest, (err, stats) => { + if (err) return cb(err); + const { srcStat, destStat } = stats; + if (destStat && areIdentical(srcStat, destStat)) { + return cb(new Error("Source and destination must not be the same.")); + } + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + return cb(new Error(errMsg(src, dest, funcName))); + } + return cb(null, { srcStat, destStat }); + }); + } + function checkPathsSync(src, dest, funcName) { + const { srcStat, destStat } = getStatsSync(src, dest); + if (destStat && areIdentical(srcStat, destStat)) { + throw new Error("Source and destination must not be the same."); + } + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)); + } + return { srcStat, destStat }; + } + function checkParentPaths(src, srcStat, dest, funcName, cb) { + const srcParent = path.resolve(path.dirname(src)); + const destParent = path.resolve(path.dirname(dest)); + if (destParent === srcParent || destParent === path.parse(destParent).root) return cb(); + const callback = (err, destStat) => { + if (err) { + if (err.code === "ENOENT") return cb(); + return cb(err); + } + if (areIdentical(srcStat, destStat)) { + return cb(new Error(errMsg(src, dest, funcName))); + } + return checkParentPaths(src, srcStat, destParent, funcName, cb); + }; + if (nodeSupportsBigInt) fs2.stat(destParent, { bigint: true }, callback); + else fs2.stat(destParent, callback); + } + function checkParentPathsSync(src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)); + const destParent = path.resolve(path.dirname(dest)); + if (destParent === srcParent || destParent === path.parse(destParent).root) return; + let destStat; + try { + destStat = statSync(destParent); + } catch (err) { + if (err.code === "ENOENT") return; + throw err; + } + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)); + } + return checkParentPathsSync(src, srcStat, destParent, funcName); + } + function areIdentical(srcStat, destStat) { + if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { + if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) { + return true; + } + if (destStat.size === srcStat.size && destStat.mode === srcStat.mode && destStat.nlink === srcStat.nlink && destStat.atimeMs === srcStat.atimeMs && destStat.mtimeMs === srcStat.mtimeMs && destStat.ctimeMs === srcStat.ctimeMs && destStat.birthtimeMs === srcStat.birthtimeMs) { + return true; + } + } + return false; + } + function isSrcSubdir(src, dest) { + const srcArr = path.resolve(src).split(path.sep).filter((i) => i); + const destArr = path.resolve(dest).split(path.sep).filter((i) => i); + return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true); + } + function errMsg(src, dest, funcName) { + return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`; + } + module2.exports = { + checkPaths, + checkPathsSync, + checkParentPaths, + checkParentPathsSync, + isSrcSubdir + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy-sync/copy-sync.js +var require_copy_sync = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy-sync/copy-sync.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + var path = require("path"); + var mkdirsSync = require_mkdirs().mkdirsSync; + var utimesMillisSync = require_utimes().utimesMillisSync; + var stat = require_stat(); + function copySync(src, dest, opts) { + if (typeof opts === "function") { + opts = { filter: opts }; + } + opts = opts || {}; + opts.clobber = "clobber" in opts ? !!opts.clobber : true; + opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; + if (opts.preserveTimestamps && process.arch === "ia32") { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; + + see https://github.com/jprichardson/node-fs-extra/issues/269`); + } + const { srcStat, destStat } = stat.checkPathsSync(src, dest, "copy"); + stat.checkParentPathsSync(src, srcStat, dest, "copy"); + return handleFilterAndCopy(destStat, src, dest, opts); + } + function handleFilterAndCopy(destStat, src, dest, opts) { + if (opts.filter && !opts.filter(src, dest)) return; + const destParent = path.dirname(dest); + if (!fs2.existsSync(destParent)) mkdirsSync(destParent); + return startCopy(destStat, src, dest, opts); + } + function startCopy(destStat, src, dest, opts) { + if (opts.filter && !opts.filter(src, dest)) return; + return getStats(destStat, src, dest, opts); + } + function getStats(destStat, src, dest, opts) { + const statSync = opts.dereference ? fs2.statSync : fs2.lstatSync; + const srcStat = statSync(src); + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts); + else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts); + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts); + } + function onFile(srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts); + return mayCopyFile(srcStat, src, dest, opts); + } + function mayCopyFile(srcStat, src, dest, opts) { + if (opts.overwrite) { + fs2.unlinkSync(dest); + return copyFile(srcStat, src, dest, opts); + } else if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`); + } + } + function copyFile(srcStat, src, dest, opts) { + fs2.copyFileSync(src, dest); + if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest); + return setDestMode(dest, srcStat.mode); + } + function handleTimestamps(srcMode, src, dest) { + if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode); + return setDestTimestamps(src, dest); + } + function fileIsNotWritable(srcMode) { + return (srcMode & 128) === 0; + } + function makeFileWritable(dest, srcMode) { + return setDestMode(dest, srcMode | 128); + } + function setDestMode(dest, srcMode) { + return fs2.chmodSync(dest, srcMode); + } + function setDestTimestamps(src, dest) { + const updatedSrcStat = fs2.statSync(src); + return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime); + } + function onDir(srcStat, destStat, src, dest, opts) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts); + if (destStat && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`); + } + return copyDir(src, dest, opts); + } + function mkDirAndCopy(srcMode, src, dest, opts) { + fs2.mkdirSync(dest); + copyDir(src, dest, opts); + return setDestMode(dest, srcMode); + } + function copyDir(src, dest, opts) { + fs2.readdirSync(src).forEach((item) => copyDirItem(item, src, dest, opts)); + } + function copyDirItem(item, src, dest, opts) { + const srcItem = path.join(src, item); + const destItem = path.join(dest, item); + const { destStat } = stat.checkPathsSync(srcItem, destItem, "copy"); + return startCopy(destStat, srcItem, destItem, opts); + } + function onLink(destStat, src, dest, opts) { + let resolvedSrc = fs2.readlinkSync(src); + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc); + } + if (!destStat) { + return fs2.symlinkSync(resolvedSrc, dest); + } else { + let resolvedDest; + try { + resolvedDest = fs2.readlinkSync(dest); + } catch (err) { + if (err.code === "EINVAL" || err.code === "UNKNOWN") return fs2.symlinkSync(resolvedSrc, dest); + throw err; + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest); + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`); + } + if (fs2.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`); + } + return copyLink(resolvedSrc, dest); + } + } + function copyLink(resolvedSrc, dest) { + fs2.unlinkSync(dest); + return fs2.symlinkSync(resolvedSrc, dest); + } + module2.exports = copySync; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy-sync/index.js +var require_copy_sync2 = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy-sync/index.js"(exports2, module2) { + "use strict"; + module2.exports = { + copySync: require_copy_sync() + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/path-exists/index.js +var require_path_exists = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/path-exists/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromPromise; + var fs2 = require_fs(); + function pathExists(path) { + return fs2.access(path).then(() => true).catch(() => false); + } + module2.exports = { + pathExists: u(pathExists), + pathExistsSync: fs2.existsSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy/copy.js +var require_copy = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy/copy.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + var path = require("path"); + var mkdirs = require_mkdirs().mkdirs; + var pathExists = require_path_exists().pathExists; + var utimesMillis = require_utimes().utimesMillis; + var stat = require_stat(); + function copy(src, dest, opts, cb) { + if (typeof opts === "function" && !cb) { + cb = opts; + opts = {}; + } else if (typeof opts === "function") { + opts = { filter: opts }; + } + cb = cb || function() { + }; + opts = opts || {}; + opts.clobber = "clobber" in opts ? !!opts.clobber : true; + opts.overwrite = "overwrite" in opts ? !!opts.overwrite : opts.clobber; + if (opts.preserveTimestamps && process.arch === "ia32") { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended; + + see https://github.com/jprichardson/node-fs-extra/issues/269`); + } + stat.checkPaths(src, dest, "copy", (err, stats) => { + if (err) return cb(err); + const { srcStat, destStat } = stats; + stat.checkParentPaths(src, srcStat, dest, "copy", (err2) => { + if (err2) return cb(err2); + if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb); + return checkParentDir(destStat, src, dest, opts, cb); + }); + }); + } + function checkParentDir(destStat, src, dest, opts, cb) { + const destParent = path.dirname(dest); + pathExists(destParent, (err, dirExists) => { + if (err) return cb(err); + if (dirExists) return startCopy(destStat, src, dest, opts, cb); + mkdirs(destParent, (err2) => { + if (err2) return cb(err2); + return startCopy(destStat, src, dest, opts, cb); + }); + }); + } + function handleFilter(onInclude, destStat, src, dest, opts, cb) { + Promise.resolve(opts.filter(src, dest)).then((include) => { + if (include) return onInclude(destStat, src, dest, opts, cb); + return cb(); + }, (error) => cb(error)); + } + function startCopy(destStat, src, dest, opts, cb) { + if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb); + return getStats(destStat, src, dest, opts, cb); + } + function getStats(destStat, src, dest, opts, cb) { + const stat2 = opts.dereference ? fs2.stat : fs2.lstat; + stat2(src, (err, srcStat) => { + if (err) return cb(err); + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb); + else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb); + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb); + }); + } + function onFile(srcStat, destStat, src, dest, opts, cb) { + if (!destStat) return copyFile(srcStat, src, dest, opts, cb); + return mayCopyFile(srcStat, src, dest, opts, cb); + } + function mayCopyFile(srcStat, src, dest, opts, cb) { + if (opts.overwrite) { + fs2.unlink(dest, (err) => { + if (err) return cb(err); + return copyFile(srcStat, src, dest, opts, cb); + }); + } else if (opts.errorOnExist) { + return cb(new Error(`'${dest}' already exists`)); + } else return cb(); + } + function copyFile(srcStat, src, dest, opts, cb) { + fs2.copyFile(src, dest, (err) => { + if (err) return cb(err); + if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb); + return setDestMode(dest, srcStat.mode, cb); + }); + } + function handleTimestampsAndMode(srcMode, src, dest, cb) { + if (fileIsNotWritable(srcMode)) { + return makeFileWritable(dest, srcMode, (err) => { + if (err) return cb(err); + return setDestTimestampsAndMode(srcMode, src, dest, cb); + }); + } + return setDestTimestampsAndMode(srcMode, src, dest, cb); + } + function fileIsNotWritable(srcMode) { + return (srcMode & 128) === 0; + } + function makeFileWritable(dest, srcMode, cb) { + return setDestMode(dest, srcMode | 128, cb); + } + function setDestTimestampsAndMode(srcMode, src, dest, cb) { + setDestTimestamps(src, dest, (err) => { + if (err) return cb(err); + return setDestMode(dest, srcMode, cb); + }); + } + function setDestMode(dest, srcMode, cb) { + return fs2.chmod(dest, srcMode, cb); + } + function setDestTimestamps(src, dest, cb) { + fs2.stat(src, (err, updatedSrcStat) => { + if (err) return cb(err); + return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb); + }); + } + function onDir(srcStat, destStat, src, dest, opts, cb) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb); + if (destStat && !destStat.isDirectory()) { + return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)); + } + return copyDir(src, dest, opts, cb); + } + function mkDirAndCopy(srcMode, src, dest, opts, cb) { + fs2.mkdir(dest, (err) => { + if (err) return cb(err); + copyDir(src, dest, opts, (err2) => { + if (err2) return cb(err2); + return setDestMode(dest, srcMode, cb); + }); + }); + } + function copyDir(src, dest, opts, cb) { + fs2.readdir(src, (err, items) => { + if (err) return cb(err); + return copyDirItems(items, src, dest, opts, cb); + }); + } + function copyDirItems(items, src, dest, opts, cb) { + const item = items.pop(); + if (!item) return cb(); + return copyDirItem(items, item, src, dest, opts, cb); + } + function copyDirItem(items, item, src, dest, opts, cb) { + const srcItem = path.join(src, item); + const destItem = path.join(dest, item); + stat.checkPaths(srcItem, destItem, "copy", (err, stats) => { + if (err) return cb(err); + const { destStat } = stats; + startCopy(destStat, srcItem, destItem, opts, (err2) => { + if (err2) return cb(err2); + return copyDirItems(items, src, dest, opts, cb); + }); + }); + } + function onLink(destStat, src, dest, opts, cb) { + fs2.readlink(src, (err, resolvedSrc) => { + if (err) return cb(err); + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc); + } + if (!destStat) { + return fs2.symlink(resolvedSrc, dest, cb); + } else { + fs2.readlink(dest, (err2, resolvedDest) => { + if (err2) { + if (err2.code === "EINVAL" || err2.code === "UNKNOWN") return fs2.symlink(resolvedSrc, dest, cb); + return cb(err2); + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest); + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)); + } + if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)); + } + return copyLink(resolvedSrc, dest, cb); + }); + } + }); + } + function copyLink(resolvedSrc, dest, cb) { + fs2.unlink(dest, (err) => { + if (err) return cb(err); + return fs2.symlink(resolvedSrc, dest, cb); + }); + } + module2.exports = copy; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy/index.js +var require_copy2 = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/copy/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + module2.exports = { + copy: u(require_copy()) + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/remove/rimraf.js +var require_rimraf = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/remove/rimraf.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + var path = require("path"); + var assert = require("assert"); + var isWindows = process.platform === "win32"; + function defaults(options) { + const methods = [ + "unlink", + "chmod", + "stat", + "lstat", + "rmdir", + "readdir" + ]; + methods.forEach((m) => { + options[m] = options[m] || fs2[m]; + m = m + "Sync"; + options[m] = options[m] || fs2[m]; + }); + options.maxBusyTries = options.maxBusyTries || 3; + } + function rimraf(p, options, cb) { + let busyTries = 0; + if (typeof options === "function") { + cb = options; + options = {}; + } + assert(p, "rimraf: missing path"); + assert.strictEqual(typeof p, "string", "rimraf: path should be a string"); + assert.strictEqual(typeof cb, "function", "rimraf: callback function required"); + assert(options, "rimraf: invalid options argument provided"); + assert.strictEqual(typeof options, "object", "rimraf: options should be object"); + defaults(options); + rimraf_(p, options, function CB(er) { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { + busyTries++; + const time = busyTries * 100; + return setTimeout(() => rimraf_(p, options, CB), time); + } + if (er.code === "ENOENT") er = null; + } + cb(er); + }); + } + function rimraf_(p, options, cb) { + assert(p); + assert(options); + assert(typeof cb === "function"); + options.lstat(p, (er, st) => { + if (er && er.code === "ENOENT") { + return cb(null); + } + if (er && er.code === "EPERM" && isWindows) { + return fixWinEPERM(p, options, er, cb); + } + if (st && st.isDirectory()) { + return rmdir(p, options, er, cb); + } + options.unlink(p, (er2) => { + if (er2) { + if (er2.code === "ENOENT") { + return cb(null); + } + if (er2.code === "EPERM") { + return isWindows ? fixWinEPERM(p, options, er2, cb) : rmdir(p, options, er2, cb); + } + if (er2.code === "EISDIR") { + return rmdir(p, options, er2, cb); + } + } + return cb(er2); + }); + }); + } + function fixWinEPERM(p, options, er, cb) { + assert(p); + assert(options); + assert(typeof cb === "function"); + if (er) { + assert(er instanceof Error); + } + options.chmod(p, 438, (er2) => { + if (er2) { + cb(er2.code === "ENOENT" ? null : er); + } else { + options.stat(p, (er3, stats) => { + if (er3) { + cb(er3.code === "ENOENT" ? null : er); + } else if (stats.isDirectory()) { + rmdir(p, options, er, cb); + } else { + options.unlink(p, cb); + } + }); + } + }); + } + function fixWinEPERMSync(p, options, er) { + let stats; + assert(p); + assert(options); + if (er) { + assert(er instanceof Error); + } + try { + options.chmodSync(p, 438); + } catch (er2) { + if (er2.code === "ENOENT") { + return; + } else { + throw er; + } + } + try { + stats = options.statSync(p); + } catch (er3) { + if (er3.code === "ENOENT") { + return; + } else { + throw er; + } + } + if (stats.isDirectory()) { + rmdirSync(p, options, er); + } else { + options.unlinkSync(p); + } + } + function rmdir(p, options, originalEr, cb) { + assert(p); + assert(options); + if (originalEr) { + assert(originalEr instanceof Error); + } + assert(typeof cb === "function"); + options.rmdir(p, (er) => { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) { + rmkids(p, options, cb); + } else if (er && er.code === "ENOTDIR") { + cb(originalEr); + } else { + cb(er); + } + }); + } + function rmkids(p, options, cb) { + assert(p); + assert(options); + assert(typeof cb === "function"); + options.readdir(p, (er, files) => { + if (er) return cb(er); + let n = files.length; + let errState; + if (n === 0) return options.rmdir(p, cb); + files.forEach((f) => { + rimraf(path.join(p, f), options, (er2) => { + if (errState) { + return; + } + if (er2) return cb(errState = er2); + if (--n === 0) { + options.rmdir(p, cb); + } + }); + }); + }); + } + function rimrafSync(p, options) { + let st; + options = options || {}; + defaults(options); + assert(p, "rimraf: missing path"); + assert.strictEqual(typeof p, "string", "rimraf: path should be a string"); + assert(options, "rimraf: missing options"); + assert.strictEqual(typeof options, "object", "rimraf: options should be object"); + try { + st = options.lstatSync(p); + } catch (er) { + if (er.code === "ENOENT") { + return; + } + if (er.code === "EPERM" && isWindows) { + fixWinEPERMSync(p, options, er); + } + } + try { + if (st && st.isDirectory()) { + rmdirSync(p, options, null); + } else { + options.unlinkSync(p); + } + } catch (er) { + if (er.code === "ENOENT") { + return; + } else if (er.code === "EPERM") { + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er); + } else if (er.code !== "EISDIR") { + throw er; + } + rmdirSync(p, options, er); + } + } + function rmdirSync(p, options, originalEr) { + assert(p); + assert(options); + if (originalEr) { + assert(originalEr instanceof Error); + } + try { + options.rmdirSync(p); + } catch (er) { + if (er.code === "ENOTDIR") { + throw originalEr; + } else if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") { + rmkidsSync(p, options); + } else if (er.code !== "ENOENT") { + throw er; + } + } + } + function rmkidsSync(p, options) { + assert(p); + assert(options); + options.readdirSync(p).forEach((f) => rimrafSync(path.join(p, f), options)); + if (isWindows) { + const startTime = Date.now(); + do { + try { + const ret = options.rmdirSync(p, options); + return ret; + } catch { + } + } while (Date.now() - startTime < 500); + } else { + const ret = options.rmdirSync(p, options); + return ret; + } + } + module2.exports = rimraf; + rimraf.sync = rimrafSync; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/remove/index.js +var require_remove = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/remove/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + var rimraf = require_rimraf(); + module2.exports = { + remove: u(rimraf), + removeSync: rimraf.sync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/empty/index.js +var require_empty = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/empty/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + var fs2 = require_graceful_fs(); + var path = require("path"); + var mkdir = require_mkdirs(); + var remove = require_remove(); + var emptyDir = u(function emptyDir2(dir, callback) { + callback = callback || function() { + }; + fs2.readdir(dir, (err, items) => { + if (err) return mkdir.mkdirs(dir, callback); + items = items.map((item) => path.join(dir, item)); + deleteItem(); + function deleteItem() { + const item = items.pop(); + if (!item) return callback(); + remove.remove(item, (err2) => { + if (err2) return callback(err2); + deleteItem(); + }); + } + }); + }); + function emptyDirSync(dir) { + let items; + try { + items = fs2.readdirSync(dir); + } catch { + return mkdir.mkdirsSync(dir); + } + items.forEach((item) => { + item = path.join(dir, item); + remove.removeSync(item); + }); + } + module2.exports = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/file.js +var require_file = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/file.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + var path = require("path"); + var fs2 = require_graceful_fs(); + var mkdir = require_mkdirs(); + function createFile(file, callback) { + function makeFile() { + fs2.writeFile(file, "", (err) => { + if (err) return callback(err); + callback(); + }); + } + fs2.stat(file, (err, stats) => { + if (!err && stats.isFile()) return callback(); + const dir = path.dirname(file); + fs2.stat(dir, (err2, stats2) => { + if (err2) { + if (err2.code === "ENOENT") { + return mkdir.mkdirs(dir, (err3) => { + if (err3) return callback(err3); + makeFile(); + }); + } + return callback(err2); + } + if (stats2.isDirectory()) makeFile(); + else { + fs2.readdir(dir, (err3) => { + if (err3) return callback(err3); + }); + } + }); + }); + } + function createFileSync(file) { + let stats; + try { + stats = fs2.statSync(file); + } catch { + } + if (stats && stats.isFile()) return; + const dir = path.dirname(file); + try { + if (!fs2.statSync(dir).isDirectory()) { + fs2.readdirSync(dir); + } + } catch (err) { + if (err && err.code === "ENOENT") mkdir.mkdirsSync(dir); + else throw err; + } + fs2.writeFileSync(file, ""); + } + module2.exports = { + createFile: u(createFile), + createFileSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/link.js +var require_link = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/link.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + var path = require("path"); + var fs2 = require_graceful_fs(); + var mkdir = require_mkdirs(); + var pathExists = require_path_exists().pathExists; + function createLink(srcpath, dstpath, callback) { + function makeLink(srcpath2, dstpath2) { + fs2.link(srcpath2, dstpath2, (err) => { + if (err) return callback(err); + callback(null); + }); + } + pathExists(dstpath, (err, destinationExists) => { + if (err) return callback(err); + if (destinationExists) return callback(null); + fs2.lstat(srcpath, (err2) => { + if (err2) { + err2.message = err2.message.replace("lstat", "ensureLink"); + return callback(err2); + } + const dir = path.dirname(dstpath); + pathExists(dir, (err3, dirExists) => { + if (err3) return callback(err3); + if (dirExists) return makeLink(srcpath, dstpath); + mkdir.mkdirs(dir, (err4) => { + if (err4) return callback(err4); + makeLink(srcpath, dstpath); + }); + }); + }); + }); + } + function createLinkSync(srcpath, dstpath) { + const destinationExists = fs2.existsSync(dstpath); + if (destinationExists) return void 0; + try { + fs2.lstatSync(srcpath); + } catch (err) { + err.message = err.message.replace("lstat", "ensureLink"); + throw err; + } + const dir = path.dirname(dstpath); + const dirExists = fs2.existsSync(dir); + if (dirExists) return fs2.linkSync(srcpath, dstpath); + mkdir.mkdirsSync(dir); + return fs2.linkSync(srcpath, dstpath); + } + module2.exports = { + createLink: u(createLink), + createLinkSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/symlink-paths.js +var require_symlink_paths = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/symlink-paths.js"(exports2, module2) { + "use strict"; + var path = require("path"); + var fs2 = require_graceful_fs(); + var pathExists = require_path_exists().pathExists; + function symlinkPaths(srcpath, dstpath, callback) { + if (path.isAbsolute(srcpath)) { + return fs2.lstat(srcpath, (err) => { + if (err) { + err.message = err.message.replace("lstat", "ensureSymlink"); + return callback(err); + } + return callback(null, { + toCwd: srcpath, + toDst: srcpath + }); + }); + } else { + const dstdir = path.dirname(dstpath); + const relativeToDst = path.join(dstdir, srcpath); + return pathExists(relativeToDst, (err, exists) => { + if (err) return callback(err); + if (exists) { + return callback(null, { + toCwd: relativeToDst, + toDst: srcpath + }); + } else { + return fs2.lstat(srcpath, (err2) => { + if (err2) { + err2.message = err2.message.replace("lstat", "ensureSymlink"); + return callback(err2); + } + return callback(null, { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + }); + }); + } + }); + } + } + function symlinkPathsSync(srcpath, dstpath) { + let exists; + if (path.isAbsolute(srcpath)) { + exists = fs2.existsSync(srcpath); + if (!exists) throw new Error("absolute srcpath does not exist"); + return { + toCwd: srcpath, + toDst: srcpath + }; + } else { + const dstdir = path.dirname(dstpath); + const relativeToDst = path.join(dstdir, srcpath); + exists = fs2.existsSync(relativeToDst); + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath + }; + } else { + exists = fs2.existsSync(srcpath); + if (!exists) throw new Error("relative srcpath does not exist"); + return { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + }; + } + } + } + module2.exports = { + symlinkPaths, + symlinkPathsSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/symlink-type.js +var require_symlink_type = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/symlink-type.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + function symlinkType(srcpath, type, callback) { + callback = typeof type === "function" ? type : callback; + type = typeof type === "function" ? false : type; + if (type) return callback(null, type); + fs2.lstat(srcpath, (err, stats) => { + if (err) return callback(null, "file"); + type = stats && stats.isDirectory() ? "dir" : "file"; + callback(null, type); + }); + } + function symlinkTypeSync(srcpath, type) { + let stats; + if (type) return type; + try { + stats = fs2.lstatSync(srcpath); + } catch { + return "file"; + } + return stats && stats.isDirectory() ? "dir" : "file"; + } + module2.exports = { + symlinkType, + symlinkTypeSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/symlink.js +var require_symlink = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/symlink.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + var path = require("path"); + var fs2 = require_graceful_fs(); + var _mkdirs = require_mkdirs(); + var mkdirs = _mkdirs.mkdirs; + var mkdirsSync = _mkdirs.mkdirsSync; + var _symlinkPaths = require_symlink_paths(); + var symlinkPaths = _symlinkPaths.symlinkPaths; + var symlinkPathsSync = _symlinkPaths.symlinkPathsSync; + var _symlinkType = require_symlink_type(); + var symlinkType = _symlinkType.symlinkType; + var symlinkTypeSync = _symlinkType.symlinkTypeSync; + var pathExists = require_path_exists().pathExists; + function createSymlink(srcpath, dstpath, type, callback) { + callback = typeof type === "function" ? type : callback; + type = typeof type === "function" ? false : type; + pathExists(dstpath, (err, destinationExists) => { + if (err) return callback(err); + if (destinationExists) return callback(null); + symlinkPaths(srcpath, dstpath, (err2, relative) => { + if (err2) return callback(err2); + srcpath = relative.toDst; + symlinkType(relative.toCwd, type, (err3, type2) => { + if (err3) return callback(err3); + const dir = path.dirname(dstpath); + pathExists(dir, (err4, dirExists) => { + if (err4) return callback(err4); + if (dirExists) return fs2.symlink(srcpath, dstpath, type2, callback); + mkdirs(dir, (err5) => { + if (err5) return callback(err5); + fs2.symlink(srcpath, dstpath, type2, callback); + }); + }); + }); + }); + }); + } + function createSymlinkSync(srcpath, dstpath, type) { + const destinationExists = fs2.existsSync(dstpath); + if (destinationExists) return void 0; + const relative = symlinkPathsSync(srcpath, dstpath); + srcpath = relative.toDst; + type = symlinkTypeSync(relative.toCwd, type); + const dir = path.dirname(dstpath); + const exists = fs2.existsSync(dir); + if (exists) return fs2.symlinkSync(srcpath, dstpath, type); + mkdirsSync(dir); + return fs2.symlinkSync(srcpath, dstpath, type); + } + module2.exports = { + createSymlink: u(createSymlink), + createSymlinkSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/index.js +var require_ensure = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/ensure/index.js"(exports2, module2) { + "use strict"; + var file = require_file(); + var link = require_link(); + var symlink = require_symlink(); + module2.exports = { + // file + createFile: file.createFile, + createFileSync: file.createFileSync, + ensureFile: file.createFile, + ensureFileSync: file.createFileSync, + // link + createLink: link.createLink, + createLinkSync: link.createLinkSync, + ensureLink: link.createLink, + ensureLinkSync: link.createLinkSync, + // symlink + createSymlink: symlink.createSymlink, + createSymlinkSync: symlink.createSymlinkSync, + ensureSymlink: symlink.createSymlink, + ensureSymlinkSync: symlink.createSymlinkSync + }; + } +}); + +// node_modules/.pnpm/universalify@2.0.1/node_modules/universalify/index.js +var require_universalify2 = __commonJS({ + "node_modules/.pnpm/universalify@2.0.1/node_modules/universalify/index.js"(exports2) { + "use strict"; + exports2.fromCallback = function(fn) { + return Object.defineProperty(function(...args) { + if (typeof args[args.length - 1] === "function") fn.apply(this, args); + else { + return new Promise((resolve, reject) => { + args.push((err, res) => err != null ? reject(err) : resolve(res)); + fn.apply(this, args); + }); + } + }, "name", { value: fn.name }); + }; + exports2.fromPromise = function(fn) { + return Object.defineProperty(function(...args) { + const cb = args[args.length - 1]; + if (typeof cb !== "function") return fn.apply(this, args); + else { + args.pop(); + fn.apply(this, args).then((r) => cb(null, r), cb); + } + }, "name", { value: fn.name }); + }; + } +}); + +// node_modules/.pnpm/jsonfile@6.2.1/node_modules/jsonfile/utils.js +var require_utils = __commonJS({ + "node_modules/.pnpm/jsonfile@6.2.1/node_modules/jsonfile/utils.js"(exports2, module2) { + function stringify(obj, { EOL = "\n", finalEOL = true, replacer = null, spaces } = {}) { + const EOF = finalEOL ? EOL : ""; + const str = JSON.stringify(obj, replacer, spaces); + if (str === void 0) { + throw new TypeError(`Converting ${typeof obj} value to JSON is not supported`); + } + return str.replace(/\n/g, EOL) + EOF; + } + function stripBom(content) { + if (Buffer.isBuffer(content)) content = content.toString("utf8"); + return content.replace(/^\uFEFF/, ""); + } + module2.exports = { stringify, stripBom }; + } +}); + +// node_modules/.pnpm/jsonfile@6.2.1/node_modules/jsonfile/index.js +var require_jsonfile = __commonJS({ + "node_modules/.pnpm/jsonfile@6.2.1/node_modules/jsonfile/index.js"(exports2, module2) { + var _fs; + try { + _fs = require_graceful_fs(); + } catch (_) { + _fs = require("fs"); + } + var universalify = require_universalify2(); + var { stringify, stripBom } = require_utils(); + async function _readFile(file, options = {}) { + if (typeof options === "string") { + options = { encoding: options }; + } + const fs2 = options.fs || _fs; + const shouldThrow = "throws" in options ? options.throws : true; + let data = await universalify.fromCallback(fs2.readFile)(file, options); + data = stripBom(data); + let obj; + try { + obj = JSON.parse(data, options ? options.reviver : null); + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}`; + throw err; + } else { + return null; + } + } + return obj; + } + var readFile = universalify.fromPromise(_readFile); + function readFileSync(file, options = {}) { + if (typeof options === "string") { + options = { encoding: options }; + } + const fs2 = options.fs || _fs; + const shouldThrow = "throws" in options ? options.throws : true; + try { + let content = fs2.readFileSync(file, options); + content = stripBom(content); + return JSON.parse(content, options.reviver); + } catch (err) { + if (shouldThrow) { + err.message = `${file}: ${err.message}`; + throw err; + } else { + return null; + } + } + } + async function _writeFile(file, obj, options = {}) { + const fs2 = options.fs || _fs; + const str = stringify(obj, options); + await universalify.fromCallback(fs2.writeFile)(file, str, options); + } + var writeFile = universalify.fromPromise(_writeFile); + function writeFileSync(file, obj, options = {}) { + const fs2 = options.fs || _fs; + const str = stringify(obj, options); + return fs2.writeFileSync(file, str, options); + } + module2.exports = { + readFile, + readFileSync, + writeFile, + writeFileSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/jsonfile.js +var require_jsonfile2 = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/jsonfile.js"(exports2, module2) { + "use strict"; + var jsonFile = require_jsonfile(); + module2.exports = { + // jsonfile exports + readJson: jsonFile.readFile, + readJsonSync: jsonFile.readFileSync, + writeJson: jsonFile.writeFile, + writeJsonSync: jsonFile.writeFileSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/output/index.js +var require_output = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/output/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + var fs2 = require_graceful_fs(); + var path = require("path"); + var mkdir = require_mkdirs(); + var pathExists = require_path_exists().pathExists; + function outputFile(file, data, encoding, callback) { + if (typeof encoding === "function") { + callback = encoding; + encoding = "utf8"; + } + const dir = path.dirname(file); + pathExists(dir, (err, itDoes) => { + if (err) return callback(err); + if (itDoes) return fs2.writeFile(file, data, encoding, callback); + mkdir.mkdirs(dir, (err2) => { + if (err2) return callback(err2); + fs2.writeFile(file, data, encoding, callback); + }); + }); + } + function outputFileSync(file, ...args) { + const dir = path.dirname(file); + if (fs2.existsSync(dir)) { + return fs2.writeFileSync(file, ...args); + } + mkdir.mkdirsSync(dir); + fs2.writeFileSync(file, ...args); + } + module2.exports = { + outputFile: u(outputFile), + outputFileSync + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/output-json.js +var require_output_json = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/output-json.js"(exports2, module2) { + "use strict"; + var { stringify } = require_utils(); + var { outputFile } = require_output(); + async function outputJson(file, data, options = {}) { + const str = stringify(data, options); + await outputFile(file, str, options); + } + module2.exports = outputJson; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/output-json-sync.js +var require_output_json_sync = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/output-json-sync.js"(exports2, module2) { + "use strict"; + var { stringify } = require_utils(); + var { outputFileSync } = require_output(); + function outputJsonSync(file, data, options) { + const str = stringify(data, options); + outputFileSync(file, str, options); + } + module2.exports = outputJsonSync; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/index.js +var require_json = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/json/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromPromise; + var jsonFile = require_jsonfile2(); + jsonFile.outputJson = u(require_output_json()); + jsonFile.outputJsonSync = require_output_json_sync(); + jsonFile.outputJSON = jsonFile.outputJson; + jsonFile.outputJSONSync = jsonFile.outputJsonSync; + jsonFile.writeJSON = jsonFile.writeJson; + jsonFile.writeJSONSync = jsonFile.writeJsonSync; + jsonFile.readJSON = jsonFile.readJson; + jsonFile.readJSONSync = jsonFile.readJsonSync; + module2.exports = jsonFile; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move-sync/move-sync.js +var require_move_sync = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move-sync/move-sync.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + var path = require("path"); + var copySync = require_copy_sync2().copySync; + var removeSync = require_remove().removeSync; + var mkdirpSync = require_mkdirs().mkdirpSync; + var stat = require_stat(); + function moveSync(src, dest, opts) { + opts = opts || {}; + const overwrite = opts.overwrite || opts.clobber || false; + const { srcStat } = stat.checkPathsSync(src, dest, "move"); + stat.checkParentPathsSync(src, srcStat, dest, "move"); + mkdirpSync(path.dirname(dest)); + return doRename(src, dest, overwrite); + } + function doRename(src, dest, overwrite) { + if (overwrite) { + removeSync(dest); + return rename(src, dest, overwrite); + } + if (fs2.existsSync(dest)) throw new Error("dest already exists."); + return rename(src, dest, overwrite); + } + function rename(src, dest, overwrite) { + try { + fs2.renameSync(src, dest); + } catch (err) { + if (err.code !== "EXDEV") throw err; + return moveAcrossDevice(src, dest, overwrite); + } + } + function moveAcrossDevice(src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true + }; + copySync(src, dest, opts); + return removeSync(src); + } + module2.exports = moveSync; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move-sync/index.js +var require_move_sync2 = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move-sync/index.js"(exports2, module2) { + "use strict"; + module2.exports = { + moveSync: require_move_sync() + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move/move.js +var require_move = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move/move.js"(exports2, module2) { + "use strict"; + var fs2 = require_graceful_fs(); + var path = require("path"); + var copy = require_copy2().copy; + var remove = require_remove().remove; + var mkdirp = require_mkdirs().mkdirp; + var pathExists = require_path_exists().pathExists; + var stat = require_stat(); + function move(src, dest, opts, cb) { + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + const overwrite = opts.overwrite || opts.clobber || false; + stat.checkPaths(src, dest, "move", (err, stats) => { + if (err) return cb(err); + const { srcStat } = stats; + stat.checkParentPaths(src, srcStat, dest, "move", (err2) => { + if (err2) return cb(err2); + mkdirp(path.dirname(dest), (err3) => { + if (err3) return cb(err3); + return doRename(src, dest, overwrite, cb); + }); + }); + }); + } + function doRename(src, dest, overwrite, cb) { + if (overwrite) { + return remove(dest, (err) => { + if (err) return cb(err); + return rename(src, dest, overwrite, cb); + }); + } + pathExists(dest, (err, destExists) => { + if (err) return cb(err); + if (destExists) return cb(new Error("dest already exists.")); + return rename(src, dest, overwrite, cb); + }); + } + function rename(src, dest, overwrite, cb) { + fs2.rename(src, dest, (err) => { + if (!err) return cb(); + if (err.code !== "EXDEV") return cb(err); + return moveAcrossDevice(src, dest, overwrite, cb); + }); + } + function moveAcrossDevice(src, dest, overwrite, cb) { + const opts = { + overwrite, + errorOnExist: true + }; + copy(src, dest, opts, (err) => { + if (err) return cb(err); + return remove(src, cb); + }); + } + module2.exports = move; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move/index.js +var require_move2 = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/move/index.js"(exports2, module2) { + "use strict"; + var u = require_universalify().fromCallback; + module2.exports = { + move: u(require_move()) + }; + } +}); + +// node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/index.js +var require_lib = __commonJS({ + "node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/index.js"(exports2, module2) { + "use strict"; + module2.exports = { + // Export promiseified graceful-fs: + ...require_fs(), + // Export extra methods: + ...require_copy_sync2(), + ...require_copy2(), + ...require_empty(), + ...require_ensure(), + ...require_json(), + ...require_mkdirs(), + ...require_move_sync2(), + ...require_move2(), + ...require_output(), + ...require_path_exists(), + ...require_remove() + }; + var fs2 = require("fs"); + if (Object.getOwnPropertyDescriptor(fs2, "promises")) { + Object.defineProperty(module2.exports, "promises", { + get() { + return fs2.promises; + } + }); + } + } +}); + +// src/demo.ts +var demo_exports = {}; +__export(demo_exports, { + demo: () => demo +}); +async function demo(dir) { + await import_fs_extra.default.ensureDir((0, import_path.join)(dir, "nested")); + await import_fs_extra.default.writeFile((0, import_path.join)(dir, "nested", "a.txt"), "bundled"); + await import_fs_extra.default.writeJson((0, import_path.join)(dir, "data.json"), { ok: true }); + const text = await import_fs_extra.default.readFile((0, import_path.join)(dir, "nested", "a.txt"), "utf8"); + const data = await import_fs_extra.default.readJson((0, import_path.join)(dir, "data.json")); + await import_fs_extra.default.copy((0, import_path.join)(dir, "nested"), (0, import_path.join)(dir, "copied")); + const copied = await import_fs_extra.default.pathExists((0, import_path.join)(dir, "copied", "a.txt")); + await import_fs_extra.default.remove((0, import_path.join)(dir, "nested")); + return [text, JSON.stringify(data), copied, import_fs_extra.default.existsSync((0, import_path.join)(dir, "nested"))].join(" "); +} +var import_fs_extra, import_path; +var init_demo = __esm({ + "src/demo.ts"() { + import_fs_extra = __toESM(require_lib()); + import_path = require("path"); + } +}); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + demo: () => demo2 +}); +module.exports = __toCommonJS(index_exports); +function demo2(dir) { + const lazy = (init_demo(), __toCommonJS(demo_exports)); + return lazy.demo(dir); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + demo +}); diff --git a/tests/fixtures/npm/node_modules/gtfsxbundle/index.d.ts b/tests/fixtures/npm/node_modules/gtfsxbundle/index.d.ts new file mode 100644 index 0000000000..f00caf3038 --- /dev/null +++ b/tests/fixtures/npm/node_modules/gtfsxbundle/index.d.ts @@ -0,0 +1 @@ +export declare function demo(dir: string): Promise; diff --git a/tests/fixtures/npm/node_modules/gtfsxbundle/package.json b/tests/fixtures/npm/node_modules/gtfsxbundle/package.json new file mode 100644 index 0000000000..66b0e05507 --- /dev/null +++ b/tests/fixtures/npm/node_modules/gtfsxbundle/package.json @@ -0,0 +1,7 @@ +{ + "name": "gtfsxbundle", + "version": "1.0.0", + "description": "real esbuild 0.27 output (--bundle --platform=node --format=cjs) of a TypeScript source that default-imports fs-extra 9.0.0 installed with pnpm, so fs-extra and its dependencies are bundled as __commonJS chunks keyed by package and version", + "main": "dist/index.js", + "types": "index.d.ts" +} diff --git a/tests/harness/npm-cases.ts b/tests/harness/npm-cases.ts index 241ce3c1fd..9f995d1c89 100644 --- a/tests/harness/npm-cases.ts +++ b/tests/harness/npm-cases.ts @@ -19,13 +19,14 @@ export function npmCases(fixturesRoot: string): NpmCase[] { return [ ...globSync(join(fixturesRoot, "npm/cases/*/main.ts")) .sort() - // 2465-2469, 2556-2567, 2571 and 2580-2588 are the --npm-static bundler-emitted-CJS + // 2465-2469, 2556-2567, 2571 and 2580-2590 are the --npm-static bundler-emitted-CJS // cases (npm-static.test.ts drives them with the opt-in): their // consumers exercise the static rewrite's surface (lexer-visible // names the shipped .d.ts never declares, the __toESM interop // family), so they stay out of the flagless island lane by design. .filter( - (entry) => !/\/(246[5-9]|255[6-9]|256[0-7]|2571|258[0-8])-[^/]+\/main\.ts$/.test(entry), + (entry) => + !/\/(246[5-9]|255[6-9]|256[0-7]|2571|258[0-9]|2590)-[^/]+\/main\.ts$/.test(entry), ) .map((entry) => ({ name: entry.split("/").at(-2)!, diff --git a/tests/harness/npm-static.test.ts b/tests/harness/npm-static.test.ts index f0724a193c..66f37f6ecd 100644 --- a/tests/harness/npm-static.test.ts +++ b/tests/harness/npm-static.test.ts @@ -76,7 +76,7 @@ async function buildStatic(entry: string, npmStatic: string[] | "auto"): Promise ...globSync( join(fixturesRoot, "npm/node_modules/cryptozoo/**/*.{js,mjs,cjs,json,d.ts}"), ).sort(), - // the bundler-emitted-CJS mini packages (cases 2465-2469, 2556-2567, 2571, 2580-2588) + // the bundler-emitted-CJS mini packages (cases 2465-2469, 2556-2567, 2571, 2580-2590) ...globSync(join(fixturesRoot, "npm/node_modules/gt*/**/*.{js,cjs,json}")).sort(), ...globSync(join(fixturesRoot, "npm/store/gt*/**/*.{js,cjs,json}")).sort(), ]; @@ -1610,6 +1610,23 @@ describe(`npm-static pilots${sanitize ? " (sanitized)" : ""}`, () => { ]); }, 180_000); + // 2589: a program class over an error class a bundled package defines + // inside a lazy initializer (build-utils' NowBuildError shape), with new + // and instanceof against both. + test("a program subclass 2589-bundled-error-subclass of a bundled error class byte-matches Node", async () => { + await expectNodeParity(join(fixturesRoot, "npm/cases/2589-bundled-error-subclass/main.ts"), [ + "gtesmerror", + ]); + }, 180_000); + + // 2590: a bundle that embeds fs-extra 9 (build-utils' shape): its + // fs-extra chunk compiles as the built-in package. + test("a bundled fs-extra copy 2590-bundled-fs-extra compiles as the built-in package", async () => { + await expectNodeParity(join(fixturesRoot, "npm/cases/2590-bundled-fs-extra/main.ts"), [ + "gtfsxbundle", + ]); + }, 180_000); + // 2562: a file with unverifiable interop that no compiled code can load // (the program imports a leaf data module and only a type from the // main entry) leaves its package static. diff --git a/tests/harness/package-shims.test.ts b/tests/harness/package-shims.test.ts index 50750b59c3..7b69754801 100644 --- a/tests/harness/package-shims.test.ts +++ b/tests/harness/package-shims.test.ts @@ -8,7 +8,10 @@ * stays unloaded: its require throws MODULE_NOT_FOUND; * - a shimmed package that is not installed, or whose major version has no * shim, resolves exactly as before (here: refused like any missing or - * uncompiled package). + * uncompiled package); + * - a CommonJS package's require() of a shimmed package (fs-extra, required + * by an installed package's JavaScript) compiles the shim, and matches + * Node running the real package. */ import { execFile } from "node:child_process"; import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -21,6 +24,7 @@ import { compile } from "@scriptc/compiler"; const execFileAsync = promisify(execFile); const repoRoot = join(import.meta.dirname, "../.."); const casesRoot = join(repoRoot, "tests/fixtures/npm/cases"); +const fsExtraModules = join(repoRoot, "tests/corpus/fs-extra-package/node_modules"); const sanitize = process.env["SCRIPTC_SAN"] === "1"; const scratch = mkdtempSync(join(tmpdir(), "scriptc-package-shims-")); @@ -72,6 +76,60 @@ describe("package shims", () => { expect(await run(result.binaryPath, [], dir)).toBe(expected); }, 180_000); + test("a CommonJS package requiring fs-extra compiles the shim", async () => { + const dir = join(scratch, "fs-extra-require"); + cpSync(fsExtraModules, join(dir, "node_modules"), { recursive: true }); + const pkg = join(dir, "node_modules/fxuser"); + mkdirSync(pkg, { recursive: true }); + writeFileSync( + join(pkg, "package.json"), + '{ "name": "fxuser", "version": "1.0.0", "main": "index.js", "types": "index.d.ts" }\n', + ); + writeFileSync( + join(pkg, "index.js"), + [ + "'use strict';", + "const fs = require('fs-extra');", + "exports.exists = function (p) { return fs.pathExistsSync(p); };", + "exports.read = function (p) { return fs.readFile(p, 'utf8'); };", + "exports.write = async function (p, obj) { await fs.outputJson(p, obj); return fs.readJsonSync(p); };", + "", + ].join("\n"), + ); + writeFileSync( + join(pkg, "index.d.ts"), + [ + "export declare function exists(p: string): boolean;", + "export declare function read(p: string): Promise;", + "export declare function write(p: string, obj: unknown): Promise;", + "", + ].join("\n"), + ); + writeFileSync(join(dir, "data.txt"), "data\n"); + writeFileSync( + join(dir, "main.ts"), + [ + 'import { exists, read, write } from "fxuser";', + "async function main(): Promise {", + ' console.log(exists("data.txt"), exists("missing.txt"));', + ' console.log(JSON.stringify(await read("data.txt")));', + ' console.log(JSON.stringify(await write("out/nested/a.json", { a: [1] })));', + "}", + "main();", + "", + ].join("\n"), + ); + const expected = await run(process.execPath, [join(dir, "main.ts")], dir); + rmSync(join(dir, "out"), { recursive: true, force: true }); + const result = await compile(join(dir, "main.ts"), { + outPath: join(dir, ".scriptc/program"), + outDir: join(dir, ".scriptc"), + sanitize, + }); + if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n")); + expect(await run(result.binaryPath, [], dir)).toBe(expected); + }, 180_000); + test("an unloaded polyfill package is not compiled as its builtin", async () => { const dir = join(scratch, "unloaded-alias"); const write = (path: string, text: string) => {