/* ************************************************** *
******************** Constructor & Inherit
************************************************** 
Initalizes a new Mongoose Adapter and configures the
parent Database Adapter class.
342365
function MongooseAdapter() {
    this.idAttributeName = cramit.config.database.idAttributeName || '_id';

    if( ! cramit.config.database.instance) {
      //console.log("MongooseAdapter():  Require Mongoose.");
      this.mongoose = require('mongoose');
    } else {
      //console.log("MongooseAdapter():  Using Mongoose instance.");
      this.mongoose = cramit.config.database.instance;
    }
    
    DatabaseAdapter.call(this, cramit.config, cramit.log);
  }
956665
function init(options) {

    var fs = require('fs');
    var path = require('path');
    var rootdir = path.dirname(require.main);
    var options = options || {
        config: require(path.join(rootdir, 'config.json')),
        root: rootdir,
        callback: function (noop) {}
    };
    var def = {};
    function ModulePaths (moduledir) {
        this.moduledir = moduledir;
    }

    ModulePaths.prototype.then = function (accept, reject) {
      var moduledir = this.moduledir;
      fs.readdir(moduledir, function (err, files) {
        if (err) reject(err);
        files.forEach(function (file) {
            var name = path.basename(file, '.js');
            def[name] = path.join(moduledir, name);
        });
        accept();
      });
    };
    var pubpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'public', 'js'));
    var prvpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'private', 'js'));

    Promise.all([pubpath, prvpath])
        .then(function () {
            var requirejs = require('requirejs');
            requirejs.config({
                baseUrl: path.join(rootdir),
                paths: def
            });

            requirejs(['loader_factory'], function (LoaderFactory) {
                var fs = require('fs');
                var config = options.config;
                config.paths.push(path.dirname(pubpath.moduledir));
                var loader = 'loader_express';
                var db = 'db_mongo';
                if (config.loader) loader = config.loader;
                if (config.db) db = config.db;

                new LoaderFactory().create(loader, db, function (loader) {
                    loader.init(config, options.callback);
                });
            });
        })
    .catch(function (err) {
        console.error('err:', err);
    });
}
777957
final void init(WSJdbcObject parent) {
        if (parent != null) {
            parentWrapper = parent;
            dsConfig = parent.dsConfig; 
            freeResourcesOnClose = parent.freeResourcesOnClose;
        }

        if (freeResourcesOnClose) // then initialize data structures to track them
        {
            arrays = new LinkedList<Array>();
            blobs = new LinkedList<Blob>();
            clobs = new LinkedList<Clob>();
            resources = new LinkedList<Closeable>();
            xmls = new LinkedList<SQLXML>();
        }
    }
844866
function inheritParent(constructor, parent) {
        var x,
            binds = parent[$class].binds,
            key,
            value;

        // Inherit binds
        for (x = binds.length - 1; x >= 0; x -= 1) {
            if (binds[x].substr(0, 2) !== '__') {
                constructor[$class].binds.push(binds[x]);
            }
        }

        // Grab properties
        append(constructor[$class].properties, parent[$class].properties);

        // Inherit static methods and properties
        append(constructor[$class].staticMethods, parent[$class].staticMethods);

        for (x =  parent[$class].staticMethods.length - 1; x >= 0; x -= 1) {
            if (parent[$class].staticMethods[x].substr(0, 2) !== '__') {
                constructor[parent[$class].staticMethods[x]] = parent[parent[$class].staticMethods[x]];
            }
        }

        for (key in parent[$class].staticProperties) {
            value = parent[$class].staticProperties[key];

            if (key.substr(0, 2) !== '__') {
                constructor[$class].staticProperties[key] = value;
                constructor[key] = value;
            }
        }

        obfuscateProperty(constructor, '$parent', parent);

        // Inherit implemented interfaces
        constructor[$class].interfaces = [].concat(parent[$class].interfaces);
    }
1229843
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {
	            db: null
	        };

	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
	            }
	        }

	        var dbInfoPromise = new Promise(function (resolve, reject) {
	            // Open the database; the openDatabase API will automatically
	            // create it for us if it doesn't exist.
	            try {
	                dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
	            } catch (e) {
	                return self.setDriver(self.LOCALSTORAGE).then(function () {
	                    return self._initStorage(options);
	                }).then(resolve)['catch'](reject);
	            }

	            // Create our key/value table if it doesn't exist.
	            dbInfo.db.transaction(function (t) {
	                t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
	                    self._dbInfo = dbInfo;
	                    resolve();
	                }, function (t, error) {
	                    reject(error);
	                });
	            });
	        });

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return dbInfoPromise;
	        });
	    }
1347989
function Behalter(parent, options) {

  // normalize arguments for the case of `new Behalter(options)`
  if (arguments.length === 1 && !(parent instanceof Behalter) && _.isPlainObject(parent)) {
    options = parent;
    parent = void 0;
  }

  // for hierarchical search, validate type of parent
  if (parent && !(parent instanceof Behalter)) {
    throw new TypeError('parent must be an instance of Behalter');
  }

  // construct this with super constructor
  EventEmitter2.call(this, options);

  // configure default properties
  this.__parent = parent;
  this.__values = {};
  this.__factories = {};

  // configure options: to INHERIT options, configure only for root
  if (!parent) {
    this.__options = {
      useGetter: true,
      useSetter: false
    };
  } else {
    this.__options = {};
  }
}
383692
function (schema) {
		if (!schema.key || schema.key === 'base' || !Array.isArray(schema.fields)) {
			return null;
			// throw exception?
		}
		// store it for later reference
		Schemas[schema.key] = schema;
		// add this schema to the NPC object so we can use it as a constructor
		// this could overwrite is that ok?
		const Base = NPC[schema.key] = function () {
			// in case we add something to NPC constructor that we need to call?
			// NPC.Base.call(this);
		};
		Base.prototype = new NPC.Base();
		Base.prototype.constructor = Base;
		Base.prototype.schema = schema.key;
		Base.prototype.fields = [];
		Base.prototype.helpers = {};
		
		// initialize schema properties...
		schema.fields.forEach((f) => {
			let default_ = null;
			switch (f.type) {
				case 'string':
				case 'text':
					default_ = '';
					break;
				case 'array':
					default_ = [];
					break;
				case 'number':
				case 'modifier':
					default_ = 0;
					break;
				case undefined:
					// ?
					break;
			}
			Base.prototype.fields[f.key] = default_;
		});
		
		if (!schema.helpers || typeof schema.helpers !== 'object') { return; }
		const helpers = Object.keys(schema.helpers);
		helpers.forEach((h) => {
			// if (typeof schema.helpers[h] === 'function') {
			//	Base.prototype.helpers[h] = schema.helpers[h];
			// }
			// create a function from the array
			Base.prototype.helpers[h] = new Function(...schema.helpers[h]);
		});
	}
1011341
SchemaProperty createDatabaseSchema(final App app, final AbstractSchemaNode schemaNode) throws FrameworkException {

		final PropertyMap getOrCreateProperties = new PropertyMap();
		final PropertyMap updateProperties      = new PropertyMap();

		getOrCreateProperties.put(SchemaProperty.name, getName());
		getOrCreateProperties.put(SchemaProperty.schemaNode, schemaNode);

		SchemaProperty property = app.nodeQuery(SchemaProperty.class).and(getOrCreateProperties).getFirst();
		if (property == null) {

			getOrCreateProperties.put(SchemaProperty.compound, isCompoundUnique());
			getOrCreateProperties.put(SchemaProperty.unique, isUnique());
			getOrCreateProperties.put(SchemaProperty.indexed, isIndexed());
			getOrCreateProperties.put(SchemaProperty.notNull, isRequired());
			getOrCreateProperties.put(SchemaProperty.readOnly, isReadOnly());
			getOrCreateProperties.put(SchemaProperty.format, getFormat());
			getOrCreateProperties.put(SchemaProperty.hint, getHint());
			getOrCreateProperties.put(SchemaProperty.category, getCategory());
			getOrCreateProperties.put(SchemaProperty.validators, validators.toArray(new String[0]));
			getOrCreateProperties.put(SchemaProperty.transformers, transformers.toArray(new String[0]));
			getOrCreateProperties.put(SchemaProperty.defaultValue, defaultValue);

			property = app.create(SchemaProperty.class, getOrCreateProperties);
		}

		if (parent != null) {

			final JsonSchema root = parent.getSchema();
			if (root != null) {

				if (SchemaService.DynamicSchemaRootURI.equals(root.getId())) {

					updateProperties.put(SchemaProperty.isPartOfBuiltInSchema, true);
				}
			}
		}

		// update properties
		property.setProperties(SecurityContext.getSuperUserInstance(), updateProperties);

		// return modified property
		return property;
	}
1309330
public function initMapper() {
		switch ($this->dbsType) {
			case 'jig':
				$this->mapper = new Jig\Mapper($this->db, $this->table);
				break;
			case 'sql':
				// ensure to load full table schema, so we can work with it at runtime
				$this->mapper = new SQL\Mapper($this->db, $this->table, null,
					($this->fluid)?0:$this->ttl);
				$this->applyWhitelist();
				break;
			case 'mongo':
				$this->mapper = new Mongo\Mapper($this->db, $this->table);
				break;
			default:
				trigger_error(sprintf(self::E_UNKNOWN_DB_ENGINE,$this->dbsType),E_USER_ERROR);
		}
		$this->queryParser = CortexQueryParser::instance();
		$this->reset();
		$this->clearFilter();
		$f3 = \Base::instance();
		$this->smartLoading = $f3->exists('CORTEX.smartLoading') ?
			$f3->get('CORTEX.smartLoading') : TRUE;
		$this->standardiseID = $f3->exists('CORTEX.standardiseID') ?
			$f3->get('CORTEX.standardiseID') : TRUE;
		if(!empty($this->fieldConf))
			foreach($this->fieldConf as &$conf) {
				$conf=static::resolveRelationConf($conf,$this->primary);
				unset($conf);
			}
	}
379726
function initAdapters(container) {

        var calls = [];

        if (container === 'webserver') {
            _.each(adapters, function (adapter) {
                if (adapter.webInit) {
                    calls.push(adapter.webInit);
                }
            });
        }
        else {
            _.each(adapters, function (adapter) {
                if (adapter.init) {
                    calls.push(adapter.init);
                }
            });
        }

        return chainPromises(calls, config)
            .then(function (returnConfig) {
                if (returnConfig) {
                    return returnConfig;
                }
                else {
                    throw new Error('An adapter in the chain is not returning the config.');
                }
            });
    }
613050
function makeSimpleStore(baseConnection) {
    baseConnection.constructor = makeSimpleStore;
    var behavior = Object.create(baseConnection);

    // this stores data like:
    // queries: {[queryKey]: {queryKey, query, recordIds}}
    // records
    return canReflect.assignMap(behavior, {
        getRecordFromParams: function(record) {
        	var id = canReflect.getIdentity(record, this.queryLogic.schema);
        	return this.getRecord(id);
        },

        log: function(){
			this._log = true;
		},

        getSets: function(){
			return this.getQueries();
		},
		getQueries: function(){
			return Promise.resolve(this.getQueriesSync());
		},
		getQueriesSync: function(){
			return this.getQueryDataSync().map(function(queryData){
				return queryData.query;
			});
		},

        getListData: function(query){
        	query = query || {};
        	var listData = this.getListDataSync(query);
        	if(listData) {
        		return Promise.resolve(listData);
        	}
        	return Promise.reject({
        		title: "no data",
        		status: "404",
        		detail: "No data available for this query.\nAvailable queries: "+
        			JSON.stringify(this.getQueriesSync())
        	});
        },
		getPaginatedListDataSync: function(superSetQueryData) {
			var records = this.getAllRecords();
			var queryWithoutPagination = this.queryLogic.removePagination(superSetQueryData.query);
			var matchingSuperRecordsNoPagination = this.queryLogic.filterMembersAndGetCount(queryWithoutPagination, {}, records);
			var startIndex = indexOf(matchingSuperRecordsNoPagination.data, superSetQueryData.startIdentity, this.queryLogic);
			var matchingSuperRecords = matchingSuperRecordsNoPagination.data.slice(startIndex, startIndex+ this.queryLogic.count(superSetQueryData.query));
			return {
				count: matchingSuperRecordsNoPagination.data.length,
				data: matchingSuperRecords
			};
		},
        getListDataSync: function(query){
			var queryData = this.getQueryDataSync(),
				superSetQueryData,
				isPaginated = this.queryLogic.isPaginated(query);

			for(var i = 0; i < queryData.length; i++) {
        		var checkSet = queryData[i].query;
        		if( this.queryLogic.isSubset(query, checkSet) ) {
					superSetQueryData = queryData[i];
        		}
        	}
			var records = this.getAllRecords();

			if(isPaginated && this.queryLogic.isPaginated(superSetQueryData.query) ) {
				var result = this.getPaginatedListDataSync(superSetQueryData);
				return this.queryLogic.filterMembersAndGetCount(query, superSetQueryData.query, result.data);
			}

            var matching = this.queryLogic.filterMembersAndGetCount(query, {}, records);
            if(matching && matching.count) {
                return matching;
            }
            // now check if we have a query  for it
        	if(superSetQueryData) {
				return {count: 0, data: []};
			}
        },

        updateListData: function(data, query){
			var queryData = this.getQueryDataSync();
        	query = query || {};
            var clonedData = canReflect.serialize(data);
        	var records = getItems(clonedData);
			// Update or create all records
			this.updateRecordsSync(records);
			var isPaginated = this.queryLogic.isPaginated(query);
			var identity = records.length ? canReflect.getIdentity(records[0],  this.queryLogic.schema) : undefined;
			if(isPaginated) {
				// we are going to merge with some paginated set
				for(var i = 0; i < queryData.length; i++) {
	        		var checkSet = queryData[i].query;
					var union = this.queryLogic.union(checkSet, query);
					if( this.queryLogic.isDefinedAndHasMembers(union)  ) {
						var siblingRecords = this.getPaginatedListDataSync(queryData[i]);
						var res = this.queryLogic.unionMembers(checkSet, query, siblingRecords.data, records );
						identity = canReflect.getIdentity(res[0],  this.queryLogic.schema);
						queryData[i] = {
							query: union,
							startIdentity: identity
						};
						this.updateQueryDataSync(queryData);
						return Promise.resolve();
					}
	        	}

				queryData.push({
					query: query,
					startIdentity: identity
				});
				this.updateQueryDataSync(queryData);
				return Promise.resolve();
			}

            // we need to remove everything that would have matched this query before, but that's not in data
            // but what if it's in another set -> we remove it
            var allRecords = this.getAllRecords();
            var curretMatching = this.queryLogic.filterMembers(query, allRecords);
            if(curretMatching.length) {
                var toBeDeleted = new Map();
                curretMatching.forEach(function(record){
                    toBeDeleted.set( canReflect.getIdentity(record, this.queryLogic.schema), record );
                }, this);

                // remove what's in records
                records.forEach(function(record){
                    toBeDeleted.delete( canReflect.getIdentity(record, this.queryLogic.schema) );
                }, this);

                this.destroyRecords( canReflect.toArray(toBeDeleted) );
            }

            // the queries that are not consumed by query
            var allQueries = this.getQueryDataSync();
            var notSubsets = allQueries.filter(function(existingQueryData){
                    return !this.queryLogic.isSubset(existingQueryData.query, query);
                }, this),
                superSets = notSubsets.filter(function(existingQueryData){
                    return this.queryLogic.isSubset(query, existingQueryData.query);
                }, this);

			// would need to note the first record ... so we can do a query w/o pagination
			//

            // if there are sets that are parents of query
            if(superSets.length) {
                this.updateQueryDataSync(notSubsets);
            } else {
                this.updateQueryDataSync(notSubsets.concat([{
					query: query,
					startIdentity:identity
				}]));
            }

        	// setData.push({query: query, items: data});
        	return Promise.resolve();
        },

        getData: function(params){
        	var id = canReflect.getIdentity(params, canReflect.getSchema( this.queryLogic ) );
        	var res = this.getRecord(id);
        	if(res){
        		return Promise.resolve( res );
        	} else {
        		return Promise.reject({
        			title: "no data",
        			status: "404",
        			detail: "No record with matching identity ("+id+")."
        		});
        	}
        },
        createData: function(record){
			this.updateRecordsSync([record]);

			return Promise.resolve(canReflect.assignMap({}, this.getRecordFromParams(record) ));
		},

		updateData: function(record){

			if(this.errorOnMissingRecord && !this.getRecordFromParams(record)) {
				var id = canReflect.getIdentity(record, this.queryLogic.schema);
				return Promise.reject({
					title: "no data",
					status: "404",
					detail: "No record with matching identity ("+id+")."
				});
			}

			this.updateRecordsSync([record]);

			return Promise.resolve(canReflect.assignMap({},this.getRecordFromParams(record) ));
		},

		destroyData: function(record){
			var id = canReflect.getIdentity(record,  this.queryLogic.schema),
				savedRecord = this.getRecordFromParams(record);

			if(this.errorOnMissingRecord && !savedRecord) {

				return Promise.reject({
					title: "no data",
					status: "404",
					detail: "No record with matching identity ("+id+")."
				});
			}
            this.destroyRecords([record]);
			return Promise.resolve(canReflect.assignMap({},savedRecord || record));
		}
    });
}
264703
function MongoDB () {
  var self = this;

  self.klass = MongoDB;
  self.klass.super_.apply(self, arguments);
}
1083123
protected function _init() {
		parent::_init();

		foreach (static::_parents() as $parent) {
			$inherit = get_class_vars($parent);

			if (isset($inherit['_render'])) {
				$this->_render += $inherit['_render'];
			}
			if ($parent === __CLASS__) {
				break;
			}
		}

		$this->request = $this->request ?: $this->_config['request'];
		$this->response = $this->_instance('response', $this->_config['response']);

		if (!$this->request || $this->_render['type']) {
			return;
		}
		if ($this->_render['negotiate']) {
			$this->_render['type'] = $this->request->accepts();
			return;
		}
		$this->_render['type'] = $this->request->get('params:type') ?: 'html';
	}
185769
function inherit(inheritor, inherited) {
    inheritor.prototype = Object.create(inherited.prototype);
    inheritor.prototype.constructor = inheritor;
  }
28405
function (dbName, sql) {
  EventEmitter.apply(this, arguments); // apply parent constructor

  this._addSqlErrorListener(); // register error handler before any SQL is executed

  this._dbName = dbName;
  this._sql = sql ? sql : new SQL(); // TODO: remove new SQL() as sql should always be injected
  this._registerDisconnectListener();

  this._globals = new Globals(this._sql);
  this._roles = new Roles(this._sql, this);
  this._userRoles = new UserRoles(this._sql);
  this._users = new Users(this._sql, this._roles, this._userRoles, this);
  this._colRoles = new ColRoles(this._sql);
  this._policy = new Policy(this._sql, this._roles, this._colRoles, this._userRoles);
  this._cols = new Cols(this._sql, this._policy);
  // this._sessions = new Sessions(this._sql, this._users);

  this._initPartitions();

  this._archive = new Archive(this._partitions, this._globals);
  this._attrs = new Attrs(this._partitions, this._policy, this._users, this._roles, this);
  this._docs = new Docs(this._partitions, this._attrs, this._policy, this._cols);
  this._attrs._docs = this._docs;
  this._queueAttrRecs = new QueueAttrRecs(this._sql);
  this._queue = new Queue(this._sql);
  this._process = new Process(this._sql, this._docs, this._users, this._queueAttrRecs,
    this._partitions, this._cols, this._policy, this._roles,
    this._userRoles, this._attrs, this);
  this._changes = new Changes(this._sql, this._globals, this._users);

  this._models = [this._globals, this._cols, this._users, this._roles, this._userRoles,
    this._colRoles, this._queueAttrRecs
    // this._sessions
  ];
}
498273
function inheritParams(currentParams, newParams, $current, $to) {
  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];

  for (var i in parents) {
    if (!parents[i].params) continue;
    // This test allows compatibility with 0.2.x and 0.3.x (optional and object params)
    parentParams = isArray(parents[i].params) ? parents[i].params : objectKeys(parents[i].params);
    if (!parentParams.length) continue;

    for (var j in parentParams) {
      if (arraySearch(inheritList, parentParams[j]) >= 0) continue;
      inheritList.push(parentParams[j]);
      inherited[parentParams[j]] = currentParams[parentParams[j]];
    }
  }
  return extend({}, inherited, newParams);
}
21680
function setupDbHelper( user_options ) {
  var options = user_options || {}

  /**
   * @returns {Promise<MongooseThenable>}
   */
  function setupDb() {
    return connection( options.connection )
      .then(
        /**
         * @param {Object} db
         * @param {Function} db.model
         *
         * @throws {Error}
         * @returns {*}
         */
        function ( db ) {
          try {
            if ( Array.isArray( options.schemas ) ) {
              options.schemas.forEach(
                function ( schema ) {
                  var keys = Object.keys( schema );

                  db.model( keys[ 0 ], schema[ keys[ 0 ] ] );
                }
              );
            }

            return db;
          } catch ( err ) {
            throw err;
          }
        }
      )
      .catch(
        function ( err ) {
          throw err
        }
      )
  }

  return setupDb
}