Transmute one JavaScript string into another by way of mutating its AST. Powered by babel and recast.

Overview

equivalent-exchange

Transmute one JavaScript string into another by way of mutating its AST. Powered by babel and recast.

Features

  • Can parse code using modern ES20XX syntax, as well as either TypeScript or Flow syntax.
  • Maintains the source formatting of the original source, where possible; only modified parts of the code will be touched.
  • Can generate a source map that maps your input file into your transformed output.

Usage Example

import { transmute, traverse, types } from "equivalent-exchange";

const someJs = "console.log('hi!');";

const result = transmute(someJs, (ast) => {
  traverse(ast, {
    StringLiteral(path) {
      const { node } = path;
      if (node.value === "hi!") {
        path.replaceWith(types.stringLiteral("goodbye!"));
      }
    },
  });
});

console.log(result.code); // console.log("goodbye!");

Note that you don't have to use the provided traverse or types; you can mutate the ast using whatever traversal method you prefer.

API Documentation

Please see api/index.d.ts for API documentation. There are lots of comments.

License

MIT

You might also like...

The awesomebooks project is a simple list, but separated into 3 parts and given a retro feel. The main page is where we can add books, and on another page we can see the list, and remove items. There is also a "contact-us" page.

Awesome Books This is the restructured version of the famous awesome-books project! Here you can find JavaScript broken into modules, using import-exp

Nov 15, 2022

Another logger in JS. This one offers a console.log-like API and formatting, colored lines and timestamps (or not if desired), all that with 0 dependencies.

Another logger in JS. This one offers a console.log-like API and formatting, colored lines and timestamps (or not if desired), all that with 0 dependencies.

hellog Your new logger ! hellog is a general-purpose logging library. It offers a console.log-like API and formatting, extensible type-safety colored

Jan 5, 2022

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions. (like child-processes, iframe, web worker etc).

Dec 29, 2022

Run async code one after another by scheduling promises.

promise-scheduler Run async code in a synchronous order by scheduling promises, with the possibility to cancel pending or active tasks. Optimized for

Dec 17, 2021

Send all tokens from one wallet to another quickly.

Send all tokens from one wallet to another quickly.

Drain Send all tokens from one wallet to another quickly. Whether getting hacked or starting fresh, Drain makes sure you get every last wei. Live Depl

Dec 22, 2022

Extract a JS/TS module and its dependencies into a new package

module-extractor Extract a module and its dependencies into a new package Usage import { extractModules } from 'module-extractor' const extraction =

Aug 9, 2022

Get into docker, its time now hhh

get_into_docker This repo is a personal reference and a guide in case of need that holds the process on my activities. This repo is a kind of knowledg

Nov 1, 2022

πŸš€ Blazing Fast S3 Powered CDN ✨ Powered By Fastify, S3 Buckets & Docker!

πŸš€ WasiCDN Blazing Fast S3 Powered CDN, Powered By Fastify, S3 Compatible Buckets & Docker! Core DockerHub: https://hub.docker.com/r/maximking19/wasic

Aug 31, 2022

A JavaScript-powered CLI for converting HTML into PDFs

Print Ready by Nicholas C. Zakas If you find this useful, please consider supporting my work with a donation. Description A JavaScript-powered CLI for

