Debian Codegraph @

packages/babel-helper-create-class-features-plugin/src/features.ts

raw
1 import type { File, types as t } from "@babel/core";
2 import type { NodePath } from "@babel/traverse";
3 import { hasOwnDecorators } from "./decorators";
4
5 export const FEATURES = Object.freeze({
6 //classes: 1 << 0,
7 fields: 1 << 1,
8 privateMethods: 1 << 2,
9 // TODO(Babel 8): Remove this
10 decorators: 1 << 3,
11 privateIn: 1 << 4,
12 staticBlocks: 1 << 5,
13 });
14
15 const featuresSameLoose = new Map([
16 [FEATURES.fields, "@babel/plugin-proposal-class-properties"],
17 [FEATURES.privateMethods, "@babel/plugin-proposal-private-methods"],
18 [FEATURES.privateIn, "@babel/plugin-proposal-private-property-in-object"],
19 ]);
20
21 // We can't use a symbol because this needs to always be the same, even if
22 // this package isn't deduped by npm. e.g.
23 // - node_modules/
24 // - @babel/plugin-class-features
25 // - @babel/plugin-proposal-decorators
26 // - node_modules
27 // - @babel-plugin-class-features
28 const featuresKey = "@babel/plugin-class-features/featuresKey";
29 const looseKey = "@babel/plugin-class-features/looseKey";
30
31 // See https://github.com/babel/babel/issues/11622.
32 // Since preset-env sets loose for the fields and private methods plugins, it can
33 // cause conflicts with the loose mode set by an explicit plugin in the config.
34 // To solve this problem, we ignore preset-env's loose mode if another plugin
35 // explicitly sets it
36 // The code to handle this logic doesn't check that "low priority loose" is always
37 // the same. However, it is only set by the preset and not directly by users:
38 // unless someone _wants_ to break it, it shouldn't be a problem.
39 const looseLowPriorityKey =
40 "@babel/plugin-class-features/looseLowPriorityKey/#__internal__@babel/preset-env__please-overwrite-loose-instead-of-throwing";
41
42 export function enableFeature(file: File, feature: number, loose: boolean) {
43 // We can't blindly enable the feature because, if it was already set,
44 // "loose" can't be changed, so that
45 // @babel/plugin-class-properties { loose: true }
46 // @babel/plugin-class-properties { loose: false }
47 // is transformed in loose mode.
48 // We only enabled the feature if it was previously disabled.
49 if (!hasFeature(file, feature) || canIgnoreLoose(file, feature)) {
50 file.set(featuresKey, file.get(featuresKey) | feature);
51 if (
52 // @ts-expect-error comparing loose with internal private magic string
53 loose ===
54 "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"
55 ) {
56 setLoose(file, feature, true);
57 file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) | feature);
58 } else if (
59 // @ts-expect-error comparing loose with internal private magic string
60 loose ===
61 "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error"
62 ) {
63 setLoose(file, feature, false);
64 file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) | feature);
65 } else {
66 setLoose(file, feature, loose);
67 }
68 }
69
70 let resolvedLoose: boolean | undefined;
71 let higherPriorityPluginName: string | undefined;
72
73 for (const [mask, name] of featuresSameLoose) {
74 if (!hasFeature(file, mask)) continue;
75
76 const loose = isLoose(file, mask);
77
78 if (canIgnoreLoose(file, mask)) {
79 continue;
80 } else if (resolvedLoose === !loose) {
81 throw new Error(
82 "'loose' mode configuration must be the same for @babel/plugin-proposal-class-properties, " +
83 "@babel/plugin-proposal-private-methods and " +
84 "@babel/plugin-proposal-private-property-in-object (when they are enabled).",
85 );
86 } else {
87 resolvedLoose = loose;
88 higherPriorityPluginName = name;
89 }
90 }
91
92 if (resolvedLoose !== undefined) {
93 for (const [mask, name] of featuresSameLoose) {
94 if (hasFeature(file, mask) && isLoose(file, mask) !== resolvedLoose) {
95 setLoose(file, mask, resolvedLoose);
96 console.warn(
97 `Though the "loose" option was set to "${!resolvedLoose}" in your @babel/preset-env ` +
98 `config, it will not be used for ${name} since the "loose" mode option was set to ` +
99 `"${resolvedLoose}" for ${higherPriorityPluginName}.\nThe "loose" option must be the ` +
100 `same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods ` +
101 `and @babel/plugin-proposal-private-property-in-object (when they are enabled): you can ` +
102 `silence this warning by explicitly adding\n` +
103 `\t["${name}", { "loose": ${resolvedLoose} }]\n` +
104 `to the "plugins" section of your Babel config.`,
105 );
106 }
107 }
108 }
109 }
110
111 function hasFeature(file: File, feature: number) {
112 return !!(file.get(featuresKey) & feature);
113 }
114
115 export function isLoose(file: File, feature: number) {
116 return !!(file.get(looseKey) & feature);
117 }
118
119 function setLoose(file: File, feature: number, loose: boolean) {
120 if (loose) file.set(looseKey, file.get(looseKey) | feature);
121 else file.set(looseKey, file.get(looseKey) & ~feature);
122
123 file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) & ~feature);
124 }
125
126 function canIgnoreLoose(file: File, feature: number) {
127 return !!(file.get(looseLowPriorityKey) & feature);
128 }
129
130 export function shouldTransform(path: NodePath<t.Class>, file: File): boolean {
131 let decoratorPath: NodePath<t.Decorator> | null = null;
132 let publicFieldPath: NodePath<t.ClassProperty> | null = null;
133 let privateFieldPath: NodePath<t.ClassPrivateProperty> | null = null;
134 let privateMethodPath: NodePath<t.ClassPrivateMethod> | null = null;
135 let staticBlockPath: NodePath<t.StaticBlock> | null = null;
136
137 if (hasOwnDecorators(path.node)) {
138 decoratorPath = path.get("decorators.0");
139 }
140 for (const el of path.get("body.body")) {
141 if (!decoratorPath && hasOwnDecorators(el.node)) {
142 decoratorPath = el.get("decorators.0");
143 }
144 if (!publicFieldPath && el.isClassProperty()) {
145 publicFieldPath = el;
146 }
147 if (!privateFieldPath && el.isClassPrivateProperty()) {
148 privateFieldPath = el;
149 }
150 // NOTE: path.isClassPrivateMethod() it isn't supported in <7.2.0
151 if (!privateMethodPath && el.isClassPrivateMethod?.()) {
152 privateMethodPath = el;
153 }
154 if (!staticBlockPath && el.isStaticBlock?.()) {
155 staticBlockPath = el;
156 }
157 }
158
159 if (decoratorPath && privateFieldPath) {
160 throw privateFieldPath.buildCodeFrameError(
161 "Private fields in decorated classes are not supported yet.",
162 );
163 }
164 if (decoratorPath && privateMethodPath) {
165 throw privateMethodPath.buildCodeFrameError(
166 "Private methods in decorated classes are not supported yet.",
167 );
168 }
169
170 if (decoratorPath && !hasFeature(file, FEATURES.decorators)) {
171 throw path.buildCodeFrameError(
172 "Decorators are not enabled." +
173 "\nIf you are using " +
174 '["@babel/plugin-proposal-decorators", { "version": "legacy" }], ' +
175 'make sure it comes *before* "@babel/plugin-proposal-class-properties" ' +
176 "and enable loose mode, like so:\n" +
177 '\t["@babel/plugin-proposal-decorators", { "version": "legacy" }]\n' +
178 '\t["@babel/plugin-proposal-class-properties", { "loose": true }]',
179 );
180 }
181
182 if (privateMethodPath && !hasFeature(file, FEATURES.privateMethods)) {
183 throw privateMethodPath.buildCodeFrameError(
184 "Class private methods are not enabled. " +
185 "Please add `@babel/plugin-proposal-private-methods` to your configuration.",
186 );
187 }
188
189 if (
190 (publicFieldPath || privateFieldPath) &&
191 !hasFeature(file, FEATURES.fields) &&
192 // We want to allow enabling the private-methods plugin even without enabling
193 // the class-properties plugin. Class fields will still be compiled in classes
194 // that contain private methods.
195 // This is already allowed with the other various class features plugins, but
196 // it's because they can fallback to a transform separated from this helper.
197 !hasFeature(file, FEATURES.privateMethods)
198 ) {
199 throw path.buildCodeFrameError(
200 "Class fields are not enabled. " +
201 "Please add `@babel/plugin-proposal-class-properties` to your configuration.",
202 );
203 }
204
205 if (staticBlockPath && !hasFeature(file, FEATURES.staticBlocks)) {
206 throw path.buildCodeFrameError(
207 "Static class blocks are not enabled. " +
208 "Please add `@babel/plugin-proposal-class-static-block` to your configuration.",
209 );
210 }
211
212 if (decoratorPath || privateMethodPath || staticBlockPath) {
213 // If one of those feature is used we know that its transform is
214 // enabled, otherwise the previous checks throw.
215 return true;
216 }
217 if (
218 (publicFieldPath || privateFieldPath) &&
219 hasFeature(file, FEATURES.fields)
220 ) {
221 return true;
222 }
223
224 return false;
225 }