UNPKG

28.4 kBTypeScriptView Raw
1// Type definitions for @babel/core 7.1
2// Project: https://github.com/babel/babel/tree/master/packages/babel-core, https://babeljs.io
3// Definitions by: Troy Gerwien <https://github.com/yortus>
4// Marvin Hagemeister <https://github.com/marvinhagemeister>
5// Melvin Groenhoff <https://github.com/mgroenhoff>
6// Jessica Franco <https://github.com/Jessidhia>
7// Ifiok Jr. <https://github.com/ifiokjr>
8// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
9// Minimum TypeScript Version: 3.4
10
11import { GeneratorOptions } from '@babel/generator';
12import { ParserOptions } from '@babel/parser';
13import template from '@babel/template';
14import traverse, { Hub, NodePath, Scope, Visitor } from '@babel/traverse';
15import * as t from '@babel/types';
16
17export { ParserOptions, GeneratorOptions, t as types, template, traverse, NodePath, Visitor };
18
19export type Node = t.Node;
20export type ParseResult = ReturnType<typeof import('@babel/parser').parse>;
21export const version: string;
22export const DEFAULT_EXTENSIONS: ['.js', '.jsx', '.es6', '.es', '.mjs'];
23
24/**
25 * Source map standard format as to revision 3
26 * @see {@link https://sourcemaps.info/spec.html}
27 * @see {@link https://github.com/mozilla/source-map/blob/HEAD/source-map.d.ts}
28 */
29interface InputSourceMap {
30 version: number;
31 sources: string[];
32 names: string[];
33 sourceRoot?: string | undefined;
34 sourcesContent?: string[] | undefined;
35 mappings: string;
36 file: string;
37}
38
39export interface TransformOptions {
40 /**
41 * Include the AST in the returned object
42 *
43 * Default: `false`
44 */
45 ast?: boolean | null | undefined;
46
47 /**
48 * Attach a comment after all non-user injected code
49 *
50 * Default: `null`
51 */
52 auxiliaryCommentAfter?: string | null | undefined;
53
54 /**
55 * Attach a comment before all non-user injected code
56 *
57 * Default: `null`
58 */
59 auxiliaryCommentBefore?: string | null | undefined;
60
61 /**
62 * Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.
63 *
64 * Default: `"."`
65 */
66 root?: string | null | undefined;
67
68 /**
69 * This option, combined with the "root" value, defines how Babel chooses its project root.
70 * The different modes define different ways that Babel can process the "root" value to get
71 * the final project root.
72 *
73 * @see https://babeljs.io/docs/en/next/options#rootmode
74 */
75 rootMode?: 'root' | 'upward' | 'upward-optional' | undefined;
76
77 /**
78 * The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.
79 *
80 * Default: `undefined`
81 */
82 configFile?: string | boolean | null | undefined;
83
84 /**
85 * Specify whether or not to use .babelrc and
86 * .babelignore files.
87 *
88 * Default: `true`
89 */
90 babelrc?: boolean | null | undefined;
91
92 /**
93 * Specify which packages should be search for .babelrc files when they are being compiled. `true` to always search, or a path string or an array of paths to packages to search
94 * inside of. Defaults to only searching the "root" package.
95 *
96 * Default: `(root)`
97 */
98 babelrcRoots?: boolean | MatchPattern | MatchPattern[] | null | undefined;
99
100 /**
101 * Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json.
102 * This is useful for projects that use a browserslist config for files that won't be compiled with Babel.
103 *
104 * If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies
105 * this option, or to `cwd` when it's passed as part of the programmatic options.
106 *
107 * Default: `true`
108 */
109 browserslistConfigFile?: boolean | null | undefined;
110
111 /**
112 * The Browserslist environment to use.
113 *
114 * Default: `undefined`
115 */
116 browserslistEnv?: string | null | undefined;
117
118 /**
119 * By default `babel.transformFromAst` will clone the input AST to avoid mutations.
120 * Specifying `cloneInputAst: false` can improve parsing performance if the input AST is not used elsewhere.
121 *
122 * Default: `true`
123 */
124 cloneInputAst?: boolean | null | undefined;
125
126 /**
127 * Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"`
128 *
129 * Default: env vars
130 */
131 envName?: string | undefined;
132
133 /**
134 * If any of patterns match, the current configuration object is considered inactive and is ignored during config processing.
135 */
136 exclude?: MatchPattern | MatchPattern[] | undefined;
137
138 /**
139 * Enable code generation
140 *
141 * Default: `true`
142 */
143 code?: boolean | null | undefined;
144
145 /**
146 * Output comments in generated output
147 *
148 * Default: `true`
149 */
150 comments?: boolean | null | undefined;
151
152 /**
153 * Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB
154 *
155 * Default: `"auto"`
156 */
157 compact?: boolean | 'auto' | null | undefined;
158
159 /**
160 * The working directory that Babel's programmatic options are loaded relative to.
161 *
162 * Default: `"."`
163 */
164 cwd?: string | null | undefined;
165
166 /**
167 * Utilities may pass a caller object to identify themselves to Babel and
168 * pass capability-related flags for use by configs, presets and plugins.
169 *
170 * @see https://babeljs.io/docs/en/next/options#caller
171 */
172 caller?: TransformCaller | undefined;
173
174 /**
175 * This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }`
176 * which will use those options when the `envName` is `production`
177 *
178 * Default: `{}`
179 */
180 env?: { [index: string]: TransformOptions | null | undefined } | null | undefined;
181
182 /**
183 * A path to a `.babelrc` file to extend
184 *
185 * Default: `null`
186 */
187 extends?: string | null | undefined;
188
189 /**
190 * Filename for use in errors etc
191 *
192 * Default: `"unknown"`
193 */
194 filename?: string | null | undefined;
195
196 /**
197 * Filename relative to `sourceRoot`
198 *
199 * Default: `(filename)`
200 */
201 filenameRelative?: string | null | undefined;
202
203 /**
204 * An object containing the options to be passed down to the babel code generator, @babel/generator
205 *
206 * Default: `{}`
207 */
208 generatorOpts?: GeneratorOptions | null | undefined;
209
210 /**
211 * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used
212 *
213 * Default: `null`
214 */
215 getModuleId?: ((moduleName: string) => string | null | undefined) | null | undefined;
216
217 /**
218 * ANSI highlight syntax error code frames
219 *
220 * Default: `true`
221 */
222 highlightCode?: boolean | null | undefined;
223
224 /**
225 * Opposite to the `only` option. `ignore` is disregarded if `only` is specified
226 *
227 * Default: `null`
228 */
229 ignore?: MatchPattern[] | null | undefined;
230
231 /**
232 * This option is a synonym for "test"
233 */
234 include?: MatchPattern | MatchPattern[] | undefined;
235
236 /**
237 * A source map object that the output source map will be based on
238 *
239 * Default: `null`
240 */
241 inputSourceMap?: InputSourceMap | null | undefined;
242
243 /**
244 * Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe)
245 *
246 * Default: `false`
247 */
248 minified?: boolean | null | undefined;
249
250 /**
251 * Specify a custom name for module ids
252 *
253 * Default: `null`
254 */
255 moduleId?: string | null | undefined;
256
257 /**
258 * If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules)
259 *
260 * Default: `false`
261 */
262 moduleIds?: boolean | null | undefined;
263
264 /**
265 * Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions
266 *
267 * Default: `(sourceRoot)`
268 */
269 moduleRoot?: string | null | undefined;
270
271 /**
272 * A glob, regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile
273 * a non-matching file it's returned verbatim
274 *
275 * Default: `null`
276 */
277 only?: MatchPattern[] | null | undefined;
278
279 /**
280 * Allows users to provide an array of options that will be merged into the current configuration one at a time.
281 * This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply
282 */
283 overrides?: TransformOptions[] | undefined;
284
285 /**
286 * An object containing the options to be passed down to the babel parser, @babel/parser
287 *
288 * Default: `{}`
289 */
290 parserOpts?: ParserOptions | null | undefined;
291
292 /**
293 * List of plugins to load and use
294 *
295 * Default: `[]`
296 */
297 plugins?: PluginItem[] | null | undefined;
298
299 /**
300 * List of presets (a set of plugins) to load and use
301 *
302 * Default: `[]`
303 */
304 presets?: PluginItem[] | null | undefined;
305
306 /**
307 * Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE**: This will not retain the columns)
308 *
309 * Default: `false`
310 */
311 retainLines?: boolean | null | undefined;
312
313 /**
314 * An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comment` option when used
315 *
316 * Default: `null`
317 */
318 shouldPrintComment?: ((commentContents: string) => boolean) | null | undefined;
319
320 /**
321 * Set `sources[0]` on returned source map
322 *
323 * Default: `(filenameRelative)`
324 */
325 sourceFileName?: string | null | undefined;
326
327 /**
328 * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"`
329 * then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!**
330 *
331 * Default: `false`
332 */
333 sourceMaps?: boolean | 'inline' | 'both' | null | undefined;
334
335 /**
336 * The root from which all sources are relative
337 *
338 * Default: `(moduleRoot)`
339 */
340 sourceRoot?: string | null | undefined;
341
342 /**
343 * Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to guess, based on the presence of ES6
344 * `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`.
345 *
346 * Default: `("module")`
347 */
348 sourceType?: 'script' | 'module' | 'unambiguous' | null | undefined;
349
350 /**
351 * If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing.
352 */
353 test?: MatchPattern | MatchPattern[] | undefined;
354
355 /**
356 * An optional callback that can be used to wrap visitor methods. **NOTE**: This is useful for things like introspection, and not really needed for implementing anything. Called as
357 * `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.
358 */
359 wrapPluginVisitorMethod?:
360 | ((
361 pluginAlias: string,
362 visitorType: 'enter' | 'exit',
363 callback: (path: NodePath, state: any) => void,
364 ) => (path: NodePath, state: any) => void)
365 | null | undefined;
366}
367
368export interface TransformCaller {
369 // the only required property
370 name: string;
371 // e.g. set to true by `babel-loader` and false by `babel-jest`
372 supportsStaticESM?: boolean | undefined;
373 supportsDynamicImport?: boolean | undefined;
374 supportsExportNamespaceFrom?: boolean | undefined;
375 supportsTopLevelAwait?: boolean | undefined;
376 // augment this with a "declare module '@babel/core' { ... }" if you need more keys
377}
378
379export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any;
380
381export interface MatchPatternContext {
382 envName: string;
383 dirname: string;
384 caller: TransformCaller | undefined;
385}
386export type MatchPattern = string | RegExp | ((filename: string | undefined, context: MatchPatternContext) => boolean);
387
388/**
389 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
390 */
391export function transform(code: string, callback: FileResultCallback): void;
392
393/**
394 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
395 */
396export function transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
397
398/**
399 * Here for backward-compatibility. Ideally use `transformSync` if you want a synchronous API.
400 */
401export function transform(code: string, opts?: TransformOptions): BabelFileResult | null;
402
403/**
404 * Transforms the passed in code. Returning an object with the generated code, source map, and AST.
405 */
406export function transformSync(code: string, opts?: TransformOptions): BabelFileResult | null;
407
408/**
409 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
410 */
411export function transformAsync(code: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
412
413/**
414 * Asynchronously transforms the entire contents of a file.
415 */
416export function transformFile(filename: string, callback: FileResultCallback): void;
417
418/**
419 * Asynchronously transforms the entire contents of a file.
420 */
421export function transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
422
423/**
424 * Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`.
425 */
426export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult | null;
427
428/**
429 * Asynchronously transforms the entire contents of a file.
430 */
431export function transformFileAsync(filename: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
432
433/**
434 * Given an AST, transform it.
435 */
436export function transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback): void;
437
438/**
439 * Given an AST, transform it.
440 */
441export function transformFromAst(
442 ast: Node,
443 code: string | undefined,
444 opts: TransformOptions | undefined,
445 callback: FileResultCallback,
446): void;
447
448/**
449 * Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API.
450 */
451export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult | null;
452
453/**
454 * Given an AST, transform it.
455 */
456export function transformFromAstAsync(
457 ast: Node,
458 code?: string,
459 opts?: TransformOptions,
460): Promise<BabelFileResult | null>;
461
462// A babel plugin is a simple function which must return an object matching
463// the following interface. Babel will throw if it finds unknown properties.
464// The list of allowed plugin keys is here:
465// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71
466export interface PluginObj<S = PluginPass> {
467 name?: string | undefined;
468 manipulateOptions?(opts: any, parserOpts: any): void;
469 pre?(this: S, file: BabelFile): void;
470 visitor: Visitor<S>;
471 post?(this: S, file: BabelFile): void;
472 inherits?: any;
473}
474
475export interface BabelFile {
476 ast: t.File;
477 opts: TransformOptions;
478 hub: Hub;
479 metadata: object;
480 path: NodePath<t.Program>;
481 scope: Scope;
482 inputMap: object | null;
483 code: string;
484}
485
486export interface PluginPass {
487 file: BabelFile;
488 key: string;
489 opts: object;
490 cwd: string;
491 filename: string | undefined;
492 get(key: unknown): any;
493 set(key: unknown, value: unknown): void;
494 [key: string]: unknown;
495}
496
497export interface BabelFileResult {
498 ast?: t.File | null | undefined;
499 code?: string | null | undefined;
500 ignored?: boolean | undefined;
501 map?: {
502 version: number;
503 sources: string[];
504 names: string[];
505 sourceRoot?: string | undefined;
506 sourcesContent?: string[] | undefined;
507 mappings: string;
508 file: string;
509 } | null | undefined;
510 metadata?: BabelFileMetadata | undefined;
511}
512
513export interface BabelFileMetadata {
514 usedHelpers: string[];
515 marked: Array<{
516 type: string;
517 message: string;
518 loc: object;
519 }>;
520 modules: BabelFileModulesMetadata;
521}
522
523export interface BabelFileModulesMetadata {
524 imports: object[];
525 exports: {
526 exported: object[];
527 specifiers: object[];
528 };
529}
530
531export type FileParseCallback = (err: Error | null, result: ParseResult | null) => any;
532
533/**
534 * Given some code, parse it using Babel's standard behavior.
535 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
536 */
537export function parse(code: string, callback: FileParseCallback): void;
538
539/**
540 * Given some code, parse it using Babel's standard behavior.
541 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
542 */
543export function parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback): void;
544
545/**
546 * Given some code, parse it using Babel's standard behavior.
547 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
548 */
549export function parse(code: string, options?: TransformOptions): ParseResult | null;
550
551/**
552 * Given some code, parse it using Babel's standard behavior.
553 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
554 */
555export function parseSync(code: string, options?: TransformOptions): ParseResult | null;
556
557/**
558 * Given some code, parse it using Babel's standard behavior.
559 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
560 */
561export function parseAsync(code: string, options?: TransformOptions): Promise<ParseResult | null>;
562
563/**
564 * Resolve Babel's options fully, resulting in an options object where:
565 *
566 * * opts.plugins is a full list of Plugin instances.
567 * * opts.presets is empty and all presets are flattened into opts.
568 * * It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel
569 * will not make a second attempt to load config files.
570 *
571 * Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to
572 * use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to
573 * invalidate properly, but it is the best we have at the moment.
574 */
575export function loadOptions(options?: TransformOptions): object | null;
576
577/**
578 * To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and
579 * presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it
580 * as then see fit and pass it back to Babel again.
581 *
582 * * `babelrc: string | void` - The path of the `.babelrc` file, if there was one.
583 * * `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
584 * * `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back
585 * to Babel again.
586 * * `plugins: Array<ConfigItem>` - See below.
587 * * `presets: Array<ConfigItem>` - See below.
588 * * It can be safely passed back to Babel. Fields like `babelrc` have been set to false so that later calls to
589 * Babel will not make a second attempt to load config files.
590 *
591 * `ConfigItem` instances expose properties to introspect the values, but each item should be treated as
592 * immutable. If changes are desired, the item should be removed from the list and replaced with either a normal
593 * Babel config value, or with a replacement item created by `babel.createConfigItem`. See that function for
594 * information about `ConfigItem` fields.
595 */
596export function loadPartialConfig(options?: TransformOptions): Readonly<PartialConfig> | null;
597export function loadPartialConfigAsync(options?: TransformOptions): Promise<Readonly<PartialConfig> | null>;
598
599export interface PartialConfig {
600 options: TransformOptions;
601 babelrc?: string | undefined;
602 babelignore?: string | undefined;
603 config?: string | undefined;
604 hasFilesystemConfig: () => boolean;
605}
606
607export interface ConfigItem {
608 /**
609 * The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
610 */
611 name?: string | undefined;
612
613 /**
614 * The resolved value of the plugin.
615 */
616 value: object | ((...args: any[]) => any);
617
618 /**
619 * The options object passed to the plugin.
620 */
621 options?: object | false | undefined;
622
623 /**
624 * The path that the options are relative to.
625 */
626 dirname: string;
627
628 /**
629 * Information about the plugin's file, if Babel knows it.
630 * *
631 */
632 file?: {
633 /**
634 * The file that the user requested, e.g. `"@babel/env"`
635 */
636 request: string;
637
638 /**
639 * The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`
640 */
641 resolved: string;
642 } | null | undefined;
643}
644
645export type PluginOptions = object | undefined | false;
646
647export type PluginTarget = string | object | ((...args: any[]) => any);
648
649export type PluginItem =
650 | ConfigItem
651 | PluginObj<any>
652 | PluginTarget
653 | [PluginTarget, PluginOptions]
654 | [PluginTarget, PluginOptions, string | undefined];
655
656export function resolvePlugin(name: string, dirname: string): string | null;
657export function resolvePreset(name: string, dirname: string): string | null;
658
659export interface CreateConfigItemOptions {
660 dirname?: string | undefined;
661 type?: 'preset' | 'plugin' | undefined;
662}
663
664/**
665 * Allows build tooling to create and cache config items up front. If this function is called multiple times for a
666 * given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected
667 * plugins and presets to inject, pre-constructing the config items would be recommended.
668 */
669export function createConfigItem(
670 value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined],
671 options?: CreateConfigItemOptions,
672): ConfigItem;
673
674// NOTE: the documentation says the ConfigAPI also exposes @babel/core's exports, but it actually doesn't
675/**
676 * @see https://babeljs.io/docs/en/next/config-files#config-function-api
677 */
678export interface ConfigAPI {
679 /**
680 * The version string for the Babel version that is loading the config file.
681 *
682 * @see https://babeljs.io/docs/en/next/config-files#apiversion
683 */
684 version: string;
685 /**
686 * @see https://babeljs.io/docs/en/next/config-files#apicache
687 */
688 cache: SimpleCacheConfigurator;
689 /**
690 * @see https://babeljs.io/docs/en/next/config-files#apienv
691 */
692 env: EnvFunction;
693 // undocumented; currently hardcoded to return 'false'
694 // async(): boolean
695 /**
696 * This API is used as a way to access the `caller` data that has been passed to Babel.
697 * Since many instances of Babel may be running in the same process with different `caller` values,
698 * this API is designed to automatically configure `api.cache`, the same way `api.env()` does.
699 *
700 * The `caller` value is available as the first parameter of the callback function.
701 * It is best used with something like this to toggle configuration behavior
702 * based on a specific environment:
703 *
704 * @example
705 * function isBabelRegister(caller?: { name: string }) {
706 * return !!(caller && caller.name === "@babel/register")
707 * }
708 * api.caller(isBabelRegister)
709 *
710 * @see https://babeljs.io/docs/en/next/config-files#apicallercb
711 */
712 caller<T extends SimpleCacheKey>(callerCallback: (caller: TransformOptions['caller']) => T): T;
713 /**
714 * While `api.version` can be useful in general, it's sometimes nice to just declare your version.
715 * This API exposes a simple way to do that with:
716 *
717 * @example
718 * api.assertVersion(7) // major version only
719 * api.assertVersion("^7.2")
720 *
721 * @see https://babeljs.io/docs/en/next/config-files#apiassertversionrange
722 */
723 assertVersion(versionRange: number | string): boolean;
724 // NOTE: this is an undocumented reexport from "@babel/parser" but it's missing from its types
725 // tokTypes: typeof tokTypes
726}
727
728/**
729 * JS configs are great because they can compute a config on the fly,
730 * but the downside there is that it makes caching harder.
731 * Babel wants to avoid re-executing the config function every time a file is compiled,
732 * because then it would also need to re-execute any plugin and preset functions
733 * referenced in that config.
734 *
735 * To avoid this, Babel expects users of config functions to tell it how to manage caching
736 * within a config file.
737 *
738 * @see https://babeljs.io/docs/en/next/config-files#apicache
739 */
740export interface SimpleCacheConfigurator {
741 // there is an undocumented call signature that is a shorthand for forever()/never()/using().
742 // (ever: boolean): void
743 // <T extends SimpleCacheKey>(callback: CacheCallback<T>): T
744 /**
745 * Permacache the computed config and never call the function again.
746 */
747 forever(): void;
748 /**
749 * Do not cache this config, and re-execute the function every time.
750 */
751 never(): void;
752 /**
753 * Any time the using callback returns a value other than the one that was expected,
754 * the overall config function will be called again and a new entry will be added to the cache.
755 *
756 * @example
757 * api.cache.using(() => process.env.NODE_ENV)
758 */
759 using<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T;
760 /**
761 * Any time the using callback returns a value other than the one that was expected,
762 * the overall config function will be called again and all entries in the cache will
763 * be replaced with the result.
764 *
765 * @example
766 * api.cache.invalidate(() => process.env.NODE_ENV)
767 */
768 invalidate<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T;
769}
770
771// https://github.com/babel/babel/blob/v7.3.3/packages/babel-core/src/config/caching.js#L231
772export type SimpleCacheKey = string | boolean | number | null | undefined;
773export type SimpleCacheCallback<T extends SimpleCacheKey> = () => T;
774
775/**
776 * Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function
777 * meant specifically for that. This API is used as a quick way to check the `"envName"` that Babel
778 * was loaded with, which takes `NODE_ENV` into account if no other overriding environment is set.
779 *
780 * @see https://babeljs.io/docs/en/next/config-files#apienv
781 */
782export interface EnvFunction {
783 /**
784 * @returns the current `envName` string
785 */
786 (): string;
787 /**
788 * @returns `true` if the `envName` is `===` any of the given strings
789 */
790 (envName: string | ReadonlyArray<string>): boolean;
791 // the official documentation is misleading for this one...
792 // this just passes the callback to `cache.using` but with an additional argument.
793 // it returns its result instead of necessarily returning a boolean.
794 <T extends SimpleCacheKey>(envCallback: (envName: NonNullable<TransformOptions['envName']>) => T): T;
795}
796
797export type ConfigFunction = (api: ConfigAPI) => TransformOptions;
798
799export as namespace babel;