diff --git a/fibers.js b/fibers.js index 3229dad..851bbe0 100644 --- a/fibers.js +++ b/fibers.js @@ -23,7 +23,7 @@ if (process.fiberLib) { throw new Error('Missing binary. See message above.'); } - setupAsyncHacks(module.exports); + //setupAsyncHacks(module.exports); } function setupAsyncHacks(Fiber) { diff --git a/fibers_async.js b/fibers_async.js new file mode 100644 index 0000000..8a5e9c7 --- /dev/null +++ b/fibers_async.js @@ -0,0 +1,64 @@ +const { AsyncResource } = require('async_hooks'); +const { timeStamp } = require('console'); +const _Fiber = require('./fibers.js'); + +const weakMap = new WeakMap(); +const Fiber = function Fiber(...args) { + if (!(this instanceof Fiber)) { + return new Fiber(...args); + } + + const _private = { + _ar: new AsyncResource('Fiber'), + _fiber: _Fiber(...args) + }; + weakMap.set(this, _private); + _private._fiber._f = this; + return this; +}; + +Fiber.__proto__ = _Fiber; + +Object.defineProperty(Fiber, 'current', { + get() { + return _Fiber.current && _Fiber.current._f; + } +}) + +_Fiber[Symbol.hasInstance] = function(obj) { + // hacky + return obj instanceof Fiber || obj.run; +}; + +module.exports = Fiber; +Fiber.prototype = { + __proto__: Fiber, + get current() { + return _Fiber.current._f; + }, + + yield() { + return _Fiber.yield(...args); + }, + + get _ar() { + return weakMap.get(this)._ar; + }, + + // because of promise fiber pool, we want this. + set _ar(ar) { + return weakMap.get(this)._ar = ar; + }, + + get _fiber() { + return weakMap.get(this)._fiber; + }, + + run(...args) { + return this._ar.runInAsyncScope(() => this._fiber.run(...args)); + }, + + throwInto(...args) { + return this._ar.runInAsyncScope(() => this._fiber.throwInto(...args)); + } +} diff --git a/package.json b/package.json index f0d749c..7ecebfe 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ ], "homepage": "https://github.com/laverdet/node-fibers", "author": "Marcel Laverdet (https://github.com/laverdet/)", - "main": "fibers", + "main": "fibers_async", "scripts": { "install": "node build.js || nodejs build.js", "test": "node test.js || nodejs test.js"