Dec 18, 2022
Comments
  • Issues with parsing jsx

    Issues with parsing jsx

    This was exactly the kind of tool I was looking for, thanks for that! :clap: But I stumbled upon something that I really can't figure out. I have issues parsing code with JSX syntax.

    Here's the way I did to reproduce:

    1. Create new project (npm init -y) and install equivalent-exchange (npm install equivalent-exchange)
    2. Create a file with the following content:
    import { transmute, traverse } from 'equivalent-exchange';
    
    const code = `
      export const Foo: React.FC<{ foo: string }> = ({foo}) => {
        return <div>{foo}</div>
      }
    `;
    
    try {
      transmute(code, { fileName: 'Foo.tsx' });
    } catch (error) {
      console.error(error);
    }
    
    1. Execute the script with node node script.mjs

    With this I get the following error thrown:

    Error: Line 3: Invalid regular expression: missing /
        at ErrorHandler.constructError (/project/node_modules/esprima/dist/esprima.js:5012:22)
        at ErrorHandler.createError (/project/node_modules/esprima/dist/esprima.js:5028:27)
        at ErrorHandler.throwError (/project/node_modules/esprima/dist/esprima.js:5035:21)
        at Scanner.throwUnexpectedToken (/project/node_modules/esprima/dist/esprima.js:5164:35)
        at Scanner.scanRegExpBody (/project/node_modules/esprima/dist/esprima.js:6139:23)
        at Scanner.scanRegExp (/project/node_modules/esprima/dist/esprima.js:6204:29)
        at Tokenizer.getNextToken (/project/node_modules/esprima/dist/esprima.js:6675:56)
        at Object.tokenize (/project/node_modules/esprima/dist/esprima.js:154:36)
        at Object.parse (/project/node_modules/recast/lib/parser.js:40:30)
        at codeToAst (/project/node_modules/equivalent-exchange/dist/index.js:45:24) {
      index: 90,
      lineNumber: 3,
      description: 'Invalid regular expression: missing /'
    }
    

    The strange thing is that when I clone this repo and try adding a test like this it all passes πŸ€”

    test('with jsx syntax', async () => {
      const code = `export const Component: React.FC = () => {
        console.log("hello!");
        return <div />
      }`;
    
      const transform = (ast: AST) => {
        traverse(ast, {
          StringLiteral(path) {
            const { node } = path;
            if (node.value === 'hello!') {
              path.replaceWith(types.stringLiteral('goodbye!'));
            }
          },
        });
      };
    
      expect(() => {
        transmute(code, transform);
      }).not.toThrow();
    });
    

    Do you have any ideas of what might be going wrong? At first I thought of different babel versions colliding. But since it didn't work in my very bare-bones repro either I'm suspecting it is something else.

    opened by adambrgmn 4
Owner
Lily Scott
Former Prettier Core Team member, Former Babel team member. Interested in JavaScript, Rust, Unity, VR, Dev Tooling, Dev Experience, React, and more.
Lily Scott
Convert some JavaScript/TypeScript code string into a .d.ts TypeScript Declaration code string

convert-to-dts Converts the source code for any .js or .ts file into the equivalent .d.ts code TypeScript would generate. Usage import { convertToDecl

Lily Scott 11 Mar 3, 2022
Babel plugin and helper functions for interoperation between Node.js native ESM and Babel ESM

babel-plugin-node-cjs-interop and node-cjs-interop: fix the default import interoperability issue in Node.js The problem to solve Consider the followi

Masaki Hara 15 Nov 6, 2022
Babel-plugin-amd-checker - Module format checking plugin for Babel usable in both Node.js the web browser environments.

babel-plugin-amd-checker A Babel plugin to check the format of your modules when compiling your code using Babel. This plugin allows you to abort the

Ferdinand Prantl 1 Jan 6, 2022
I forgot about el.outerHTML so I made this, it takes a DOM element and returns its html as string

htmlToString Convert html/DOM element to string Works with rendered and virtual DOM Installation npm install htmltostring Or using CDN <script src="ht

Shuvo 4 Jul 22, 2022
Manipulate the AST to transform your code.

unplugin-ast Manipulate the AST to transform your code. Installation npm i unplugin-ast Vite // vite.config.ts import AST from 'unplugin-ast/vite' ex

三咲智子 32 Dec 3, 2022
It's a repository to studies. Its idea is to learn about Nx and its plugins.

StudyingNx This project was generated using Nx. ?? Smart, Fast and Extensible Build System Adding capabilities to your workspace Nx supports many plug

Open-ish 4 May 13, 2022
Can see everything, beware of its omniscience, kneel before its greatness.

Can see everything, beware of its omniscience, kneel before its greatness. Summary Presentation Installation Removing Credits Presentation Main goal T

Duc Justin 3 Sep 30, 2022
Download all Moodle files with one click. This is a Chrome extension built to save time and effort from downloading files manually one by one!

Moodle Downloader Extension Moodle downloader extension for Chrome. The extension is tested with both the TUM moodle and the official moodle demo. Not

Zhongpin Wang 8 Nov 15, 2022
An utility library for Encoding and Compressing whatever you give him into a small string.

?? ORBIT ENCODER βš™οΈ ??️ ORBIT-ENCODER is an utility library for Data Compression and Encoding. It can take whatever object you give him as argument an

Orbit Turner 7 Nov 16, 2022
Strcmp-node - A cli string comparison tool, because apparently one doesn't exist.

strcmp-node I couldn't find a string comparison command, so i made my own. its probably the ugliest thing since godzilla with makeup on, but it works.

Gingka/Ginger Pepper 1 Jan 1, 2022