Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

HookCodeFactory.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. class HookCodeFactory {
  7. constructor(config) {
  8. this.config = config;
  9. this.options = undefined;
  10. this._args = undefined;
  11. }
  12. create(options) {
  13. this.init(options);
  14. let fn;
  15. switch (this.options.type) {
  16. case "sync":
  17. fn = new Function(
  18. this.args(),
  19. '"use strict";\n' +
  20. this.header() +
  21. this.content({
  22. onError: err => `throw ${err};\n`,
  23. onResult: result => `return ${result};\n`,
  24. resultReturns: true,
  25. onDone: () => "",
  26. rethrowIfPossible: true
  27. })
  28. );
  29. break;
  30. case "async":
  31. fn = new Function(
  32. this.args({
  33. after: "_callback"
  34. }),
  35. '"use strict";\n' +
  36. this.header() +
  37. this.content({
  38. onError: err => `_callback(${err});\n`,
  39. onResult: result => `_callback(null, ${result});\n`,
  40. onDone: () => "_callback();\n"
  41. })
  42. );
  43. break;
  44. case "promise":
  45. let errorHelperUsed = false;
  46. const content = this.content({
  47. onError: err => {
  48. errorHelperUsed = true;
  49. return `_error(${err});\n`;
  50. },
  51. onResult: result => `_resolve(${result});\n`,
  52. onDone: () => "_resolve();\n"
  53. });
  54. let code = "";
  55. code += '"use strict";\n';
  56. code += "return new Promise((_resolve, _reject) => {\n";
  57. if (errorHelperUsed) {
  58. code += "var _sync = true;\n";
  59. code += "function _error(_err) {\n";
  60. code += "if(_sync)\n";
  61. code += "_resolve(Promise.resolve().then(() => { throw _err; }));\n";
  62. code += "else\n";
  63. code += "_reject(_err);\n";
  64. code += "};\n";
  65. }
  66. code += this.header();
  67. code += content;
  68. if (errorHelperUsed) {
  69. code += "_sync = false;\n";
  70. }
  71. code += "});\n";
  72. fn = new Function(this.args(), code);
  73. break;
  74. }
  75. this.deinit();
  76. return fn;
  77. }
  78. setup(instance, options) {
  79. instance._x = options.taps.map(t => t.fn);
  80. }
  81. /**
  82. * @param {{ type: "sync" | "promise" | "async", taps: Array<Tap>, interceptors: Array<Interceptor> }} options
  83. */
  84. init(options) {
  85. this.options = options;
  86. this._args = options.args.slice();
  87. }
  88. deinit() {
  89. this.options = undefined;
  90. this._args = undefined;
  91. }
  92. header() {
  93. let code = "";
  94. if (this.needContext()) {
  95. code += "var _context = {};\n";
  96. } else {
  97. code += "var _context;\n";
  98. }
  99. code += "var _x = this._x;\n";
  100. if (this.options.interceptors.length > 0) {
  101. code += "var _taps = this.taps;\n";
  102. code += "var _interceptors = this.interceptors;\n";
  103. }
  104. for (let i = 0; i < this.options.interceptors.length; i++) {
  105. const interceptor = this.options.interceptors[i];
  106. if (interceptor.call) {
  107. code += `${this.getInterceptor(i)}.call(${this.args({
  108. before: interceptor.context ? "_context" : undefined
  109. })});\n`;
  110. }
  111. }
  112. return code;
  113. }
  114. needContext() {
  115. for (const tap of this.options.taps) if (tap.context) return true;
  116. return false;
  117. }
  118. callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) {
  119. let code = "";
  120. let hasTapCached = false;
  121. for (let i = 0; i < this.options.interceptors.length; i++) {
  122. const interceptor = this.options.interceptors[i];
  123. if (interceptor.tap) {
  124. if (!hasTapCached) {
  125. code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`;
  126. hasTapCached = true;
  127. }
  128. code += `${this.getInterceptor(i)}.tap(${
  129. interceptor.context ? "_context, " : ""
  130. }_tap${tapIndex});\n`;
  131. }
  132. }
  133. code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`;
  134. const tap = this.options.taps[tapIndex];
  135. switch (tap.type) {
  136. case "sync":
  137. if (!rethrowIfPossible) {
  138. code += `var _hasError${tapIndex} = false;\n`;
  139. code += "try {\n";
  140. }
  141. if (onResult) {
  142. code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({
  143. before: tap.context ? "_context" : undefined
  144. })});\n`;
  145. } else {
  146. code += `_fn${tapIndex}(${this.args({
  147. before: tap.context ? "_context" : undefined
  148. })});\n`;
  149. }
  150. if (!rethrowIfPossible) {
  151. code += "} catch(_err) {\n";
  152. code += `_hasError${tapIndex} = true;\n`;
  153. code += onError("_err");
  154. code += "}\n";
  155. code += `if(!_hasError${tapIndex}) {\n`;
  156. }
  157. if (onResult) {
  158. code += onResult(`_result${tapIndex}`);
  159. }
  160. if (onDone) {
  161. code += onDone();
  162. }
  163. if (!rethrowIfPossible) {
  164. code += "}\n";
  165. }
  166. break;
  167. case "async":
  168. let cbCode = "";
  169. if (onResult) cbCode += `(_err${tapIndex}, _result${tapIndex}) => {\n`;
  170. else cbCode += `_err${tapIndex} => {\n`;
  171. cbCode += `if(_err${tapIndex}) {\n`;
  172. cbCode += onError(`_err${tapIndex}`);
  173. cbCode += "} else {\n";
  174. if (onResult) {
  175. cbCode += onResult(`_result${tapIndex}`);
  176. }
  177. if (onDone) {
  178. cbCode += onDone();
  179. }
  180. cbCode += "}\n";
  181. cbCode += "}";
  182. code += `_fn${tapIndex}(${this.args({
  183. before: tap.context ? "_context" : undefined,
  184. after: cbCode
  185. })});\n`;
  186. break;
  187. case "promise":
  188. code += `var _hasResult${tapIndex} = false;\n`;
  189. code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({
  190. before: tap.context ? "_context" : undefined
  191. })});\n`;
  192. code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`;
  193. code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`;
  194. code += `_promise${tapIndex}.then(_result${tapIndex} => {\n`;
  195. code += `_hasResult${tapIndex} = true;\n`;
  196. if (onResult) {
  197. code += onResult(`_result${tapIndex}`);
  198. }
  199. if (onDone) {
  200. code += onDone();
  201. }
  202. code += `}, _err${tapIndex} => {\n`;
  203. code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`;
  204. code += onError(`_err${tapIndex}`);
  205. code += "});\n";
  206. break;
  207. }
  208. return code;
  209. }
  210. callTapsSeries({
  211. onError,
  212. onResult,
  213. resultReturns,
  214. onDone,
  215. doneReturns,
  216. rethrowIfPossible
  217. }) {
  218. if (this.options.taps.length === 0) return onDone();
  219. const firstAsync = this.options.taps.findIndex(t => t.type !== "sync");
  220. const somethingReturns = resultReturns || doneReturns || false;
  221. let code = "";
  222. let current = onDone;
  223. for (let j = this.options.taps.length - 1; j >= 0; j--) {
  224. const i = j;
  225. const unroll = current !== onDone && this.options.taps[i].type !== "sync";
  226. if (unroll) {
  227. code += `function _next${i}() {\n`;
  228. code += current();
  229. code += `}\n`;
  230. current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`;
  231. }
  232. const done = current;
  233. const doneBreak = skipDone => {
  234. if (skipDone) return "";
  235. return onDone();
  236. };
  237. const content = this.callTap(i, {
  238. onError: error => onError(i, error, done, doneBreak),
  239. onResult:
  240. onResult &&
  241. (result => {
  242. return onResult(i, result, done, doneBreak);
  243. }),
  244. onDone: !onResult && done,
  245. rethrowIfPossible:
  246. rethrowIfPossible && (firstAsync < 0 || i < firstAsync)
  247. });
  248. current = () => content;
  249. }
  250. code += current();
  251. return code;
  252. }
  253. callTapsLooping({ onError, onDone, rethrowIfPossible }) {
  254. if (this.options.taps.length === 0) return onDone();
  255. const syncOnly = this.options.taps.every(t => t.type === "sync");
  256. let code = "";
  257. if (!syncOnly) {
  258. code += "var _looper = () => {\n";
  259. code += "var _loopAsync = false;\n";
  260. }
  261. code += "var _loop;\n";
  262. code += "do {\n";
  263. code += "_loop = false;\n";
  264. for (let i = 0; i < this.options.interceptors.length; i++) {
  265. const interceptor = this.options.interceptors[i];
  266. if (interceptor.loop) {
  267. code += `${this.getInterceptor(i)}.loop(${this.args({
  268. before: interceptor.context ? "_context" : undefined
  269. })});\n`;
  270. }
  271. }
  272. code += this.callTapsSeries({
  273. onError,
  274. onResult: (i, result, next, doneBreak) => {
  275. let code = "";
  276. code += `if(${result} !== undefined) {\n`;
  277. code += "_loop = true;\n";
  278. if (!syncOnly) code += "if(_loopAsync) _looper();\n";
  279. code += doneBreak(true);
  280. code += `} else {\n`;
  281. code += next();
  282. code += `}\n`;
  283. return code;
  284. },
  285. onDone:
  286. onDone &&
  287. (() => {
  288. let code = "";
  289. code += "if(!_loop) {\n";
  290. code += onDone();
  291. code += "}\n";
  292. return code;
  293. }),
  294. rethrowIfPossible: rethrowIfPossible && syncOnly
  295. });
  296. code += "} while(_loop);\n";
  297. if (!syncOnly) {
  298. code += "_loopAsync = true;\n";
  299. code += "};\n";
  300. code += "_looper();\n";
  301. }
  302. return code;
  303. }
  304. callTapsParallel({
  305. onError,
  306. onResult,
  307. onDone,
  308. rethrowIfPossible,
  309. onTap = (i, run) => run()
  310. }) {
  311. if (this.options.taps.length <= 1) {
  312. return this.callTapsSeries({
  313. onError,
  314. onResult,
  315. onDone,
  316. rethrowIfPossible
  317. });
  318. }
  319. let code = "";
  320. code += "do {\n";
  321. code += `var _counter = ${this.options.taps.length};\n`;
  322. if (onDone) {
  323. code += "var _done = () => {\n";
  324. code += onDone();
  325. code += "};\n";
  326. }
  327. for (let i = 0; i < this.options.taps.length; i++) {
  328. const done = () => {
  329. if (onDone) return "if(--_counter === 0) _done();\n";
  330. else return "--_counter;";
  331. };
  332. const doneBreak = skipDone => {
  333. if (skipDone || !onDone) return "_counter = 0;\n";
  334. else return "_counter = 0;\n_done();\n";
  335. };
  336. code += "if(_counter <= 0) break;\n";
  337. code += onTap(
  338. i,
  339. () =>
  340. this.callTap(i, {
  341. onError: error => {
  342. let code = "";
  343. code += "if(_counter > 0) {\n";
  344. code += onError(i, error, done, doneBreak);
  345. code += "}\n";
  346. return code;
  347. },
  348. onResult:
  349. onResult &&
  350. (result => {
  351. let code = "";
  352. code += "if(_counter > 0) {\n";
  353. code += onResult(i, result, done, doneBreak);
  354. code += "}\n";
  355. return code;
  356. }),
  357. onDone:
  358. !onResult &&
  359. (() => {
  360. return done();
  361. }),
  362. rethrowIfPossible
  363. }),
  364. done,
  365. doneBreak
  366. );
  367. }
  368. code += "} while(false);\n";
  369. return code;
  370. }
  371. args({ before, after } = {}) {
  372. let allArgs = this._args;
  373. if (before) allArgs = [before].concat(allArgs);
  374. if (after) allArgs = allArgs.concat(after);
  375. if (allArgs.length === 0) {
  376. return "";
  377. } else {
  378. return allArgs.join(", ");
  379. }
  380. }
  381. getTapFn(idx) {
  382. return `_x[${idx}]`;
  383. }
  384. getTap(idx) {
  385. return `_taps[${idx}]`;
  386. }
  387. getInterceptor(idx) {
  388. return `_interceptors[${idx}]`;
  389. }
  390. }
  391. module.exports = HookCodeFactory;