## model.js `can.Model` _A `can.Observe` that connects to a RESTful interface._ Generic deferred piping function
18589
function (self, type, success, error, method) {
            var args;
            // if we pass an array as `self` it it means we are coming from
            // the queued request, and we're passing already serialized data
            // self's signature will be: [self, serializedData]
            if (can.isArray(self)) {
                args = self[1];
                self = self[0];
            } else {
                args = self.serialize();
            }
            args = [args];
            var deferred,
            // The model.
            model = self.constructor,
                jqXHR;

            // `destroy` does not need data.
            if (type == 'destroy') {
                args.shift();
            }
            // `update` and `destroy` need the `id`.
            if (type !== 'create') {
                args.unshift(getId(self));
            }


            jqXHR = model[type].apply(model, args);

            deferred = jqXHR.pipe(function (data) {
                self[method || type + "d"](data, jqXHR);
                return self;
            });

            // Hook up `abort`
            if (jqXHR.abort) {
                deferred.abort = function () {
                    jqXHR.abort();
                };
            }

            deferred.then(success, error);
            return deferred;
        }
615355
function Model(defaults){

    // Make sure "new" is always used,
    // so we can use "instanceof" to check if something is a Model.
    if (!(this instanceof Model)) {
      return new Model(defaults);
    }

    // `model` is the public API object returned from invoking `new Model()`.
    var model = this,

        // The internal stored values for tracked properties. { property -> value }
        values = {},

        // The callback functions for each tracked property. { property -> [callback] }
        listeners = {},

        // The set of tracked properties. { property -> true }
        trackedProperties = {};

    // The functional reactive "when" operator.
    //
    //  * `properties` An array of property names (can also be a single property string).
    //  * `callback` A callback function that is called:
    //    * with property values as arguments, ordered corresponding to the properties array,
    //    * only if all specified properties have values,
    //    * once for initialization,
    //    * whenever one or more specified properties change,
    //    * on the next tick of the JavaScript event loop after properties change,
    //    * only once as a result of one or more synchronous changes to dependency properties.
    function when(properties, callback, thisArg){
      
      // Make sure the default `this` becomes 
      // the object you called `.on` on.
      thisArg = thisArg || this;

      // Handle either an array or a single string.
      properties = (properties instanceof Array) ? properties : [properties];

      // This function will trigger the callback to be invoked.
      var listener = debounce(function (){
        var args = properties.map(function(property){
          return values[property];
        });
        if(allAreDefined(args)){
          callback.apply(thisArg, args);
        }
      });

      // Trigger the callback once for initialization.
      listener();
      
      // Trigger the callback whenever specified properties change.
      properties.forEach(function(property){
        on(property, listener);
      });

      // Return this function so it can be removed later with `model.cancel(listener)`.
      return listener;
    }

    // Adds a change listener for a given property with Backbone-like behavior.
    // Similar to http://backbonejs.org/#Events-on
    function on(property, callback, thisArg){
      thisArg = thisArg || this;
      getListeners(property).push(callback);
      track(property, thisArg);
    }
    
    // Gets or creates the array of listener functions for a given property.
    function getListeners(property){
      return listeners[property] || (listeners[property] = []);
    }

    // Tracks a property if it is not already tracked.
    function track(property, thisArg){
      if(!(property in trackedProperties)){
        trackedProperties[property] = true;
        values[property] = model[property];
        Object.defineProperty(model, property, {
          get: function () { return values[property]; },
          set: function(newValue) {
            var oldValue = values[property];
            values[property] = newValue;
            getListeners(property).forEach(function(callback){
              callback.call(thisArg, newValue, oldValue);
            });
          }
        });
      }
    }

    // Cancels a listener returned by a call to `model.when(...)`.
    function cancel(listener){
      for(var property in listeners){
        off(property, listener);
      }
    }

    // Removes a change listener added using `on`.
    function off(property, callback){
      listeners[property] = listeners[property].filter(function (listener) {
        return listener !== callback;
      });
    }

    // Sets all of the given values on the model.
    // `newValues` is an object { property -> value }.
    function set(newValues){
      for(var property in newValues){
        model[property] = newValues[property];
      }
    }

    // Transfer defaults passed into the constructor to the model.
    set(defaults);

    // Public API.
    model.when = when;
    model.cancel = cancel;
    model.on = on;
    model.off = off;
    model.set = set;
  }
