/*
find entities that are defined with object literals:

const data = {
'hash:thing1': {
value: {}
},
entities: {
'hash:thing2: {
value: {}
}
}
}
190119
function getEntityObjectFromProperties (entityId, j, root) {
  return root
    .find(j.Property, {
      key: {
        type: 'Literal',
        value: getEntityKeyRegexFn(entityId)
      }
    })
    .map(node => node.get('value'))
}
1092116
function find(array, exp) {
  return (isArray(array) && isDefined(exp))
    //return the member and not an array like `first`
    ? findInArray(array, $parse(exp), false)
    : array;
}
1131944
function (type, definitions) {
      var isPrimitive, listType;

      if (type instanceof Array) {
        listType = true;
        type = type[0];
      }

      // Convert undefined to string of 'undefined'
      if (typeof type === 'undefined') {
        type = 'undefined';
        isPrimitive = true;

      } else if (definitions[type]){
        // a model def exists?
        type = definitions[type]; /* Model */
        isPrimitive = false;

      } else if (getInlineModel(type)) {
        type = getInlineModel(type); /* Model */
        isPrimitive = false;

      } else {
        // We default to primitive
        isPrimitive = true;
      }

      if (isPrimitive) {
        if (listType) {
          return 'Array[' + type + ']';
        } else {
          return type.toString();
        }
      } else {
        if (listType) {
          return 'Array[' + getModelSignature(type.name, type.definition, type.models, type.modelPropertyMacro) + ']';
        } else {
          return getModelSignature(type.name, type.definition, type.models, type.modelPropertyMacro);
        }
      }
  }
1186243
function objectToRecord(object, strict) {
  if (object === null || typeof object !== 'object') {
    throw new TypeError('object must be an Object');
  }

  const keys = Object.keys(object);
  const fields = [];

  for (let i = 0, len = keys.length; i < len; ++i) {
    const label = keys[i];
    const value = object[keys[i]];

    if (strict && !(0, _validator.isValidLabel)(label)) {
      throw new SyntaxError(`unexpected character of label: "${label}"`);
    }

    if (strict && !(0, _validator.isValidValue)(value)) {
      throw new SyntaxError(`unexpected character of value: "${value}"`);
    }

    fields[i] = label + ':' + value;
  }

  return fields.join('\t');
}
1315007
function getEntityNameKeyMap(structure) {
    const result = {};
    for (const kk in structure) {
      const vv = structure[kk];
      if (typeof vv === 'string') {
        if (types.isMap(vv)) {
          const info = types.getTypeInfo(vv);
          const entityName = info.entity;

          if (_entityNameType[entityName]) throw new Error(`Duplicate entity ${entityName}`);
          _entityNameType[entityName] = vv;

          result[entityName] = kk;
          delete structure[kk];
        }
      }
    }
    return result;
  }
700166
function findWhereKey(arr, key) {

  return arr.find(elem => {

    for (const [k] of getIterableObjectEntries(elem)) {

      if (k === key) {
        return true;
      }
    }
  });
}
669866
function fetch_objects_by_expression(data, prop, fields, expression) {
				if(!is_object(data)) { return error('fetch_objects_by_expression(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_objects_by_expression(..., prop, ...) not string: '+ prop); }
				if(!is_string(expression)) { return warn('Expression was not string: {' + expression + '}, typeof ' + (typeof expression)); }

				prop = prop.trim();
				expression = expression.trim();

				var type_name, type_prop;
				var type_start = expression.indexOf('#');
				if(type_start >= 0) {
					type_name = expression.substr(0, type_start).trim();
					type_prop = expression.substr(type_start+1).trim();
				} else {
					type_name = expression;
				}

				if(!type_prop) {
					return error('No property name in expression: {'+ expression+'}');
				}

				var rows = expression_query(data, prop, type_name, type_prop, fields);
				if(!is_array(rows)) {
					return rows;
				}

				var warnings = [];

				if(!data.documents) {
					data.documents = {};
				}

				if(!data.documents.expressions) {
					data.documents.expressions = {};
				}

				if(!is_array(data.documents.expressions[prop])) {
					if(data.documents.expressions.hasOwnProperty(prop)) {
						data.documents.expressions[prop] = [data.documents.expressions[prop]];
					} else {
						data.documents.expressions[prop] = [];
					}
				}

				var id_list = data.documents.expressions[prop];

				rows.forEach(function(row) {
					var uuid = row.id;
					if(is_uuid(uuid)) {
						id_list.push(uuid);
						if(data.documents[uuid] === undefined) {
							data.documents[uuid] = row;
						//} else {
						//	warnings.push( warn('Document already fetched: ' + uuid) );
						}
					} else {
						warnings.push( warn('Document did not have UUID property: ' + JSON.stringify(row, null, 2) ) );
					}
				});

				if(warnings.length >= 1) {
					return warnings.shift();
				}
			}
