MCPcopy Create free account
hub / github.com/babel/babel / pluginBabelBitDecorator

Function pluginBabelBitDecorator

scripts/babel-plugin-bit-decorator/plugin.ts:9–135  ·  view source on GitHub ↗

* Babel plugin to transform @bit decorators into class accessors. * It replaces @bit decorators with getter and setter methods that manipulate * a storage field defined with @bit.storage.

({
  types: t,
  template,
}: PluginAPI)

Source from the content-addressed store, hash-verified

7 * a storage field defined with @bit.storage.
8 */
9function pluginBabelBitDecorator({
10 types: t,
11 template,
12}: PluginAPI): PluginObject {
13 const bodyTemplate = template.statement({ allowReturnOutsideFunction: true });
14
15 return {
16 manipulateOptions({ parserOpts }) {
17 // @ts-expect-error parserOpts.plugins is defined in our Babel config
18 parserOpts.plugins.push("decorators", "decoratorAutoAccessors");
19 },
20 visitor: {
21 Class(path) {
22 let storageField;
23 let storageName;
24
25 for (const element of path.get("body.body")) {
26 if (
27 (element.isClassProperty() || element.isClassPrivateProperty()) &&
28 element.node.decorators?.some(dec =>
29 t.matchesPattern(dec.expression, "bit.storage")
30 )
31 ) {
32 element.node.decorators = element.node.decorators.filter(
33 dec => !t.matchesPattern(dec.expression, "bit.storage")
34 );
35 storageField = element;
36 storageName = element.node.key;
37 break;
38 }
39 }
40
41 let initial = 0;
42 let nextMask = 1;
43
44 for (const element of path.get("body.body")) {
45 let dec;
46 if (
47 element.isClassAccessorProperty() &&
48 (dec =
49 element.node.decorators &&
50 element
51 .get("decorators")
52 .find(
53 ({ node: dec }) =>
54 t.isIdentifier(dec.expression, { name: "bit" }) ||
55 (t.isCallExpression(dec.expression) &&
56 t.isIdentifier(dec.expression.callee, { name: "bit" }))
57 ))
58 ) {
59 if (element.node.static || t.isPrivateName(element.node.key)) {
60 throw element.buildCodeFrameError(
61 "@bit cannot be used on static or private fields"
62 );
63 }
64 if (element.node.decorators.length > 1) {
65 throw element.buildCodeFrameError(
66 "@bit cannot be used with other decorators"

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected