@babel/types#stringLiteral TypeScript Examples

The following examples show how to use @babel/types#stringLiteral. 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: 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 #2
Source File: translate.ts    From nota with MIT License 6 votes vote down vote up
processText = (text: string): StringLiteral => {
  return t.stringLiteral(
    text
      .replace(/\\%/g, "%")
      .replace(/\\\[/g, "[")
      .replace(/\\\]/g, "]")
      .replace(/\\@/g, "@")
      .replace(/\\#/g, "#")
      .replace(/---/g, "—")
  );
}
Example #3
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
exportNamedDeclaration = (
  declaration?: Declaration,
  source: StringLiteral | null = null,
  specifiers: ExportSpecifier[] = []
): ExportNamedDeclaration => ({
  type: "ExportNamedDeclaration",
  declaration,
  specifiers,
  source,
  ...baseNode,
})
Example #4
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
importSpecifier = (
  local: Identifier,
  imported: Identifier | StringLiteral
): ImportSpecifier => ({
  type: "ImportSpecifier",
  local,
  imported,
  ...baseNode,
})
Example #5
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
importDeclaration = (
  specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>,
  source: StringLiteral
): ImportDeclaration => ({
  type: "ImportDeclaration",
  specifiers,
  source,
  ...baseNode,
})
Example #6
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 #7
Source File: addWildcardImport.ts    From engine with MIT License 6 votes vote down vote up
addWildcardImport: AddWildcardImport = (babel, state, ref) => {
  const producerName = "@c11/engine.producer";
  const pathImport = importDeclaration(
    [importSpecifier(identifier("wildcard"), identifier("wildcard"))],
    stringLiteral(producerName)
  );
  const program = ref.findParent((p) => p.isProgram());
  if (!program) {
    throw new Error("");
  }

  const macroImport = program.get("body").find((p) => {
    const result =
      p.isImportDeclaration() &&
      p.node.source.value.indexOf("@c11/engine.macro") !== -1;
    return result;
  });

  if (macroImport) {
    // @ts-ignore
    macroImport.insertAfter(pathImport);
  }
}
Example #8
Source File: addPathImport.ts    From engine with MIT License 6 votes vote down vote up
addPathImport: AddPathImport = (babel, state, ref) => {
  const producerName = "@c11/engine.producer";
  const pathImport = importDeclaration(
    [importSpecifier(identifier("path"), identifier("path"))],
    stringLiteral(producerName)
  );

  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;
  });

  if (macroImport) {
    // @ts-ignore
    macroImport.insertAfter(pathImport);
  }
}
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: index.ts    From tailchat with GNU General Public License v3.0 5 votes vote down vote up
export default function sourceRef(): Plugin {
  return {
    name: 'source-ref',
    transform(code, id) {
      const filepath = id;

      const ast = parse(code, {
        sourceType: 'module',
        plugins: ['jsx', 'typescript'],
      });

      traverse(ast, {
        JSXOpeningElement(path) {
          const location = path.node.loc;
          if (!location) {
            return;
          }

          if (Array.isArray(location)) {
            return;
          }

          const name = path.node.name;
          if (isJSXIdentifier(name) && name.name === 'Fragment') {
            return;
          }
          if (
            isJSXMemberExpression(name) &&
            name.property.name === 'Fragment'
          ) {
            return;
          }

          const line = location.start.line;
          const col = location.start.column;

          const attrs = path.node.attributes;
          for (let i = 0; i < attrs.length; i++) {
            const attr = attrs[i];
            if (attr.type === 'JSXAttribute' && attr.name.name === TRACE_ID) {
              // existed
              return;
            }
          }

          const traceId = `${filepath}:${line}:${col}`;

          attrs.push(
            jsxAttribute(jsxIdentifier(TRACE_ID), stringLiteral(traceId))
          );
        },
      });

      const res = generate(ast);

      return { code: res.code, map: res.map };
    },
  };
}
Example #14
Source File: index.ts    From tailchat with GNU General Public License v3.0 5 votes vote down vote up
async function loader(this: LoaderContext<any>, source: string): Promise<void> {
  const done = this.async();

  const { available } = this.getOptions();
  if (!available) {
    // skip if not
    done(null, source);
    return;
  }

  const ast = parse(source, {
    sourceType: 'module',
    plugins: ['jsx', 'typescript'],
  });
  const filepath = this.resourcePath;
  if (filepath.includes('node_modules')) {
    done(null, source);
    return;
  }

  traverse(ast, {
    JSXOpeningElement(path) {
      const location = path.node.loc;
      if (!location) {
        return;
      }

      if (Array.isArray(location)) {
        return;
      }

      const name = path.node.name;
      if (isJSXIdentifier(name) && name.name === 'Fragment') {
        return;
      }
      if (isJSXMemberExpression(name) && name.property.name === 'Fragment') {
        return;
      }

      const line = location.start.line;
      const col = location.start.column;

      const attrs = path.node.attributes;
      for (let i = 0; i < attrs.length; i++) {
        const attr = attrs[i];
        if (attr.type === 'JSXAttribute' && attr.name.name === TRACE_ID) {
          // existed
          return;
        }
      }

      const traceId = `${filepath}:${line}:${col}`;

      attrs.push(jsxAttribute(jsxIdentifier(TRACE_ID), stringLiteral(traceId)));
    },
  });

  const code = generate(ast).code;

  done(null, code);
}
Example #15
Source File: constants.ts    From prettier-plugin-sort-imports with Apache License 2.0 5 votes vote down vote up
newLineNode = expressionStatement(
    stringLiteral(PRETTIER_PLUGIN_SORT_IMPORTS_NEW_LINE),
)
Example #16
Source File: babel-polyfill.ts    From nota with MIT License 5 votes vote down vote up
stringLiteral = (value: string): StringLiteral => ({
  type: "StringLiteral",
  value,
  ...baseNode,
})
Example #17
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 #18
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]);
}