281275
function(input, callback, context, remoteData)
  {
    var db = this;
    var promise = new Promise();

    promise.success( callback, context || db );

    function checkModel()
    {
      var result = db.parseModel( input, remoteData );

      if ( result !== false && !promise.isComplete() && db.initialized )
      {
        var remoteLoaded = db.remoteLoaded || !db.hasLoad( Load.All );
        var missingModel = (result === null || !result.$isSaved());
        var lazyLoad = db.hasLoad( Load.Lazy );

        if ( lazyLoad && remoteLoaded && missingModel )
        {
          if ( !result )
          {
            result = db.keyHandler.buildObjectFromKey( db.keyHandler.buildKeyFromInput( input ) );
          }

          result.$once( Model.Events.RemoteGets, function()
          {
            if ( !promise.isComplete() )
            {
              if ( isObject( input ) )
              {
                result.$set( input );
              }

              promise.resolve( result.$isSaved() ? result : null );
            }
          });

          result.$refresh( Cascade.All, db.fetchOptions );
        }
        else
        {
          promise.resolve( result );
        }
      }

      return promise.isComplete() ? false : true;
    }

    if ( checkModel() )
    {
      db.ready( checkModel, db, true );
    }

    return promise;
  }
272568
function Observer(obj, keypath, callback, options) {
    this.options = options || {}
    this.options.adapters = this.options.adapters || {}
    this.obj = obj
    this.keypath = keypath
    this.callback = callback
    this.objectPath = []
    this.update = this.update.bind(this)
    this.parse()

    if (isObject(this.target = this.realize())) {
      this.set(true, this.key, this.target, this.callback)
    }
  }
516732
function Deferred(opts){
 	/**
	 * @define {object} Collection of public methods.
	 */
	var self = {};

	/**
	 * @define {object} options for the constructor 
	 */
	var opts = opts || {};

	/**
	 * @define {object} A promise object that will be returned
	 */
	var promise = {};

	/**
	 * @define {object} Event system for controlling events
	 */
	var event = Event();
	
	/**
	 * Promise then method
	 * This is for chaining promis callbacks
	 * @example promiseFunction().then(
	 * function(){ // success }, 
	 * function(){ // rejected }, 
	 * function(){ // notify } 
	 * ).then( ... );
	 * @param {function} sucess Success callback
	 * @param {function} reject Reject callback
	 * @param {function} notify notify callback
	 * @return {object} Returns the promise object
	 */
	function promiseThen(success, reject, notify){
		/**
		 * @define {object} Return a new promise
		 */
		var def = Deferred();

		/**
		 * Resolved promise
		 * @example example
		 * @param {string} A string key for the event system
		 * @param {function} A callback when event is triggered
		 * @return {object} Returns promise object
		 */
		event.on('resolve', function(){ 
			/**
			 * If the success callback returns a promise
			 * then resolve/reject/notify that returned promise
			 */
			var promise = success();
			if(!promise) return;
			promise.success(function(){
				/** handle the returned deferred object */
				def.resolve();
			});
			promise.error(function(){
				def.reject();
			});
			promise.notify(function(){
				def.notify();
			});
		});

		/**
		 * If promise is rejected/notify trigger the callback
		 */
		event.on('reject', function(){ 
			if(reject) reject();
		});

		event.on('notify', function(){ 
			if(notify) notify();
		});

		/**
		 * @return {object} Returns a promise object
		 */
		return def.promise; 
	}

	/**
	 * Promise methods
	 * @example promise.then( //new promise ).then(...)
	 * @example promise.success(...).error(...).notify(...)
	 * @param {function} callback A callback for the promise
	 * @return {object} Return the promise
	 */
	function promiseSuccess(callback){
		event.on('resolve', callback);
		return promise;
	}

	function promiseError(callback){
		event.on('reject', callback);
		return promise;
	}

	function promiseNotified(callback){
		event.on('notify', callback);
		return promise;
	}

	/**
	 * Deferred methods to trigger the promise
	 * @example def.resolve(args)
	 * @example def.reject(args)
	 * @example def.notify(args)
	 */
	function resolve(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('resolve', args);
	}

	function reject(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('reject', args);	
	}

	function notify(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('notify', args);		
	}

	/**
	 * Add the promise methods to the promise object
	 */
	promise.then = promiseThen;
	promise.success = promiseSuccess;
	promise.error = promiseError;
	promise.notify = promiseNotified;

	/**
	 * The promise object
	 * @public {object}
	 */
	self.promise = promise;

	/**
	 * Deferred public methods	
	 * @public {function}
	 */
	self.resolve = resolve;
	self.reject = reject;
	self.notify = notify;

	/**
	 * @return {object} return public methos
	 */
	return self;
}
514364
function() {
			canReflect.onValue( observation, updater,"notify");
			if (observation.hasOwnProperty("_value")) {// can-observation 4.1+
				compute.value = observation._value;
			} else {// can-observation < 4.1
				compute.value = observation.value;
			}
		}