804223
function (body, value, constant) {

            // we want to match "define('CONST', 'blah');" with any whitespace and any quote type
            // note that heredoc and now doc are NOT covered

            // Quote matching possiblities
            // JS doesn't support look backs, not sure if there is a more elegant solution (maybe with capture groups?)
            var envRegexSLSR = new RegExp("(define\\s*\\(\\s*[']" + constant + "[']\\s*,\\s*['])[^']*([']\\s*\\)\\s*;)"),
                envRegexSLDR = new RegExp("(define\\s*\\(\\s*[']" + constant + "[']\\s*,\\s*[\"])[^\"]*([\"]\\s*\\)\\s*;)"),
                envRegexDLDR = new RegExp("(define\\s*\\(\\s*[\"]" + constant + "[\"]\\s*,\\s*[\"])[^\"]*([\"]\\s*\\)\\s*;)"),
                envRegexDLSR = new RegExp("(define\\s*\\(\\s*[\"]" + constant + "[\"]\\s*,\\s*['])[^']*([']\\s*\\)\\s*;)"),
                envRegexSLNR = new RegExp("(define\\s*\\(\\s*[']" + constant + "[']\\s*,\\s*)[^\\s]+(\\s*\\)\\s*;)"),
                envRegexDLNR = new RegExp("(define\\s*\\(\\s*[\"]" + constant + "[\"]\\s*,\\s*)[^\\s]+(\\s*\\)\\s*;)"),
                lines = body.replace(/\r\n/g, '\n').split(/\n/),
                output = [];

            lines.forEach(function (oneLine) {
                // If a regex matches, that's it, we stop

                var theEnv =    envRegexSLSR.exec(oneLine) ||
                                envRegexSLDR.exec(oneLine) ||
                                envRegexDLDR.exec(oneLine) ||
                                envRegexDLSR.exec(oneLine) ||
                                envRegexSLNR.exec(oneLine) ||
                                envRegexDLNR.exec(oneLine);


                if (theEnv) {
                    oneLine = updateLine(oneLine, theEnv, value);
                }

                output.push(oneLine);

            });

            return output.join('\n');
        }
794857
function(key, ctx, partials, returnFound) {
      var val = false,
          v = null,
          found = false;

      for (var i = ctx.length - 1; i >= 0; i--) {
        v = ctx[i];
        if (v && typeof v == 'object' && key in v) {
          val = v[key];
          found = true;
          break;
        }
      }

      if (!found) {
        return (returnFound) ? false : "";
      }

      if (!returnFound && typeof val == 'function') {
        val = this.lv(val, ctx, partials);
      }

      return val;
    }
966205
function EntityInfo(obj) {
    const {id, states, destinStates} = obj

    this.id = id
    this.states = states
    this.destinStates = destinStates

    this.trackerWebsite = tracker.getLink(id)
}
908162
def literal_matches_objectliteral(v1: Literal, v2: ShExJ.ObjectLiteral) -> bool:
    
    v2_lit = Literal(str(v2.value), datatype=iriref_to_uriref(v2.type), lang=str(v2.language) if v2.language else None)
    return v1 == v2_lit
687974
function (objectLiteral, callback, scope) {
            if (objectLiteral) {
                parseObjectLiteral(objectLiteral).some(function (tuple) {
                    return (callback.call(scope, tuple[0], tuple[1]) === true);
                });
            }
        }
899007
function getContainingObjectLiteralElement(node) {
        switch (node.kind) {
            case 9 /* StringLiteral */:
            case 8 /* NumericLiteral */:
                if (node.parent.kind === 140 /* ComputedPropertyName */) {
                    return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined;
                }
            // intential fall through
            case 69 /* Identifier */:
                return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined;
        }
        return undefined;
    }
