创建 saga
@param {Array} models model 列表
495513
function createSagas() {
  var models = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  // 已经定义的 namespace
  var existentNamespace = {}; // 所有的 saga watchers

  var sagaWatchers = [];
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    var _loop = function _loop() {
      var model = _step.value;
      var namespace = model.namespace,
          _model$effects = model.effects,
          effects = _model$effects === void 0 ? {} : _model$effects; // 检测 namespace 是否有定义

      if (!namespace) {
        throw new Error('namespace 未定义或为空字符串.');
      } // 检测 namespace 是否重复定义(必须全局唯一)


      if (existentNamespace[namespace]) {
        throw new Error("namespace: ".concat(namespace, " \u91CD\u590D\u5B9A\u4E49."));
      } // 检查 effects 类型


      if (!(0, _utils.isType)(effects, 'Object')) {
        throw new Error("effects \u6570\u636E\u7C7B\u578B\u5FC5\u987B\u4E3A\u5BF9\u8C61.");
      } // 设置该 namespace 已存在


      existentNamespace[namespace] = true; // 获取定义的 effect

      Object.keys(effects).forEach(function (effectName) {
        var effect = effects[effectName];
        var effectFunc =
        /*#__PURE__*/
        regeneratorRuntime.mark(function effectFunc() {
          return regeneratorRuntime.wrap(function effectFunc$(_context8) {
            while (1) {
              switch (_context8.prev = _context8.next) {
                case 0:
                case "end":
                  return _context8.stop();
              }
            }
          }, effectFunc, this);
        }); // effect 函数

        var type = ''; // effect watch 类型

        var throttleTime = 0; // type 为 throttle 的 time 参数

        if ((0, _utils.isType)(effect, 'GeneratorFunction')) {
          effectFunc = effect;
          type = 'takeEvery';
        } else if ((0, _utils.isType)(effect, 'Array') && (0, _utils.isType)(effect[0], 'GeneratorFunction') && (0, _utils.isType)(effect[1], 'Object')) {
          effectFunc = effect[0];
          type = effect[1].type || 'takeEvery';
          throttleTime = effect[1].throttleTime || 0;
        } else {
          throw new Error('effect 的格式为 *(action, effects) => void 或 [*(action, effects) => void, { type }]');
        }

        sagaWatchers.push( // 生成 saga watcher
        effectWatcherCreator(namespace, effectName, effectFunc, {
          type: type,
          throttleTime: throttleTime
        }));
      });
    };

    for (var _iterator = models[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      _loop();
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return != null) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return (
    /*#__PURE__*/
    regeneratorRuntime.mark(function rootSaga() {
      return regeneratorRuntime.wrap(function rootSaga$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              _context7.next = 2;
              return _effects.default.all(sagaWatchers.map(function (saga) {
                return _effects.default.spawn(
                /*#__PURE__*/
                regeneratorRuntime.mark(function _callee6() {
                  return regeneratorRuntime.wrap(function _callee6$(_context6) {
                    while (1) {
                      switch (_context6.prev = _context6.next) {
                        case 0:
                          if (!true) {
                            _context6.next = 11;
                            break;
                          }

                          _context6.prev = 1;
                          _context6.next = 4;
                          return _effects.default.call(saga);

                        case 4:
                          _context6.next = 9;
                          break;

                        case 6:
                          _context6.prev = 6;
                          _context6.t0 = _context6["catch"](1);
                          console.error(_context6.t0);

                        case 9:
                          _context6.next = 0;
                          break;

                        case 11:
                        case "end":
                          return _context6.stop();
                      }
                    }
                  }, _callee6, this, [[1, 6]]);
                }));
              }));

            case 2:
            case "end":
              return _context7.stop();
          }
        }
      }, rootSaga, this);
    })
  );
}
873396
private function addModelToArraySimpleMode($models, $model)
    {
        $apply_to_models = array();
        
        if (count($models) > 0) {
            foreach ($models as $item) {
                $object = $model->find($item);
                if ($object != null) {
                    $apply_to_models[] = $object;
                }
            }
        }
        
        return $apply_to_models;
    }
1176716
function(models, options) {
      var removed = [];
      for (var i = 0; i < models.length; i++) {
        var model = this.get(models[i]);
        if (!model) continue;

        var index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;

        // Remove references before triggering 'remove' event to prevent an
        // infinite loop. #3693
        delete this._byId[model.cid];
        var id = this.modelId(model.attributes);
        if (id != null) delete this._byId[id];

        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }

        removed.push(model);
        this._removeReference(model, options);
      }
      return removed;
    }
382064
private function addModelToArray($models, $model)
    {
        $apply_to_models = array();
        
        if (count($models) > 0) {
            foreach ($models as $item_json) {
                $item = json_decode($item_json);
                $object = $model->find($item->id);
                if ($object != null) {
                    for ($count = 1; $count <= $item->quantity; $count++) {
                        $apply_to_models[] = $object;
                    }
                }
            }
        }
        
        return $apply_to_models;
    }
435400
function OrganizationMethods(models) {
      this.models = models;
      this.create = bind(this.create, this);
      this.patch = bind(this.patch, this);
      this.getByNameOrId = bind(this.getByNameOrId, this);
      this.getByName = bind(this.getByName, this);
      this.destroy = bind(this.destroy, this);
      this.get = bind(this.get, this);
      this.all = bind(this.all, this);
      Hoek.assert(this.models, i18n.assertModelsRequired);
      Hoek.assert(this.models.Organization, i18n.assertOrganizationInModelsRequired);
    }
469622
function (model) {
        var newModels = slice.call(this.models);
        var modelIndex = newModels.indexOf(model);
        if (modelIndex > -1) {
            newModels.splice(modelIndex, 1);
            this.models = newModels;
            this._removeIndex(this._indexes, model);
            return true;
        }
        return false;
    }
386988
function(){
      var result = [];

      ko.utils.arrayForEach(this.models(), function(model){
        result.push(model.toJSON());
      });

      return result;
    }
635381
function(index){
        var len = arguments.length, i = 0, results;

        if (len > 1) {
            results = [];

            while(len--){
                results.push(this.get(arguments[i++]));
            }

            return results;
        }

        return this._models[index];
    }
57808
function(model) {
    const maxLen = model.get("seq").length;
    const selection = [];
    const sels = this.g.selcol.getSelForRow(model.get("id"));
    const rows = find(sels, function(el) { return el.get("type") === "row"; });
    if ((typeof rows !== "undefined" && rows !== null)) {
      // full match
      const end = maxLen - 1;
      for (let n = 0; n <= end; n++) {
        selection.push(n);
      }
    } else if (sels.length > 0) {
      for (let i = 0, sel; i < sels.length; i++) {
        sel = sels[i];
        const start = sel.get("xStart");
        const end = sel.get("xEnd");
        for (let n = start; n <= end; n++) {
          selection.push(n);
        }
      }
    }

    return selection;
  }
458261
function produce(model) {
	//console.log("model is " + JSON.stringify(model, null, 4));
	let thing = {
		properties: {},
		actions: {},
		events: {},
		clients: {},	// stream ID -> stream
		sockets: [],	// list of web sockets
		model: model
	};
	
	let name,
		properties = model.properties,
		actions = model.actions,
		events = model.events;
		
	thing.id = model.id;
	thing.name = model.name;
	model.platform = "https://github.com/draggett/arena-webhub";
	
	thing.emitEvent = function (name, json) {
		if (thing.events.hasOwnProperty(name)) {
			// note that event: is no longer supported for SSE
			// so use an object wrapper to convey event name
			if (json === undefined)
				json = {"event":name};
			else
				json = {"event":name,"data":json};
				
			let message = JSON.stringify(json);
			message = "data: "+ message.replace(/\n/g, '\ndata: ') + "\n\n";

			// clients for server-sent event stream
			let clients = thing.clients;
		
			for (let id in clients) {
				if (clients.hasOwnProperty(id)) {
					let client = clients[id];
					client.response.write(message);
				}
			}
			
			let sockets = thing.sockets;
			
			for (let i = 0; i < sockets.length; ++i) {
				ws_send(sockets[i], JSON.stringify(json));
			}
		} else {
			console.log('unknown event: ' + name + ' on ' + thing.name);
		}
	};
	
	thing.emitValue = function (name, value) {
		// note that event: is no longer supported for SSE
		// so use an object wrapper to convey event name
		if (thing.properties.hasOwnProperty(name)) {
			// be safe as stringify throws exception on undefined
			if (value === undefined)
				value = {"property":name};
			else
				value = {"property":name,"data":value};
				
			let message = JSON.stringify(value);
			message = "data: "+ message.replace(/\n/g, '\ndata: ') + "\n\n";
			let clients = thing.clients;

			if (clients !== undefined) {
				for (var id in clients) {
					if (clients.hasOwnProperty(id)) {
						let client = clients[id];
						client.response.write(message);
					}
				}
			}

			let sockets = thing.sockets;
			if (sockets !== undefined ) {
				//console.log('there are ' + sockets.length + ' socket clients');
				for (let i = 0; i < sockets.length; ++i) {
					ws_send(sockets[i], JSON.stringify(value));
				}
				
				//console.log('sent data to sockets');
			}
		} else {
			console.log('unknown property: ' + name + ' on ' + thing.name);
		}
	};
	
	thing.emitState = function (properties) {
		// note that event: is no longer supported for SSE
		// so use an object wrapper to convey event name
		let obj = {};
		
		if (properties === undefined)
			properties = thing.properties;
			
		for (var name in properties) {
			if (properties.hasOwnProperty(name)) {
				let value =  properties[name].value;
				
				if (value !== undefined)
					obj[name] = value;
			}
		}
		
		let json = JSON.stringify({"state":obj});
		
		// for server-sent event stream
		message = "data: "+ message.replace(/\n/g, '\ndata: ') + "\n\n";
		let clients = thing.clients;

		for (var id in clients) {
			if (clients.hasOwnProperty(id)) {
				let client = clients[id];
				client.response.write(message);
			}
		}

		let sockets = thing.sockets;
		
		for (let i = 0; i < sockets.length; ++i) {
			ws_send(sockets[i], JSON.stringify(json));
		}
	};
	
	for (name in properties) {
		if (properties.hasOwnProperty(name)) {
			thing.properties[name] = new ThingProperty(thing, name, properties[name]);
		}
	}
	
	for (name in actions) {
		if (actions.hasOwnProperty(name)) {
			thing.actions[name] = new ThingAction(thing, name, actions[name]);
		}
	}
	
	for (name in events) {
		if (events.hasOwnProperty(name)) {
			thing.events[name] = new ThingEvent(thing, name, events[name]);
		}
	}
				
	thing.setActionHandler = function (name, handler) {
		if (thing.actions[name])
			thing.actions[name].handler = handler;
	};
	
	thing.setWriteHandler = function (name, handler) {
		if (thing.properties[name])
			thing.properties[name].handler = handler;
	};
	
	thing.receive = function (socket, message) {
		// handle incoming web socket message
		
		// be safe against zero length messages
		if (message.length === 0)
			return;
			
		let fail = (id, status, description) => {
			if (typeof id !== "string")
				id = "unknown";
				
			console.log('fail: ' + id + ' ' + status + ' ' + description);
			let json = {
				id: id,
				status: status
			};
			
			if (description !== undefined)
				json.description = description;
				
			ws_send(socket, JSON.stringify(json));
		};
		
		let succeed = (id, json) => {
			if (json) {
				json.id = id;
				json.status = 200;
			} else {
				console.log('succeed with no data to return');
				json = {
					id: id,
					status: 200
				};
			}

			ws_send(socket, JSON.stringify(json));
		};
		
		try {
			let json = JSON.parse(message);
			
			if (json.property) {
				let property = thing.properties[json.property];
				
				if (property !== undefined) {
					try {
						property.write(json.data);
						console.log("write succeeded");
						succeed(json.id);
					} catch (err) {
						console.log("couldn't write " + json.data + ' to ' + property.name);
						fail(json.id, 400, "bad request");
					}
				} else {
					console.log("message with undefined property");
					fail(json.id, 400, "bad request");
				}
			} else if (json.state !== undefined) {
				let obj = json.state;
				let properties = thing.properties;
				
				for (name in obj) {
					if (obj.hasOwnProperty(name) && properties.hasOwnProperty(name)) {
						try {
							properties[name].write(obj[name]);
						} catch (err) {
							console.log("couldn't write " + obj[name] + ' to ' + name);
							return fail(json.id, 400, "bad request");
						}
					}
				}
				succeed(json.id);
			} else if (json.action !== undefined) {
				let action = thing.actions[json.action];
				
				if (action !== undefined) {
					action.invoke(json.input)
						.then(output => {
							console.log('output is ' + JSON.stringify(output));
							if (output !== undefined)
								succeed(json.id, {'output':output});
							else
								succeed(json.id);
						}).catch(err => {
							fail(json.id, 500, "action failed");
						});
				} else {
					fail(json.id, 400, "bad request");
				}
			} else {
				fail(json.id, 400, "bad request");
			}
			
		} catch (err) {
			console.log('badly formed client message: ' + message);
			fail(socket, 444, "badly formed client message");
		}
	};
	
	// used to attach a new web socket
	thing.addSocket = function(socket) {
		thing.sockets.push(socket);
		//.log('addSocket: there are ' + thing.sockets.length + ' sockets');
		
		socket.on('close', () => {
			// drop socket from thing.sockets
			let sockets = thing.sockets;
			const index = sockets.indexOf(socket);

			if (index !== -1) {
				sockets.splice(index, 1);
			};
		});
		
		// send state of all properties to sync new client
		let state = {};
		let properties = thing.properties;
		
		for (let name in properties) {
			if (properties.hasOwnProperty(name)) {
				state[name] = properties[name].value;
			}
		}
		
		ws_send(socket, JSON.stringify({state: state}));
	};
	
	// why isn't this capability on the action itself?
	thing.addActionHandler = (name, handler) => {
		if (thing.actions.hasOwnProperty(name))
			thing.actions[name].handler = handler;
	};
	
	// sent text string to all clients via web sockets
	
	thing.send = function (data) {
		let sockets = thing.sockets;
		
		for (let i = 0; i < sockets.length; ++i) {
			ws_send(sockets[i], data);
		}
	};
	
	thing.expose = function () {
		let publish = (resolve, reject) => {
			things[thing.model.name] = thing;
			resolve(model);
		}
		
		return new Promise(function (resolve, reject) {
			publish(resolve, reject);
		});
	};
	
	//things[model.name] = thing;
	
	return thing;
}
1326856
function(models) {
        for (var i = 0, j = models.length; i < j; i++) {
            var model = models[i];

            // обнуляем попытки после завершения запроса
            model.retries = 0;
            // удаляем модель из списка запрашиваемых
            delete this._keys[model.key];
        }
    }
