Skip to content

Commit

Permalink
Pass "targets" to plugins and presets
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Oct 15, 2020
1 parent 96e0bbf commit 31431e0
Show file tree
Hide file tree
Showing 11 changed files with 95 additions and 12 deletions.
4 changes: 2 additions & 2 deletions packages/babel-core/src/config/files/configuration.js
Expand Up @@ -9,7 +9,7 @@ import {
makeWeakCacheSync,
type CacheConfigurator,
} from "../caching";
import makeAPI, { type PluginAPI } from "../helpers/config-api";
import { makeConfigAPI, type ConfigAPI } from "../helpers/config-api";
import { makeStaticFileCache } from "./utils";
import loadCjsOrMjsDefault from "./module-types";
import pathPatternToRegex from "../pattern-to-regex";
Expand Down Expand Up @@ -204,7 +204,7 @@ const readConfigJS = makeStrongCache(function* readConfigJS(
let assertCache = false;
if (typeof options === "function") {
yield* []; // if we want to make it possible to use async configs
options = ((options: any): (api: PluginAPI) => {})(makeAPI(cache));
options = ((options: any): (api: ConfigAPI) => {})(makeConfigAPI(cache));

assertCache = true;
}
Expand Down
24 changes: 18 additions & 6 deletions packages/babel-core/src/config/full.js
Expand Up @@ -14,6 +14,7 @@ import {
type PresetInstance,
} from "./config-chain";
import type { UnloadedDescriptor } from "./config-descriptors";
import type { Targets } from "@babel/helper-compilation-targets";
import traverse from "@babel/traverse";
import {
makeWeakCache,
Expand All @@ -27,7 +28,7 @@ import {
type PluginItem,
} from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
import makeAPI from "./helpers/config-api";
import { makePluginAPI } from "./helpers/config-api";

import loadPrivatePartialConfig from "./partial";
import type { ValidatedOptions } from "./validation/options";
Expand All @@ -39,6 +40,11 @@ type LoadedDescriptor = {
alias: string,
};

type PluginContext = {
...ConfigContext,
targets: Targets,
};

export type { InputOptions } from "./validation/options";

export type ResolvedConfig = {
Expand All @@ -55,6 +61,7 @@ export type PluginPasses = Array<PluginPassList>;
type SimpleContext = {
envName: string,
caller: CallerMetadata | void,
targets: Targets,
};

export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
Expand All @@ -78,6 +85,11 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
throw new Error("Assertion failure - plugins and presets exist");
}

const pluginContext: PluginContext = {
...context,
targets: options.targets,
};

const toDescriptor = (item: PluginItem) => {
const desc = getItemDescriptor(item);
if (!desc) {
Expand Down Expand Up @@ -112,12 +124,12 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
// in the previous pass.
if (descriptor.ownPass) {
presets.push({
preset: yield* loadPresetDescriptor(descriptor, context),
preset: yield* loadPresetDescriptor(descriptor, pluginContext),
pass: [],
});
} else {
presets.unshift({
preset: yield* loadPresetDescriptor(descriptor, context),
preset: yield* loadPresetDescriptor(descriptor, pluginContext),
pass: pluginDescriptorsPass,
});
}
Expand Down Expand Up @@ -172,7 +184,7 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
const descriptor: UnloadedDescriptor = descs[i];
if (descriptor.options !== false) {
try {
pass.push(yield* loadPluginDescriptor(descriptor, context));
pass.push(yield* loadPluginDescriptor(descriptor, pluginContext));
} catch (e) {
if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") {
// print special message for `plugins: ["@babel/foo", { foo: "option" }]`
Expand Down Expand Up @@ -230,7 +242,7 @@ const loadDescriptor = makeWeakCache(function* (
if (typeof value === "function") {
const api = {
...context,
...makeAPI(cache),
...makePluginAPI(cache),
};
try {
item = value(api, options, dirname);
Expand Down Expand Up @@ -368,7 +380,7 @@ const validatePreset = (
*/
function* loadPresetDescriptor(
descriptor: UnloadedDescriptor,
context: ConfigContext,
context: PluginContext,
): Handler<ConfigChain | null> {
const preset = instantiatePreset(yield* loadDescriptor(descriptor, context));
validatePreset(preset, context, descriptor);
Expand Down
33 changes: 29 additions & 4 deletions packages/babel-core/src/config/helpers/config-api.js
@@ -1,6 +1,8 @@
// @flow

import semver from "semver";
import type { Targets } from "@babel/helper-compilation-targets";

import { version as coreVersion } from "../../";
import {
assertSimpleType,
Expand All @@ -20,7 +22,9 @@ type EnvFunction = {

type CallerFactory = ((CallerMetadata | void) => mixed) => SimpleType;

export type PluginAPI = {|
type TargetsFunction = () => Targets;

export type ConfigAPI = {|
version: string,
cache: SimpleCacheConfigurator,
env: EnvFunction,
Expand All @@ -29,9 +33,14 @@ export type PluginAPI = {|
caller?: CallerFactory,
|};

export default function makeAPI(
cache: CacheConfigurator<{ envName: string, caller: CallerMetadata | void }>,
): PluginAPI {
export type PluginAPI = {|
...ConfigAPI,
targets: TargetsFunction,
|};

export function makeConfigAPI<
SideChannel: { envName: string, caller: CallerMetadata | void },
>(cache: CacheConfigurator<SideChannel>): ConfigAPI {
const env: any = value =>
cache.using(data => {
if (typeof value === "undefined") return data.envName;
Expand Down Expand Up @@ -61,6 +70,22 @@ export default function makeAPI(
};
}

export function makePluginAPI(
cache: CacheConfigurator<{
envName: string,
caller: CallerMetadata | void,
targets: Targets,
}>,
): PluginAPI {
const targets = () =>
// We are using JSON.parse/JSON.stringify because it's only possible to cache
// primitive values. We can safely stringify the targets object because it
// only contains strings as its properties.
// Please make the Record and Tuple proposal happen!
JSON.parse(cache.using(data => JSON.stringify(data.targets)));
return { ...makeConfigAPI(cache), targets };
}

function assertVersion(range: string | number): void {
if (typeof range === "number") {
if (!Number.isInteger(range)) {
Expand Down
@@ -0,0 +1 @@
;
@@ -0,0 +1,4 @@
{
"targets": ["firefox 64", "node 8"],
"plugins": ["./plugin"]
}
@@ -0,0 +1,2 @@
;
"plugin: {\"firefox\":\"64.0.0\",\"node\":\"8.17.0\"}"
14 changes: 14 additions & 0 deletions packages/babel-core/test/fixtures/plugins/targets/plugin/plugin.js
@@ -0,0 +1,14 @@
module.exports = function (api) {
const { types: t } = api;

const targets = api.targets();

return {
visitor: {
Program(path) {
const output = t.stringLiteral(`plugin: ${JSON.stringify(targets)}`);
path.pushContainer("body", output);
},
},
};
};
@@ -0,0 +1 @@
;
@@ -0,0 +1,4 @@
{
"targets": ["firefox 64", "node 8"],
"presets": ["./preset"]
}
@@ -0,0 +1,2 @@
;
"preset: {\"firefox\":\"64.0.0\",\"node\":\"8.17.0\"}"
18 changes: 18 additions & 0 deletions packages/babel-core/test/fixtures/plugins/targets/preset/preset.js
@@ -0,0 +1,18 @@
module.exports = function (api) {
const targets = api.targets();

return {
plugins: [plugin],
};

function plugin({ types: t }) {
return {
visitor: {
Program(path) {
const output = t.stringLiteral(`preset: ${JSON.stringify(targets)}`);
path.pushContainer("body", output);
},
},
};
}
};

0 comments on commit 31431e0

Please sign in to comment.