@babel/types#ObjectProperty TypeScript Examples

The following examples show how to use @babel/types#ObjectProperty. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: valueParser.ts    From engine with MIT License 6 votes vote down vote up
processValue = (node: ObjectProperty): Operation | void => {
  let valueNode;
  if (isAssignmentPattern(node.value)) {
    valueNode = node.value.right;
  } else {
    valueNode = node.value;
  }

  if (valueNode && Values[valueNode.type]) {
    return Values[valueNode.type](valueNode);
  } else {
    return constValue({ __node__: valueNode });
  }
}
Example #2
Source File: pathCompiler.ts    From engine with MIT License 6 votes vote down vote up
pathCompiler = (path: InvokablePath): ArrayExpression => {
  const parts = path.map((x) => {
    let type = objectProperty(identifier("type"), stringLiteral(x.type));
    let value = objectProperty(identifier("ignored"), nullLiteral());
    if (x.type === ValueTypes.CONST) {
      let paramValue;
      if (x.value.__node__) {
        paramValue = x.value.__node__;
      } else {
        paramValue = stringLiteral(x.value.toString());
      }
      value = objectProperty(identifier("value"), paramValue);
    } else if (
      x.type === ValueTypes.INTERNAL ||
      x.type === ValueTypes.EXTERNAL
    ) {
      const path = x.path.map((y: string) => stringLiteral(y));
      value = objectProperty(identifier("path"), arrayExpression(path));
    } else if (x.type === ValueTypes.INVOKE) {
      const path = x.path.map((y: string) => stringLiteral(y));
      value = objectProperty(identifier("path"), arrayExpression(path));
    }
    return objectExpression([type, value]);
  });
  const result = arrayExpression(parts);
  return result;
}
Example #3
Source File: funcOperationCompiler.ts    From engine with MIT License 6 votes vote down vote up
funcOperationCompiler = (op: FuncOperation): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(op.type));
  const paramsList = op.value.params.map((x) => {
    const type = objectProperty(identifier("type"), stringLiteral(x.type));
    const value = objectProperty(identifier("value"), stringLiteral("value"));
    return objectExpression([type, value]);
  });
  const fn = objectProperty(identifier("fn"), stringLiteral("fn"));
  const paramsArray = arrayExpression(paramsList);
  const params = objectProperty(identifier("params"), paramsArray);
  const internal = objectExpression([params, fn]);
  const value = objectProperty(identifier("value"), internal);
  return objectExpression([type, value]);
}
Example #4
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
objectProperty = (
  key: Expression | Identifier | StringLiteral | NumericLiteral,
  value: Expression | PatternLike,
  shorthand: boolean = false
): ObjectProperty => ({
  type: "ObjectProperty",
  key,
  value,
  computed: false,
  shorthand,
  ...baseNode,
})
Example #5
Source File: rawObjectCompiler.ts    From engine with MIT License 6 votes vote down vote up
rawObjectCompiler = (obj: any): ObjectExpression => {
  const props = Object.keys(obj).reduce((acc, x) => {
    let val: any = obj[x];
    let result;
    if (isString(val)) {
      result = stringLiteral(val);
    } else if (typeof val === "number") {
      result = numericLiteral(toNumber(val));
    } else if (isArray(val)) {
      let list = val.map((x) => stringLiteral(x));
      result = arrayExpression(list);
    } else if (isPlainObject(val)) {
      result = rawObjectCompiler(val);
    } else {
      throw new Error("Meta type for " + val + " not supported");
    }
    if (result) {
      acc.push(objectProperty(identifier(x), result));
    }
    return acc;
  }, [] as ObjectProperty[]);

  return objectExpression(props);
}
Example #6
Source File: traverse.ts    From react-optimized-image with MIT License 6 votes vote down vote up
resolveRequireExportName = (node: VariableDeclarator, binding: Binding): string | undefined => {
  // check for const { Svg } = require('react-optimized-image') calls
  if (node.id.type === 'ObjectPattern') {
    return (node.id.properties.find(
      (property) =>
        property.type === 'ObjectProperty' &&
        property.value.type === 'Identifier' &&
        property.value.name === binding.identifier.name,
    ) as ObjectProperty).key.name;
  }

  // check for require('react-optimized-image').default calls
  if (
    node.init &&
    node.init.type === 'MemberExpression' &&
    node.init.object.type === 'CallExpression' &&
    node.init.property.type === 'Identifier'
  ) {
    return node.init.property.name;
  }
}
Example #7
Source File: structOperationCompiler.ts    From engine with MIT License 6 votes vote down vote up
structOperationCompiler = (
  opOrig: StructOperation
): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(opOrig.type));
  const keys: ObjectProperty[] = Object.keys(opOrig.value)
    .map((x) => {
      const op = opOrig.value[x];
      let result;
      if (op.type === OperationTypes.GET) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.OBSERVE) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.UPDATE) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.FUNC) {
        result = funcOperationCompiler(op);
      } else if (op.type === OperationTypes.STRUCT) {
        result = structOperationCompiler(op);
      } else if (op.type === OperationTypes.VALUE) {
        result = valueOperationCompiler(op);
      } else {
        throw new Error(`Operation ${op} not supported`);
      }
      return objectProperty(identifier(x), result, false, true);
    })
    .filter((x) => !!x);
  const value = objectProperty(identifier("value"), objectPattern(keys));
  if (opOrig.meta) {
    const meta = objectProperty(
      identifier("meta"),
      rawObjectCompiler(opOrig.meta)
    );
    return objectExpression([type, value, meta]);
  } else {
    return objectExpression([type, value]);
  }
}
Example #8
Source File: resolveJsxComponent.ts    From react-optimized-image with MIT License 6 votes vote down vote up
resolveObjectProperty = (path: NodePath<ObjectExpression>, property: ObjectProperty): string[] => {
  let bindings: string[] = [];
  const parent = path.findParent(() => true);

  if (parent.node.type === 'ObjectProperty') {
    bindings = [...resolveObjectProperty(parent.findParent(() => true) as NodePath<ObjectExpression>, parent.node)];
  } else if (parent.node.type === 'VariableDeclarator' && parent.node.id.type === 'Identifier') {
    bindings.push(parent.node.id.name);
  }

  bindings.push(property.key.name);

  return bindings;
}
Example #9
Source File: structParser.ts    From engine with MIT License 6 votes vote down vote up
structParser = (obj: ObjectPattern): StructOperation => {
  const result = obj.properties.reduce(
    (acc, x) => {
      if (isObjectProperty(x)) {
        const node = x as ObjectProperty;
        const propName = (node.key as Identifier).name;
        const propValue = processValue(node);
        if (propValue) {
          acc.value[propName] = propValue;
        }
      } else {
        console.log("Not object property", x);
      }
      return acc;
    },
    {
      type: OperationTypes.STRUCT,
      value: {},
    } as StructOperation
  );
  return result;
}
Example #10
Source File: structOperationCompiler.ts    From engine with MIT License 6 votes vote down vote up
structOperationCompiler = (
  opOrig: StructOperation
): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(opOrig.type));
  const keys: ObjectProperty[] = Object.keys(opOrig.value)
    .map((x) => {
      const op = opOrig.value[x];
      let result;
      if (op.type === OperationTypes.GET) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.OBSERVE) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.UPDATE) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.FUNC) {
        result = funcOperationCompiler(op);
      } else if (op.type === OperationTypes.STRUCT) {
        result = structOperationCompiler(op);
      } else if (op.type === OperationTypes.VALUE) {
        result = valueOperationCompiler(op);
      } else {
        throw new Error(`Operation ${op} not supported`);
      }
      return objectProperty(identifier(x), result, false, true);
    })
    .filter((x) => !!x);
  const value = objectProperty(identifier("value"), objectPattern(keys));
  if (opOrig.meta) {
    const meta = objectProperty(
      identifier("meta"),
      rawObjectCompiler(opOrig.meta)
    );
    return objectExpression([type, value, meta]);
  } else {
    return objectExpression([type, value]);
  }
}
Example #11
Source File: rawObjectCompiler.ts    From engine with MIT License 6 votes vote down vote up
rawObjectCompiler = (obj: any): ObjectExpression => {
  const props = Object.keys(obj).reduce((acc, x) => {
    let val: any = obj[x];
    let result;
    if (isString(val)) {
      result = stringLiteral(val);
    } else if (typeof val === "number") {
      result = numericLiteral(toNumber(val));
    } else if (isArray(val)) {
      let list = val.map((x) => stringLiteral(x));
      result = arrayExpression(list);
    } else if (isPlainObject(val)) {
      result = rawObjectCompiler(val);
    } else {
      throw new Error("Meta type for " + val + " not supported");
    }
    if (result) {
      acc.push(objectProperty(identifier(x), result));
    }
    return acc;
  }, [] as ObjectProperty[]);

  return objectExpression(props);
}
Example #12
Source File: paramsCompiler.ts    From engine with MIT License 6 votes vote down vote up
paramsCompiler = (
  babel: typeof Babel,
  struct: StructOperation
): ObjectPattern[] => {
  const t = babel.types;
  const properties = Object.keys(struct.value).reduce((acc, x) => {
    acc.push(t.objectProperty(t.identifier(x), t.identifier(x), false, true));
    return acc;
  }, [] as ObjectProperty[]);
  const result = [t.objectPattern(properties)];
  return result;
}
Example #13
Source File: valueParser.ts    From engine with MIT License 6 votes vote down vote up
processValue = (
  babel: typeof Babel,
  node: ObjectProperty
): Operation | void => {
  const t = babel.types;
  let valueNode;
  if (t.isAssignmentPattern(node.value)) {
    valueNode = node.value.right;
  } else {
    valueNode = node.value;
  }

  if (valueNode && Values[valueNode.type]) {
    return Values[valueNode.type](babel, valueNode);
  } else {
    return constValue({ __node__: valueNode });
  }
}
Example #14
Source File: structParser.ts    From engine with MIT License 6 votes vote down vote up
structParser = (
  babel: typeof Babel,
  obj: ObjectPattern
): StructOperation => {
  const t = babel.types;
  const result = obj.properties.reduce(
    (acc, x) => {
      if (t.isObjectProperty(x)) {
        const node = x as ObjectProperty;
        const propName = (node.key as Identifier).name;
        const propValue = processValue(babel, node);
        if (propValue) {
          acc.value[propName] = propValue;
        }
      } else {
        console.log("Not object property", x);
      }
      return acc;
    },
    {
      type: OperationTypes.STRUCT,
      value: {},
    } as StructOperation
  );
  return result;
}
Example #15
Source File: structOperationCompiler.ts    From engine with MIT License 6 votes vote down vote up
structOperationCompiler = (
  babel: typeof Babel,
  opOrig: StructOperation
): ObjectExpression => {
  const t = babel.types;
  const type = t.objectProperty(
    t.identifier("type"),
    t.stringLiteral(opOrig.type)
  );
  const keys: ObjectProperty[] = Object.keys(opOrig.value)
    .map((x) => {
      const op = opOrig.value[x];
      let result;
      if (op.type === OperationTypes.GET) {
        result = pathOperationCompiler(babel, op);
      } else if (op.type === OperationTypes.OBSERVE) {
        result = pathOperationCompiler(babel, op);
      } else if (op.type === OperationTypes.UPDATE) {
        result = pathOperationCompiler(babel, op);
      } else if (op.type === OperationTypes.FUNC) {
        result = funcOperationCompiler(babel, op);
      } else if (op.type === OperationTypes.STRUCT) {
        result = structOperationCompiler(babel, op);
      } else if (op.type === OperationTypes.VALUE) {
        result = valueOperationCompiler(babel, op);
      } else if (op.type === OperationTypes.CONSTRUCTOR) {
        result = constructorOperationCompiler(babel, op);
      } else {
        throw new Error(`Operation ${op} not supported`);
      }
      return t.objectProperty(t.identifier(x), result, false, true);
    })
    .filter((x) => !!x);

  const value = t.objectProperty(t.identifier("value"), t.objectPattern(keys));
  return t.objectExpression([type, value]);
}
Example #16
Source File: rawObjectCompiler.ts    From engine with MIT License 6 votes vote down vote up
rawObjectCompiler = (
  babel: typeof Babel,
  obj: any
): ObjectExpression => {
  const t = babel.types;
  const props = Object.keys(obj).reduce((acc, x) => {
    let val: any = obj[x];
    let result;
    if (isString(val)) {
      result = t.stringLiteral(val);
    } else if (typeof val === "number") {
      result = t.numericLiteral(toNumber(val));
    } else if (isArray(val)) {
      let list = val.map((x) => t.stringLiteral(x));
      result = t.arrayExpression(list);
    } else if (isPlainObject(val)) {
      result = rawObjectCompiler(babel, val);
    } else if (val === undefined) {
      result = t.identifier("undefined");
    } else {
      throw new Error("Meta type for " + val + " not supported");
    }
    if (result) {
      acc.push(t.objectProperty(t.identifier(x), result));
    }
    return acc;
  }, [] as ObjectProperty[]);

  return t.objectExpression(props);
}
Example #17
Source File: prepareForEngine.ts    From engine with MIT License 5 votes vote down vote up
prepareForEngine: PrepareForEngine = (babel, state, ref, type) => {
  const validation = validateRef(ref);
  if (validation.error) {
    throw new Error(validation.errorMessage);
  }

  const config = getConfig(state);

  const op = parseRef(babel, state, ref);
  const props = structOperationCompiler(op);
  const parent = ref.findParent((p) => p.isVariableDeclarator());
  if (!parent) {
    throw new Error(
      "Misuse of the view/producer keyword. It needs to be a variable declaration e.g. let foo: view = ..."
    );
  }
  const node = parent.node as VariableDeclarator;
  const fn = node.init as ArrowFunctionExpression;

  fn.params = paramsCompiler(op);
  const result = objectExpression([
    objectProperty(identifier("props"), props),
    objectProperty(identifier("fn"), fn),
  ]);

  if (type === TransformType.PRODUCER) {
    node.init = result;
  } else if (type === TransformType.VIEW) {
    const viewCall = callExpression(identifier("view"), [result]);
    node.init = viewCall;
    const viewImport = config.view.importFrom;
    const program = ref.findParent((p) => p.isProgram());
    if (!program) {
      throw new Error("Internal error. Cannot find program node");
    }
    const macroImport = program.get("body").find((p) => {
      const result =
        p.isImportDeclaration() &&
        p.node.source.value.indexOf("@c11/engine.macro") !== -1;
      return result;
    });

    const engineImport = program.get("body").find((p) => {
      const result =
        p.isImportDeclaration() &&
        p.node.source.value.indexOf(viewImport) !== -1;
      return result;
    });

    if (macroImport) {
      if (!engineImport) {
        const importView = importDeclaration(
          [importSpecifier(identifier("view"), identifier("view"))],
          stringLiteral(viewImport)
        );
        // @ts-ignore
        macroImport.insertAfter(importView);
      } else {
        const node = engineImport.node as ImportDeclaration;
        const viewNode = node.specifiers.find((node) => {
          return (
            isImportSpecifier(node) &&
            isIdentifier(node.imported) &&
            node.imported.name === "view"
          );
        });
        if (!viewNode) {
          node.specifiers.push(
            importSpecifier(identifier("view"), identifier("view"))
          );
        }
      }
    } else {
      throw new Error("Could not find macro import");
    }
  }
}
Example #18
Source File: valueOperationCompiler.ts    From engine with MIT License 5 votes vote down vote up
valueOperationCompiler = (
  op: ValueOperation
): ObjectExpression => {
  let value = objectProperty(identifier("path"), stringLiteral("___"));
  const type = objectProperty(identifier("type"), stringLiteral(op.type));
  if (op.value.type === ValueTypes.CONST) {
    const val = op.value.value;

    let valType;
    if (val && val.__node__) {
      valType = val.__node__;
    } else if (typeof val === "string") {
      valType = stringLiteral(val);
    } else if (typeof val === "number") {
      valType = numericLiteral(val);
    } else if (typeof val === "boolean") {
      valType = booleanLiteral(val);
    } else {
      throw new Error("Value type not supported yet: " + typeof val);
    }

    value = objectProperty(
      identifier("value"),
      objectExpression([
        objectProperty(identifier("type"), stringLiteral(ValueTypes.CONST)),
        objectProperty(identifier("value"), valType),
      ])
    );
  } else if (
    op.value.type === ValueTypes.EXTERNAL ||
    op.value.type === ValueTypes.INTERNAL
  ) {
    const path = arrayExpression(op.value.path.map((x) => stringLiteral(x)));
    value = objectProperty(
      identifier("value"),
      objectExpression([
        objectProperty(identifier("type"), stringLiteral(op.value.type)),
        objectProperty(identifier("path"), path),
      ])
    );
  }
  return objectExpression([type, value]);
}
Example #19
Source File: pathOperationCompiler.ts    From engine with MIT License 5 votes vote down vote up
pathOperationCompiler = (
  op: GetOperation | UpdateOperation | ObserveOperation
): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(op.type));
  let value = objectProperty(identifier("path"), stringLiteral("___"));
  value = objectProperty(identifier("path"), pathCompiler(op.path));
  return objectExpression([type, value]);
}
Example #20
Source File: paramsCompiler.ts    From engine with MIT License 5 votes vote down vote up
paramsCompiler = (struct: StructOperation): ObjectPattern[] => {
  const properties = Object.keys(struct.value).reduce((acc, x) => {
    acc.push(objectProperty(identifier(x), identifier(x)));
    return acc;
  }, [] as ObjectProperty[]);
  const result = [objectPattern(properties)];
  return result;
}
Example #21
Source File: babel-polyfill.ts    From nota with MIT License 5 votes vote down vote up
objectPattern = (properties: Array<RestElement | ObjectProperty>): ObjectPattern => ({
  type: "ObjectPattern",
  properties,
  ...baseNode,
})
Example #22
Source File: babel-polyfill.ts    From nota with MIT License 5 votes vote down vote up
objectExpression = (
  properties: Array<ObjectMethod | ObjectProperty | SpreadElement>
): ObjectExpression => ({
  type: "ObjectExpression",
  properties,
  ...baseNode,
})
Example #23
Source File: resolveJsxComponent.ts    From react-optimized-image with MIT License 5 votes vote down vote up
resolveObject = (types: Babel['types'], path: NodePath<JSXElement>, bindings: string[]): Binding | undefined => {
  if (bindings.length < 2) {
    return;
  }

  const variableName = bindings[bindings.length - 1];
  const object = path.scope.getBinding(bindings[0]);
  if (!object) {
    return;
  }

  const program = path.findParent((node) => node.isProgram());
  let declarationPath: any = null; // eslint-disable-line
  let initializer;

  // search for object declaration
  program.traverse({
    // styles.StyledImg = ...
    MemberExpression(exPath: NodePath<MemberExpression>) {
      if (exPath.node.property && exPath.node.property.name === variableName) {
        const exBindings = resolveMemberExpression(exPath.node);

        if (arraysMatch(bindings, exBindings) && exPath.parent.type === 'AssignmentExpression') {
          declarationPath = exPath;
          initializer = exPath.parent.right;
          exPath.stop();
        }
      }
    },

    // const styles = { StyledImg: ... }
    ObjectProperty(opPath: NodePath<ObjectProperty>) {
      if (opPath.node.key && opPath.node.key.type === 'Identifier' && opPath.node.key.name === variableName) {
        const exBindings = resolveObjectProperty(
          opPath.findParent(() => true) as NodePath<ObjectExpression>,
          opPath.node,
        );

        if (arraysMatch(bindings, exBindings)) {
          declarationPath = opPath;
          initializer = opPath.node.value;
          opPath.stop();
        }
      }
    },
  });

  if (!declarationPath) {
    return;
  }

  declarationPath = declarationPath as NodePath<MemberExpression>;

  // mock a binding
  const binding: Partial<Binding> = {
    kind: 'const',
    scope: declarationPath.scope,
    identifier: types.identifier(variableName),
    path: {
      ...(declarationPath as any), // eslint-disable-line
      node: types.variableDeclarator(
        types.objectPattern([types.objectProperty(types.identifier(variableName), types.identifier(variableName))]),
        initializer,
      ),
    },
  };

  return binding as Binding;
}
Example #24
Source File: img.ts    From react-optimized-image with MIT License 5 votes vote down vote up
buildRawSrcAttribute = (
  types: Babel['types'],
  requireArgs: CallExpression['arguments'],
  config: ImageConfig,
  globalQuery: Record<string, string>,
): JSXAttribute => {
  const properties: ObjectProperty[] = [];

  ['fallback', ...(config.webp ? ['webp'] : [])].forEach((type) => {
    const typeProperties: ObjectProperty[] = [];
    const query: Record<string, string> = type === 'webp' ? { ...globalQuery, webp: '' } : { ...globalQuery };

    (config.sizes && config.sizes.length > 0 ? config.sizes : ['original']).forEach(
      (size: number | string, index: number, allSizes: Array<number | string>) => {
        const sizeProperties: ObjectProperty[] = [];

        // only inline image if there is 1 size and no fallback
        if (
          typeof query.url === 'undefined' &&
          typeof query.inline === 'undefined' &&
          ((type === 'fallback' && config.webp) || allSizes.length > 1 || (config.densities || [1]).length > 1)
        ) {
          query.url = '';
        }

        (config.densities || [1]).forEach((density) => {
          const sizeQuery: Record<string, string> = {
            ...query,
            ...(typeof size === 'number' ? { width: `${size * density}` } : {}),
          };

          sizeProperties.push(
            types.objectProperty(
              types.numericLiteral(density),
              buildRequireStatement(types, clone(requireArgs), sizeQuery),
            ),
          );
        });

        typeProperties.push(
          types.objectProperty(
            typeof size === 'string' ? types.identifier(size) : types.numericLiteral(size),
            types.objectExpression(sizeProperties),
          ),
        );
      },
    );

    properties.push(types.objectProperty(types.identifier(type), types.objectExpression(typeProperties)));
  });

  return types.jsxAttribute(
    types.jsxIdentifier('rawSrc'),
    types.jsxExpressionContainer(types.objectExpression(properties)),
  );
}
Example #25
Source File: paramsCompiler.ts    From engine with MIT License 5 votes vote down vote up
paramsCompiler = (struct: StructOperation): ObjectPattern[] => {
  const properties = Object.keys(struct.value).reduce((acc, x) => {
    acc.push(objectProperty(identifier(x), identifier(x)));
    return acc;
  }, [] as ObjectProperty[]);
  const result = [objectPattern(properties)];
  return result;
}