1198797
function dict(schema, defaults, options) {
  if (kindOf(schema) !== 'array' || schema.length !== 2) {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Dict structs must be defined as an array with two elements, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const obj = scalar('object', undefined, options)
  const keys = any(schema[0], undefined, options)
  const values = any(schema[1], undefined, options)
  const name = 'dict'
  const type = `dict<${keys.type},${values.type}>`
  const validate = value => {
    const resolved = resolveDefaults(defaults)
    value = resolved ? { ...resolved, ...value } : value
    const [error] = obj.validate(value)

    if (error) {
      error.type = type
      return [error]
    }

    const ret = {}
    const errors = []

    for (let k in value) {
      const v = value[k]
      const [e, r] = keys.validate(k)

      if (e) {
        const allE = e.errors || [e]
        allE.forEach(singleE => {
          singleE.path = [k].concat(singleE.path)
          singleE.data = value
          errors.push(singleE)
        })
        continue
      }

      k = r
      const [e2, r2] = values.validate(v)

      if (e2) {
        const allE2 = e2.errors || [e2]
        allE2.forEach(singleE => {
          singleE.path = [k].concat(singleE.path)
          singleE.data = value
          errors.push(singleE)
        })
        continue
      }

      ret[k] = r2
    }

    if (errors.length) {
      const first = errors[0]
      first.errors = errors
      return [first]
    }

    return [undefined, ret]
  }

  return new Kind(name, type, validate)
}
315471
function parseStoredType(value /* , context */) {
    const regex = /^(\w+)(\((.*?)\))?$/;
    const result = value.match(regex);
    if (!result) throw new ImplementationError(`Invalid storedType "${value}"`);

    const type = result[1];
    const options = {};
    if (result[2]) {
        const regexOptions = /^(\w+)=(.*)/;
        result[3].split(';').forEach(o => {
            const resultOptions = o.match(regexOptions);
            if (!resultOptions) throw new ImplementationError(`Invalid storedType "${value}"`);
            options[resultOptions[1]] = resultOptions[2];
        });
    }

    return { type, options };
}
910837
function normalizeEntity(base, input) {
  if (!input) return {};

  var result = Object.assign(clone(input), {
    class: normalizeClass(input.class),
    properties: normalizeProperties(input.properties),
    entities: normalizeEntities(base, input.entities),
    links: normalizeLinks(base, input.links),
    actions: normalizeActions(base, input.actions),
    title: input.title
  });

  // strip undefined values from the result
  return filter(result, function (v) {
    return typeof v !== 'undefined';
  });
}
549626
function findByNameEx(args, matches) {

		// create a variable to store the matches
		matches = matches || [];
		
		// set option defaults
		args.name       = Array.isArray(args.name) ? args.name : [args.name];
		args.recursive  = (typeof(args.recursive) === 'boolean') ? args.recursive : false;
		args.limit      = !isNaN(args.limit) ? args.limit : 1;
		args.properties = args.properties || [];
		
		// check for a starting point, if one doesnt exist begin at the datacenter level
		if (!args.parent) {
			return rootSearch(args)
			.then(function(parents) {
				return findByNameEx({
					type       : args.type,
					name       : args.name,
					properties : args.properties,
					parent     : parents,
					recursive  : args.recursive,
					limit      : args.limit
				}, matches);
			});
		}
		
		// convert the parent to an array if it is not one
		args.parent = Array.isArray(args.parent) ? args.parent : [args.parent];
		
		// perform the search
		return Promise.each(args.parent, function(parent) {
			
			// check if the match limit is met
			if (matches.length >= args.limit) {
				return;
			}
			
			// perform the search on each name
			return Promise.each(args.name, function(name) {
				
				// check if the match limit is met
				if (matches.length >= args.limit) {
					return;
				}
				
				// perform the search
				return _client.getServiceContent({
					method: 'FindChild',
					service: 'searchIndex',
					params: {
						entity: util.moRef(parent.type, parent.id),
						name: name
					}
				})
				.then(function(result) {

					var id = _.get(result, '$value');
					
					if (id) {
						matches.push(id);
					}					
				});
			})
			.then(function() {
				
				// check if the match limit is met, if not and recursive
				// attempt to descend the child objects
				if (matches.length < args.limit && args.recursive) {
					
					// get the children of the current parent
					return _client.retrieve({
						type: parent.type,
						id: parent.id,
						properties: ['childEntity']
					})
					.then(function(mo) {

						var parents = [];
						
						// get all of the child folders
						_.forEach(_.get(mo, '[0].childEntity'), function(child) {
							if (child.match(/^group-.*/)) {
								parents.push({
									type: 'Folder',
									id: child
								});
							}
						});
						
						// if there were folders, recurse
						if (parents.length > 0) {
							return findByNameEx({
								type       : args.type,
								name       : args.name,
								properties : args.properties,
								parent     : parents,
								recursive  : args.recursive,
								limit      : args.limit
							}, matches);
						}
					});
				}
			});
		})
		.then(function() {
			return matches;
		});
	}