1.0.0 • Published 4 years ago

make-code-sync v1.0.0

Weekly downloads
3
License
ISC
Repository
github
Last release
4 years ago

make-code-sync

Makes common async calls like setTimout sync.

npm version build status ISC-licensed minimum Node.js version chat with me on Gitter support me on Patreon

This module takes an abstract syntax tree (AST) and transforms it so that all calls to e.g. setTimeout will be executed synchronously.

If your code does not use any other async funtions like fetch, it will be easy to do analyses on it or run it using vm.runInNewContext.

Caveats

  • Right now only setTimeout works, but I plan to support setImmediate as well setInterval.
  • The setTimeout mock is not spec-compatible. Actually, it is quite lacking.

Installing

npm install make-code-sync

Usage

const parse = require('acorn').parse
const generate = require('escodegen').generate
const vm = require('vm')
const assert = require('assert')

const syncify = require('.')
// `now` filters out all calls to `setTimeout`.
// `defer`, running in the end, executes all `setTimeout` callbacks, ordered by delay.
const {now, defer} = require('./hooks')

const code = `
	let x = 2
	setTimeout(() => {
		x += 1
	}, 100)
	x = 0
`

const parsed = parse(code, {ecmaVersion: 6})
const sync = syncify(parsed)
const transformed = generate(sync.ast)
	+ '\nx' // to get the value of `x`s
const ctx = {setTimeout, [sync.nameOfNow]: now, [sync.nameOfDefer]: defer}

assert.strictEqual(vm.runInNewContext(transformed, ctx), 1)

Contributing

If you have a question, found a bug or want to propose a feature, have a look at the issues page.