UNPKG

36.5 kBTypeScriptView Raw
1/**
2Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
3
4@category Type
5*/
6type Primitive =
7 | null
8 | undefined
9 | string
10 | number
11 | boolean
12 | symbol
13 | bigint;
14
15/**
16Matches a JSON object.
17
18This 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 { … }`.
19
20@category JSON
21*/
22type JsonObject = {[Key in string]: JsonValue} & {[Key in string]?: JsonValue | undefined};
23
24/**
25Matches a JSON array.
26
27@category JSON
28*/
29type JsonArray = JsonValue[] | readonly JsonValue[];
30
31/**
32Matches any valid JSON primitive value.
33
34@category JSON
35*/
36type JsonPrimitive = string | number | boolean | null;
37
38/**
39Matches any valid JSON value.
40
41@see `Jsonify` if you need to transform a type to one that is assignable to `JsonValue`.
42
43@category JSON
44*/
45type JsonValue = JsonPrimitive | JsonObject | JsonArray;
46
47declare global {
48 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
49 interface SymbolConstructor {
50 readonly observable: symbol;
51 }
52}
53
54/**
55Remove spaces from the left side.
56*/
57type TrimLeft<V extends string> = V extends `${Whitespace}${infer R}` ? TrimLeft<R> : V;
58
59/**
60Remove spaces from the right side.
61*/
62type TrimRight<V extends string> = V extends `${infer R}${Whitespace}` ? TrimRight<R> : V;
63
64/**
65Remove leading and trailing spaces from a string.
66
67@example
68```
69import type {Trim} from 'type-fest';
70
71Trim<' foo '>
72//=> 'foo'
73```
74
75@category String
76@category Template literal
77*/
78type Trim<V extends string> = TrimLeft<TrimRight<V>>;
79
80type Whitespace =
81 | '\u{9}' // '\t'
82 | '\u{A}' // '\n'
83 | '\u{B}' // '\v'
84 | '\u{C}' // '\f'
85 | '\u{D}' // '\r'
86 | '\u{20}' // ' '
87 | '\u{85}'
88 | '\u{A0}'
89 | '\u{1680}'
90 | '\u{2000}'
91 | '\u{2001}'
92 | '\u{2002}'
93 | '\u{2003}'
94 | '\u{2004}'
95 | '\u{2005}'
96 | '\u{2006}'
97 | '\u{2007}'
98 | '\u{2008}'
99 | '\u{2009}'
100 | '\u{200A}'
101 | '\u{2028}'
102 | '\u{2029}'
103 | '\u{202F}'
104 | '\u{205F}'
105 | '\u{3000}'
106 | '\u{FEFF}';
107
108type WordSeparators = '-' | '_' | Whitespace;
109
110/**
111Returns a boolean for whether the string is lowercased.
112*/
113type IsLowerCase<T extends string> = T extends Lowercase<T> ? true : false;
114
115/**
116Returns a boolean for whether the string is uppercased.
117*/
118type IsUpperCase<T extends string> = T extends Uppercase<T> ? true : false;
119
120/**
121Returns a boolean for whether the string is numeric.
122
123This type is a workaround for [Microsoft/TypeScript#46109](https://github.com/microsoft/TypeScript/issues/46109#issuecomment-930307987).
124*/
125type IsNumeric<T extends string> = T extends `${number}`
126 ? Trim<T> extends T
127 ? true
128 : false
129 : false;
130
131/**
132Allows 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.
133
134Currently, 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.
135
136This 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.
137
138@example
139```
140import type {LiteralUnion} from 'type-fest';
141
142// Before
143
144type Pet = 'dog' | 'cat' | string;
145
146const pet: Pet = '';
147// Start typing in your TypeScript-enabled IDE.
148// You **will not** get auto-completion for `dog` and `cat` literals.
149
150// After
151
152type Pet2 = LiteralUnion<'dog' | 'cat', string>;
153
154const pet: Pet2 = '';
155// You **will** get auto-completion for `dog` and `cat` literals.
156```
157
158@category Type
159*/
160type LiteralUnion<
161 LiteralType,
162 BaseType extends Primitive,
163> = LiteralType | (BaseType & Record<never, never>);
164
165type SkipEmptyWord<Word extends string> = Word extends '' ? [] : [Word];
166
167type RemoveLastCharacter<Sentence extends string, Character extends string> = Sentence extends `${infer LeftSide}${Character}`
168 ? SkipEmptyWord<LeftSide>
169 : never;
170
171/**
172Split a string (almost) like Lodash's `_.words()` function.
173
174- Split on each word that begins with a capital letter.
175- Split on each {@link WordSeparators}.
176- Split on numeric sequence.
177
178@example
179```
180type Words0 = SplitWords<'helloWorld'>; // ['hello', 'World']
181type Words1 = SplitWords<'helloWORLD'>; // ['hello', 'WORLD']
182type Words2 = SplitWords<'hello-world'>; // ['hello', 'world']
183type Words3 = SplitWords<'--hello the_world'>; // ['hello', 'the', 'world']
184type Words4 = SplitWords<'lifeIs42'>; // ['life', 'Is', '42']
185```
186
187@internal
188@category Change case
189@category Template literal
190*/
191type SplitWords<
192 Sentence extends string,
193 LastCharacter extends string = '',
194 CurrentWord extends string = '',
195> = Sentence extends `${infer FirstCharacter}${infer RemainingCharacters}`
196 ? FirstCharacter extends WordSeparators
197 // Skip word separator
198 ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters>]
199 : LastCharacter extends ''
200 // Fist char of word
201 ? SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>
202 // Case change: non-numeric to numeric, push word
203 : [false, true] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
204 ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>]
205 // Case change: numeric to non-numeric, push word
206 : [true, false] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
207 ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>]
208 // No case change: concat word
209 : [true, true] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
210 ? SplitWords<RemainingCharacters, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
211 // Case change: lower to upper, push word
212 : [true, true] extends [IsLowerCase<LastCharacter>, IsUpperCase<FirstCharacter>]
213 ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>]
214 // Case change: upper to lower, brings back the last character, push word
215 : [true, true] extends [IsUpperCase<LastCharacter>, IsLowerCase<FirstCharacter>]
216 ? [...RemoveLastCharacter<CurrentWord, LastCharacter>, ...SplitWords<RemainingCharacters, FirstCharacter, `${LastCharacter}${FirstCharacter}`>]
217 // No case change: concat word
218 : SplitWords<RemainingCharacters, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
219 : [...SkipEmptyWord<CurrentWord>];
220
221/**
222CamelCase options.
223
224@see {@link CamelCase}
225*/
226type CamelCaseOptions = {
227 /**
228 Whether to preserved consecutive uppercase letter.
229
230 @default true
231 */
232 preserveConsecutiveUppercase?: boolean;
233};
234
235/**
236Convert an array of words to camel-case.
237*/
238type CamelCaseFromArray<
239 Words extends string[],
240 Options extends CamelCaseOptions,
241 OutputString extends string = '',
242> = Words extends [
243 infer FirstWord extends string,
244 ...infer RemainingWords extends string[],
245]
246 ? Options['preserveConsecutiveUppercase'] extends true
247 ? `${Capitalize<FirstWord>}${CamelCaseFromArray<RemainingWords, Options>}`
248 : `${Capitalize<Lowercase<FirstWord>>}${CamelCaseFromArray<RemainingWords, Options>}`
249 : OutputString;
250
251/**
252Convert a string literal to camel-case.
253
254This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
255
256By default, consecutive uppercase letter are preserved. See {@link CamelCaseOptions.preserveConsecutiveUppercase preserveConsecutiveUppercase} option to change this behaviour.
257
258@example
259```
260import type {CamelCase} from 'type-fest';
261
262// Simple
263
264const someVariable: CamelCase<'foo-bar'> = 'fooBar';
265
266// Advanced
267
268type CamelCasedProperties<T> = {
269 [K in keyof T as CamelCase<K>]: T[K]
270};
271
272interface RawOptions {
273 'dry-run': boolean;
274 'full_family_name': string;
275 foo: number;
276 BAR: string;
277 QUZ_QUX: number;
278 'OTHER-FIELD': boolean;
279}
280
281const dbResult: CamelCasedProperties<RawOptions> = {
282 dryRun: true,
283 fullFamilyName: 'bar.js',
284 foo: 123,
285 bar: 'foo',
286 quzQux: 6,
287 otherField: false
288};
289```
290
291@category Change case
292@category Template literal
293*/
294type CamelCase<Type, Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true}> = Type extends string
295 ? string extends Type
296 ? Type
297 : Uncapitalize<CamelCaseFromArray<SplitWords<Type extends Uppercase<Type> ? Lowercase<Type> : Type>, Options>>
298 : Type;
299
300/**
301Convert object properties to camel case but not recursively.
302
303This can be useful when, for example, converting some API types from a different style.
304
305@see CamelCasedPropertiesDeep
306@see CamelCase
307
308@example
309```
310import type {CamelCasedProperties} from 'type-fest';
311
312interface User {
313 UserId: number;
314 UserName: string;
315}
316
317const result: CamelCasedProperties<User> = {
318 userId: 1,
319 userName: 'Tom',
320};
321```
322
323@category Change case
324@category Template literal
325@category Object
326*/
327type CamelCasedProperties<Value, Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true}> = Value extends Function
328 ? Value
329 : Value extends Array<infer U>
330 ? Value
331 : {
332 [K in keyof Value as CamelCase<K, Options>]: Value[K];
333 };
334
335declare namespace PackageJson {
336 /**
337 A person who has been involved in creating or maintaining the package.
338 */
339 export type Person =
340 | string
341 | {
342 name: string;
343 url?: string;
344 email?: string;
345 };
346
347 export type BugsLocation =
348 | string
349 | {
350 /**
351 The URL to the package's issue tracker.
352 */
353 url?: string;
354
355 /**
356 The email address to which issues should be reported.
357 */
358 email?: string;
359 };
360
361 export type DirectoryLocations = {
362 [directoryType: string]: JsonValue | undefined;
363
364 /**
365 Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder.
366 */
367 bin?: string;
368
369 /**
370 Location for Markdown files.
371 */
372 doc?: string;
373
374 /**
375 Location for example scripts.
376 */
377 example?: string;
378
379 /**
380 Location for the bulk of the library.
381 */
382 lib?: string;
383
384 /**
385 Location for man pages. Sugar to generate a `man` array by walking the folder.
386 */
387 man?: string;
388
389 /**
390 Location for test files.
391 */
392 test?: string;
393 };
394
395 export type Scripts = {
396 /**
397 Run **before** the package is published (Also run on local `npm install` without any arguments).
398 */
399 prepublish?: string;
400
401 /**
402 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`.
403 */
404 prepare?: string;
405
406 /**
407 Run **before** the package is prepared and packed, **only** on `npm publish`.
408 */
409 prepublishOnly?: string;
410
411 /**
412 Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies).
413 */
414 prepack?: string;
415
416 /**
417 Run **after** the tarball has been generated and moved to its final destination.
418 */
419 postpack?: string;
420
421 /**
422 Run **after** the package is published.
423 */
424 publish?: string;
425
426 /**
427 Run **after** the package is published.
428 */
429 postpublish?: string;
430
431 /**
432 Run **before** the package is installed.
433 */
434 preinstall?: string;
435
436 /**
437 Run **after** the package is installed.
438 */
439 install?: string;
440
441 /**
442 Run **after** the package is installed and after `install`.
443 */
444 postinstall?: string;
445
446 /**
447 Run **before** the package is uninstalled and before `uninstall`.
448 */
449 preuninstall?: string;
450
451 /**
452 Run **before** the package is uninstalled.
453 */
454 uninstall?: string;
455
456 /**
457 Run **after** the package is uninstalled.
458 */
459 postuninstall?: string;
460
461 /**
462 Run **before** bump the package version and before `version`.
463 */
464 preversion?: string;
465
466 /**
467 Run **before** bump the package version.
468 */
469 version?: string;
470
471 /**
472 Run **after** bump the package version.
473 */
474 postversion?: string;
475
476 /**
477 Run with the `npm test` command, before `test`.
478 */
479 pretest?: string;
480
481 /**
482 Run with the `npm test` command.
483 */
484 test?: string;
485
486 /**
487 Run with the `npm test` command, after `test`.
488 */
489 posttest?: string;
490
491 /**
492 Run with the `npm stop` command, before `stop`.
493 */
494 prestop?: string;
495
496 /**
497 Run with the `npm stop` command.
498 */
499 stop?: string;
500
501 /**
502 Run with the `npm stop` command, after `stop`.
503 */
504 poststop?: string;
505
506 /**
507 Run with the `npm start` command, before `start`.
508 */
509 prestart?: string;
510
511 /**
512 Run with the `npm start` command.
513 */
514 start?: string;
515
516 /**
517 Run with the `npm start` command, after `start`.
518 */
519 poststart?: string;
520
521 /**
522 Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
523 */
524 prerestart?: string;
525
526 /**
527 Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
528 */
529 restart?: string;
530
531 /**
532 Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
533 */
534 postrestart?: string;
535 } & Partial<Record<string, string>>;
536
537 /**
538 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.
539 */
540 export type Dependency = Partial<Record<string, string>>;
541
542 /**
543 A mapping of conditions and the paths to which they resolve.
544 */
545 type ExportConditions = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
546 [condition: string]: Exports;
547 };
548
549 /**
550 Entry points of a module, optionally with conditions and subpath exports.
551 */
552 export type Exports =
553 | null
554 | string
555 | Array<string | ExportConditions>
556 | ExportConditions;
557
558 /**
559 Import map entries of a module, optionally with conditions and subpath imports.
560 */
561 export type Imports = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
562 [key: `#${string}`]: Exports;
563 };
564
565 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
566 export interface NonStandardEntryPoints {
567 /**
568 An ECMAScript module ID that is the primary entry point to the program.
569 */
570 module?: string;
571
572 /**
573 A module ID with untranspiled code that is the primary entry point to the program.
574 */
575 esnext?:
576 | string
577 | {
578 [moduleName: string]: string | undefined;
579 main?: string;
580 browser?: string;
581 };
582
583 /**
584 A hint to JavaScript bundlers or component tools when packaging modules for client side use.
585 */
586 browser?:
587 | string
588 | Partial<Record<string, string | false>>;
589
590 /**
591 Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused.
592
593 [Read more.](https://webpack.js.org/guides/tree-shaking/)
594 */
595 sideEffects?: boolean | string[];
596 }
597
598 export type TypeScriptConfiguration = {
599 /**
600 Location of the bundled TypeScript declaration file.
601 */
602 types?: string;
603
604 /**
605 Version selection map of TypeScript.
606 */
607 typesVersions?: Partial<Record<string, Partial<Record<string, string[]>>>>;
608
609 /**
610 Location of the bundled TypeScript declaration file. Alias of `types`.
611 */
612 typings?: string;
613 };
614
615 /**
616 An alternative configuration for workspaces.
617 */
618 export type WorkspaceConfig = {
619 /**
620 An array of workspace pattern strings which contain the workspace packages.
621 */
622 packages?: WorkspacePattern[];
623
624 /**
625 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.
626
627 [Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn.
628 [Not supported](https://github.com/npm/rfcs/issues/287) by npm.
629 */
630 nohoist?: WorkspacePattern[];
631 };
632
633 /**
634 A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process.
635
636 The patterns are handled with [minimatch](https://github.com/isaacs/minimatch).
637
638 @example
639 `docs` → Include the docs directory and install its dependencies.
640 `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`.
641 */
642 type WorkspacePattern = string;
643
644 export type YarnConfiguration = {
645 /**
646 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`.
647
648 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.
649 */
650 flat?: boolean;
651
652 /**
653 Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file.
654 */
655 resolutions?: Dependency;
656 };
657
658 export type JSPMConfiguration = {
659 /**
660 JSPM configuration.
661 */
662 jspm?: PackageJson;
663 };
664
665 /**
666 Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties.
667 */
668 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
669 export interface PackageJsonStandard {
670 /**
671 The name of the package.
672 */
673 name?: string;
674
675 /**
676 Package version, parseable by [`node-semver`](https://github.com/npm/node-semver).
677 */
678 version?: string;
679
680 /**
681 Package description, listed in `npm search`.
682 */
683 description?: string;
684
685 /**
686 Keywords associated with package, listed in `npm search`.
687 */
688 keywords?: string[];
689
690 /**
691 The URL to the package's homepage.
692 */
693 homepage?: LiteralUnion<'.', string>;
694
695 /**
696 The URL to the package's issue tracker and/or the email address to which issues should be reported.
697 */
698 bugs?: BugsLocation;
699
700 /**
701 The license for the package.
702 */
703 license?: string;
704
705 /**
706 The licenses for the package.
707 */
708 licenses?: Array<{
709 type?: string;
710 url?: string;
711 }>;
712
713 author?: Person;
714
715 /**
716 A list of people who contributed to the package.
717 */
718 contributors?: Person[];
719
720 /**
721 A list of people who maintain the package.
722 */
723 maintainers?: Person[];
724
725 /**
726 The files included in the package.
727 */
728 files?: string[];
729
730 /**
731 Resolution algorithm for importing ".js" files from the package's scope.
732
733 [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field)
734 */
735 type?: 'module' | 'commonjs';
736
737 /**
738 The module ID that is the primary entry point to the program.
739 */
740 main?: string;
741
742 /**
743 Subpath exports to define entry points of the package.
744
745 [Read more.](https://nodejs.org/api/packages.html#subpath-exports)
746 */
747 exports?: Exports;
748
749 /**
750 Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself.
751
752 [Read more.](https://nodejs.org/api/packages.html#subpath-imports)
753 */
754 imports?: Imports;
755
756 /**
757 The executable files that should be installed into the `PATH`.
758 */
759 bin?:
760 | string
761 | Partial<Record<string, string>>;
762
763 /**
764 Filenames to put in place for the `man` program to find.
765 */
766 man?: string | string[];
767
768 /**
769 Indicates the structure of the package.
770 */
771 directories?: DirectoryLocations;
772
773 /**
774 Location for the code repository.
775 */
776 repository?:
777 | string
778 | {
779 type: string;
780 url: string;
781
782 /**
783 Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo).
784
785 [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md)
786 */
787 directory?: string;
788 };
789
790 /**
791 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.
792 */
793 scripts?: Scripts;
794
795 /**
796 Is used to set configuration parameters used in package scripts that persist across upgrades.
797 */
798 config?: JsonObject;
799
800 /**
801 The dependencies of the package.
802 */
803 dependencies?: Dependency;
804
805 /**
806 Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling.
807 */
808 devDependencies?: Dependency;
809
810 /**
811 Dependencies that are skipped if they fail to install.
812 */
813 optionalDependencies?: Dependency;
814
815 /**
816 Dependencies that will usually be required by the package user directly or via another dependency.
817 */
818 peerDependencies?: Dependency;
819
820 /**
821 Indicate peer dependencies that are optional.
822 */
823 peerDependenciesMeta?: Partial<Record<string, {optional: true}>>;
824
825 /**
826 Package names that are bundled when the package is published.
827 */
828 bundledDependencies?: string[];
829
830 /**
831 Alias of `bundledDependencies`.
832 */
833 bundleDependencies?: string[];
834
835 /**
836 Engines that this package runs on.
837 */
838 engines?: {
839 [EngineName in 'npm' | 'node' | string]?: string;
840 };
841
842 /**
843 @deprecated
844 */
845 engineStrict?: boolean;
846
847 /**
848 Operating systems the module runs on.
849 */
850 os?: Array<LiteralUnion<
851 | 'aix'
852 | 'darwin'
853 | 'freebsd'
854 | 'linux'
855 | 'openbsd'
856 | 'sunos'
857 | 'win32'
858 | '!aix'
859 | '!darwin'
860 | '!freebsd'
861 | '!linux'
862 | '!openbsd'
863 | '!sunos'
864 | '!win32',
865 string
866 >>;
867
868 /**
869 CPU architectures the module runs on.
870 */
871 cpu?: Array<LiteralUnion<
872 | 'arm'
873 | 'arm64'
874 | 'ia32'
875 | 'mips'
876 | 'mipsel'
877 | 'ppc'
878 | 'ppc64'
879 | 's390'
880 | 's390x'
881 | 'x32'
882 | 'x64'
883 | '!arm'
884 | '!arm64'
885 | '!ia32'
886 | '!mips'
887 | '!mipsel'
888 | '!ppc'
889 | '!ppc64'
890 | '!s390'
891 | '!s390x'
892 | '!x32'
893 | '!x64',
894 string
895 >>;
896
897 /**
898 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.
899
900 @deprecated
901 */
902 preferGlobal?: boolean;
903
904 /**
905 If set to `true`, then npm will refuse to publish it.
906 */
907 private?: boolean;
908
909 /**
910 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.
911 */
912 publishConfig?: PublishConfig;
913
914 /**
915 Describes and notifies consumers of a package's monetary support information.
916
917 [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md)
918 */
919 funding?: string | {
920 /**
921 The type of funding.
922 */
923 type?: LiteralUnion<
924 | 'github'
925 | 'opencollective'
926 | 'patreon'
927 | 'individual'
928 | 'foundation'
929 | 'corporation',
930 string
931 >;
932
933 /**
934 The URL to the funding page.
935 */
936 url: string;
937 };
938
939 /**
940 Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/).
941
942 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.
943
944 Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces.
945 */
946 workspaces?: WorkspacePattern[] | WorkspaceConfig;
947 }
948
949 /**
950 Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions).
951 */
952 export type NodeJsStandard = {
953 /**
954 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.
955
956 __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.__
957
958 @example
959 ```json
960 {
961 "packageManager": "<package manager name>@<version>"
962 }
963 ```
964 */
965 packageManager?: string;
966 };
967
968 export type PublishConfig = {
969 /**
970 Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig).
971 */
972 [additionalProperties: string]: JsonValue | undefined;
973
974 /**
975 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.
976 */
977 access?: 'public' | 'restricted';
978
979 /**
980 The base URL of the npm registry.
981
982 Default: `'https://registry.npmjs.org/'`
983 */
984 registry?: string;
985
986 /**
987 The tag to publish the package under.
988
989 Default: `'latest'`
990 */
991 tag?: string;
992 };
993}
994
995/**
996Type 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.
997
998@category File
999*/
1000type PackageJson =
1001JsonObject &
1002PackageJson.NodeJsStandard &
1003PackageJson.PackageJsonStandard &
1004PackageJson.NonStandardEntryPoints &
1005PackageJson.TypeScriptConfiguration &
1006PackageJson.YarnConfiguration &
1007PackageJson.JSPMConfiguration;
1008
1009type FlagType = 'string' | 'boolean' | 'number';
1010
1011/**
1012Callback function to determine if a flag is required during runtime.
1013
1014@param flags - Contains the flags converted to camel-case excluding aliases.
1015@param input - Contains the non-flag arguments.
1016
1017@returns True if the flag is required, otherwise false.
1018*/
1019type IsRequiredPredicate = (flags: Readonly<AnyFlags>, input: readonly string[]) => boolean;
1020
1021type Flag<PrimitiveType extends FlagType, Type, IsMultiple = false> = {
1022 /**
1023 Type of value. (Possible values: `string` `boolean` `number`)
1024 */
1025 readonly type?: PrimitiveType;
1026
1027 /**
1028 Limit valid values to a predefined set of choices.
1029
1030 @example
1031 ```
1032 unicorn: {
1033 isMultiple: true,
1034 choices: ['rainbow', 'cat', 'unicorn']
1035 }
1036 ```
1037 */
1038 readonly choices?: Type extends unknown[] ? Type : Type[];
1039
1040 /**
1041 Default value when the flag is not specified.
1042
1043 @example
1044 ```
1045 unicorn: {
1046 type: 'boolean',
1047 default: true
1048 }
1049 ```
1050 */
1051 readonly default?: Type;
1052
1053 /**
1054 A short flag alias.
1055
1056 @example
1057 ```
1058 unicorn: {
1059 shortFlag: 'u'
1060 }
1061 ```
1062 */
1063 readonly shortFlag?: string;
1064
1065 /**
1066 Other names for the flag.
1067
1068 @example
1069 ```
1070 unicorn: {
1071 aliases: ['unicorns', 'uni']
1072 }
1073 ```
1074 */
1075 readonly aliases?: string[];
1076
1077 /**
1078 Indicates a flag can be set multiple times. Values are turned into an array.
1079
1080 Multiple values are provided by specifying the flag multiple times, for example, `$ foo -u rainbow -u cat`. Space- or comma-separated values [currently *not* supported](https://github.com/sindresorhus/meow/issues/164).
1081
1082 @default false
1083 */
1084 readonly isMultiple?: IsMultiple;
1085
1086 /**
1087 Determine if the flag is required.
1088
1089 If it's only known at runtime whether the flag is required or not you can pass a Function instead of a boolean, which based on the given flags and other non-flag arguments should decide if the flag is required.
1090
1091 - The first argument is the **flags** object, which contains the flags converted to camel-case excluding aliases.
1092 - The second argument is the **input** string array, which contains the non-flag arguments.
1093 - The function should return a `boolean`, true if the flag is required, otherwise false.
1094
1095 @default false
1096
1097 @example
1098 ```
1099 isRequired: (flags, input) => {
1100 if (flags.otherFlag) {
1101 return true;
1102 }
1103
1104 return false;
1105 }
1106 ```
1107 */
1108 readonly isRequired?: boolean | IsRequiredPredicate;
1109};
1110
1111type StringFlag = Flag<'string', string> | Flag<'string', string[], true>;
1112type BooleanFlag = Flag<'boolean', boolean> | Flag<'boolean', boolean[], true>;
1113type NumberFlag = Flag<'number', number> | Flag<'number', number[], true>;
1114type AnyFlag = StringFlag | BooleanFlag | NumberFlag;
1115type AnyFlags = Record<string, AnyFlag>;
1116
1117type Options<Flags extends AnyFlags> = {
1118 /**
1119 Pass in [`import.meta`](https://nodejs.org/dist/latest/docs/api/esm.html#esm_import_meta). This is used to find the correct package.json file.
1120 */
1121 readonly importMeta: ImportMeta;
1122
1123 /**
1124 Define argument flags.
1125
1126 The key is the flag name in camel-case and the value is an object with any of:
1127
1128 - `type`: Type of value. (Possible values: `string` `boolean` `number`)
1129 - `choices`: Limit valid values to a predefined set of choices.
1130 - `default`: Default value when the flag is not specified.
1131 - `shortFlag`: A short flag alias.
1132 - `aliases`: Other names for the flag.
1133 - `isMultiple`: Indicates a flag can be set multiple times. Values are turned into an array. (Default: false)
1134 - Multiple values are provided by specifying the flag multiple times, for example, `$ foo -u rainbow -u cat`. Space- or comma-separated values [currently *not* supported](https://github.com/sindresorhus/meow/issues/164).
1135 - `isRequired`: Determine if the flag is required. (Default: false)
1136 - If it's only known at runtime whether the flag is required or not, you can pass a `Function` instead of a `boolean`, which based on the given flags and other non-flag arguments, should decide if the flag is required. Two arguments are passed to the function:
1137 - The first argument is the **flags** object, which contains the flags converted to camel-case excluding aliases.
1138 - The second argument is the **input** string array, which contains the non-flag arguments.
1139 - The function should return a `boolean`, true if the flag is required, otherwise false.
1140
1141 Note that flags are always defined using a camel-case key (`myKey`), but will match arguments in kebab-case (`--my-key`).
1142
1143 @example
1144 ```
1145 flags: {
1146 unicorn: {
1147 type: 'string',
1148 choices: ['rainbow', 'cat', 'unicorn'],
1149 default: ['rainbow', 'cat'],
1150 shortFlag: 'u',
1151 aliases: ['unicorns']
1152 isMultiple: true,
1153 isRequired: (flags, input) => {
1154 if (flags.otherFlag) {
1155 return true;
1156 }
1157
1158 return false;
1159 }
1160 }
1161 }
1162 ```
1163 */
1164 readonly flags?: Flags;
1165
1166 /**
1167 Description to show above the help text. Default: The package.json `"description"` property.
1168
1169 Set it to `false` to disable it altogether.
1170 */
1171 readonly description?: string | false;
1172
1173 /**
1174 The help text you want shown.
1175
1176 The input is reindented and starting/ending newlines are trimmed which means you can use a [template literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings) without having to care about using the correct amount of indent.
1177
1178 The description will be shown above your help text automatically.
1179
1180 Set it to `false` to disable it altogether.
1181 */
1182 readonly help?: string | false;
1183
1184 /**
1185 Set a custom version output. Default: The package.json `"version"` property.
1186
1187 Set it to `false` to disable it altogether.
1188 */
1189 readonly version?: string | false;
1190
1191 /**
1192 Automatically show the help text when the `--help` flag is present. Useful to set this value to `false` when a CLI manages child CLIs with their own help text.
1193
1194 This option is only considered when there is only one argument in `process.argv`.
1195 */
1196 readonly autoHelp?: boolean;
1197
1198 /**
1199 Automatically show the version text when the `--version` flag is present. Useful to set this value to `false` when a CLI manages child CLIs with their own version text.
1200
1201 This option is only considered when there is only one argument in `process.argv`.
1202 */
1203 readonly autoVersion?: boolean;
1204
1205 /**
1206 `package.json` as an `Object`. Default: Closest `package.json` upwards.
1207
1208 Note: Setting this stops `meow` from finding a package.json.
1209
1210 _You most likely don't need this option._
1211 */
1212 readonly pkg?: Record<string, unknown>;
1213
1214 /**
1215 Custom arguments object.
1216
1217 @default process.argv.slice(2)
1218 */
1219 readonly argv?: readonly string[];
1220
1221 /**
1222 Infer the argument type.
1223
1224 By default, the argument `5` in `$ foo 5` becomes a string. Enabling this would infer it as a number.
1225
1226 @default false
1227 */
1228 readonly inferType?: boolean;
1229
1230 /**
1231 Value of `boolean` flags not defined in `argv`.
1232
1233 If set to `undefined`, the flags not defined in `argv` will be excluded from the result. The `default` value set in `boolean` flags take precedence over `booleanDefault`.
1234
1235 _Note: If used in conjunction with `isMultiple`, the default flag value is set to `[]`._
1236
1237 __Caution: Explicitly specifying `undefined` for `booleanDefault` has different meaning from omitting key itself.__
1238
1239 @example
1240 ```
1241 import meow from 'meow';
1242
1243 const cli = meow(`
1244 Usage
1245 $ foo
1246
1247 Options
1248 --rainbow, -r Include a rainbow
1249 --unicorn, -u Include a unicorn
1250 --no-sparkles Exclude sparkles
1251
1252 Examples
1253 $ foo
1254 🌈 unicorns✨🌈
1255 `, {
1256 importMeta: import.meta,
1257 booleanDefault: undefined,
1258 flags: {
1259 rainbow: {
1260 type: 'boolean',
1261 default: true,
1262 shortFlag: 'r'
1263 },
1264 unicorn: {
1265 type: 'boolean',
1266 default: false,
1267 shortFlag: 'u'
1268 },
1269 cake: {
1270 type: 'boolean',
1271 shortFlag: 'c'
1272 },
1273 sparkles: {
1274 type: 'boolean',
1275 default: true
1276 }
1277 }
1278 });
1279
1280 //{
1281 // flags: {
1282 // rainbow: true,
1283 // unicorn: false,
1284 // sparkles: true
1285 // },
1286 // unnormalizedFlags: {
1287 // rainbow: true,
1288 // r: true,
1289 // unicorn: false,
1290 // u: false,
1291 // sparkles: true
1292 // },
1293 // …
1294 //}
1295 ```
1296 */
1297 // eslint-disable-next-line @typescript-eslint/ban-types
1298 readonly booleanDefault?: boolean | null | undefined;
1299
1300 // TODO: Remove this in meow 14.
1301 /**
1302 Whether to use [hard-rejection](https://github.com/sindresorhus/hard-rejection) or not. Disabling this can be useful if you need to handle `process.on('unhandledRejection')` yourself.
1303
1304 @deprecated This is the default behavior since Node.js 16, so this option is moot.
1305 @default true
1306 */
1307 readonly hardRejection?: boolean;
1308
1309 /**
1310 Whether to allow unknown flags or not.
1311
1312 @default true
1313 */
1314 readonly allowUnknownFlags?: boolean;
1315
1316 /**
1317 The number of spaces to use for indenting the help text.
1318
1319 @default 2
1320 */
1321 readonly helpIndent?: number;
1322};
1323
1324type TypedFlag<Flag extends AnyFlag> =
1325 Flag extends {type: 'number'}
1326 ? number
1327 : Flag extends {type: 'string'}
1328 ? string
1329 : Flag extends {type: 'boolean'}
1330 ? boolean
1331 : unknown;
1332
1333type PossiblyOptionalFlag<Flag extends AnyFlag, FlagType> =
1334 Flag extends {isRequired: true}
1335 ? FlagType
1336 : Flag extends {default: any}
1337 ? FlagType
1338 : FlagType | undefined;
1339
1340type TypedFlags<Flags extends AnyFlags> = {
1341 [F in keyof Flags]: Flags[F] extends {isMultiple: true}
1342 ? PossiblyOptionalFlag<Flags[F], Array<TypedFlag<Flags[F]>>>
1343 : PossiblyOptionalFlag<Flags[F], TypedFlag<Flags[F]>>
1344};
1345
1346type Result<Flags extends AnyFlags> = {
1347 /**
1348 Non-flag arguments.
1349 */
1350 input: string[];
1351
1352 /**
1353 Flags converted to camelCase excluding aliases.
1354 */
1355 flags: CamelCasedProperties<TypedFlags<Flags>> & Record<string, unknown>;
1356
1357 /**
1358 Flags converted camelCase including aliases.
1359 */
1360 unnormalizedFlags: TypedFlags<Flags> & Record<string, unknown>;
1361
1362 /**
1363 The `package.json` object.
1364 */
1365 pkg: PackageJson;
1366
1367 /**
1368 The help text used with `--help`.
1369 */
1370 help: string;
1371
1372 /**
1373 Show the help text and exit with code.
1374
1375 @param exitCode - The exit code to use. Default: `2`.
1376 */
1377 showHelp: (exitCode?: number) => never;
1378
1379 /**
1380 Show the version text and exit.
1381 */
1382 showVersion: () => void;
1383};
1384/**
1385@param helpMessage - Shortcut for the `help` option.
1386
1387@example
1388```
1389#!/usr/bin/env node
1390import meow from 'meow';
1391import foo from './index.js';
1392
1393const cli = meow(`
1394 Usage
1395 $ foo <input>
1396
1397 Options
1398 --rainbow, -r Include a rainbow
1399
1400 Examples
1401 $ foo unicorns --rainbow
1402 🌈 unicorns 🌈
1403`, {
1404 importMeta: import.meta,
1405 flags: {
1406 rainbow: {
1407 type: 'boolean',
1408 shortFlag: 'r'
1409 }
1410 }
1411});
1412
1413//{
1414// input: ['unicorns'],
1415// flags: {rainbow: true},
1416// ...
1417//}
1418
1419foo(cli.input.at(0), cli.flags);
1420```
1421*/
1422declare function meow<Flags extends AnyFlags>(helpMessage: string, options?: Options<Flags>): Result<Flags>;
1423declare function meow<Flags extends AnyFlags>(options?: Options<Flags>): Result<Flags>;
1424
1425export { type Flag, type FlagType, type IsRequiredPredicate, type Options, type Result, type TypedFlags, meow as default };