UNPKG

@visulima/package

Version:

One Package to rule them all, finds your root-dir, monorepo, or package manager.

1,912 lines (1,580 loc) 50.5 kB
import { WriteJsonOptions } from '@visulima/fs'; import { InstallPackageOptions } from '@antfu/install-pkg'; import { Package } from 'normalize-package-data'; /** Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). @category Type */ type Primitive = | null | undefined | string | number | boolean | symbol | bigint; /** Matches a JSON object. This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. @category JSON */ type JsonObject = {[Key in string]: JsonValue} & {[Key in string]?: JsonValue | undefined}; /** Matches a JSON array. @category JSON */ type JsonArray = JsonValue[] | readonly JsonValue[]; /** Matches any valid JSON primitive value. @category JSON */ type JsonPrimitive = string | number | boolean | null; /** Matches any valid JSON value. @see `Jsonify` if you need to transform a type to one that is assignable to `JsonValue`. @category JSON */ type JsonValue = JsonPrimitive | JsonObject | JsonArray; declare global { // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged. interface SymbolConstructor { readonly observable: symbol; } } declare const emptyObjectSymbol: unique symbol; /** Represents a strictly empty plain object, the `{}` value. When you annotate something as the type `{}`, it can be anything except `null` and `undefined`. This means that you cannot use `{}` to represent an empty plain object ([read more](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference/52193484#52193484)). @example ``` import type {EmptyObject} from 'type-fest'; // The following illustrates the problem with `{}`. const foo1: {} = {}; // Pass const foo2: {} = []; // Pass const foo3: {} = 42; // Pass const foo4: {} = {a: 1}; // Pass // With `EmptyObject` only the first case is valid. const bar1: EmptyObject = {}; // Pass const bar2: EmptyObject = 42; // Fail const bar3: EmptyObject = []; // Fail const bar4: EmptyObject = {a: 1}; // Fail ``` Unfortunately, `Record<string, never>`, `Record<keyof any, never>` and `Record<never, never>` do not work. See {@link https://github.com/sindresorhus/type-fest/issues/395 #395}. @category Object */ type EmptyObject = {[emptyObjectSymbol]?: never}; /** Returns a boolean for whether the two given types are equal. @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650 @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796 Use-cases: - If you want to make a conditional branch based on the result of a comparison of two types. @example ``` import type {IsEqual} from 'type-fest'; // This type returns a boolean for whether the given array includes the given item. // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal. type Includes<Value extends readonly any[], Item> = Value extends readonly [Value[0], ...infer rest] ? IsEqual<Value[0], Item> extends true ? true : Includes<rest, Item> : false; ``` @category Type Guard @category Utilities */ type IsEqual<A, B> = (<G>() => G extends A & G | G ? 1 : 2) extends (<G>() => G extends B & G | G ? 1 : 2) ? true : false; /** Represents an array with `unknown` value. Use case: You want a type that all arrays can be assigned to, but you don't care about the value. @example ``` import type {UnknownArray} from 'type-fest'; type IsArray<T> = T extends UnknownArray ? true : false; type A = IsArray<['foo']>; //=> true type B = IsArray<readonly number[]>; //=> true type C = IsArray<string>; //=> false ``` @category Type @category Array */ type UnknownArray = readonly unknown[]; /** Returns the static, fixed-length portion of the given array, excluding variable-length parts. @example ``` type A = [string, number, boolean, ...string[]]; type B = StaticPartOfArray<A>; //=> [string, number, boolean] ``` */ type StaticPartOfArray<T extends UnknownArray, Result extends UnknownArray = []> = T extends unknown ? number extends T['length'] ? T extends readonly [infer U, ...infer V] ? StaticPartOfArray<V, [...Result, U]> : Result : T : never; // Should never happen /** Returns the variable, non-fixed-length portion of the given array, excluding static-length parts. @example ``` type A = [string, number, boolean, ...string[]]; type B = VariablePartOfArray<A>; //=> string[] ``` */ type VariablePartOfArray<T extends UnknownArray> = T extends unknown ? T extends readonly [...StaticPartOfArray<T>, ...infer U] ? U : [] : never; // Can eventually be replaced with the built-in once this library supports // TS5.4+ only. Tracked in https://github.com/sindresorhus/type-fest/issues/848 type NoInfer<T> = T extends infer U ? U : never; /** Returns a boolean for whether the given type is `any`. @link https://stackoverflow.com/a/49928360/1490091 Useful in type utilities, such as disallowing `any`s to be passed to a function. @example ``` import type {IsAny} from 'type-fest'; const typedObject = {a: 1, b: 2} as const; const anyObject: any = {a: 1, b: 2}; function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) { return obj[key]; } const typedA = get(typedObject, 'a'); //=> 1 const anyA = get(anyObject, 'a'); //=> any ``` @category Type Guard @category Utilities */ type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false; type Numeric = number | bigint; type Zero = 0 | 0n; /** Matches the hidden `Infinity` type. Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript. @see NegativeInfinity @category Numeric */ // See https://github.com/microsoft/TypeScript/issues/31752 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision type PositiveInfinity = 1e999; /** Matches the hidden `-Infinity` type. Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript. @see PositiveInfinity @category Numeric */ // See https://github.com/microsoft/TypeScript/issues/31752 // eslint-disable-next-line @typescript-eslint/no-loss-of-precision type NegativeInfinity = -1e999; /** A negative `number`/`bigint` (`-∞ < x < 0`) Use-case: Validating and documenting parameters. @see NegativeInteger @see NonNegative @category Numeric */ type Negative<T extends Numeric> = T extends Zero ? never : `${T}` extends `-${string}` ? T : never; /** Returns a boolean for whether the given number is a negative number. @see Negative @example ``` import type {IsNegative} from 'type-fest'; type ShouldBeFalse = IsNegative<1>; type ShouldBeTrue = IsNegative<-1>; ``` @category Numeric */ type IsNegative<T extends Numeric> = T extends Negative<T> ? true : false; /** Returns a boolean for whether two given types are both true. Use-case: Constructing complex conditional types where multiple conditions must be satisfied. @example ``` import type {And} from 'type-fest'; And<true, true>; //=> true And<true, false>; //=> false ``` @see {@link Or} */ type And<A extends boolean, B extends boolean> = [A, B][number] extends true ? true : true extends [IsEqual<A, false>, IsEqual<B, false>][number] ? false : never; /** Returns a boolean for whether either of two given types are true. Use-case: Constructing complex conditional types where multiple conditions must be satisfied. @example ``` import type {Or} from 'type-fest'; Or<true, false>; //=> true Or<false, false>; //=> false ``` @see {@link And} */ type Or<A extends boolean, B extends boolean> = [A, B][number] extends false ? false : true extends [IsEqual<A, true>, IsEqual<B, true>][number] ? true : never; /** Returns a boolean for whether a given number is greater than another number. @example ``` import type {GreaterThan} from 'type-fest'; GreaterThan<1, -5>; //=> true GreaterThan<1, 1>; //=> false GreaterThan<1, 5>; //=> false ``` */ type GreaterThan<A extends number, B extends number> = number extends A | B ? never : [ IsEqual<A, PositiveInfinity>, IsEqual<A, NegativeInfinity>, IsEqual<B, PositiveInfinity>, IsEqual<B, NegativeInfinity>, ] extends infer R extends [boolean, boolean, boolean, boolean] ? Or< And<IsEqual<R[0], true>, IsEqual<R[2], false>>, And<IsEqual<R[3], true>, IsEqual<R[1], false>> > extends true ? true : Or< And<IsEqual<R[1], true>, IsEqual<R[3], false>>, And<IsEqual<R[2], true>, IsEqual<R[0], false>> > extends true ? false : true extends R[number] ? false : [IsNegative<A>, IsNegative<B>] extends infer R extends [boolean, boolean] ? [true, false] extends R ? false : [false, true] extends R ? true : [false, false] extends R ? PositiveNumericStringGt<`${A}`, `${B}`> : PositiveNumericStringGt<`${NumberAbsolute<B>}`, `${NumberAbsolute<A>}`> : never : never; /** Returns a boolean for whether a given number is greater than or equal to another number. @example ``` import type {GreaterThanOrEqual} from 'type-fest'; GreaterThanOrEqual<1, -5>; //=> true GreaterThanOrEqual<1, 1>; //=> true GreaterThanOrEqual<1, 5>; //=> false ``` */ type GreaterThanOrEqual<A extends number, B extends number> = number extends A | B ? never : A extends B ? true : GreaterThan<A, B>; /** Returns a boolean for whether a given number is less than another number. @example ``` import type {LessThan} from 'type-fest'; LessThan<1, -5>; //=> false LessThan<1, 1>; //=> false LessThan<1, 5>; //=> true ``` */ type LessThan<A extends number, B extends number> = number extends A | B ? never : GreaterThanOrEqual<A, B> extends true ? false : true; // Should never happen /** Create a tuple type of the given length `<L>` and fill it with the given type `<Fill>`. If `<Fill>` is not provided, it will default to `unknown`. @link https://itnext.io/implementing-arithmetic-within-typescripts-type-system-a1ef140a6f6f */ type BuildTuple<L extends number, Fill = unknown, T extends readonly unknown[] = []> = number extends L ? Fill[] : L extends T['length'] ? T : BuildTuple<L, Fill, [...T, Fill]>; /** Return a string representation of the given string or number. Note: This type is not the return type of the `.toString()` function. */ type ToString<T> = T extends string | number ? `${T}` : never; /** Converts a numeric string to a number. @example ``` type PositiveInt = StringToNumber<'1234'>; //=> 1234 type NegativeInt = StringToNumber<'-1234'>; //=> -1234 type PositiveFloat = StringToNumber<'1234.56'>; //=> 1234.56 type NegativeFloat = StringToNumber<'-1234.56'>; //=> -1234.56 type PositiveInfinity = StringToNumber<'Infinity'>; //=> Infinity type NegativeInfinity = StringToNumber<'-Infinity'>; //=> -Infinity ``` @category String @category Numeric @category Template literal */ type StringToNumber<S extends string> = S extends `${infer N extends number}` ? N : S extends 'Infinity' ? PositiveInfinity : S extends '-Infinity' ? NegativeInfinity : never; /** Returns an array of the characters of the string. @example ``` StringToArray<'abcde'>; //=> ['a', 'b', 'c', 'd', 'e'] StringToArray<string>; //=> never ``` @category String */ type StringToArray<S extends string, Result extends string[] = []> = string extends S ? never : S extends `${infer F}${infer R}` ? StringToArray<R, [...Result, F]> : Result; /** Returns the length of the given string. @example ``` StringLength<'abcde'>; //=> 5 StringLength<string>; //=> never ``` @category String @category Template literal */ type StringLength<S extends string> = string extends S ? never : StringToArray<S>['length']; /** Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both numeric strings and have the same length. @example ``` SameLengthPositiveNumericStringGt<'50', '10'>; //=> true SameLengthPositiveNumericStringGt<'10', '10'>; //=> false ``` */ type SameLengthPositiveNumericStringGt<A extends string, B extends string> = A extends `${infer FirstA}${infer RestA}` ? B extends `${infer FirstB}${infer RestB}` ? FirstA extends FirstB ? SameLengthPositiveNumericStringGt<RestA, RestB> : PositiveNumericCharacterGt<FirstA, FirstB> : never : false; type NumericString = '0123456789'; /** Returns a boolean for whether `A` is greater than `B`, where `A` and `B` are both positive numeric strings. @example ``` PositiveNumericStringGt<'500', '1'>; //=> true PositiveNumericStringGt<'1', '1'>; //=> false PositiveNumericStringGt<'1', '500'>; //=> false ``` */ type PositiveNumericStringGt<A extends string, B extends string> = A extends B ? false : [BuildTuple<StringLength<A>, 0>, BuildTuple<StringLength<B>, 0>] extends infer R extends [readonly unknown[], readonly unknown[]] ? R[0] extends [...R[1], ...infer Remain extends readonly unknown[]] ? 0 extends Remain['length'] ? SameLengthPositiveNumericStringGt<A, B> : true : false : never; /** Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both positive numeric characters. @example ``` PositiveNumericCharacterGt<'5', '1'>; //=> true PositiveNumericCharacterGt<'1', '1'>; //=> false ``` */ type PositiveNumericCharacterGt<A extends string, B extends string> = NumericString extends `${infer HeadA}${A}${infer TailA}` ? NumericString extends `${infer HeadB}${B}${infer TailB}` ? HeadA extends `${HeadB}${infer _}${infer __}` ? true : false : never : never; /** Returns the absolute value of a given value. @example ``` NumberAbsolute<-1>; //=> 1 NumberAbsolute<1>; //=> 1 NumberAbsolute<NegativeInfinity> //=> PositiveInfinity ``` */ type NumberAbsolute<N extends number> = `${N}` extends `-${infer StringPositiveN}` ? StringToNumber<StringPositiveN> : N; /** Check whether the given type is a number or a number string. Supports floating-point as a string. @example ``` type A = IsNumberLike<'1'>; //=> true type B = IsNumberLike<'-1.1'>; //=> true type C = IsNumberLike<1>; //=> true type D = IsNumberLike<'a'>; //=> false */ type IsNumberLike<N> = N extends number ? true : N extends `${number}` ? true : N extends `${number}.${number}` ? true : false; /** Returns the number with reversed sign. @example ``` ReverseSign<-1>; //=> 1 ReverseSign<1>; //=> -1 ReverseSign<NegativeInfinity> //=> PositiveInfinity ReverseSign<PositiveInfinity> //=> NegativeInfinity ``` */ type ReverseSign<N extends number> = // Handle edge cases N extends 0 ? 0 : N extends PositiveInfinity ? NegativeInfinity : N extends NegativeInfinity ? PositiveInfinity : // Handle negative numbers `${N}` extends `-${infer P extends number}` ? P // Handle positive numbers : `-${N}` extends `${infer R extends number}` ? R : never; /** Matches any primitive, `void`, `Date`, or `RegExp` value. */ type BuiltIns = Primitive | void | Date | RegExp; /** Matches non-recursive types. */ type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown); /** Returns the difference between two numbers. Note: - A or B can only support `-999` ~ `999`. @example ``` import type {Subtract} from 'type-fest'; Subtract<333, 222>; //=> 111 Subtract<111, -222>; //=> 333 Subtract<-111, 222>; //=> -333 Subtract<18, 96>; //=> -78 Subtract<PositiveInfinity, 9999>; //=> PositiveInfinity Subtract<PositiveInfinity, PositiveInfinity>; //=> number ``` @category Numeric */ // TODO: Support big integer. type Subtract<A extends number, B extends number> = // Handle cases when A or B is the actual "number" type number extends A | B ? number // Handle cases when A and B are both +/- infinity : A extends B & (PositiveInfinity | NegativeInfinity) ? number // Handle cases when A is - infinity or B is + infinity : A extends NegativeInfinity ? NegativeInfinity : B extends PositiveInfinity ? NegativeInfinity // Handle cases when A is + infinity or B is - infinity : A extends PositiveInfinity ? PositiveInfinity : B extends NegativeInfinity ? PositiveInfinity // Handle case when numbers are equal to each other : A extends B ? 0 // Handle cases when A or B is 0 : A extends 0 ? ReverseSign<B> : B extends 0 ? A // Handle remaining regular cases : SubtractPostChecks<A, B>; /** Subtracts two numbers A and B, such that they are not equal and neither of them are 0, +/- infinity or the `number` type */ type SubtractPostChecks<A extends number, B extends number, AreNegative = [IsNegative<A>, IsNegative<B>]> = AreNegative extends [false, false] ? SubtractPositives<A, B> : AreNegative extends [true, true] // When both numbers are negative we subtract the absolute values and then reverse the sign ? ReverseSign<SubtractPositives<NumberAbsolute<A>, NumberAbsolute<B>>> // When the signs are different we can add the absolute values and then reverse the sign if A < B : [...BuildTuple<NumberAbsolute<A>>, ...BuildTuple<NumberAbsolute<B>>] extends infer R extends unknown[] ? LessThan<A, B> extends true ? ReverseSign<R['length']> : R['length'] : never; /** Subtracts two positive numbers. */ type SubtractPositives<A extends number, B extends number> = LessThan<A, B> extends true // When A < B we can reverse the result of B - A ? ReverseSign<SubtractIfAGreaterThanB<B, A>> : SubtractIfAGreaterThanB<A, B>; /** Subtracts two positive numbers A and B such that A > B. */ type SubtractIfAGreaterThanB<A extends number, B extends number> = // This is where we always want to end up and do the actual subtraction BuildTuple<A> extends [...BuildTuple<B>, ...infer R] ? R['length'] : never; /** Paths options. @see {@link Paths} */ type PathsOptions = { /** The maximum depth to recurse when searching for paths. @default 10 */ maxRecursionDepth?: number; /** Use bracket notation for array indices and numeric object keys. @default false @example ``` type ArrayExample = { array: ['foo']; }; type A = Paths<ArrayExample, {bracketNotation: false}>; //=> 'array' | 'array.0' type B = Paths<ArrayExample, {bracketNotation: true}>; //=> 'array' | 'array[0]' ``` @example ``` type NumberKeyExample = { 1: ['foo']; }; type A = Paths<NumberKeyExample, {bracketNotation: false}>; //=> 1 | '1' | '1.0' type B = Paths<NumberKeyExample, {bracketNotation: true}>; //=> '[1]' | '[1][0]' ``` */ bracketNotation?: boolean; /** Only include leaf paths in the output. @default false @example ``` type Post = { id: number; author: { id: number; name: { first: string; last: string; }; }; }; type AllPaths = Paths<Post, {leavesOnly: false}>; //=> 'id' | 'author' | 'author.id' | 'author.name' | 'author.name.first' | 'author.name.last' type LeafPaths = Paths<Post, {leavesOnly: true}>; //=> 'id' | 'author.id' | 'author.name.first' | 'author.name.last' ``` @example ``` type ArrayExample = { array: Array<{foo: string}>; tuple: [string, {bar: string}]; }; type AllPaths = Paths<ArrayExample, {leavesOnly: false}>; //=> 'array' | `array.${number}` | `array.${number}.foo` | 'tuple' | 'tuple.0' | 'tuple.1' | 'tuple.1.bar' type LeafPaths = Paths<ArrayExample, {leavesOnly: true}>; //=> `array.${number}.foo` | 'tuple.0' | 'tuple.1.bar' ``` */ leavesOnly?: boolean; /** Only include paths at the specified depth. By default all paths up to {@link PathsOptions.maxRecursionDepth | `maxRecursionDepth`} are included. Note: Depth starts at `0` for root properties. @default number @example ``` type Post = { id: number; author: { id: number; name: { first: string; last: string; }; }; }; type DepthZero = Paths<Post, {depth: 0}>; //=> 'id' | 'author' type DepthOne = Paths<Post, {depth: 1}>; //=> 'author.id' | 'author.name' type DepthTwo = Paths<Post, {depth: 2}>; //=> 'author.name.first' | 'author.name.last' type LeavesAtDepthOne = Paths<Post, {leavesOnly: true; depth: 1}>; //=> 'author.id' ``` */ depth?: number; }; type DefaultPathsOptions = { maxRecursionDepth: 10; bracketNotation: false; leavesOnly: false; depth: number; }; /** Generate a union of all possible paths to properties in the given object. It also works with arrays. Use-case: You want a type-safe way to access deeply nested properties in an object. @example ``` import type {Paths} from 'type-fest'; type Project = { filename: string; listA: string[]; listB: [{filename: string}]; folder: { subfolder: { filename: string; }; }; }; type ProjectPaths = Paths<Project>; //=> 'filename' | 'listA' | 'listB' | 'folder' | `listA.${number}` | 'listB.0' | 'listB.0.filename' | 'folder.subfolder' | 'folder.subfolder.filename' declare function open<Path extends ProjectPaths>(path: Path): void; open('filename'); // Pass open('folder.subfolder'); // Pass open('folder.subfolder.filename'); // Pass open('foo'); // TypeError // Also works with arrays open('listA.1'); // Pass open('listB.0'); // Pass open('listB.1'); // TypeError. Because listB only has one element. ``` @category Object @category Array */ type Paths<T, Options extends PathsOptions = {}> = _Paths<T, { // Set default maxRecursionDepth to 10 maxRecursionDepth: Options['maxRecursionDepth'] extends number ? Options['maxRecursionDepth'] : DefaultPathsOptions['maxRecursionDepth']; // Set default bracketNotation to false bracketNotation: Options['bracketNotation'] extends boolean ? Options['bracketNotation'] : DefaultPathsOptions['bracketNotation']; // Set default leavesOnly to false leavesOnly: Options['leavesOnly'] extends boolean ? Options['leavesOnly'] : DefaultPathsOptions['leavesOnly']; // Set default depth to number depth: Options['depth'] extends number ? Options['depth'] : DefaultPathsOptions['depth']; }>; type _Paths<T, Options extends Required<PathsOptions>> = T extends NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> ? never : IsAny<T> extends true ? never : T extends UnknownArray ? number extends T['length'] // We need to handle the fixed and non-fixed index part of the array separately. ? InternalPaths<StaticPartOfArray<T>, Options> | InternalPaths<Array<VariablePartOfArray<T>[number]>, Options> : InternalPaths<T, Options> : T extends object ? InternalPaths<T, Options> : never; type InternalPaths<T, Options extends Required<PathsOptions>> = Options['maxRecursionDepth'] extends infer MaxDepth extends number ? Required<T> extends infer T ? T extends EmptyObject | readonly [] ? never : { [Key in keyof T]: Key extends string | number // Limit `Key` to string or number. ? ( Options['bracketNotation'] extends true ? IsNumberLike<Key> extends true ? `[${Key}]` : (Key | ToString<Key>) : never | Options['bracketNotation'] extends false // If `Key` is a number, return `Key | `${Key}``, because both `array[0]` and `array['0']` work. ? (Key | ToString<Key>) : never ) extends infer TranformedKey extends string | number ? // 1. If style is 'a[0].b' and 'Key' is a numberlike value like 3 or '3', transform 'Key' to `[${Key}]`, else to `${Key}` | Key // 2. If style is 'a.0.b', transform 'Key' to `${Key}` | Key | ((Options['leavesOnly'] extends true ? MaxDepth extends 0 ? TranformedKey : T[Key] extends EmptyObject | readonly [] | NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> ? TranformedKey : never : TranformedKey ) extends infer _TransformedKey // If `depth` is provided, the condition becomes truthy only when it reaches `0`. // Otherwise, since `depth` defaults to `number`, the condition is always truthy, returning paths at all depths. ? 0 extends Options['depth'] ? _TransformedKey : never : never) | ( // Recursively generate paths for the current key GreaterThan<MaxDepth, 0> extends true // Limit the depth to prevent infinite recursion ? _Paths<T[Key], { bracketNotation: Options['bracketNotation']; maxRecursionDepth: Subtract<MaxDepth, 1>; leavesOnly: Options['leavesOnly']; depth: Subtract<Options['depth'], 1>; }> extends infer SubPath ? SubPath extends string | number ? ( Options['bracketNotation'] extends true ? SubPath extends `[${any}]` | `[${any}]${string}` ? `${TranformedKey}${SubPath}` // If next node is number key like `[3]`, no need to add `.` before it. : `${TranformedKey}.${SubPath}` : never ) | ( Options['bracketNotation'] extends false ? `${TranformedKey}.${SubPath}` : never ) : never : never : never ) : never : never }[keyof T & (T extends UnknownArray ? number : unknown)] : never : never; /** Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals. This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore. @example ``` import type {LiteralUnion} from 'type-fest'; // Before type Pet = 'dog' | 'cat' | string; const pet: Pet = ''; // Start typing in your TypeScript-enabled IDE. // You **will not** get auto-completion for `dog` and `cat` literals. // After type Pet2 = LiteralUnion<'dog' | 'cat', string>; const pet: Pet2 = ''; // You **will** get auto-completion for `dog` and `cat` literals. ``` @category Type */ type LiteralUnion< LiteralType, BaseType extends Primitive, > = LiteralType | (BaseType & Record<never, never>); declare namespace PackageJson$1 { /** A person who has been involved in creating or maintaining the package. */ export type Person = | string | { name: string; url?: string; email?: string; }; export type BugsLocation = | string | { /** The URL to the package's issue tracker. */ url?: string; /** The email address to which issues should be reported. */ email?: string; }; export type DirectoryLocations = { [directoryType: string]: JsonValue | undefined; /** Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder. */ bin?: string; /** Location for Markdown files. */ doc?: string; /** Location for example scripts. */ example?: string; /** Location for the bulk of the library. */ lib?: string; /** Location for man pages. Sugar to generate a `man` array by walking the folder. */ man?: string; /** Location for test files. */ test?: string; }; export type Scripts = { /** Run **before** the package is published (Also run on local `npm install` without any arguments). */ prepublish?: string; /** Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`. */ prepare?: string; /** Run **before** the package is prepared and packed, **only** on `npm publish`. */ prepublishOnly?: string; /** Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies). */ prepack?: string; /** Run **after** the tarball has been generated and moved to its final destination. */ postpack?: string; /** Run **after** the package is published. */ publish?: string; /** Run **after** the package is published. */ postpublish?: string; /** Run **before** the package is installed. */ preinstall?: string; /** Run **after** the package is installed. */ install?: string; /** Run **after** the package is installed and after `install`. */ postinstall?: string; /** Run **before** the package is uninstalled and before `uninstall`. */ preuninstall?: string; /** Run **before** the package is uninstalled. */ uninstall?: string; /** Run **after** the package is uninstalled. */ postuninstall?: string; /** Run **before** bump the package version and before `version`. */ preversion?: string; /** Run **before** bump the package version. */ version?: string; /** Run **after** bump the package version. */ postversion?: string; /** Run with the `npm test` command, before `test`. */ pretest?: string; /** Run with the `npm test` command. */ test?: string; /** Run with the `npm test` command, after `test`. */ posttest?: string; /** Run with the `npm stop` command, before `stop`. */ prestop?: string; /** Run with the `npm stop` command. */ stop?: string; /** Run with the `npm stop` command, after `stop`. */ poststop?: string; /** Run with the `npm start` command, before `start`. */ prestart?: string; /** Run with the `npm start` command. */ start?: string; /** Run with the `npm start` command, after `start`. */ poststart?: string; /** Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. */ prerestart?: string; /** Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. */ restart?: string; /** Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. */ postrestart?: string; } & Partial<Record<string, string>>; /** Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL. */ export type Dependency = Partial<Record<string, string>>; /** A mapping of conditions and the paths to which they resolve. */ type ExportConditions = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style [condition: string]: Exports; }; /** Entry points of a module, optionally with conditions and subpath exports. */ export type Exports = | null | string | Array<string | ExportConditions> | ExportConditions; /** Import map entries of a module, optionally with conditions and subpath imports. */ export type Imports = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style [key: `#${string}`]: Exports; }; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export interface NonStandardEntryPoints { /** An ECMAScript module ID that is the primary entry point to the program. */ module?: string; /** A module ID with untranspiled code that is the primary entry point to the program. */ esnext?: | string | { [moduleName: string]: string | undefined; main?: string; browser?: string; }; /** A hint to JavaScript bundlers or component tools when packaging modules for client side use. */ browser?: | string | Partial<Record<string, string | false>>; /** Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. [Read more.](https://webpack.js.org/guides/tree-shaking/) */ sideEffects?: boolean | string[]; } export type TypeScriptConfiguration = { /** Location of the bundled TypeScript declaration file. */ types?: string; /** Version selection map of TypeScript. */ typesVersions?: Partial<Record<string, Partial<Record<string, string[]>>>>; /** Location of the bundled TypeScript declaration file. Alias of `types`. */ typings?: string; }; /** An alternative configuration for workspaces. */ export type WorkspaceConfig = { /** An array of workspace pattern strings which contain the workspace packages. */ packages?: WorkspacePattern[]; /** Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns. [Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn. [Not supported](https://github.com/npm/rfcs/issues/287) by npm. */ nohoist?: WorkspacePattern[]; }; /** A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process. The patterns are handled with [minimatch](https://github.com/isaacs/minimatch). @example `docs` → Include the docs directory and install its dependencies. `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`. */ type WorkspacePattern = string; export type YarnConfiguration = { /** If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`. Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line. */ flat?: boolean; /** Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file. */ resolutions?: Dependency; }; export type JSPMConfiguration = { /** JSPM configuration. */ jspm?: PackageJson$1; }; /** Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. */ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export interface PackageJsonStandard { /** The name of the package. */ name?: string; /** Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). */ version?: string; /** Package description, listed in `npm search`. */ description?: string; /** Keywords associated with package, listed in `npm search`. */ keywords?: string[]; /** The URL to the package's homepage. */ homepage?: LiteralUnion<'.', string>; /** The URL to the package's issue tracker and/or the email address to which issues should be reported. */ bugs?: BugsLocation; /** The license for the package. */ license?: string; /** The licenses for the package. */ licenses?: Array<{ type?: string; url?: string; }>; author?: Person; /** A list of people who contributed to the package. */ contributors?: Person[]; /** A list of people who maintain the package. */ maintainers?: Person[]; /** The files included in the package. */ files?: string[]; /** Resolution algorithm for importing ".js" files from the package's scope. [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) */ type?: 'module' | 'commonjs'; /** The module ID that is the primary entry point to the program. */ main?: string; /** Subpath exports to define entry points of the package. [Read more.](https://nodejs.org/api/packages.html#subpath-exports) */ exports?: Exports; /** Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself. [Read more.](https://nodejs.org/api/packages.html#subpath-imports) */ imports?: Imports; /** The executable files that should be installed into the `PATH`. */ bin?: | string | Partial<Record<string, string>>; /** Filenames to put in place for the `man` program to find. */ man?: string | string[]; /** Indicates the structure of the package. */ directories?: DirectoryLocations; /** Location for the code repository. */ repository?: | string | { type: string; url: string; /** Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo). [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md) */ directory?: string; }; /** Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. */ scripts?: Scripts; /** Is used to set configuration parameters used in package scripts that persist across upgrades. */ config?: JsonObject; /** The dependencies of the package. */ dependencies?: Dependency; /** Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. */ devDependencies?: Dependency; /** Dependencies that are skipped if they fail to install. */ optionalDependencies?: Dependency; /** Dependencies that will usually be required by the package user directly or via another dependency. */ peerDependencies?: Dependency; /** Indicate peer dependencies that are optional. */ peerDependenciesMeta?: Partial<Record<string, {optional: true}>>; /** Package names that are bundled when the package is published. */ bundledDependencies?: string[]; /** Alias of `bundledDependencies`. */ bundleDependencies?: string[]; /** Engines that this package runs on. */ engines?: { [EngineName in 'npm' | 'node' | string]?: string; }; /** @deprecated */ engineStrict?: boolean; /** Operating systems the module runs on. */ os?: Array<LiteralUnion< | 'aix' | 'darwin' | 'freebsd' | 'linux' | 'openbsd' | 'sunos' | 'win32' | '!aix' | '!darwin' | '!freebsd' | '!linux' | '!openbsd' | '!sunos' | '!win32', string >>; /** CPU architectures the module runs on. */ cpu?: Array<LiteralUnion< | 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x32' | 'x64' | '!arm' | '!arm64' | '!ia32' | '!mips' | '!mipsel' | '!ppc' | '!ppc64' | '!s390' | '!s390x' | '!x32' | '!x64', string >>; /** If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. @deprecated */ preferGlobal?: boolean; /** If set to `true`, then npm will refuse to publish it. */ private?: boolean; /** A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. */ publishConfig?: PublishConfig; /** Describes and notifies consumers of a package's monetary support information. [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md) */ funding?: string | { /** The type of funding. */ type?: LiteralUnion< | 'github' | 'opencollective' | 'patreon' | 'individual' | 'foundation' | 'corporation', string >; /** The URL to the funding page. */ url: string; }; /** Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/). Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run your install command once in order to install all of them in a single pass. Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces. */ workspaces?: WorkspacePattern[] | WorkspaceConfig; } /** Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions). */ export type NodeJsStandard = { /** Defines which package manager is expected to be used when working on the current project. It can set to any of the [supported package managers](https://nodejs.org/api/corepack.html#supported-package-managers), and will ensure that your teams use the exact same package manager versions without having to install anything else than Node.js. __This field is currently experimental and needs to be opted-in; check the [Corepack](https://nodejs.org/api/corepack.html) page for details about the procedure.__ @example ```json { "packageManager": "<package manager name>@<version>" } ``` */ packageManager?: string; }; export type PublishConfig = { /** Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig). */ [additionalProperties: string]: JsonValue | undefined; /** When publishing scoped packages, the access level defaults to restricted. If you want your scoped package to be publicly viewable (and installable) set `--access=public`. The only valid values for access are public and restricted. Unscoped packages always have an access level of public. */ access?: 'public' | 'restricted'; /** The base URL of the npm registry. Default: `'https://registry.npmjs.org/'` */ registry?: string; /** The tag to publish the package under. Default: `'latest'` */ tag?: string; }; } /** Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. @category File */ type PackageJson$1 = JsonObject & PackageJson$1.NodeJsStandard & PackageJson$1.PackageJsonStandard & PackageJson$1.NonStandardEntryPoints & PackageJson$1.TypeScriptConfiguration & PackageJson$1.YarnConfiguration & PackageJson$1.JSPMConfiguration; type Prettify<T> = { [K in keyof T]: T[K]; } & {}; type PartialDeep<T> = T extends object ? { [P in keyof T]?: PartialDeep<T[P]>; } : T; /** * Union type representing the possible statuses of a prompt. * * - `'loading'`: The prompt is currently loading. * - `'idle'`: The prompt is loaded and currently waiting for the user to * submit an answer. * - `'done'`: The user has submitted an answer and the prompt is finished. * - `string`: Any other string: The prompt is in a custom state. */ type Status = 'loading' | 'idle' | 'done' | (string & {}); type DefaultTheme = { /** * Prefix to prepend to the message. If a function is provided, it will be * called with the current status of the prompt, and the return value will be * used as the prefix. * * @remarks * If `status === 'loading'`, this property is ignored and the spinner (styled * by the `spinner` property) will be displayed instead. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (status) => status === 'done' ? colors.green('✔') : colors.blue('?') * ``` */ prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>; /** * Configuration for the spinner that is displayed when the prompt is in the * `'loading'` state. * * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners. */ spinner: { /** * The time interval between frames, in milliseconds. * * @defaultValue * ```ts * 80 * ``` */ interval: number; /** * A list of frames to show for the spinner. * * @defaultValue * ```ts * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] * ``` */ frames: string[]; }; /** * Object containing functions to style different parts of the prompt. */ style: { /** * Style to apply to the user's answer once it has been submitted. * * @param text - The user's answer. * @returns The styled answer. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text) => colors.cyan(text) * ``` */ answer: (text: string) => string; /** * Style to apply to the message displayed to the user. * * @param text - The message to style. * @param status - The current status of the prompt. * @returns The styled message. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text, status) => colors.bold(text) * ``` */ message: (text: string, status: Status) => string; /** * Style to apply to error messages. * * @param text - The error message. * @returns The styled error message. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text) => colors.red(`> ${text}`) * ``` */ error: (text: string) => string; /** * Style to apply to the default answer when one is provided. * * @param text - The default answer. * @returns The styled default answer. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text) => colors.dim(`(${text})`) * ``` */ defaultAnswer: (text: string) => string; /** * Style to apply to help text. * * @param text - The help text. * @returns The styled help text. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text) => colors.dim(text) * ``` */ help: (text: string) => string; /** * Style to apply to highlighted text. * * @param text - The text to highlight. * @returns The highlighted text. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text) => colors.cyan(text) * ``` */ highlight: (text: string) => string; /** * Style to apply to keyboard keys referred to in help texts. * * @param text - The key to style. * @returns The styled key. * * @defaultValue * ```ts * // import colors from 'yoctocolors-cjs'; * (text) => colors.cyan(colors.bold(`<${text}>`)) * ``` */ key: (text: string) => string; }; }; type Theme<Extension extends object = object> = Prettify<Extension & DefaultTheme>; type NormalizedPackageJson = Package & PackageJson; type PackageJson = PackageJson$1; type Cache<T = any> = Map<string, T>; type EnsurePackagesOptions = { confirm?: { default?: boolean; message: string | ((packages: string[]) => string); theme?: PartialDeep<Theme>; transformer?: (value: boolean) => string; }; cwd?: URL | string; deps?: boolean; devDeps?: boolean; installPackage?: Omit<InstallPackageOptions, "cwd" | "dev">; peerDeps?: boolean; }; type ReadOptions = { cache?: FindPackageJsonCache | boolean; ignoreWarnings?: (RegExp | string)[]; strict?: boolean; }; type FindPackageJsonCache = Cache<NormalizedReadResult>; type NormalizedReadResult = { packageJson: NormalizedPackageJson; path: string; }; declare const findPackageJson: (cwd?: URL | string, options?: ReadOptions) => Promise<NormalizedReadResult>; declare const findPackageJsonSync: (cwd?: URL | string, options?: ReadOptions) => NormalizedReadResult; declare const writePackageJson: <T = PackageJson>(data: T, options?: WriteJsonOptions & { cwd?: URL | string; }) => Promise<void>; declare const writePackageJsonSync: <T = PackageJson>(data: T, options?: WriteJsonOptions & { cwd?: URL | string; }) => void; declare const parsePackageJson: (packageFile: JsonObject | string, options?: { ignoreWarnings?: (RegExp | string)[]; strict?: boolean; }) => NormalizedPackageJson; declare const getPackageJsonProperty: <T = unknown>(packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>, defaultValue?: T) => T; declare const hasPackageJsonProperty: (packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>) => boolean; declare const hasPackageJsonAnyDependency: (packageJson: NormalizedPackageJson, arguments_: string[], options?: { peerDeps?: boolean; }) => boolean; declare const ensurePackages: (packageJson: NormalizedPackageJson, packages: string[],