358864
function(arg, typeSpec) {
				var result = new Deferred();
				var predictions = this._getPredictions(arg.text, typeSpec);
				result.resolve(this._createCompletion(arg.text, predictions));
				return result;
			}
606128
function speakIt({ action }) {
    const { toSpeak } = action.payload

    // Remember: unlike Promises, which share a similar construction,
    // the observable function is not run until the Observable recieves
    // a subscribe() call.
    return new Observable(observer => {
      try {
        const say = require("say")
        say.speak(toSpeak, null, null, () => {
          observer.complete()
        })

        // An Observable allows for cancellation by returning a
        // cancellation function
        return () => {
          say.stop()
        }
      } catch (error) {
        log("-- speech synthesis not available --")
        observer.error()
      }
    })
  }
557159
function autowire({type: ModelType}) {
  return function (target) {
    const {key} = target
    const getter = function () {
      let tempo = this.tempo || (this.props && this.props.tempo)
      if(tempo){
        return tempo.diObjects[ModelType.namespace];
      } else {
        throw new Error('use autowire out of Controller of Model')
      }
    }
    getter.__ModelType = ModelType;

    target.key = '_'+key
    return {
      kind: 'method',
      key,
      placement: 'prototype',
      descriptor: {
        get:getter,
        configurable: true,
        enumerable: true,
      }
    }
  }
}
772084
function eval(req, res, source, args) {
  this.spawn();
  this.reply(req, res, this._limit);
  // need to coerce buffers for the moment
  args = args.map(function(a) {
    if(a instanceof Buffer) return a.toString();
    return a;
  })
  this.ps.send({event: 'eval', source: source, args: args});
}
1296229
function(action, data) {

    if(isUndefined(data)) {
      data = {};
    } else if(!isObject(data) && !isFunction) {
      throw new Error('Data passed to an advisor action must be in instance of Object.');
    }

    var executeAction;
    if(isFunction(data)) {
      executeAction = compose(this._askAdvisor.actions[action], data)
    } else {
      executeAction = partial(this._askAdvisor.actions[action], data);
    }

    this.then(function(advisorEvent, deferred, consequenceActions, streamEvent) {
      data.triggeringEvents = {
        advisor: advisorEvent,
        stream: streamEvent
      };
      if(isFunction(data)) {
        executeAction(advisorEvent, streamEvent);
      } else {
        if(this._waitTime) {
          setTimeout(function(){
            executeAction();
            deferred.resolve();
          }, this._waitTime);
          return;
        } else {
          executeAction();
        }
      }
      deferred.resolve();
    });

    // terminate chain
    return this;
  }
223159
function modelItemMediator(item, index) {
    const { Model } = this;

    // if an item is already instance of Model
    if (item instanceof Model) {
        return item;
    }

    let itemData;

    if (item && typeof item.toJSON === 'function') {
        // if item is not falsy and if it has toJSON method
        // then retrieve instance data by this method
        itemData = item.toJSON(false);
    } else {
        // if not then use an item as its data
        itemData = item;
    }

    return new Model(itemData, this, index);
}
16865
function(view, data, helpers, callback) {
                    return can.view.renderAs("string", view, data, helpers, callback);
                }
621294
function(modelObj, type, success, error, method) {
                var args;

                // If `modelObj` is an Array, it it means we are coming from
                // the queued request, and we're passing already-serialized data.
                if (can.isArray(modelObj)) {
                    // In that case, modelObj's signature will be `[modelObj, serializedData]`, so we need to unpack it.
                    args = modelObj[1];
                    modelObj = modelObj[0];
                } else {
                    // If we aren't supplied with serialized data, we'll make our own.
                    args = modelObj.serialize();
                }
                args = [args];

                var deferred,
                    model = modelObj.constructor,
                    jqXHR;

                // When calling `update` and `destroy`, the current ID needs to be the first parameter in the AJAX call.
                if (type === 'update' || type === 'destroy') {
                    args.unshift(getId(modelObj));
                }
                jqXHR = model[type].apply(model, args);

                // Make sure that can.Model can react to the request before anything else does.
                deferred = pipe(jqXHR, modelObj, function(data) {
                    // `method` is here because `"destroyed" !== "destroy" + "d"`.
                    // TODO: Do something smarter/more consistent here?
                    modelObj[method || type + "d"](data, jqXHR);
                    return modelObj;
                });

                // Hook up `abort`
                if (jqXHR.abort) {
                    deferred.abort = function() {
                        jqXHR.abort();
                    };
                }

                deferred.then(success, error);
                return deferred;
            }
