-
Notifications
You must be signed in to change notification settings - Fork 65
/
meld.js
598 lines (487 loc) · 14.9 KB
/
meld.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/** @license MIT License (c) copyright 2011-2013 original author or authors */
/**
* meld
* Aspect Oriented Programming for Javascript
*
* meld is part of the cujo.js family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @author Brian Cavalier
* @author John Hann
* @version 1.3.1
*/
(function (define) {
define(function () {
//
// Public API
//
// Add a single, specific type of advice
// returns a function that will remove the newly-added advice
meld.before = adviceApi('before');
meld.around = adviceApi('around');
meld.on = adviceApi('on');
meld.afterReturning = adviceApi('afterReturning');
meld.afterThrowing = adviceApi('afterThrowing');
meld.after = adviceApi('after');
// Access to the current joinpoint in advices
meld.joinpoint = joinpoint;
// DEPRECATED: meld.add(). Use meld() instead
// Returns a function that will remove the newly-added aspect
meld.add = function() { return meld.apply(null, arguments); };
/**
* Add an aspect to all matching methods of target, or to target itself if
* target is a function and no pointcut is provided.
* @param {object|function} target
* @param {string|array|RegExp|function} [pointcut]
* @param {object} aspect
* @param {function?} aspect.before
* @param {function?} aspect.on
* @param {function?} aspect.around
* @param {function?} aspect.afterReturning
* @param {function?} aspect.afterThrowing
* @param {function?} aspect.after
* @returns {{ remove: function }|function} if target is an object, returns a
* remover { remove: function } whose remove method will remove the added
* aspect. If target is a function, returns the newly advised function.
*/
function meld(target, pointcut, aspect) {
var pointcutType, remove;
if(arguments.length < 3) {
return addAspectToFunction(target, pointcut);
} else {
if (isArray(pointcut)) {
remove = addAspectToAll(target, pointcut, aspect);
} else {
pointcutType = typeof pointcut;
if (pointcutType === 'string') {
if (typeof target[pointcut] === 'function') {
remove = addAspectToMethod(target, pointcut, aspect);
}
} else if (pointcutType === 'function') {
remove = addAspectToAll(target, pointcut(target), aspect);
} else {
remove = addAspectToMatches(target, pointcut, aspect);
}
}
return remove;
}
}
function Advisor(target, func) {
var orig, advisor, advised;
this.target = target;
this.func = func;
this.aspects = {};
orig = this.orig = target[func];
advisor = this;
advised = this.advised = function() {
var context, joinpoint, args, callOrig, afterType;
// If called as a constructor (i.e. using "new"), create a context
// of the correct type, so that all advice types (including before!)
// are called with the correct context.
if(this instanceof advised) {
// shamelessly derived from https://github.com/cujojs/wire/blob/c7c55fe50238ecb4afbb35f902058ab6b32beb8f/lib/component.js#L25
context = objectCreate(orig.prototype);
callOrig = function (args) {
return applyConstructor(orig, context, args);
};
} else {
context = this;
callOrig = function(args) {
return orig.apply(context, args);
};
}
args = slice.call(arguments);
afterType = 'afterReturning';
// Save the previous joinpoint and set the current joinpoint
joinpoint = pushJoinpoint({
target: context,
method: func,
args: args
});
try {
advisor._callSimpleAdvice('before', context, args);
try {
joinpoint.result = advisor._callAroundAdvice(context, func, args, callOrigAndOn);
} catch(e) {
joinpoint.result = joinpoint.exception = e;
// Switch to afterThrowing
afterType = 'afterThrowing';
}
args = [joinpoint.result];
callAfter(afterType, args);
callAfter('after', args);
if(joinpoint.exception) {
throw joinpoint.exception;
}
return joinpoint.result;
} finally {
// Restore the previous joinpoint, if necessary.
popJoinpoint();
}
function callOrigAndOn(args) {
var result = callOrig(args);
advisor._callSimpleAdvice('on', context, args);
return result;
}
function callAfter(afterType, args) {
advisor._callSimpleAdvice(afterType, context, args);
}
};
defineProperty(advised, '_advisor', { value: advisor, configurable: true });
}
Advisor.prototype = {
/**
* Invoke all advice functions in the supplied context, with the supplied args
*
* @param adviceType
* @param context
* @param args
*/
_callSimpleAdvice: function(adviceType, context, args) {
// before advice runs LIFO, from most-recently added to least-recently added.
// All other advice is FIFO
var iterator, advices;
advices = this.aspects[adviceType];
if(!advices) {
return;
}
iterator = iterators[adviceType];
iterator(this.aspects[adviceType], function(aspect) {
var advice = aspect.advice;
advice && advice.apply(context, args);
});
},
/**
* Invoke all around advice and then the original method
*
* @param context
* @param method
* @param args
* @param applyOriginal
*/
_callAroundAdvice: function (context, method, args, applyOriginal) {
var len, aspects;
aspects = this.aspects.around;
len = aspects ? aspects.length : 0;
/**
* Call the next function in the around chain, which will either be another around
* advice, or the orig method.
* @param i {Number} index of the around advice
* @param args {Array} arguments with with to call the next around advice
*/
function callNext(i, args) {
// If we exhausted all aspects, finally call the original
// Otherwise, if we found another around, call it
return i < 0
? applyOriginal(args)
: callAround(aspects[i].advice, i, args);
}
function callAround(around, i, args) {
var proceedCalled, joinpoint;
proceedCalled = 0;
// Joinpoint is immutable
// TODO: Use Object.freeze once v8 perf problem is fixed
joinpoint = pushJoinpoint({
target: context,
method: method,
args: args,
proceed: proceedCall,
proceedApply: proceedApply,
proceedCount: proceedCount
});
try {
// Call supplied around advice function
return around.call(context, joinpoint);
} finally {
popJoinpoint();
}
/**
* The number of times proceed() has been called
* @return {Number}
*/
function proceedCount() {
return proceedCalled;
}
/**
* Proceed to the original method/function or the next around
* advice using original arguments or new argument list if
* arguments.length > 0
* @return {*} result of original method/function or next around advice
*/
function proceedCall(/* newArg1, newArg2... */) {
return proceed(arguments.length > 0 ? slice.call(arguments) : args);
}
/**
* Proceed to the original method/function or the next around
* advice using original arguments or new argument list if
* newArgs is supplied
* @param [newArgs] {Array} new arguments with which to proceed
* @return {*} result of original method/function or next around advice
*/
function proceedApply(newArgs) {
return proceed(newArgs || args);
}
/**
* Create proceed function that calls the next around advice, or
* the original. May be called multiple times, for example, in retry
* scenarios
* @param [args] {Array} optional arguments to use instead of the
* original arguments
*/
function proceed(args) {
proceedCalled++;
return callNext(i - 1, args);
}
}
return callNext(len - 1, args);
},
/**
* Adds the supplied aspect to the advised target method
*
* @param aspect
*/
add: function(aspect) {
var advisor, aspects;
advisor = this;
aspects = advisor.aspects;
insertAspect(aspects, aspect);
return {
remove: function () {
var remaining = removeAspect(aspects, aspect);
// If there are no aspects left, restore the original method
if (!remaining) {
advisor.remove();
}
}
};
},
/**
* Removes the Advisor and thus, all aspects from the advised target method, and
* restores the original target method, copying back all properties that may have
* been added or updated on the advised function.
*/
remove: function () {
delete this.advised._advisor;
this.target[this.func] = this.orig;
}
};
/**
* Returns the advisor for the target object-function pair. A new advisor
* will be created if one does not already exist.
* @param target {*} target containing a method with the supplied methodName
* @param methodName {String} name of method on target for which to get an advisor
* @return {Object|undefined} existing or newly created advisor for the supplied method
*/
Advisor.get = function(target, methodName) {
if(!(methodName in target)) {
return;
}
var advisor, advised;
advised = target[methodName];
if(typeof advised !== 'function') {
throw new Error('Advice can only be applied to functions: ' + methodName);
}
advisor = advised._advisor;
if(!advisor) {
advisor = new Advisor(target, methodName);
target[methodName] = advisor.advised;
}
return advisor;
};
/**
* Add an aspect to a pure function, returning an advised version of it.
* NOTE: *only the returned function* is advised. The original (input) function
* is not modified in any way.
* @param func {Function} function to advise
* @param aspect {Object} aspect to add
* @return {Function} advised function
*/
function addAspectToFunction(func, aspect) {
var name, placeholderTarget;
name = func.name || '_';
placeholderTarget = {};
placeholderTarget[name] = func;
addAspectToMethod(placeholderTarget, name, aspect);
return placeholderTarget[name];
}
function addAspectToMethod(target, method, aspect) {
var advisor = Advisor.get(target, method);
return advisor && advisor.add(aspect);
}
function addAspectToAll(target, methodArray, aspect) {
var removers, added, f, i;
removers = [];
i = 0;
while((f = methodArray[i++])) {
added = addAspectToMethod(target, f, aspect);
added && removers.push(added);
}
return createRemover(removers);
}
function addAspectToMatches(target, pointcut, aspect) {
var removers = [];
// Assume the pointcut is a an object with a .test() method
for (var p in target) {
// TODO: Decide whether hasOwnProperty is correct here
// Only apply to own properties that are functions, and match the pointcut regexp
if (typeof target[p] == 'function' && pointcut.test(p)) {
// if(object.hasOwnProperty(p) && typeof object[p] === 'function' && pointcut.test(p)) {
removers.push(addAspectToMethod(target, p, aspect));
}
}
return createRemover(removers);
}
function createRemover(removers) {
return {
remove: function() {
for (var i = removers.length - 1; i >= 0; --i) {
removers[i].remove();
}
}
};
}
// Create an API function for the specified advice type
function adviceApi(type) {
return function(target, method, adviceFunc) {
var aspect = {};
if(arguments.length === 2) {
aspect[type] = method;
return meld(target, aspect);
} else {
aspect[type] = adviceFunc;
return meld(target, method, aspect);
}
};
}
/**
* Insert the supplied aspect into aspectList
* @param aspectList {Object} list of aspects, categorized by advice type
* @param aspect {Object} aspect containing one or more supported advice types
*/
function insertAspect(aspectList, aspect) {
var adviceType, advice, advices;
for(adviceType in iterators) {
advice = aspect[adviceType];
if(advice) {
advices = aspectList[adviceType];
if(!advices) {
aspectList[adviceType] = advices = [];
}
advices.push({
aspect: aspect,
advice: advice
});
}
}
}
/**
* Remove the supplied aspect from aspectList
* @param aspectList {Object} list of aspects, categorized by advice type
* @param aspect {Object} aspect containing one or more supported advice types
* @return {Number} Number of *advices* left on the advised function. If
* this returns zero, then it is safe to remove the advisor completely.
*/
function removeAspect(aspectList, aspect) {
var adviceType, advices, remaining;
remaining = 0;
for(adviceType in iterators) {
advices = aspectList[adviceType];
if(advices) {
remaining += advices.length;
for (var i = advices.length - 1; i >= 0; --i) {
if (advices[i].aspect === aspect) {
advices.splice(i, 1);
--remaining;
break;
}
}
}
}
return remaining;
}
function applyConstructor(C, instance, args) {
try {
// Try to define a constructor, but don't care if it fails
defineProperty(instance, 'constructor', {
value: C,
enumerable: false
});
} catch(e) {
// ignore
}
C.apply(instance, args);
return instance;
}
var currentJoinpoint, joinpointStack,
ap, prepend, append, iterators, slice, isArray, defineProperty, objectCreate;
// TOOD: Freeze joinpoints when v8 perf problems are resolved
// freeze = Object.freeze || function (o) { return o; };
joinpointStack = [];
ap = Array.prototype;
prepend = ap.unshift;
append = ap.push;
slice = ap.slice;
isArray = Array.isArray || function(it) {
return Object.prototype.toString.call(it) == '[object Array]';
};
// Check for a *working* Object.defineProperty, fallback to
// simple assignment.
defineProperty = definePropertyWorks()
? Object.defineProperty
: function(obj, prop, descriptor) {
obj[prop] = descriptor.value;
};
objectCreate = Object.create ||
(function() {
function F() {}
return function(proto) {
F.prototype = proto;
var instance = new F();
F.prototype = null;
return instance;
};
}());
iterators = {
// Before uses reverse iteration
before: forEachReverse,
around: false
};
// All other advice types use forward iteration
// Around is a special case that uses recursion rather than
// iteration. See Advisor._callAroundAdvice
iterators.on
= iterators.afterReturning
= iterators.afterThrowing
= iterators.after
= forEach;
function forEach(array, func) {
for (var i = 0, len = array.length; i < len; i++) {
func(array[i]);
}
}
function forEachReverse(array, func) {
for (var i = array.length - 1; i >= 0; --i) {
func(array[i]);
}
}
function joinpoint() {
return currentJoinpoint;
}
function pushJoinpoint(newJoinpoint) {
joinpointStack.push(currentJoinpoint);
return currentJoinpoint = newJoinpoint;
}
function popJoinpoint() {
return currentJoinpoint = joinpointStack.pop();
}
function definePropertyWorks() {
try {
return 'x' in Object.defineProperty({}, 'x', {});
} catch (e) { /* return falsey */ }
}
return meld;
});
})(typeof define == 'function' && define.amd ? define : function (factory) { module.exports = factory(); }
);