UNPKG

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