1336226
def _connectRelay(self, process, protocolFactory):
        
        try:
            wf = _WrappingFactory(protocolFactory)
            connector = RelayConnector(process, wf, self.timeout,
                                       self.inductor.reactor)
            connector.connect()
        except:
            return defer.fail()
        # Return a deferred that is called back when the protocol is connected.
        return wf._onConnection
873196
function ngOutletDirective($animate, $injector, $q, $router, $componentMapper, $controller) {
  var rootRouter = $router;

  return {
    restrict: 'AE',
    transclude: 'element',
    terminal: true,
    priority: 400,
    require: ['?^^ngOutlet', 'ngOutlet'],
    link: outletLink,
    controller: function() {},
    controllerAs: '$$ngOutlet'
  };

  function invoke(method, context, instruction) {
    return $injector.invoke(method, context, instruction.locals);
  }

  function outletLink(scope, $element, attrs, ctrls, $transclude) {
    var outletName = attrs.ngOutlet || 'default',
        parentCtrl = ctrls[0],
        myCtrl = ctrls[1],
        router = (parentCtrl && parentCtrl.$$router) || rootRouter;

    var currentScope,
        newScope,
        currentController,
        currentElement,
        previousLeaveAnimation,
        previousInstruction;

    function cleanupLastView() {
      if (previousLeaveAnimation) {
        $animate.cancel(previousLeaveAnimation);
        previousLeaveAnimation = null;
      }

      if (currentScope) {
        currentScope.$destroy();
        currentScope = null;
      }
      if (currentElement) {
        previousLeaveAnimation = $animate.leave(currentElement);
        previousLeaveAnimation.then(function() {
          previousLeaveAnimation = null;
        });
        currentElement = null;
      }
    }

    router.registerOutlet({
      canDeactivate: function(instruction) {
        if (currentController && currentController.canDeactivate) {
          return invoke(currentController.canDeactivate, currentController, instruction);
        }
        return true;
      },
      activate: function(instruction) {
        var nextInstruction = serializeInstruction(instruction);
        if (nextInstruction === previousInstruction) {
          return;
        }

        var controllerConstructor = instruction.controllerConstructor;

        if (!instruction.locals.$scope) {
          instruction.locals.$scope = scope.$new();
        }
        newScope = instruction.locals.$scope;

        if (controllerConstructor === NOOP_CONTROLLER) {
          console.warn && console.warn('Could not find controller for', $componentMapper.controllerName(instruction.component));
        }
        var ctrl = $controller(controllerConstructor, instruction.locals);
        instruction.controllerAs = $componentMapper.controllerAs(instruction.component);
        instruction.controller = ctrl;

        myCtrl.$$router = instruction.router;
        myCtrl.$$template = instruction.template;
        var controllerAs = instruction.controllerAs || instruction.component;
        var clone = $transclude(newScope, function(clone) {
          $animate.enter(clone, null, currentElement || $element);
          cleanupLastView();
        });

        var newController = instruction.controller;
        newScope[controllerAs] = newController;

        var result;
        if (currentController && currentController.deactivate) {
          result = $q.when(invoke(currentController.deactivate, currentController, instruction));
        }

        currentController = newController;

        currentElement = clone;
        currentScope = newScope;

        previousInstruction = nextInstruction;

        // finally, run the hook
        if (newController.activate) {
          var activationResult = $q.when(invoke(newController.activate, newController, instruction));
          if (result) {
            return result.then(activationResult);
          } else {
            return activationResult;
          }
        }
        return result;
      }
    }, outletName);
  }

  // TODO: how best to serialize?
  function serializeInstruction(instruction) {
    return JSON.stringify({
      path: instruction.path,
      component: instruction.component,
      params: Object.keys(instruction.params).reduce(function (acc, key) {
        return (key !== 'childRoute' && (acc[key] = instruction.params[key])), acc;
      }, {})
    });
  }
}
994995
function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) {
        var modelEvents = getModelAndCollectionEvents(modelType, _this);
        var ev = args[0];
        var cb = args[1];
        var ctx = args[2];
        modelEvents[ev] = {
            type: type,
            ev: ev,
            cb: cb,
            ctx: ctx
        };

        function _on(modelOrCollection) {
            _this[type === 'on' ? 'listenTo' : 'listenToOnce'](modelOrCollection, ev, cb, ctx);
        }
        if (modelEvents.__bound) {
            if (_modelOrCollection) {
                _on(_modelOrCollection);
            } else {
                getModelOrCollections(modelType, _this, _on);
            }
        }
    }