Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Aug 18, 2020
0 parents commit 088b9b3
Show file tree
Hide file tree
Showing 13 changed files with 259 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
3 changes: 3 additions & 0 deletions .github/funding.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
github: sindresorhus
open_collective: sindresorhus
custom: https://sindresorhus.com/donate
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
4 changes: 4 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
language: node_js
node_js:
- '14'
- '12'
32 changes: 32 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {AsyncReturnType} from 'type-fest';

// TODO: Move these to https://github.com/sindresorhus/type-fest
type AsyncFunction = (...args: any[]) => Promise<unknown>;
type ReplaceReturnType<T extends (...arguments_: any) => unknown, NewReturnType> = (...arguments_: Parameters<T>) => NewReturnType;

/**
Returns a wrapped version of the given async function which executes synchronously. This means no other code will execute (not even async code) until the given async function is done.
The given function is executed in a subprocess, so you cannot use any variables/imports from outside the scope of the function. You can pass in arguments to the function. To import dependencies, use either `require(…)` or `await import(…)` in the function body.
It uses the V8 serialization API transfer arguments, return values, errors between the subprocess and the current process. It supports most values, but not functions and symbols.
@example
```
import makeSynchronous = require('make-synchronous');
const fn = makeSynchronous(async number => {
const delay = require('delay');
await delay(100);
return number * 2;
});
console.log(fn(2));
//=> 4
```
*/
declare function makeSynchronous<T extends AsyncFunction>(asyncFunction: T): ReplaceReturnType<T, AsyncReturnType<T>>;

export = makeSynchronous;
62 changes: 62 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'use strict';
const childProcess = require('child_process');
const v8 = require('v8');
const Subsume = require('subsume');

const HUNDRED_MEGABYTES = 1000 * 1000 * 100;

module.exports = function_ => {
return (...arguments_) => {
const serializedArguments = v8.serialize(arguments_).toString('hex');
const subsume = new Subsume();

const input = `
const v8 = require('v8');
const Subsume = require('subsume');
const subsume = new Subsume('${subsume.id}');
const send = value => {
const serialized = v8.serialize(value).toString('hex');
process.stdout.write(subsume.compose(serialized));
};
(async () => {
try {
const arguments_ = v8.deserialize(Buffer.from('${serializedArguments}', 'hex'));
const result = await (${function_})(...arguments_);
send({result});
} catch (error) {
send({error});
}
})();
`;

const {error: subprocessError, stdout, stderr} = childProcess.spawnSync(process.execPath, ['-'], {
input,
encoding: 'utf8',
maxBuffer: HUNDRED_MEGABYTES
});

if (subprocessError) {
throw subprocessError;
}

const {data, rest} = subsume.parse(stdout);

process.stdout.write(rest);
process.stderr.write(stderr);

if (!data) {
return;
}

const {error, result} = v8.deserialize(Buffer.from(data, 'hex'));

if (error) {
throw error;
}

return result;
};
};
6 changes: 6 additions & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {expectType} from 'tsd';
import makeSynchronous = require('.');

const fn = makeSynchronous(async (number: number) => number * 2);

expectType<number>(fn(2));
9 changes: 9 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
47 changes: 47 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "make-synchronous",
"version": "0.0.0",
"description": "Make an asynchronous function synchronous",
"license": "MIT",
"repository": "sindresorhus/make-synchronous",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "[email protected]",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"function",
"synchronous",
"sync",
"block",
"main",
"thread",
"deasync",
"fiber",
"asynchronous",
"async"
],
"dependencies": {
"subsume": "^3.0.0",
"type-fest": "^0.16.0"
},
"devDependencies": {
"ava": "^2.4.0",
"delay": "^4.4.0",
"in-range": "^2.0.0",
"time-span": "^4.0.0",
"tsd": "^0.13.1",
"xo": "^0.33.0"
}
}
46 changes: 46 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# make-synchronous [![Build Status](https://travis-ci.com/sindresorhus/make-synchronous.svg?branch=master)](https://travis-ci.com/github/sindresorhus/make-synchronous)

> Make an asynchronous function synchronous
**This is the wrong tool for most tasks!** Prefer using async APIs whenever possible.

The benefit of this package over packages like [`deasync`](https://github.com/abbr/deasync) is that this one is not a native Node.js addon (which comes with a lot of problems). Instead, this package executes the given function synchronously in a subprocess.

Works in Node.js only, not the browser.

## Install

```
$ npm install make-synchronous
```

## Usage

```js
const makeSynchronous = require('make-synchronous');

const fn = makeSynchronous(async number => {
const delay = require('delay');

await delay(100);

return number * 2;
});

console.log(fn(2));
//=> 4
```

## API

### makeSynchronous(asyncFunction)

Returns a wrapped version of the given async function which executes synchronously. This means no other code will execute (not even async code) until the given async function is done.

The given function is executed in a subprocess, so you cannot use any variables/imports from outside the scope of the function. You can pass in arguments to the function. To import dependencies, use either `require(…)` or `await import(…)` in the function body.

It uses the V8 serialization API transfer arguments, return values, errors between the subprocess and the current process. It supports most values, but not functions and symbols.

## Related

- [sleep-synchronously](https://github.com/sindresorhus/sleep-synchronously) - Block the main thread for a given amount of time
34 changes: 34 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {serial as test} from 'ava';
import timeSpan from 'time-span';
import inRange from 'in-range';
import makeSynchronous from '.';

test('main', t => {
const fixture = '🦄';
const end = timeSpan();

const result = makeSynchronous(async fixture => {
const delay = require('delay');

await delay(200);

return fixture;
})(fixture);

t.true(inRange(end(), {start: 190, end: 300}));
t.is(result, fixture);
});

test('error', t => {
t.throws(
() => {
makeSynchronous(async () => {
throw new TypeError('unicorn');
})();
},
{
instanceOf: TypeError,
message: 'unicorn'
}
);
});

0 comments on commit 088b9b3

Please sign in to comment.