| 1 |
"use strict"; |
| 2 |
|
| 3 |
// These use the global symbol registry so that multiple copies of this |
| 4 |
// library can work together in case they are not deduped. |
| 5 |
const GENSYNC_START = Symbol.for("gensync:v1:start"); |
| 6 |
const GENSYNC_SUSPEND = Symbol.for("gensync:v1:suspend"); |
| 7 |
|
| 8 |
const GENSYNC_EXPECTED_START = "GENSYNC_EXPECTED_START"; |
| 9 |
const GENSYNC_EXPECTED_SUSPEND = "GENSYNC_EXPECTED_SUSPEND"; |
| 10 |
const GENSYNC_OPTIONS_ERROR = "GENSYNC_OPTIONS_ERROR"; |
| 11 |
const GENSYNC_RACE_NONEMPTY = "GENSYNC_RACE_NONEMPTY"; |
| 12 |
const GENSYNC_ERRBACK_NO_CALLBACK = "GENSYNC_ERRBACK_NO_CALLBACK"; |
| 13 |
|
| 14 |
module.exports = Object.assign( |
| 15 |
function gensync(optsOrFn) { |
| 16 |
let genFn = optsOrFn; |
| 17 |
if (typeof optsOrFn !== "function") { |
| 18 |
genFn = newGenerator(optsOrFn); |
| 19 |
} else { |
| 20 |
genFn = wrapGenerator(optsOrFn); |
| 21 |
} |
| 22 |
|
| 23 |
return Object.assign(genFn, makeFunctionAPI(genFn)); |
| 24 |
}, |
| 25 |
{ |
| 26 |
all: buildOperation({ |
| 27 |
name: "all", |
| 28 |
arity: 1, |
| 29 |
sync: function(args) { |
| 30 |
const items = Array.from(args[0]); |
| 31 |
return items.map(item => evaluateSync(item)); |
| 32 |
}, |
| 33 |
async: function(args, resolve, reject) { |
| 34 |
const items = Array.from(args[0]); |
| 35 |
|
| 36 |
let count = 0; |
| 37 |
const results = items.map(() => undefined); |
| 38 |
items.forEach((item, i) => { |
| 39 |
evaluateAsync( |
| 40 |
item, |
| 41 |
val => { |
| 42 |
results[i] = val; |
| 43 |
count += 1; |
| 44 |
|
| 45 |
if (count === results.length) resolve(results); |
| 46 |
}, |
| 47 |
reject |
| 48 |
); |
| 49 |
}); |
| 50 |
}, |
| 51 |
}), |
| 52 |
race: buildOperation({ |
| 53 |
name: "race", |
| 54 |
arity: 1, |
| 55 |
sync: function(args) { |
| 56 |
const items = Array.from(args[0]); |
| 57 |
if (items.length === 0) { |
| 58 |
throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); |
| 59 |
} |
| 60 |
|
| 61 |
return evaluateSync(items[0]); |
| 62 |
}, |
| 63 |
async: function(args, resolve, reject) { |
| 64 |
const items = Array.from(args[0]); |
| 65 |
if (items.length === 0) { |
| 66 |
throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); |
| 67 |
} |
| 68 |
|
| 69 |
for (const item of items) { |
| 70 |
evaluateAsync(item, resolve, reject); |
| 71 |
} |
| 72 |
}, |
| 73 |
}), |
| 74 |
} |
| 75 |
); |
| 76 |
|
| 77 |
/** |
| 78 |
* Given a generator function, return the standard API object that executes |
| 79 |
* the generator and calls the callbacks. |
| 80 |
*/ |
| 81 |
function makeFunctionAPI(genFn) { |
| 82 |
const fns = { |
| 83 |
sync: function(...args) { |
| 84 |
return evaluateSync(genFn.apply(this, args)); |
| 85 |
}, |
| 86 |
async: function(...args) { |
| 87 |
return new Promise((resolve, reject) => { |
| 88 |
evaluateAsync(genFn.apply(this, args), resolve, reject); |
| 89 |
}); |
| 90 |
}, |
| 91 |
errback: function(...args) { |
| 92 |
const cb = args.pop(); |
| 93 |
if (typeof cb !== "function") { |
| 94 |
throw makeError( |
| 95 |
"Asynchronous function called without callback", |
| 96 |
GENSYNC_ERRBACK_NO_CALLBACK |
| 97 |
); |
| 98 |
} |
| 99 |
|
| 100 |
let gen; |
| 101 |
try { |
| 102 |
gen = genFn.apply(this, args); |
| 103 |
} catch (err) { |
| 104 |
cb(err); |
| 105 |
return; |
| 106 |
} |
| 107 |
|
| 108 |
evaluateAsync(gen, val => cb(undefined, val), err => cb(err)); |
| 109 |
}, |
| 110 |
}; |
| 111 |
return fns; |
| 112 |
} |
| 113 |
|
| 114 |
function assertTypeof(type, name, value, allowUndefined) { |
| 115 |
if ( |
| 116 |
typeof value === type || |
| 117 |
(allowUndefined && typeof value === "undefined") |
| 118 |
) { |
| 119 |
return; |
| 120 |
} |
| 121 |
|
| 122 |
let msg; |
| 123 |
if (allowUndefined) { |
| 124 |
msg = `Expected opts.${name} to be either a ${type}, or undefined.`; |
| 125 |
} else { |
| 126 |
msg = `Expected opts.${name} to be a ${type}.`; |
| 127 |
} |
| 128 |
|
| 129 |
throw makeError(msg, GENSYNC_OPTIONS_ERROR); |
| 130 |
} |
| 131 |
function makeError(msg, code) { |
| 132 |
return Object.assign(new Error(msg), { code }); |
| 133 |
} |
| 134 |
|
| 135 |
/** |
| 136 |
* Given an options object, return a new generator that dispatches the |
| 137 |
* correct handler based on sync or async execution. |
| 138 |
*/ |
| 139 |
function newGenerator({ name, arity, sync, async, errback }) { |
| 140 |
assertTypeof("string", "name", name, true /* allowUndefined */); |
| 141 |
assertTypeof("number", "arity", arity, true /* allowUndefined */); |
| 142 |
assertTypeof("function", "sync", sync); |
| 143 |
assertTypeof("function", "async", async, true /* allowUndefined */); |
| 144 |
assertTypeof("function", "errback", errback, true /* allowUndefined */); |
| 145 |
if (async && errback) { |
| 146 |
throw makeError( |
| 147 |
"Expected one of either opts.async or opts.errback, but got _both_.", |
| 148 |
GENSYNC_OPTIONS_ERROR |
| 149 |
); |
| 150 |
} |
| 151 |
|
| 152 |
if (typeof name !== "string") { |
| 153 |
let fnName; |
| 154 |
if (errback && errback.name && errback.name !== "errback") { |
| 155 |
fnName = errback.name; |
| 156 |
} |
| 157 |
if (async && async.name && async.name !== "async") { |
| 158 |
fnName = async.name.replace(/Async$/, ""); |
| 159 |
} |
| 160 |
if (sync && sync.name && sync.name !== "sync") { |
| 161 |
fnName = sync.name.replace(/Sync$/, ""); |
| 162 |
} |
| 163 |
|
| 164 |
if (typeof fnName === "string") { |
| 165 |
name = fnName; |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
if (typeof arity !== "number") { |
| 170 |
arity = sync.length; |
| 171 |
} |
| 172 |
|
| 173 |
return buildOperation({ |
| 174 |
name, |
| 175 |
arity, |
| 176 |
sync: function(args) { |
| 177 |
return sync.apply(this, args); |
| 178 |
}, |
| 179 |
async: function(args, resolve, reject) { |
| 180 |
if (async) { |
| 181 |
async.apply(this, args).then(resolve, reject); |
| 182 |
} else if (errback) { |
| 183 |
errback.call(this, ...args, (err, value) => { |
| 184 |
if (err == null) resolve(value); |
| 185 |
else reject(err); |
| 186 |
}); |
| 187 |
} else { |
| 188 |
resolve(sync.apply(this, args)); |
| 189 |
} |
| 190 |
}, |
| 191 |
}); |
| 192 |
} |
| 193 |
|
| 194 |
function wrapGenerator(genFn) { |
| 195 |
return setFunctionMetadata(genFn.name, genFn.length, function(...args) { |
| 196 |
return genFn.apply(this, args); |
| 197 |
}); |
| 198 |
} |
| 199 |
|
| 200 |
function buildOperation({ name, arity, sync, async }) { |
| 201 |
return setFunctionMetadata(name, arity, function*(...args) { |
| 202 |
const resume = yield GENSYNC_START; |
| 203 |
if (!resume) { |
| 204 |
return sync.call(this, args); |
| 205 |
} |
| 206 |
|
| 207 |
let result; |
| 208 |
try { |
| 209 |
async.call( |
| 210 |
this, |
| 211 |
args, |
| 212 |
value => { |
| 213 |
if (result) return; |
| 214 |
|
| 215 |
result = { value }; |
| 216 |
resume(); |
| 217 |
}, |
| 218 |
err => { |
| 219 |
if (result) return; |
| 220 |
|
| 221 |
result = { err }; |
| 222 |
resume(); |
| 223 |
} |
| 224 |
); |
| 225 |
} catch (err) { |
| 226 |
result = { err }; |
| 227 |
resume(); |
| 228 |
} |
| 229 |
|
| 230 |
// Suspend until the callbacks run. Will resume synchronously if the |
| 231 |
// callback was already called. |
| 232 |
yield GENSYNC_SUSPEND; |
| 233 |
|
| 234 |
if (result.hasOwnProperty("err")) { |
| 235 |
throw result.err; |
| 236 |
} |
| 237 |
|
| 238 |
return result.value; |
| 239 |
}); |
| 240 |
} |
| 241 |
|
| 242 |
function evaluateSync(gen) { |
| 243 |
let value; |
| 244 |
while (!({ value } = gen.next()).done) { |
| 245 |
assertStart(value, gen); |
| 246 |
} |
| 247 |
return value; |
| 248 |
} |
| 249 |
|
| 250 |
function evaluateAsync(gen, resolve, reject) { |
| 251 |
(function step() { |
| 252 |
try { |
| 253 |
let value; |
| 254 |
while (!({ value } = gen.next()).done) { |
| 255 |
assertStart(value, gen); |
| 256 |
|
| 257 |
// If this throws, it is considered to have broken the contract |
| 258 |
// established for async handlers. If these handlers are called |
| 259 |
// synchronously, it is also considered bad behavior. |
| 260 |
let sync = true; |
| 261 |
let didSyncResume = false; |
| 262 |
const out = gen.next(() => { |
| 263 |
if (sync) { |
| 264 |
didSyncResume = true; |
| 265 |
} else { |
| 266 |
step(); |
| 267 |
} |
| 268 |
}); |
| 269 |
sync = false; |
| 270 |
|
| 271 |
assertSuspend(out, gen); |
| 272 |
|
| 273 |
if (!didSyncResume) { |
| 274 |
// Callback wasn't called synchronously, so break out of the loop |
| 275 |
// and let it call 'step' later. |
| 276 |
return; |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
return resolve(value); |
| 281 |
} catch (err) { |
| 282 |
return reject(err); |
| 283 |
} |
| 284 |
})(); |
| 285 |
} |
| 286 |
|
| 287 |
function assertStart(value, gen) { |
| 288 |
if (value === GENSYNC_START) return; |
| 289 |
|
| 290 |
throwError( |
| 291 |
gen, |
| 292 |
makeError( |
| 293 |
`Got unexpected yielded value in gensync generator: ${JSON.stringify( |
| 294 |
value |
| 295 |
)}. Did you perhaps mean to use 'yield*' instead of 'yield'?`, |
| 296 |
GENSYNC_EXPECTED_START |
| 297 |
) |
| 298 |
); |
| 299 |
} |
| 300 |
function assertSuspend({ value, done }, gen) { |
| 301 |
if (!done && value === GENSYNC_SUSPEND) return; |
| 302 |
|
| 303 |
throwError( |
| 304 |
gen, |
| 305 |
makeError( |
| 306 |
done |
| 307 |
? "Unexpected generator completion. If you get this, it is probably a gensync bug." |
| 308 |
: `Expected GENSYNC_SUSPEND, got ${JSON.stringify( |
| 309 |
value |
| 310 |
)}. If you get this, it is probably a gensync bug.`, |
| 311 |
GENSYNC_EXPECTED_SUSPEND |
| 312 |
) |
| 313 |
); |
| 314 |
} |
| 315 |
|
| 316 |
function throwError(gen, err) { |
| 317 |
// Call `.throw` so that users can step in a debugger to easily see which |
| 318 |
// 'yield' passed an unexpected value. If the `.throw` call didn't throw |
| 319 |
// back to the generator, we explicitly do it to stop the error |
| 320 |
// from being swallowed by user code try/catches. |
| 321 |
if (gen.throw) gen.throw(err); |
| 322 |
throw err; |
| 323 |
} |
| 324 |
|
| 325 |
function isIterable(value) { |
| 326 |
return ( |
| 327 |
!!value && |
| 328 |
(typeof value === "object" || typeof value === "function") && |
| 329 |
!value[Symbol.iterator] |
| 330 |
); |
| 331 |
} |
| 332 |
|
| 333 |
function setFunctionMetadata(name, arity, fn) { |
| 334 |
if (typeof name === "string") { |
| 335 |
// This should always work on the supported Node versions, but for the |
| 336 |
// sake of users that are compiling to older versions, we check for |
| 337 |
// configurability so we don't throw. |
| 338 |
const nameDesc = Object.getOwnPropertyDescriptor(fn, "name"); |
| 339 |
if (!nameDesc || nameDesc.configurable) { |
| 340 |
Object.defineProperty( |
| 341 |
fn, |
| 342 |
"name", |
| 343 |
Object.assign(nameDesc || {}, { |
| 344 |
configurable: true, |
| 345 |
value: name, |
| 346 |
}) |
| 347 |
); |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
if (typeof arity === "number") { |
| 352 |
const lengthDesc = Object.getOwnPropertyDescriptor(fn, "length"); |
| 353 |
if (!lengthDesc || lengthDesc.configurable) { |
| 354 |
Object.defineProperty( |
| 355 |
fn, |
| 356 |
"length", |
| 357 |
Object.assign(lengthDesc || {}, { |
| 358 |
configurable: true, |
| 359 |
value: arity, |
| 360 |
}) |
| 361 |
); |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
return fn; |
| 366 |
} |