528630
function( model ) {
			var modelColl = model.collection;
			var coll = this.getCollection( model );
			coll && coll._add( model );
			model.collection = modelColl;
		}
950972
function () {
        var list = slice.call(this.indexes || []);
        var i = 0;
        list.push(this.mainIndex);
        list.push('cid');
        var l = list.length;
        this.models = [];
        this._indexes = {};
        for (; i < l; i++) {
            this._indexes[list[i]] = {};
        }
    }
4660
function expandModel (model, view) {
  const modelPath = new BunsenModelPath(model)
  const modelExpansions = aggregateModels(view, modelPath)
  let newModel = model
  _.forEach(modelExpansions, (propertyModel, path) => {
    newModel = addBunsenModelProperty(newModel, propertyModel, path)
  })
  return newModel
}
98866
function init (model) {
    if (model.__ttl) return;

    var distinct_ = model.distinct;
    model.distinct = function distinct (field, cond, cb) {
      applyTTL(cond);
      return distinct_.call(model, field, cond, cb);
    }

    'findOne find count'.split(' ').forEach(function (method) {
      var fn = model[method];

      model[method] = function (cond, fields, opts, cb) {
        if (!cond) {
          cond = {};
        } else if ('function' == typeof cond) {
          cb = cond;
          cond = {};
        }

        applyTTL(cond);
        return fn.call(model, cond, fields, opts, cb);
      }
    });

    'where $where'.split(' ').forEach(function (method) {
      var fn = model[method];
      model[method] = function () {
        var query = fn.apply(this, arguments)
          , cond = {};
        applyTTL(cond);
        return query.find(cond);
      }
    });

    if (reap) {
      model.startTTLReaper();
    }
  }
433446
public function linkModels(Models $models, Models $foreign, Closure $yield)
    {
        foreach ($models as $model) {

            $linked = [];

            foreach ($foreign as $foreignModel) {
                if ($this->areLinked($model, $foreignModel)) {
                    $linked []= $foreignModel;
                }
            }

            $link = $this->newLinkFrom($model, $linked);

            $yield($link);
        }
    }
1331835
function(models, options) {
    if(!models) return false;
    this.remove(models, options);
    var singular = !_.isArray(models);
    models = singular ? [models] : _.clone(models);
    return this._callAdapter('removeFromIndex', options, models);
  }