index.d.ts 36 KB

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