Debian Codegraph @

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

raw
1 import { types as t } from "@babel/core";
2 import type { PluginAPI, PluginObject } from "@babel/core";
3 import type { NodePath } from "@babel/traverse";
4 import nameFunction from "@babel/helper-function-name";
5 import splitExportDeclaration from "@babel/helper-split-export-declaration";
6 import {
7 buildPrivateNamesNodes,
8 buildPrivateNamesMap,
9 transformPrivateNamesUsage,
10 buildFieldsInitNodes,
11 buildCheckInRHS,
12 } from "./fields";
13 import type { PropPath } from "./fields";
14 import { buildDecoratedClass, hasDecorators } from "./decorators";
15 import { injectInitialization, extractComputedKeys } from "./misc";
16 import { enableFeature, FEATURES, isLoose, shouldTransform } from "./features";
17 import { assertFieldTransformed } from "./typescript";
18
19 export { FEATURES, enableFeature, injectInitialization, buildCheckInRHS };
20
21 declare const PACKAGE_JSON: { name: string; version: string };
22
23 // Note: Versions are represented as an integer. e.g. 7.1.5 is represented
24 // as 70000100005. This method is easier than using a semver-parsing
25 // package, but it breaks if we release x.y.z where x, y or z are
26 // greater than 99_999.
27 const version = PACKAGE_JSON.version
28 .split(".")
29 .reduce((v, x) => v * 1e5 + +x, 0);
30 const versionKey = "@babel/plugin-class-features/version";
31
32 interface Options {
33 name: string;
34 feature: number;
35 loose?: boolean;
36 inherits?: PluginObject["inherits"];
37 manipulateOptions?: PluginObject["manipulateOptions"];
38 api?: PluginAPI;
39 }
40
41 export function createClassFeaturePlugin({
42 name,
43 feature,
44 loose,
45 manipulateOptions,
46 // @ts-ignore(Babel 7 vs Babel 8) TODO(Babel 8): Remove the default value
47 api = { assumption: () => void 0 },
48 inherits,
49 }: Options): PluginObject {
50 const setPublicClassFields = api.assumption("setPublicClassFields");
51 const privateFieldsAsProperties = api.assumption("privateFieldsAsProperties");
52 const constantSuper = api.assumption("constantSuper");
53 const noDocumentAll = api.assumption("noDocumentAll");
54
55 if (loose === true) {
56 const explicit = [];
57
58 if (setPublicClassFields !== undefined) {
59 explicit.push(`"setPublicClassFields"`);
60 }
61 if (privateFieldsAsProperties !== undefined) {
62 explicit.push(`"privateFieldsAsProperties"`);
63 }
64 if (explicit.length !== 0) {
65 console.warn(
66 `[${name}]: You are using the "loose: true" option and you are` +
67 ` explicitly setting a value for the ${explicit.join(" and ")}` +
68 ` assumption${explicit.length > 1 ? "s" : ""}. The "loose" option` +
69 ` can cause incompatibilities with the other class features` +
70 ` plugins, so it's recommended that you replace it with the` +
71 ` following top-level option:\n` +
72 `\t"assumptions": {\n` +
73 `\t\t"setPublicClassFields": true,\n` +
74 `\t\t"privateFieldsAsProperties": true\n` +
75 `\t}`,
76 );
77 }
78 }
79
80 return {
81 name,
82 manipulateOptions,
83 inherits,
84
85 pre(file) {
86 enableFeature(file, feature, loose);
87
88 if (!file.get(versionKey) || file.get(versionKey) < version) {
89 file.set(versionKey, version);
90 }
91 },
92
93 visitor: {
94 Class(path, { file }) {
95 if (file.get(versionKey) !== version) return;
96
97 if (!shouldTransform(path, file)) return;
98
99 if (path.isClassDeclaration()) assertFieldTransformed(path);
100
101 const loose = isLoose(file, feature);
102
103 let constructor: NodePath<t.ClassMethod>;
104 const isDecorated = hasDecorators(path.node);
105 const props: PropPath[] = [];
106 const elements = [];
107 const computedPaths: NodePath<t.ClassProperty | t.ClassMethod>[] = [];
108 const privateNames = new Set<string>();
109 const body = path.get("body");
110
111 for (const path of body.get("body")) {
112 if (
113 // check path.node.computed is enough, but ts will complain
114 (path.isClassProperty() || path.isClassMethod()) &&
115 path.node.computed
116 ) {
117 computedPaths.push(path);
118 }
119
120 if (path.isPrivate()) {
121 const { name } = path.node.key.id;
122 const getName = `get ${name}`;
123 const setName = `set ${name}`;
124
125 if (path.isClassPrivateMethod()) {
126 if (path.node.kind === "get") {
127 if (
128 privateNames.has(getName) ||
129 (privateNames.has(name) && !privateNames.has(setName))
130 ) {
131 throw path.buildCodeFrameError("Duplicate private field");
132 }
133 privateNames.add(getName).add(name);
134 } else if (path.node.kind === "set") {
135 if (
136 privateNames.has(setName) ||
137 (privateNames.has(name) && !privateNames.has(getName))
138 ) {
139 throw path.buildCodeFrameError("Duplicate private field");
140 }
141 privateNames.add(setName).add(name);
142 }
143 } else {
144 if (
145 (privateNames.has(name) &&
146 !privateNames.has(getName) &&
147 !privateNames.has(setName)) ||
148 (privateNames.has(name) &&
149 (privateNames.has(getName) || privateNames.has(setName)))
150 ) {
151 throw path.buildCodeFrameError("Duplicate private field");
152 }
153
154 privateNames.add(name);
155 }
156 }
157
158 if (path.isClassMethod({ kind: "constructor" })) {
159 constructor = path;
160 } else {
161 elements.push(path);
162 if (
163 path.isProperty() ||
164 path.isPrivate() ||
165 path.isStaticBlock?.()
166 ) {
167 props.push(path as PropPath);
168 }
169 }
170 }
171
172 if (process.env.BABEL_8_BREAKING) {
173 if (!props.length) return;
174 } else {
175 if (!props.length && !isDecorated) return;
176 }
177
178 const innerBinding = path.node.id;
179 let ref: t.Identifier;
180 if (!innerBinding || path.isClassExpression()) {
181 nameFunction(path);
182 ref = path.scope.generateUidIdentifier("class");
183 } else {
184 ref = t.cloneNode(path.node.id);
185 }
186
187 // NODE: These three functions don't support decorators yet,
188 // but verifyUsedFeatures throws if there are both
189 // decorators and private fields.
190 const privateNamesMap = buildPrivateNamesMap(props);
191 const privateNamesNodes = buildPrivateNamesNodes(
192 privateNamesMap,
193 privateFieldsAsProperties ?? loose,
194 file,
195 );
196
197 transformPrivateNamesUsage(
198 ref,
199 path,
200 privateNamesMap,
201 {
202 privateFieldsAsProperties: privateFieldsAsProperties ?? loose,
203 noDocumentAll,
204 innerBinding,
205 },
206 file,
207 );
208
209 let keysNodes: t.Statement[],
210 staticNodes: t.Statement[],
211 instanceNodes: t.Statement[],
212 pureStaticNodes: t.FunctionDeclaration[],
213 wrapClass: (path: NodePath<t.Class>) => NodePath;
214
215 if (!process.env.BABEL_8_BREAKING) {
216 if (isDecorated) {
217 staticNodes = pureStaticNodes = keysNodes = [];
218 ({ instanceNodes, wrapClass } = buildDecoratedClass(
219 ref,
220 path,
221 elements,
222 file,
223 ));
224 } else {
225 keysNodes = extractComputedKeys(path, computedPaths, file);
226 ({ staticNodes, pureStaticNodes, instanceNodes, wrapClass } =
227 buildFieldsInitNodes(
228 ref,
229 path.node.superClass,
230 props,
231 privateNamesMap,
232 file,
233 setPublicClassFields ?? loose,
234 privateFieldsAsProperties ?? loose,
235 constantSuper ?? loose,
236 innerBinding,
237 ));
238 }
239 } else {
240 keysNodes = extractComputedKeys(path, computedPaths, file);
241 ({ staticNodes, pureStaticNodes, instanceNodes, wrapClass } =
242 buildFieldsInitNodes(
243 ref,
244 path.node.superClass,
245 props,
246 privateNamesMap,
247 file,
248 setPublicClassFields ?? loose,
249 privateFieldsAsProperties ?? loose,
250 constantSuper ?? loose,
251 innerBinding,
252 ));
253 }
254
255 if (instanceNodes.length > 0) {
256 injectInitialization(
257 path,
258 constructor,
259 instanceNodes,
260 (referenceVisitor, state) => {
261 if (!process.env.BABEL_8_BREAKING) {
262 if (isDecorated) return;
263 }
264 for (const prop of props) {
265 // @ts-expect-error: TS doesn't infer that prop.node is not a StaticBlock
266 if (t.isStaticBlock?.(prop.node) || prop.node.static) continue;
267 prop.traverse(referenceVisitor, state);
268 }
269 },
270 );
271 }
272
273 // rename to make ts happy
274 const wrappedPath = wrapClass(path);
275 wrappedPath.insertBefore([...privateNamesNodes, ...keysNodes]);
276 if (staticNodes.length > 0) {
277 wrappedPath.insertAfter(staticNodes);
278 }
279 if (pureStaticNodes.length > 0) {
280 wrappedPath
281 .find(parent => parent.isStatement() || parent.isDeclaration())
282 .insertAfter(pureStaticNodes);
283 }
284 },
285
286 ExportDefaultDeclaration(path, { file }) {
287 if (!process.env.BABEL_8_BREAKING) {
288 if (file.get(versionKey) !== version) return;
289
290 const decl = path.get("declaration");
291
292 if (decl.isClassDeclaration() && hasDecorators(decl.node)) {
293 if (decl.node.id) {
294 // export default class Foo {}
295 // -->
296 // class Foo {} export { Foo as default }
297 splitExportDeclaration(path);
298 } else {
299 // @ts-expect-error Anonymous class declarations can be
300 // transformed as if they were expressions
301 decl.node.type = "ClassExpression";
302 }
303 }
304 }
305 },
306 },
307 };
308 }