diff --git a/.gitignore b/.gitignore index 485dee6..b7ed6d0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ .idea +/node_modules +.DS_Store diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..6022d27 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "6.1" +before_script: + - npm install grunt-cli -g + diff --git a/Gruntfile.js b/Gruntfile.js index a2b7b6f..df52419 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,31 +1,20 @@ module.exports = function(grunt) { var files = [ - "lib/modules/util/Event.js", - "lib/modules/util/Logger.js", "lib/modules/util/Promise.js", - "lib/modules/util/Ajax.js", + "lib/modules/util/lodash.js", + "lib/modules/UsergridEnums.js", + "lib/modules/util/UsergridHelpers.js", + "lib/modules/UsergridClient.js", "lib/Usergrid.js", - "lib/modules/Client.js", - "lib/modules/Entity.js", - "lib/modules/Collection.js", - "lib/modules/Group.js", - "lib/modules/Counter.js", - "lib/modules/Folder.js", - "lib/modules/Asset.js", - "lib/modules/Error.js" - ]; - var tests = ["tests/mocha/index.html", "tests/mocha/test_*.html"]; - // Project configuration. - grunt.initConfig({ - //pkg: grunt.file.readJSON('package.json'), - "meta": { - "package": grunt.file.readJSON("package.json") - }, - "clean": ["usergrid.js", "usergrid.min.js"], - "uglify": { - "unminified": { - "options": { - "banner": "/*! \n\ + "lib/modules/UsergridQuery.js", + "lib/modules/UsergridRequest.js", + "lib/modules/UsergridAuth.js", + "lib/modules/UsergridEntity.js", + "lib/modules/UsergridUser.js", + "lib/modules/UsergridResponse.js", + "lib/modules/UsergridAsset.js" + ]; + var banner = "/*! \n\ *Licensed to the Apache Software Foundation (ASF) under one\n\ *or more contributor license agreements. See the NOTICE file\n\ *distributed with this work for additional information\n\ @@ -45,50 +34,32 @@ module.exports = function(grunt) { * \n\ * \n\ * <%= meta.package.name %>@<%= meta.package.version %> <%= grunt.template.today('yyyy-mm-dd') %> \n\ - */\n", + */\n"; + + // Project configuration. + grunt.initConfig({ + "meta": { "package": grunt.file.readJSON("package.json") }, + "clean": ["usergrid.js", "usergrid.min.js"], + "uglify": { + "unminified": { + "options": { + "banner": banner, "mangle": false, - "compress": false, "beautify": true, - "preserveComments": function(node, comment){ - //console.log((node.parent_scope!==undefined&&comment.value.indexOf('*Licensed to the Apache Software Foundation')===-1)?"has parent":comment.value); - return comment.type==='comment2'&&comment.value.indexOf('*Licensed to the Apache Software Foundation')===-1; - } + "compress": false, + "preserveComments": "some" }, - "files": { - "usergrid.js": files - } + "files": { "usergrid.js": files } }, "minified": { "options": { - "banner": "/*! \n\ - *Licensed to the Apache Software Foundation (ASF) under one\n\ - *or more contributor license agreements. See the NOTICE file\n\ - *distributed with this work for additional information\n\ - *regarding copyright ownership. The ASF licenses this file\n\ - *to you under the Apache License, Version 2.0 (the\n\ - *\"License\"); you may not use this file except in compliance\n\ - *with the License. You may obtain a copy of the License at\n\ - *\n\ - * http://www.apache.org/licenses/LICENSE-2.0\n\ - * \n\ - *Unless required by applicable law or agreed to in writing,\n\ - *software distributed under the License is distributed on an\n\ - *\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\ - *KIND, either express or implied. See the License for the\n\ - *specific language governing permissions and limitations\n\ - *under the License.\n\ - * \n\ - * \n\ - * <%= meta.package.name %>@<%= meta.package.version %> <%= grunt.template.today('yyyy-mm-dd') %> \n\ - */\n", + "banner": banner, "mangle": false, - "compress": true, "beautify": false, + "compress": {}, "preserveComments": "some" }, - "files": { - "usergrid.min.js": files - } + "files": { "usergrid.min.js": files } } }, "connect": { @@ -109,21 +80,23 @@ module.exports = function(grunt) { "files": [files, 'Gruntfile.js'], "tasks": ["default"] }, - "blanket_mocha": { - //"all": tests, - urls: [ 'http://localhost:8000/tests/mocha/index.html' ], - "options": { - "dest": "report/coverage.html", - "reporter": "Spec", - "threshold": 70 + "mocha": { + "test": { + "options": { + "urls": [ 'http://localhost:<%= connect.test.options.port %>/tests/mocha/index.html' ], + "reporter": "Spec", + "threshold": 70, + "run":true + } } } }); + grunt.loadNpmTasks("grunt-mocha"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-connect"); - grunt.loadNpmTasks("grunt-blanket-mocha"); + grunt.loadNpmTasks("should"); grunt.registerTask("default", [ "clean", "uglify" @@ -134,6 +107,6 @@ module.exports = function(grunt) { ]); grunt.registerTask("test", [ "connect:test", - "blanket_mocha" + "mocha:test" ]); }; diff --git a/README.md b/README.md index 41a2b5a..43c1bb5 100755 --- a/README.md +++ b/README.md @@ -1,868 +1,723 @@ # Usergrid JavaScript SDK -##Quickstart -Detailed instructions follow but if you just want a quick example of how to get started with this SDK, here’s a minimal HTML5 file that shows you how to include & initialize the SDK, as well as how to read & write data from Usergrid with it. +[![Build Status](https://travis-ci.org/RobertWalsh/usergrid-javascript.svg?branch=master)](https://travis-ci.org/RobertWalsh/usergrid-javascript) -```html - - - - - - +Version 2.0 of this SDK is currently a work in progress; documentation and implementation are subject to change. - - - - +1. The singleton pattern is both convenient and enables the developer to use a globally available and always-initialized shared instance of Usergrid. + + ```js + Usergrid.init({ + orgId: '', + appId: '' + }) + ``` + +2. The instance pattern enables the developer to manage instances of the Usergrid client independently and in an isolated fashion. The primary use-case for this is when an application connects to multiple Usergrid targets. + + ```js + var client = new UsergridClient(config) + ``` + +_**Note:** Examples in this readme assume you are using the `Usergrid` shared instance. If you've implemented the instance pattern instead, simply replace `Usergrid` with your client instance variable. See `/tests` for additional examples._ + +## RESTful operations + +When making any RESTful call, a `type` parameter (or `path`) is always required. Whether you specify this as an argument, in an object as a parameter, or as part of a `UsergridQuery` object is up to you. + +### GET() + +To get entities in a collection: + +```js +Usergrid.GET('collection', function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects +}) ``` + +To get a specific entity in a collection by uuid or name: -##Version +```js +Usergrid.GET('collection', '', function(error, usergridResponse) { + // usergridResponse.entity, if found, is a UsergridEntity object +}) +``` + +To get specific entities in a collection by passing a UsergridQuery object: + +```js +var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'blue') + .or + .eq('color', 'orange') + +// this will build out the following query: +// select * where weight > 2.4 and color contains 'bl*' and not color = 'blue' or color = 'orange' + +Usergrid.GET(query, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified query +}) +``` + +### POST() and PUT() + +POST and PUT requests both require a JSON body payload. You can pass either a standard JavaScript object or a `UsergridEntity` instance. While the former works in principle, best practise is to use a `UsergridEntity` wherever practical. When an entity has a uuid or name property and already exists on the server, use a PUT request to update it. If it does not, use POST to create it. + +To create a new entity in a collection (POST): + +```js +var entity = new UsergridEntity({ + type: 'restaurant', + restaurant: 'Dino's Deep Dish, + cuisine: 'pizza' +}) + +// or + +var entity = { + type: 'restaurant', + restaurant: 'Dino's Deep Dish, + cuisine: 'pizza' +} + +Usergrid.POST(entity, function(error, usergridResponse) { + // usergridResponse.entity should now have a uuid property and be created +}) + +// you can also POST an array of entities: + +var entities = [ + new UsergridEntity({ + type: 'restaurant', + restaurant: 'Dino's Deep Dish, + cuisine: 'pizza' + }), + new UsergridEntity({ + type: 'restaurant', + restaurant: 'Pizza da Napoli', + cuisine: 'pizza' + }) +] + +Usergrid.POST(entities, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified entity objects. +}) +``` + +To update an entity in a collection (PUT request): + +```js +var entity = new UsergridEntity({ + type: 'restaurant', + restaurant: 'Pizza da Napoli', + cuisine: 'pizza' +}) + +Usergrid.POST(entity, function(error, usergridResponse) { + entity.owner = 'Mia Carrara' + Usergrid.PUT(entity, function(error, usergridResponse) { + // entity now has the property 'owner' + }) +}) + +// or update a set of entities by passing a UsergridQuery object + +var query = new UsergridQuery('restaurants') + .eq('cuisine', 'italian') + +// this will build out the following query: +// select * where cuisine = 'italian' + +Usergrid.PUT(query, { keywords: ['pasta'] }, function(error, usergridResponse) { + /* the first 10 entities matching this query criteria will be updated: + e.g.: + [ + { + "type": "restaurant", + "restaurant": "Il Tarazzo", + "cuisine": "italian", + "keywords": [ + "pasta" + ] + }, + { + "type": "restaurant", + "restaurant": "Cono Sur Pizza & Pasta", + "cuisine": "italian", + "keywords": [ + "pasta" + ] + } + ] + */ +}) +``` + +### DELETE() -Current Version: **0.11.0** +DELETE requests require either a specific entity or a `UsergridQuery` object to be passed as an argument. + +To delete a specific entity in a collection by uuid or name: -See change log: +```js +Usergrid.DELETE('collection', '', function(error, usergridResponse) { + // if successful, entity will now be deleted +}) +``` + +To specific entities in a collection by passing a `UsergridQuery` object: + +```js +var query = new UsergridQuery('cats') + .eq('color', 'black') + .or + .eq('color', 'white') + +// this will build out the following query: +// select * where color = 'black' or color = 'white' + +Usergrid.DELETE(query, function(error, usergridResponse) { + // the first 10 entities matching this query criteria will be deleted +}) +``` - +## Entity operations and convenience methods -##Comments / questions -For help using this SDK, reach out on the Usergrid google group: +`UsergridEntity` has a number of helper/convenience methods to make working with entities more convenient. If you are _not_ utilizing the `Usergrid` shared instance, you must pass an instance of `UsergridClient` as the first argument to any of these helper methods. -https://groups.google.com/forum/?hl=en#!forum/usergrid +### reload() -Or just open github issues. +Reloads the entity from the server +```js +entity.reload(function(error, usergridResponse) { + // entity is now reloaded from the server +}) +``` + +### save() +Saves (or creates) the entity on the server -##Overview -This open source SDK simplifies writing JavaScript / HTML5 applications that connect to Usergrid. The repo is located here: +```js +entity.aNewProperty = 'A new value' +entity.save(function(error, usergridResponse) { + // entity is now updated on the server +}) +``` + +### remove() - +Deletes the entity from the server -To find out more about Usergrid, see: +```js +entity.remove(function(error, usergridResponse) { + // entity is now deleted on the server and the local instance should be destroyed +}) +``` + +## Authentication, current user, and auth-fallback - +### appAuth and authenticateApp() -To view the Usergrid documentation, see: +`Usergrid` can use the app client ID and secret that were passed upon initialization and automatically retrieve an app-level token for these credentials. - +```js +Usergrid.setAppAuth('', '') +Usergrid.authenticateApp(function(error, usergridResponse, token) { + // Usergrid.appAuth is created automatically when this call is successful +}) +``` +### currentUser and authenticateUser() -##Node.js -Want to use Node.js? No problem - use the Usergrid Node Module: +`Usergrid` has a special `currentUser` property. By default, when calling `authenticateUser()`, `.currentUser` will be set to this user if the authentication flow is successful. - +```js +Usergrid.authenticateUser({ + username: '', + password: '' +}, function(error, usergridResponse, token) { + // Usergrid.currentUser is set to the authenticated user and the token is stored within that context +}) +``` + +If you want to utilize authenticateUser without setting as the current user, simply pass a `false` boolean value as the second parameter: + +```js +Usergrid.authenticateUser({ + username: '', + password: '' +}, false, function(error, usergridResponse, token) { + +}) +``` -or on github: +### authMode - +Auth-mode defines what the client should do when a user token is not present. By default, `Usergrid.authMode` is set to `UsergridAuthMode.NONE`, whereby when a token is *not* present, an API call will be performed unauthenticated. If instead `Usergrid.authMode` is set to `UsergridAuthMode.APP`, the API call will instead be performed using client credentials, _if_ they're available (i.e. `authenticateApp()` was performed at some point). -The syntax for this Javascript SDK and the Usergrid Node module are almost exactly the same so you can easily transition between them. +### usingAuth() +At times it is desireable to have complete, granular control over the authentication context of an API call. To facilitate this, the passthrough function `.usingAuth()` allows you to pre-define the auth context of the next API call. -##About the samples -This SDK comes with a variety of samples that you can use to learn how to connect your project to App Services (Usergrid). +```js +// assume Usergrid.authMode = UsergridAuthMode.NONE + +Usergrid.usingAuth(Usergrid.appAuth).POST('roles/guest/permissions', { + permission: "get,post,put,delete:/**" +}, function(error, usergridResponse) { + // here we've temporarily used the client credentials to modify permissions + // subsequent calls will not use this auth context +}) +``` + +## User operations and convenience methods + +`UsergridUser` has a number of helper/convenience methods to make working with user entities more convenient. If you are _not_ utilizing the `Usergrid` shared instance, you must pass an instance of `UsergridClient` as the first argument to any of these helper methods. + +### create() + +Creating a new user: + +```js +var user = new UsergridUser({ + username: 'username', + password: 'password' +}) + +user.create(function(error, usergridResponse, user) { + // user has now been created and should have a valid uuid +}) +``` + +### login() + +A simpler means of retrieving a user-level token: + +```js +var user = new UsergridUser({ + username: 'username', + password: 'password' +}) + +user.login(function(error, usergridResponse, token) { + // user is now logged in +}) +``` -**Note:** All the sample code in this file is pulled directly from the "test" example, so you can rest-assured that it will work! You can find it here: +### logout() - +Logs out the selected user. You can also use this convenience method on `Usergrid.currentUser`. +```js +user.logout(function(error, usergridResponse, success) { + // user is now logged out +}) +``` + +### logoutAllSessions() -##Installing -Once you have downloaded the SDK, add the usergrid.js file to your project. This file is located in the root of the SDK. Include it in the top of your HTML file (in between the head tags): +Logs out all sessions for the selected user and destroys all active tokens. You can also use this convenience method on `Usergrid.currentUser`. - +```js +user.logoutAllSessions(function(error, usergridResponse, success) { + // user is now logged out from everywhere +}) +``` + +### resetPassword() + +Resets the password for the selected user. + +```js +user.resetPassword({ + oldPassword: '2cool4u', + newPassword: 'correct-horse-battery-staple', +}, function(error, response) { + // if it was done correctly, the new password will be changed +}) +``` + +### UsergridUser.CheckAvailable() + +This is a class (static) method that allows you to check whether a username or email address is available or not. + +```js +UsergridUser.CheckAvailable(client, { + email: 'email' +}, function(err, response, exists) { + // 'exists' is a boolean value that indicates whether a user already exists +}) + +UsergridUser.CheckAvailable(client, { + username: 'username' +}, function(err, response, exists) { + +}) + +UsergridUser.CheckAvailable(client, { + email: 'email', + username: 'username', // checks both email and username +}, function(err, response, exists) { + // 'exists' returns true if either username or email exist +}) +``` + +## Querying and filtering data -##Getting started -You are now ready to create a new `Client` object, which is the main entry point in the SDK: +### UsergridQuery initialization - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, // Optional - turn on logging, off by default - buildCurl: true // Optional - turn on curl commands, off by default - }); +The `UsergridQuery` class allows you to build out complex query filters using the Usergrid [query syntax](http://docs.apigee.com/app-services/content/querying-your-data). -The last two items are optional. The `logging` option will enable console.log output from the client, and will output various bits of information (calls that are being made, errors that happen). The `buildCurl` option will cause cURL equivalent commands of all calls to the API to be displayed in the console.log output (see more about this below). +The first parameter of the `UsergridQuery` builder pattern should be the collection (or type) you intend to query. You can either pass this as an argument, or as the first builder object: -You are now ready to use the `Client` object to make calls against the API. +```js +var query = new UsergridQuery('cats') +// or +var query = new UsergridQuery().type('cats') +var query = new UsergridQuery().collection('cats') +``` -##Asynchronous vs. synchronous calls (a quick discussion) -This SDK works by making RESTful API calls from your application to the App Services (Usergrid) API. This SDK currently only supports asynchronous calls. +You then can layer on additional queries: -If an API call is _synchronous_, it means that code execution will block (or wait) for the API call to return before continuing. This SDK does not yet support synchronous calls. +```js +var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'white') + .or + .eq('color', 'orange') +``` + +You can also adjust the number of results returned: -_Asynchronous_ calls, which are supported by this SDK, do not block (or wait) for the API call to return from the server. Execution continues on in your program, and when the call returns from the server, a "callback" function is executed. For example, in the following code, the function `dogCreateCallback` will be called when the `createEntity` call returns from the server. Meanwhile, execution will continue. +```js +var query = new UsergridQuery('cats').eq('color', 'black').limit(100) +// returns a maximum of 100 entiteis +``` + +And sort the results: - function dogCreateCallback(err, dog) { - alert('I will probably be called second'); - if (err) { - // Error - Dog not created - } else { - // Success - Dog was created - } - } - - client.createEntity({type:'dogs'}, dogCreateCallback); - - alert('I will probably be called first'); +```js +var query = new UsergridQuery('cats').eq('color', 'black').asc('name') +// sorts by 'name', ascending +``` + +And you can do geo-location queries: -The result of this is that we cannot guarantee the order of the two alert statements. Most likely, the alert right after the `createEntity` function will be called first because the API call will take a second or so to complete. +```js +var query = new UsergridQuery('devices').locationWithin(, , ) +``` + +### Using a query in a request + +Queries can be passed as parameters to GET, PUT, and DELETE requests: + +```js +Usergrid.GET(query, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified query +}) + +Usergrid.PUT(query, { aNewProperty: "A new value" }, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified query that contain aNewProperty equal to "A new value" +}) + +Usergrid.DELETE(query, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified query that are now deleted +}) +``` + +While not a typical use case, sometimes it is useful to be able to create a query that works on multiple collections. Therefore, in each one of these RESTful calls, you can optionally pass a 'type' string as the first argument: -The important point is that program execution will continue asynchronously, the callback function will be called once program execution completes. +```js +Usergrid.GET('cats', query, function(error, usergridResponse) { + // usergridResponse.entities is an array of UsergridEntity objects matching the specified query with the type of 'cats' +}) +``` + +### List of query builder objects -##Entities and collections -Usergrid stores its data as _entities_ in _collections_. Entities are essentially JSON objects and collections are just like folders for storing these objects. You can learn more about entities and collections in the App Services docs: - - +`type('string')` +> The collection name to query -##Entities -You can easily create new entities, or access existing ones. Here is a simple example that shows how to create a new entity of type "dogs": - - var options = { - type:'dogs', - name:'einstein' - } - - client.createEntity(options, function (err, dog) { - if (err) { - //Error - Dog not created - } else { - //Success - Dog was created - } - }); - -**Note:** All calls to the API will be executed asynchronously, so it is important that you use a callback. - -Once your object is created, you can update properties on it by using the `set` method, then save it back to the database using the `save` method: - - // Once the dog is created, you can set single properties (key, value) - dog.set('breed','mutt'); - - // The set function can also take a JSON object - var data = { - master:'Doc', - state:'hungry' - } - - // Set is additive, so previously set properties are not overwritten unless a property with the same name exists in the data object - dog.set(data); - - // And save back to the database - dog.save(function(err){ - if (err){ - // Error - dog not saved - } else { - // Success - dog was saved - } - }); - -**Note:** Using the `set` function will set the properties locally. Make sure you call the `save` method on the entity to save them back to the database! - -You can also refresh the object from the database if needed (in case the data has been updated by a different client or device) by using the `fetch` method. Use the `get` method to retrieve properties from the object: - - // Call fetch to refresh the data from the server - dog.fetch(function(err){ - if (err){ - // Error - dog not refreshed from database - } else { - // Dog has been refreshed from the database - // Will only work if the UUID for the entity is in the dog object - - // Get single properties from the object using the get method - var master = dog.get('master'); - var name = dog.get('name'); - - // Or, get all the data as a JSON object: - var data = dog.get(); - - // Based on statements above, the data object should look like this: - /* - { - type:'dogs', - name:'einstein', - master:'Doc', - state:'hungry', - breed:'mutt' - } - */ - - } - }); - -Use the `destroy` method to remove the entity from the database: - - // The destroy method will delete the entity from the database - dog.destroy(function(err){ - if (err){ - // Error - dog not removed from database - } else { - // Success - dog was removed from database - dog = null; - // No real dogs were harmed! - } - }); - -##The collection object -The collection object models collections in the database. Once you start programming your app, you will likely find that this is a useful method of interacting with the database. Creating a collection will automatically populate the object with entities from the collection. - -The following example shows how to create a collection object, then how to use those entities once they have been populated from the server: - - // Options object needs to have the type (which is the collection type) - // ”qs” is for “query string”. “ql” is for “query language” - var options = { - type:'dogs', - qs:{ql:'order by index'} - } - - client.createCollection(options, function (err, dogs) { - if (err) { - // Error - could not make collection - } else { - // Success - new collection created - - // We got the dogs, now display the entities - while(dogs.hasNextEntity()) { - // Get a reference to the dog - dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - - } - }); - -You can also add a new entity of the same type to the collection: - - // Create a new dog and add it to the collection - var options = { - name:'extra-dog', - fur:'shedding' - } - // Just pass the options to the addEntity method - // to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - // Error - extra dog not saved or added to collection - } else { - // Success - extra dog saved and added to collection - } - }); - -##Collection iteration and paging -At any given time, the collection object will have one page of data loaded. To get the next page of data from the server and iterate across the entities, use the following pattern: - - if (dogs.hasNextPage()) { - // There is a next page, so get it from the server - dogs.getNextPage(function(err){ - if (err) { - // Error - could not get next page of dogs - } else { - // Success - got next page of dogs, so do something with it - while(dogs.hasNextEntity()) { - // Get a reference to the dog - dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - } - }); - } - -You can use the same pattern with the `hasPreviousPage` and `getPreviousPage` methods to get a previous page of data. - -By default, the database will return 10 entities per page. Use the `qs` (query string) property (more about this below) to set a different limit (up to 999): - - var options = { - type:'dogs', - qs:{limit:50} // Set a limit of 50 entities per page - } - - client.createCollection(options, function (err, dogs) { - if (err) { - // Error - could not get all dogs - } else { - // Success - got at most 50 dogs - - // We got 50 dogs, now display the entities - while(dogs.hasNextEntity()) { - // Get a reference to the dog - var dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - - // Wait! What if we want to display them again?? - // Simple! Just reset the entity pointer: - dogs.resetEntityPointer(); - while(dogs.hasNextEntity()) { - // Get a reference to the dog - var dog = dogs.getNextEntity(); - // Do something with the entity - var name = dog.get('name'); - } - - } - }); - -Several convenience methods exist to make working with pages of data easier: - -* `resetPaging` - Calls made after this will get the first page of data (the cursor, which points to the current page of data, is deleted) -* `getFirstEntity` - Gets the first entity of a page -* `getLastEntity` - Gets the last entity of a page -* `resetEntityPointer` - Sets the internal pointer back to the first element of the page -* `getEntityByUUID` - Returns the entity if it is in the current page - -###Custom Queries -A custom query allows you to tell the API that you want your results filtered or altered in some way. - -Use the `qs` property in the options object - "qs" stands for "query string". By adding a JSON object of key/value pairs to the `qs` property of the options object, you signal that you want those values used for the key/value pairs in the query string that is sent to the server. - -For example, to specify that the query results should be ordered by creation date, add the `qs` parameter to the options object: - - var options = { - type:'dogs', - qs:{ql:'order by created DESC'} - }; - -The `qs` object above will be converted into a query language call that looks like this: - - /dogs?ql=order by created DESC +`collection('string')` -If you also wanted to get more entities in the result set than the default 10, say 100, you can specify a query similar to the following (the limit can be a maximum of 999): +> An alias for `type` - dogs.qs = {ql:'order by created DESC',limit:'100'}; +`eq('key', 'value')` or `equal('key', 'value')` -The `qs` object above will be converted into a call that looks like this: - - /dogs?ql=order by created DESC&limit=100 - -**Note**: There are many cases where expanding the result set is useful. But be careful -- the more results you get back in a single call, the longer it will take to transmit the data back to your app. +> Equal to (e.g. `where color = 'black'`) -If you need to change the query on an existing object, simply access the `qs` property directly: +`contains('key', 'value')` - dogs.qs = {ql:'order by created DESC'}; +> Contains a string (e.g.` where color contains 'bl*'`) -Then make your fetch call: +`gt('key', 'value')` or `greaterThan('key', 'value')` - dogs.fetch(...) +> Greater than (e.g. `where weight > 2.4`) -Another common requirement is to limit the results to a specific query. For example, to get all brown dogs, use the following syntax: +`gte('key', 'value')` or `greaterThanOrEqual('key', 'value')` - dogs.qs = {ql:"select * where color='brown'"}; +> Greater than or equal to (e.g. `where weight >= 2.4`) -You can also limit the results returned such that only the fields you specify are returned: +`lt('key', 'value')` or `lessThan('key', 'value')` - dogs.qs = {'ql':"select name, age where color='brown'"}; +> Less than (e.g. `where weight < 2.4`) -**Note:** In the two preceding examples that we put single quotes around 'brown', so it will be searched as a string. +`lte('key', 'value')` or `lessThanOrEqual('key', 'value')` -You can find more information on custom queries here: +> Less than or equal to (e.g. `where weight <= 2.4`) - -##Counters -Counters can be used by an application to create custom statistics, such as how many times an a file has been downloaded or how many instances of an application are in use. +`not` -###Create the counter instance +> Negates the next block in the builder pattern, e.g.: -**Note:** The count is not altered upon instantiation +```js +var query = new UsergridQuery('cats').not.eq('color', 'black') +// select * from cats where not color = 'black' +``` - var counter = new Usergrid.Counter({ - client: client, - data: { - category: 'usage', - //a timestamp of '0' defaults to the current time - timestamp: 0, - counters: { - running_instances: 0, - total_instances: 0 - } - } - }, function(err, data) { - if (err) { - // Error - there was a problem creating the counter - } else { - // Success - the counter was created properly - } - }); - -###Updating counters +`and` -When an application starts, we want to increment the 'running_instances' and 'total_instances' counters. +> Joins two queries by requiring both of them. `and` is also implied when joining two queries _without_ an operator. E.g.: - // add 1 running instance - counter.increment({ - name: 'running_instances', - value: 1 - }, function(err, data) { - // ... - }); +```js +var query = new UsergridQuery('cats').eq('color', 'black').eq('fur', 'longHair') +// is identical to: +var query = new UsergridQuery('cats').eq('color', 'black').and.eq('fur', 'longHair') +``` - // add 1 total instance - counter.increment({ - name: 'total_instances', - value: 1 - }, function(err, data) { - // ... - }); +`or` -When the application exits, we want to decrement 'running_instances' +> Joins two queries by requiring only one of them. `or` is never implied. E.g.: - // subtract 1 total instance - counter.decrement({ - name: 'total_instances', - value: 1 - }, function(err, data) { - // ... - }); +```js +var query = new UsergridQuery('cats').eq('color', 'black').or.eq('color', 'white') +``` + +> When using `or` and `and` operators, `and` joins will take precedence over `or` joins. You can read more about query operators and precedence [here](http://docs.apigee.com/api-baas/content/supported-query-operators-data-types). -Once you have completed your testing, you can reset these values to 0. +`locationWithin(distanceInMeters, latitude, longitude)` - counter.reset({ - name: 'total_instances' - }, function(err, data) { - // ... - }); +> Returns entities which have a location within the specified radius. Arguments can be `float` or `int`. -##Assets +`asc('key')` -Assets can be attached to any entity as binary data. This can be used by your application to store images and other file types. There is a limit of one asset per entity. +> Sorts the results by the specified property, ascending -####Attaching an asset - -An asset can be attached to any entity using Enity.attachAsset(file, callback). You can also call attachAsset() on the same entity to change the asset attached to it. - - //Create a new entity to attach an asset to - you can also use an existing entity - var properties = { - type:'user', - username:'someUser', - }; - - dataClient.createEntity(properties, function(err, response, entity) { - if (!err) { - //The entity was created, so call attachAsset() on it. - entity.attachAsset(file, function(err, response){ - if (!err){ - //Success - the asset was attached - } else { - //Error - } - }); - } - }); - -##Retrieving Assets - -To retrieve the data, call Entity.downloadAsset(callback). A blob is returned -in the success callback. - - entity.downloadAsset(function(err, file){ - if (err) { - // Error - there was a problem retrieving the data - } else { - // Success - the asset was downloaded - - // Create an image tag to hold our downloaded image data - var img = document.createElement("img"); - - // Create a FileReader to feed the image - // into our newly-created element - var reader = new FileReader(); - reader.onload = (function(aImg) { - return function(e) { - aImg.src = e.target.result; - }; - })(img); - reader.readAsDataURL(file); - - // Append the img element to our page - document.body.appendChild(img); - } - }) +`desc('key')` +> Sorts the results by the specified property, descending +`sort('key', 'order')` -##Modeling users with the entity object -Use the entity object to model users. Simply specify a type of "users". - -**Note:** Remember that user entities use "username", not "name", as the distinct key. -Here is an example: - - // Type is 'users', set additional parameters as needed. - var options = { - type:'users', - username:'marty', - password:'mysecurepassword', - name:'Marty McFly', - city:'Hill Valley' - } - - client.createEntity(options, function (err, marty) { - if (err){ - //Error - user not created - } else { - //Success - user created - var name = marty.get('name'); - } - }); - -If the user is modified, just call save on the user again: - - // Add properties cumulatively. - marty.set('state', 'California'); - marty.set('girlfriend','Jennifer'); - - marty.save(function(err){ - if (err){ - // Error - user not updated - } else { - // Success - user updated - } - }); - -To refresh the user's information in the database: - - marty.fetch(function(err){ - if (err){ - // Error - not refreshed - } else { - // Success - user refreshed - - // Do something with the entity - var girlfriend = marty.get('girlfriend'); - } - }); - -###To sign up a new user -When a new user wants to sign up in your app, simply create a form to catch their information, then use the `client.signup` method: - - // Method signature: client.signup(username, password, email, name, callback) - client.signup('marty', 'mysecurepassword', 'marty@timetravel.com', 'Marty McFly', - function (err, marty) { - if (err){ - error('User not created'); - runner(step, marty); - } else { - success('User created'); - runner(step, marty); - } - } - ); - - -###To log a user in -Logging a user in means sending the user's username and password to the server, and getting back an access (OAuth) token. You can then use this token to make calls to the API on the user's behalf. The following example shows how to log a user in and log them out: - - username = 'marty'; - password = 'mysecurepassword'; - client.login(username, password, function (err) { - if (err) { - // Error - could not log user in - } else { - // Success - user has been logged in - - // The login call will return an OAuth token, which is saved - // in the client. Any calls made now will use the token. - // Once a user has logged in, their user object is stored - // in the client and you can access it this way: - var token = client.token; - - // Then make calls against the API. For example, you can - // get the logged in user entity this way: - client.getLoggedInUser(function(err, data, user) { - if(err) { - // Error - could not get logged in user - } else { - // Success - got logged in user - - // You can then get info from the user entity object: - var username = user.get('username'); - } - }); - } - }); - -If you need to change a user's password, set the `oldpassword` and `newpassword` fields, then call save: - - marty.set('oldpassword', 'mysecurepassword'); - marty.set('newpassword', 'mynewsecurepassword'); - marty.save(function(err){ - if (err){ - // Error - user password not updated - } else { - // Success - user password updated - } - }); - -To log a user out, call the `logout` function: - - client.logout(); - - // verify the logout worked - if (client.isLoggedIn()) { - // Error - logout failed - } else { - // Success - user has been logged out - } - -###Making connections -Connections are a way to connect two entities with a word, typically a verb. This is called an _entity relationship_. For example, if you have a user entity with username of marty, and a dog entity with a name of einstein, then using our RESTful API, you could make a call like this: - - POST users/marty/likes/dogs/einstein - -This creates a one-way connection between marty and einstein, where marty "likes" einstein. - -Complete documentation on the entity relationships API can be found here: - - - -For example, say we have a new dog named einstein: - - var options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - - client.createEntity(options, function (err, dog) { - if (err) { - // Error - new dog not created - } else { - // Success - new dog created - } - }); - -Then, we can create a "likes" connection between our user, Marty, and the dog named einstein: - - marty.connect('likes', dog, function (err, data) { - if (err) { - // Error - connection not created - } else { - // Success - the connection call succeeded - // Now let’s do a getConnections call to verify that it worked - marty.getConnections('likes', function (err, data) { - if (err) { - // Error - could not get connections - } else { - // Success - got all the connections - // Verify that connection exists - if (marty.likes.einstein) { - // Success - connection exists - } else { - // Error - connection does not exist - } - } - }); - } - }); - -We could have just as easily used any other word as the connection (e.g. "owns", "feeds", "cares-for", etc.). - -Now, if you want to remove the connection, do the following: - - marty.disconnect('likes', dog, function (err, data) { - if (err) { - // Error - connection not deleted - } else { - // Success - the connection has been deleted - marty.getConnections('likes', function (err, data) { - if (err) { - // Error - error getting connections - } else { - // Success! - now verify that the connection exists - if (marty.likes.einstein) { - // Error - connection still exists - } else { - // Success - connection deleted - } - } - }); - } - }); - -If you no longer need the object, call the `destroy` method and the object will be deleted from database: - - marty.destroy(function(err){ - if (err){ - // Error - user not deleted from database - } else { - // Success - user deleted from database - marty = null; // Blow away the local object - } - }); - -##Making generic calls -If you find that you need to make calls to the API that fall outside of the scope of the entity and collection objects, you can use the following format to make any REST calls against the API: - - client.request(options, callback); - -This format allows you to make almost any call against the Usergrid API. For example, to get a list of users: - - var options = { - method:'GET', - endpoint:'users' - }; - client.request(options, function (err, data) { - if (err) { - // Error - GET failed - } else { - // Data will contain raw results from API call - // Success - GET worked - } - }); - -Or, to create a new user: - - var options = { - method:'POST', - endpoint:'users', - body:{ username:'fred', password:'secret' } - }; - client.request(options, function (err, data) { - if (err) { - // Error - POST failed - } else { - // Data will contain raw results from API call - // Success - POST worked - } - }); - -Or, to update a user: - - var options = { - method:'PUT', - endpoint:'users/fred', - body:{ newkey:'newvalue' } - }; - client.request(options, function (err, data) { - if (err) { - // Error - PUT failed - } else { - // Data will contain raw results from API call - // Success - PUT worked - } - }); - -Or, to delete a user: - - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - if (err) { - // Error - DELETE failed - } else { - // Data will contain raw results from API call - // Success - DELETE worked - } - }); - -The `options` object for the `client.request` function includes the following: - -* `method` - HTTP method (`GET`, `POST`, `PUT`, or `DELETE`), defaults to `GET` -* `qs` - object containing querystring values to be appended to the URI -* `body` - object containing entity body for POST and PUT requests -* `endpoint` - API endpoint, for example "users/fred" -* `mQuery` - boolean, set to `true` if running management query, defaults to `false` -* `buildCurl` - boolean, set to `true` if you want to see equivalent curl commands in console.log, defaults to `false` - -You can make any call to the API using the format above. However, in practice using the higher level entity and collection objects will make life easier as they take care of much of the heavy lifting. - - -###Validation -An extension for validation is provided for you to use in your apps. The file is located here: - - /extensions/usergrid.session.js - -Include this file at the top of your HTML file - AFTER the SDK file: - - - +> Sorts the results by the specified property, in the specified order (`asc` or `desc`). + +`limit(int)` -A variety of functions are provided for verifying many common types such as usernames, passwords, and so on. Feel free to copy and modify these functions for use in your own projects. - - -###cURL -[cURL](http://curl.haxx.se/) is an excellent way to make calls directly against the API. As mentioned in the **Getting started** section of this guide, one of the parameters you can add to the new client `options` object is **buildCurl**: - - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, // Optional - turn on logging, off by default - buildCurl: true // Optional - turn on curl commands, off by default - }); +> The maximum number of entities to return -If you set this parameter to `true`, the SDK will build equivalent `curl` commands and send them to the console.log window. +`cursor('string')` -More information on cURL can be found here: - - - -## Contributing -We welcome your enhancements! - -Like [Usergrid](https://github.com/apache/usergrid-javascript), the Usergrid Javascript SDK is open source and licensed under the Apache License, Version 2.0. +> A pagination cursor string -1. Fork it. -2. Create your feature branch (`git checkout -b my-new-feature`). -3. Commit your changes (`git commit -am 'Added some feature'`). -4. Push your changes to the upstream branch (`git push origin my-new-feature`). -5. Create new Pull Request (make sure you describe what you did and why your mod is needed). +`fromString('query string')` -###Contributing to usergrid.js -usergrid.js and usergrid.min.js are built from modular components using Grunt. If you want to contribute updates to these files, please commit your changes to the modules in /lib/modules. Do not contribute directly to usergrid.js or your changes could get overwritten in a future build. +> A special builder property that allows you to input a pre-defined query string. All other builder properties will be ignored when this property is defined. For example: + +```js +var query = new UsergridQuery().fromString("select * where color = 'black' order by name asc") +``` -##More information -For more information on Usergrid, visit . +## UsergridResponse -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +### ok - +You can check `usergridResponse.ok`, a `bool` value, to see if the response was successful. Any status code < 400 returns true. -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. +```js +Usergrid.GET('collection', function(error, usergridResponse) { + if (usergridResponse.ok) { + // woo! + } +}) +``` + +### entity, entities, user, users, first, last + +Depending on the call you make, you will receive either an array of UsergridEntity objects, or a single entity as the third parameter in the callback. If you're querying the `users` collection, these will also be `UsergridUser` objects, a subclass of `UsergridEntity`. + +- `.first` returns the first entity in an array of entities; `.entity` is an alias to `.first`. If there are no entities, both of these will be undefined. +- `.last` returns the last entity in an array of entities; if there is only one entity in the array, this will be the same as `.first` _and_ `.entity`, and will be undefined if there are no entities in the response. +- `.entities` will either be an array of entities in the response, or an empty array. +- `.user` is a special alias for `.entity` for when querying the `users` collection. Instead of being a `UsergridEntity`, it will be its subclass, `UsergridUser`. +- `.users` is the same as `.user`, though behaves as `.entities` does by returning either an array of UsergridUser objects or an empty array. + +Examples: + +```js +Usergrid.GET('collection', function(error, response) { + // you can access: + // response.entities (the returned entities) + // response.first (the first entity) + // response.entity (same as response.first) + // response.last (the last entity returned) +}) + +Usergrid.GET('collection', '', function(error, response) { + // you can access: + // response.entity (the returned entity) + // response.entities (containing only the returned entity) + // response.first (same as response.entity) + // response.last (same as response.entity) +}) + +Usergrid.GET('users', function(error, usergridResponse) { + // you can access: + // response.users (the returned users) + // response.entities (same as response.users) + // response.user (the first user) + // response.entity (same as response.user) + // response.first (same as response.user) + // response.last (the last user) +}) + +Usergrid.GET('users', '', function(error, response) { + // you can access; + // response.users (containing only the one user) + // response.entities (same as response.users) + // response.user (the returned user) + // response.entity (same as response.user) + // response.first (same as response.user) + // response.last (same as response.user) +}) +``` + +## Connections + +Connections can be managed using `Usergrid.connect()`, `Usergrid.disconnect()`, and `Usergrid.getConnections()`, or entity convenience methods of the same name. + +### connect +Create a connection between two entities: +```js +Usergrid.connect(entity1, 'relationship', entity2, function(error, usergridResponse) { + // entity1 now has an outbound connection to entity2 +}) +``` + +### getConnections + +Retrieve outbound connections: + +```js +client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, 'relationship', function(error, usergridResponse) { + // usergridResponse.entities is an array of entities that entity1 is connected to via 'relationship' + // in this case, we'll see entity2 in the array +}) +``` + +Retrieve inbound connections: + +```js +client.getConnections(UsergridClient.Connections.DIRECTION_IN, entity2, 'relationship', function(error, usergridResponse) { + // usergridResponse.entities is an array of entities that connect to entity2 via 'relationship' + // in this case, we'll see entity1 in the array +})``` + +### disconnect + +Delete a connection between two entities: + +```js +Usergrid.disconnect(entity1, 'relationship', entity2, function(error, usergridResponse) { + // entity1's outbound connection to entity2 has been destroyed +}) +``` + +## Assets + +Assets can be uploaded and downloaded either directly using `Usergrid.uploadAsset()` or `Usergrid.downloadAsset()`, or via `UsergridEntity` convenience methods. Before uploading an asset, you will need to initialize a `UsergridAsset` instance. + +### UsergridAsset init + +UsergridAsset's can only be initialized with [File](https://developer.mozilla.org/en-US/docs/Web/API/File) or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects. + +Loading an image blob via `XMLHttpRequest`: + +```js +var usergridAsset; +var req = new XMLHttpRequest(); +req.open('GET', 'https://raw.githubusercontent.com/apache/usergrid-javascript/master/tests/resources/images/apigee.png', true); +req.responseType = 'blob'; +req.onload = function () { + var blobResponse = req.response; + usergridAsset = new UsergridAsset(blobResponse); // asset.data will now contain the contents and info from the 'blob' response. +}; +req.send(null); +``` + +You can also access `asset.contentType` and `asset.contentLength` once data has been loaded into a `UsergridAsset`. + +###Usergrid.uploadAsset() and Usergrid.downloadAsset() + +POST binary data to a collection by creating a new entity: + +```js +var asset = new UsergridAsset(fileOrBlob); +Usergrid.uploadAsset('collection',asset,function(error, assetResponse, entityWithAsset) { + // asset is now uploaded to Usergrid +}); +``` + +PUT binary data to an existing entity via attachAsset(): + + +```js +var asset = new UsergridAsset(fileOrBlob); +entity.attachAsset(asset); +Usergrid.uploadAsset(entity,function(error, assetResponse, entityWithAsset) { + // access the asset via entity.asset +}); +``` + +### UsergridEntity convenience methods + +`entity.uploadAsset()` is a convenient way to upload an asset that is attached to an entity: + +```js +var asset = new UsergridAsset(fileOrBlob) +entity.attachAsset(asset) +entity.uploadAsset(function(error, assetResponse, entityWithAsset) { + // asset is now uploaded to Usergrid +}) +``` + +`entity.downloadAsset()` allows you to download a binary asset: + +```js +entity.uploadAsset(function(error, assetResponse, entityWithAsset) { + // access the asset via entityWithAsset.asset +})``` + \ No newline at end of file diff --git a/examples/all-calls/app.js b/examples/all-calls/app.js index 6bf804e..8d6720d 100755 --- a/examples/all-calls/app.js +++ b/examples/all-calls/app.js @@ -1,29 +1,4 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - /* -* All Calls is a sample app that is powered by Usergrid -* This app shows how to make the 4 REST calls (GET, POST, -* PUT, DELETE) against the usergrid API. -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -44,14 +19,8 @@ * This file contains the main program logic for All Calls App. */ $(document).ready(function () { - //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!) - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'yourappname', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); + var client = new UsergridClient({orgId: "rwalsh", appId: "jssdktestapp", authMode: UsergridAuthMode.NONE}); function hideAllSections(){ $('#get-page').hide(); @@ -133,41 +102,24 @@ $(document).ready(function () { function _get() { var endpoint = $("#get-path").val(); - - var options = { - method:'GET', - endpoint:endpoint - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.GET(endpoint, function(err,usergridResponse) { if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
ERROR: '+output+'
'); + $("#response").html('
ERROR: '+JSON.stringify(err,null,2)+'
'); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
'+output+'
'); + $("#response").html('
'+JSON.stringify(usergridResponse.entities,null,2)+'
'); } - }); + }) } function _post() { var endpoint = $("#post-path").val(); var data = $("#post-data").val(); data = JSON.parse(data); - - var options = { - method:'POST', - endpoint:endpoint, - body:data - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.POST(endpoint, data, function (err,usergridResponse) { if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
ERROR: '+output+'
'); + $("#response").html('
ERROR: '+JSON.stringify(err,null,2)+'
'); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
'+output+'
'); + $("#response").html('
'+JSON.stringify(usergridResponse.entity,null,2)+'
'); } }); } @@ -176,39 +128,22 @@ $(document).ready(function () { var endpoint = $("#put-path").val(); var data = $("#put-data").val(); data = JSON.parse(data); - - var options = { - method:'PUT', - endpoint:endpoint, - body:data - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.PUT(endpoint, data, function (err,usergridResponse) { if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
ERROR: '+output+'
'); + $("#response").html('
ERROR: '+JSON.stringify(err,null,2)+'
'); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
'+output+'
'); + $("#response").html('
'+JSON.stringify(usergridResponse.entity,null,2)+'
'); } }); } function _delete() { var endpoint = $("#delete-path").val(); - - var options = { - method:'DELETE', - endpoint:endpoint - }; - client.request(options, function (err, data) { - //data will contain raw results from API call + client.DELETE(endpoint, function (err,usergridResponse) { if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
ERROR: '+output+'
'); + $("#response").html('
ERROR: '+JSON.stringify(err,null,2)+'
'); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
'+output+'
'); + $("#response").html('
'+JSON.stringify(usergridResponse.entity,null,2)+'
'); } }); } @@ -216,21 +151,12 @@ $(document).ready(function () { function _login() { var username = $("#username").val(); var password = $("#password").val(); - - client.login(username, password, function (err, data) { - //at this point, the user has been logged in succesfully and the OAuth token for the user has been stored - //however, in this example, we don't want to use that token for the rest of the API calls, so we will now - //reset it. In your app, you will most likely not want to do this, as you are effectively logging the user - //out. Our calls work because we are going against the Sandbox app, which has no restrictions on permissions. - client.token = null; //delete the user's token by setting it to null + client.authenticateUser({username:username, password:password}, function (err,usergridResponse,token) { if (err) { - var output = JSON.stringify(data, null, 2); - $("#response").html('
ERROR: '+output+'
'); + $("#response").html('
ERROR: '+JSON.stringify(err,null,2)+'
'); } else { - var output = JSON.stringify(data, null, 2); - $("#response").html('
'+output+'
'); + $("#response").html('
'+JSON.stringify(usergridResponse,null,2)+'
'); } }); } - }); \ No newline at end of file diff --git a/examples/dogs/app.js b/examples/dogs/app.js index 930c175..69565d9 100755 --- a/examples/dogs/app.js +++ b/examples/dogs/app.js @@ -1,194 +1,135 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** -* dogs is a sample app that is powered by Usergrid -* This app shows how to use the Usergrid SDK to connect -* to Usergrid, how to add entities, and how to page through -* a result set of entities -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/** -* @file app.js -* @author Rod Simpson (rod@apigee.com) -* -* This file contains the main program logic for Dogs. -*/ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + $(document).ready(function () { - //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!) - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'dogs', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); - - //make a new "dogs" Collection - var options = { - type:'dogs', - qs:{ql:'order by created DESC'} - } - - var dogs; - - client.createCollection(options, function (err, response, collection) { - if (err) { - $('#mydoglist').html('could not load dogs'); - } else { - dogs=collection; - //bind the next button to the proper method in the collection object - $('#next-button').bind('click', function() { - $('#message').html(''); - dogs.getNextPage(function(err, data){ - if (err) { - alert('could not get next page of dogs'); - } else { - drawDogs(); - } - }); - }); - - //bind the previous button to the proper method in the collection object - $('#previous-button').bind('click', function() { - $('#message').html(''); - dogs.getPreviousPage(function(err, data){ - if (err) { - alert('could not get previous page of dogs'); - } else { - drawDogs(); - } - }); - }); - - //bind the new button to show the "create new dog" form - $('#new-dog-button').bind('click', function() { - $('#dogs-list').hide(); - $('#new-dog').show(); - }); - - //bind the create new dog button - $('#create-dog').bind('click', function() { - newdog(); - }); - - //bind the create new dog button - $('#cancel-create-dog').bind('click', function() { - $('#new-dog').hide(); - $('#dogs-list').show(); - drawDogs(); - }); - - function drawDogs() { - dogs.fetch(function(err, data) { - if(err) { - alert('there was an error getting the dogs'); + + var client = new UsergridClient({orgId: "rwalsh", appId: "jssdktestapp", authMode: UsergridAuthMode.NONE}), + lastResponse, + lastQueryUsed, + previousCursors = []; + + var message = $('#message'), + nextButton = $('#next-button'), + previousButton = $('#previous-button'), + dogsList = $('#dogs-list'), + myDogList = $('#mydoglist'), + newDog = $('#new-dog'), + newDogButton = $('#new-dog-button'), + createDogButton = $('#create-dog'), + cancelCreateDogButton = $('#cancel-create-dog'); + + nextButton.bind('click', function() { + message.html(''); + previousCursors.push(lastQueryUsed._cursor); + lastQueryUsed = new UsergridQuery('dogs').desc('created').cursor(_.get(lastResponse,'responseJSON.cursor')); + lastResponse.loadNextPage(client,function(error,usergridResponse) { + handleGETDogResponse(error,usergridResponse) + }) + }); + + previousButton.bind('click', function() { + message.html(''); + var cursor = previousCursors.pop(); + if( cursor === '' ) { + previousCursors = ''; + cursor = undefined + } + drawDogs(cursor) + }); + + //bind the new button to show the "create new dog" form + newDogButton.bind('click', function() { + dogsList.hide(); + newDog.show(); + }); + + //bind the create new dog button + createDogButton.bind('click', function() { + newdog(); + }); + + //bind the create new dog button + cancelCreateDogButton.bind('click', function() { + newDog.hide(); + dogsList.show(); + drawDogs(); + }); + + function drawDogs(cursor) { + lastQueryUsed = new UsergridQuery('dogs').desc('created'); + if( cursor !== undefined && !_.isEmpty(cursor) ) { + lastQueryUsed.cursor(cursor) + } + client.GET(lastQueryUsed,function(error,usergridResponse) { + handleGETDogResponse(error,usergridResponse) + }); + } + + function handleGETDogResponse(error,usergridResponse) { + lastResponse = usergridResponse; + if(error) { + alert('there was an error getting the dogs'); } else { - //first empty out all the current dogs in the list - $('#mydoglist').empty(); - //then hide the next / previous buttons - $('#next-button').hide(); - $('#previous-button').hide(); - //iterate through all the items in this "page" of data - //make sure we reset the pointer so we start at the beginning - dogs.resetEntityPointer(); - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - //display the dog in the list - $('#mydoglist').append('
  • '+ dog.get('name') + '
  • '); - } - //if there is more data, display a "next" button - if (dogs.hasNextPage()) { - //show the button - $('#next-button').show(); - } - //if there are previous pages, show a "previous" button - if (dogs.hasPreviousPage()) { - //show the button - $('#previous-button').show(); - } + myDogList.empty(); + nextButton.hide(); + previousButton.hide(); + + _.forEach(lastResponse.entities,function(dog) { + myDogList.append('
  • '+ dog.name + '
  • '); + }); + + if (lastResponse.hasNextPage) { + nextButton.show(); + } + if (previousCursors.length > 0) { + previousButton.show(); + } } - }); - } - - function newdog() { - $('#create-dog').addClass("disabled"); - //get the values from the form - var name = $("#name").val(); - - //make turn off all hints and errors - $("#name-help").hide(); - $("#name-control").removeClass('error'); - - //make sure the input was valid - if (Usergrid.validation.validateName(name, function (){ - $("#name").focus(); - $("#name-help").show(); - $("#name-control").addClass('error'); - $("#name-help").html(Usergrid.validation.getNameAllowedChars()); - $('#create-dog').removeClass("disabled");}) - ) { - - //all is well, so make the new dog - //create a new dog and add it to the collection - var options = { - name:name - } - //just pass the options to the addEntity method - //to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - //let the user know there was a problem - alert('Oops! There was an error creating the dog.'); - //enable the button so the form will be ready for next time - $('#create-dog').removeClass("disabled"); - } else { - $('#message').html('New dog created!'); - //the save worked, so hide the new dog form - $('#new-dog').hide(); - //then show the dogs list - $('#dogs-list').show(); - //then call the function to get the list again - drawDogs(); - //finally enable the button so the form will be ready for next time - $('#create-dog').removeClass("disabled"); - } - }); - } - } - drawDogs(); - - } - }); - + } + + function newdog() { + createDogButton.addClass("disabled"); + + var nameInput = $("#name"), + nameHelp = $("#name-help"), + nameControl = $("#name-control"); + + nameHelp.hide(); + nameControl.removeClass('error'); + + if (Usergrid.validation.validateName(nameInput.val(), function (){ + nameInput.focus(); + nameHelp.show(); + nameControl.addClass('error'); + nameHelp.html(Usergrid.validation.getNameAllowedChars()); + createDogButton.removeClass("disabled");}) + ) { + client.POST('dogs',{ name:nameInput.val() }, function(error,usergridResponse) { + if (error) { + alert('Oops! There was an error creating the dog. \n' + JSON.stringify(error,null,2)); + createDogButton.removeClass("disabled"); + } else { + message.html('New dog created!'); + newDog.hide(); + dogsList.show(); + createDogButton.removeClass("disabled"); + previousCursors = []; + drawDogs(); + } + }) + } + } + + drawDogs(); }); diff --git a/examples/dogs/dogs.html b/examples/dogs/dogs.html index 8f92830..4320012 100755 --- a/examples/dogs/dogs.html +++ b/examples/dogs/dogs.html @@ -5,9 +5,9 @@ The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - + http://www.apache.org/licenses/LICENSE-2.0 - + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ - + @@ -32,7 +32,7 @@ App Services (Usergrid) Javascript SDK

    Dogs

    diff --git a/examples/facebook/app.js b/examples/facebook/app.js deleted file mode 100755 index 35b646d..0000000 --- a/examples/facebook/app.js +++ /dev/null @@ -1,129 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** -* dogs is a sample app that is powered by Usergrid -* This app shows how to use the Usergrid SDK to connect -* to Usergrid, how to add entities, and how to page through -* a result set of entities -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/** -* @file app.js -* @author Rod Simpson (rod@apigee.com) -* -* This file contains the main program logic for Facebook Login Example. -*/ -$(document).ready(function () { - //first set the org / app path (must be orgname / appname or org id / app id - can't mix names and uuids!!) - - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); - - //bind the login button so we can send the user to facebook - $('#login-button').bind('click', function() { - //get the - var apiKey = $("#api-key").val(); - var location = window.location.protocol + '//' + window.location.host; - var path = window.location.pathname; - - var link = "https://www.facebook.com/dialog/oauth?client_id="; - link += apiKey; - link += "&redirect_uri="; - link += location+path - link += "&scope&COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES&response_type=token"; - - //now forward the user to facebook - window.location = link; - }); - //bind the previous button to the proper method in the collection object - $('#logout-button').bind('click', function() { - logout(); - }); - - //load up the facebook api sdk - window.fbAsyncInit = function() { - FB.init({ - appId : '308790195893570', // App ID - channelUrl : '//usergridsdk.dev//examples/channel.html', // Channel File - status : true, // check login status - cookie : true, // enable cookies to allow the server to access the session - xfbml : true // parse XFBML - }); - }; - - function logout() { - FB.logout(function(response) { - client.logoutAppUser(); - var html = "User logged out. \r\n\r\n // Press 'Log in' to log in with Facebook."; - $('#facebook-status').html(html); - }); - } - - function login(facebookAccessToken) { - client.loginFacebook(facebookAccessToken, function(err, response){ - var output = JSON.stringify(response, null, 2); - if (err) { - var html = '
    Oops!  There was an error logging you in. \r\n\r\n';
    -        html += 'Error: \r\n' + output+'
    '; - } else { - var html = '
    Hurray!  You have been logged in. \r\n\r\n';
    -        html += 'Facebook Token: ' + '\r\n' + facebookAccessToken + '\r\n\r\n';
    -        html += 'Facebook Profile data stored in Usergrid: \r\n' + output+'
    '; - } - $('#facebook-status').html(html); - }) - } - - //pull the access token out of the query string - var ql = []; - if (window.location.hash) { - // split up the query string and store in an associative array - var params = window.location.hash.slice(1).split("#"); - var tmp = params[0].split("&"); - for (var i = 0; i < tmp.length; i++) { - var vals = tmp[i].split("="); - ql[vals[0]] = unescape(vals[1]); - } - } - - if (ql['access_token']) { - var facebookAccessToken = ql['access_token'] - //try to log in with facebook - login(facebookAccessToken); - } -}); \ No newline at end of file diff --git a/examples/facebook/facebook.html b/examples/facebook/facebook.html deleted file mode 100755 index 2ea8943..0000000 --- a/examples/facebook/facebook.html +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - Facebook Login Example App for Apigee App Services (Usergrid) - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    - -
    - This sample application will show you how to log into App Services (Usergrid) using Facebook and the Usergrid Javascript SDK. - Enter the API Key that you get from Facebook, then log in. -

    - The Log in button sends the user to the facebook login page. Once the user logs in, they are redirected back to - this page and automatically logged into Usergrid. If the user is already logged into facebook, then they don't need to log in again. -

    - Clicking the log out button calls the logout method of the Facebook JS SDK, and also logs the user out of Usergrid by calling the Usergrid logoutAppUser method. -

    - For a step by step walk-thru on how to get this app running, see this guide. -

    - For more information on App Services, see our docs site, specifically or our Facebook docs page. -

    - For more information on how using the Facebook JS SDK to log users in, see this guide: http://developers.facebook.com/docs/howtos/login/getting-started/ -
    -
    -
    Log in with Facebook
    -
    -
    -
    - - -   - - -   -
    -
    -
    -
    API Response
    -
    - // Press 'Log in' to log in with Facebook. -
    -
    -
    - - diff --git a/examples/facebook/guide.html b/examples/facebook/guide.html deleted file mode 100755 index 725dd9a..0000000 --- a/examples/facebook/guide.html +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - To get the Facebook example working on your development machine, follow these steps: -

    - 1. Sign up -
    Sign up for a Facebook account. -

    - 2. Create a new app -
    Go to https://developers.facebook.com and follow - the prompts to authenticate yourself. Then, go to the Facebook App Dashboard, and create a new app. -

    - 3. Specify your Facebook integration method -
    On the app creation page, make sure you specify that you will use "Website with Facebook Login". - You should see something like this. You should enter the url where - you will host this sample (e.g. http://mywebsite.com/path-to-my-code). If want just to test with our gh-pages repo, - located here: http://apigee.github.com/usergrid-javascript-sdk/, - then enter http://apigee.github.com/usergrid-javascript-sdk in the field instead. -

    - 4. Get your App Id -
    Once your app is created, you can get the app id by going here: https://developers.facebook.com/apps -

    - 5. Download this code (skip this step if you plan to run it on our gh-pages repo) -
    If you haven't done so already, download the Usergrid Javascript SDK: https://github.com/apigee/usergrid-javascript-sdk - and save to a local directory on your hard drive. You will then need to deploy the code to your server. -

    - 6. Run the file -
    Navigate your browser to the location where you uploaded your code, or go to our gh-pages repo - ( http://apigee.github.com/usergrid-javascript-sdk/) and choose "Facebook Login Example". -

    - 7. Log in! -
    Enter your API key, and follow the prompts. -
    - - - diff --git a/examples/persistence/test.html b/examples/persistence/test.html deleted file mode 100644 index 3d7c553..0000000 --- a/examples/persistence/test.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Readme File Tests - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - This sample application runs tests to demonstrate how to persist collections using the collection.serialize() method. -
    -
    -
    README sample code tests
    -
    -
    -
    - -   -
    -
    -
    -
    Test Output
    -
    -
    // Press Start button to begin
    -
    - - diff --git a/examples/persistence/test.js b/examples/persistence/test.js deleted file mode 100644 index 352323a..0000000 --- a/examples/persistence/test.js +++ /dev/null @@ -1,130 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -$(document).ready(function () { - -//call the runner function to start the process - $('#start-button').bind('click', function() { - $('#start-button').attr("disabled", "disabled"); - $('#test-output').html(''); - runner(0); - }); - - var logSuccess = true; - var successCount = 0; - var logError = true; - var errorCount = 0; - var logNotice = true; - - var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); - - function runner(step, arg, arg2){ - step++; - switch(step) - { - case 1: - notice('-----running step '+step+': create and serialize collection'); - createAndSerialzeCollection(step); - break; - case 2: - notice('-----running step '+step+': de-serialize collection'); - deserializeCollection(step); - break; - default: - notice('-----test complete!-----'); - notice('Success count= ' + successCount); - notice('Error count= ' + errorCount); - notice('-----thank you for playing!-----'); - $('#start-button').removeAttr("disabled"); - } - } - -//logging functions - function success(message){ - successCount++; - if (logSuccess) { - console.log('SUCCESS: ' + message); - var html = $('#test-output').html(); - html += ('SUCCESS: ' + message + '\r\n'); - $('#test-output').html(html); - } - } - - function error(message){ - errorCount++ - if (logError) { - console.log('ERROR: ' + message); - var html = $('#test-output').html(); - html += ('ERROR: ' + message + '\r\n'); - $('#test-output').html(html); - } - } - - function notice(message){ - if (logNotice) { - console.log('NOTICE: ' + message); - var html = $('#test-output').html(); - html += (message + '\r\n'); - $('#test-output').html(html); - } - } - - - function createAndSerialzeCollection(step){ - var options = { - type:'books', - qs:{ql:'order by name'} - } - - client.createCollection(options, function (err, books) { - if (err) { - error('could not make collection'); - } else { - - //collection made, now serialize and store - localStorage.setItem('item', books.serialize()); - - success('new Collection created and data stored'); - - runner(step); - - } - }); - } - - - function deserializeCollection(step){ - var books = client.restoreCollection(localStorage.getItem('item')); - - while(books.hasNextEntity()) { - //get a reference to the book - book = books.getNextEntity(); - var name = book.get('name'); - notice('book is called ' + name); - } - - success('looped through books'); - - runner(step); - } - -}); \ No newline at end of file diff --git a/examples/resources/css/styles.css b/examples/resources/css/styles.css index 7492f93..0095631 100755 --- a/examples/resources/css/styles.css +++ b/examples/resources/css/styles.css @@ -1,12 +1,4 @@ /** -* All Calls is a Node.js sample app that is powered by Usergrid -* This app shows how to make the 4 REST calls (GET, POST, -* PUT, DELETE) against the usergrid API. -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/examples/resources/js/json2.js b/examples/resources/js/json2.js deleted file mode 100755 index c7745df..0000000 --- a/examples/resources/js/json2.js +++ /dev/null @@ -1,486 +0,0 @@ -/* - json2.js - 2012-10-08 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, regexp: true */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (typeof JSON !== 'object') { - JSON = {}; -} - -(function () { - 'use strict'; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function (key) { - - return isFinite(this.valueOf()) - ? this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' - : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' - ? c - : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 - ? '[]' - : gap - ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' - : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 - ? '{}' - : gap - ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' - : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof JSON.stringify !== 'function') { - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof JSON.parse !== 'function') { - JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' - ? walk({'': j}, '') - : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); diff --git a/extensions/usergrid.validation.js b/examples/resources/js/usergrid.validation.js similarity index 100% rename from extensions/usergrid.validation.js rename to examples/resources/js/usergrid.validation.js diff --git a/examples/test/test.html b/examples/test/test.html deleted file mode 100755 index e66fcb3..0000000 --- a/examples/test/test.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Readme File Tests - - - - - - - - - -
    - App Services (Usergrid) Javascript SDK -
    -
    - This sample application runs tests on the sample code examples in the readme file. Tests are run against App Services (Usergrid) using the Usergrid Javascript SDK. -
    -
    -
    README sample code tests
    -
    -
    -
    - -   -
    -
    -
    -
    Test Output
    -
    -
    // Press Start button to begin
    -
    - - diff --git a/examples/test/test.js b/examples/test/test.js deleted file mode 100755 index fb65d98..0000000 --- a/examples/test/test.js +++ /dev/null @@ -1,978 +0,0 @@ -/** -* Test suite for all the examples in the readme -* -* NOTE: No, this test suite doesn't use the traditional format for -* a test suite. This is because the goal is to require as little -* alteration as possible during the copy / paste operation from this test -* suite to the readme file. -* -* @author rod simpson (rod@apigee.com) -*/ - -$(document).ready(function () { - -//call the runner function to start the process -$('#start-button').bind('click', function() { - $('#start-button').attr("disabled", "disabled"); - $('#test-output').html(''); - runner(0); -}); - -var logSuccess = true; -var successCount = 0; -var logError = true; -var errorCount = 0; -var logNotice = true; -var _unique = new Date().getTime(); -var _username = 'marty'+_unique; -var _email = 'marty'+_unique+'@timetravel.com'; -var _password = 'password2'; -var _newpassword = 'password3'; - -var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default -}); - -client.logout(); - -function runner(step, arg, arg2){ - step++; - switch(step) - { - case 1: - notice('-----running step '+step+': DELETE user from DB to prep test'); - clearUser(step); - break; - case 2: - notice('-----running step '+step+': GET test'); - testGET(step); - break; - case 3: - notice('-----running step '+step+': POST test'); - testPOST(step); - break; - case 4: - notice('-----running step '+step+': PUT test'); - testPUT(step); - break; - case 5: - notice('-----running step '+step+': DELETE test'); - testDELETE(step); - break; - case 6: - notice('-----running step '+step+': prepare database - remove all dogs (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 7: - notice('-----running step '+step+': make a new dog'); - makeNewDog(step); - break; - case 8: - notice('-----running step '+step+': update our dog'); - updateDog(step, arg); - break; - case 9: - notice('-----running step '+step+': refresh our dog'); - refreshDog(step, arg); - break; - case 10: - notice('-----running step '+step+': remove our dog from database (no real dogs harmed here!!)'); - removeDogFromDatabase(step, arg); - break; - case 11: - notice('-----running step '+step+': make lots of dogs!'); - makeSampleData(step, arg); - break; - case 12: - notice('-----running step '+step+': make a dogs collection and show each dog'); - testDogsCollection(step); - break; - case 13: - notice('-----running step '+step+': get the next page of the dogs collection and show each dog'); - getNextDogsPage(step, arg); - break; - case 14: - notice('-----running step '+step+': get the previous page of the dogs collection and show each dog'); - getPreviousDogsPage(step, arg); - break; - case 15: - notice('-----running step '+step+': remove all dogs from the database (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 16: - notice('-----running step '+step+': prepare database (remove existing user if present)'); - prepareDatabaseForNewUser(step); - break; - case 17: - notice('-----running step '+step+': create a new user'); - createUser(step); - break; - case 18: - notice('-----running step '+step+': update the user'); - updateUser(step, arg); - break; - case 19: - notice('-----running step '+step+': get the existing user'); - getExistingUser(step, arg); - break; - case 20: - notice('-----running step '+step+': refresh the user from the database'); - refreshUser(step, arg); - break; - case 21: - notice('-----running step '+step+': log user in'); - loginUser(step, arg); - break; - case 22: - notice('-----running step '+step+': change users password'); - changeUsersPassword(step, arg); - break; - case 23: - notice('-----running step '+step+': log user out'); - logoutUser(step, arg); - break; - case 24: - notice('-----running step '+step+': relogin user'); - reloginUser(step, arg); - break; - case 25: - notice('-----running step '+step+': logged in user creates dog'); - createDog(step, arg); - break; - case 26: - notice('-----running step '+step+': logged in user likes dog'); - userLikesDog(step, arg, arg2); - break; - case 27: - notice('-----running step '+step+': logged in user removes likes connection to dog'); - removeUserLikesDog(step, arg, arg2); - break; - case 28: - notice('-----running step '+step+': user removes dog'); - removeDog(step, arg, arg2); - break; - case 29: - notice('-----running step '+step+': log the user out'); - logoutUser(step, arg); - break; - case 30: - notice('-----running step '+step+': remove the user from the database'); - destroyUser(step, arg); - break; - case 31: - notice('-----running step '+step+': try to create existing entity'); - createExistingEntity(step, arg); - break; - case 32: - notice('-----running step '+step+': try to create new entity with no name'); - createNewEntityNoName(step, arg); - break; - case 33: - notice('-----running step '+step+': clean up users'); - cleanUpUsers(step, arg); - break; - case 34: - notice('-----running step '+step+': clean up dogs'); - cleanUpDogs(step, arg); - break; - default: - notice('-----test complete!-----'); - notice('Success count= ' + successCount); - notice('Error count= ' + errorCount); - notice('-----thank you for playing!-----'); - $('#start-button').removeAttr("disabled"); - } -} - -//logging functions -function success(message){ - successCount++; - if (logSuccess) { - console.log('SUCCESS: ' + message); - var html = $('#test-output').html(); - html += ('SUCCESS: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function error(message){ - errorCount++ - if (logError) { - console.log('ERROR: ' + message); - var html = $('#test-output').html(); - html += ('ERROR: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function notice(message){ - if (logNotice) { - console.log('NOTICE: ' + message); - var html = $('#test-output').html(); - html += (message + '\r\n'); - $('#test-output').html(html); - } -} - -//tests -function clearUser(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - //data will contain raw results from API call - success('User cleared from DB'); - runner(step); - }); -} - -function testGET(step) { - var options = { - method:'GET', - endpoint:'users' - }; - client.request(options, function (err, data) { - if (err) { - error('GET failed'); - } else { - //data will contain raw results from API call - success('GET worked'); - runner(step); - } - }); -} - -function testPOST(step) { - var options = { - method:'POST', - endpoint:'users', - body:{ username:'fred', password:'secret' } - }; - client.request(options, function (err, data) { - if (err) { - error('POST failed'); - } else { - //data will contain raw results from API call - success('POST worked'); - runner(step); - } - }); -} - -function testPUT(step) { - var options = { - method:'PUT', - endpoint:'users/fred', - body:{ newkey:'newvalue' } - }; - client.request(options, function (err, data) { - if (err) { - error('PUT failed'); - } else { - //data will contain raw results from API call - success('PUT worked'); - runner(step); - } - }); -} - -function testDELETE(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - if (err) { - error('DELETE failed'); - } else { - //data will contain raw results from API call - success('DELETE worked'); - runner(step); - } - }); -} - -function makeNewDog(step) { - - var options = { - type:'dogs', - name:'Ralph'+_unique - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('dog not created'); - } else { - success('dog is created'); - - //once the dog is created, you can set single properties: - dog.set('breed','Dinosaur'); - - //the set function can also take a JSON object: - var data = { - master:'Fred', - state:'hungry' - } - //set is additive, so previously set properties are not overwritten - dog.set(data); - - //finally, call save on the object to save it back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('new dog is saved'); - runner(step, dog); - } - }); - } - }); - -} - -function updateDog(step, dog) { - - //change a property in the object - dog.set("state", "fed"); - //and save back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('dog is saved'); - runner(step, dog); - } - }); - -} - -function refreshDog(step, dog){ - - //call fetch to refresh the data from the server - dog.fetch(function(err){ - if (err){ - error('dog not refreshed from database'); - } else { - //dog has been refreshed from the database - //will only work if the UUID for the entity is in the dog object - success('dog entity refreshed from database'); - runner(step, dog); - } - }); - -} - -function removeDogFromDatabase(step, dog){ - - //the destroy method will delete the entity from the database - dog.destroy(function(err){ - if (err){ - error('dog not removed from database'); - } else { - success('dog removed from database'); // no real dogs were harmed! - dog = null; //no real dogs were harmed! - runner(step, 1); - } - }); - -} - -function makeSampleData(step, i) { - notice('making dog '+i); - - var options = { - type:'dogs', - name:'dog'+_unique+i, - index:i - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('dog ' + i + ' not created'); - } else { - if (i >= 30) { - //data made, ready to go - success('all dogs made'); - runner(step); - } else { - success('dog ' + i + ' made'); - //keep making dogs - makeSampleData(step, ++i); - } - } - }); -} - -function testDogsCollection(step) { - - var options = { - type:'dogs', - qs:{ql:'order by index'} - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not make collection'); - } else { - - success('new Collection created'); - - //we got the dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - - success('looped through dogs'); - - //create a new dog and add it to the collection - var options = { - name:'extra-dog', - fur:'shedding' - } - //just pass the options to the addEntity method - //to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - error('extra dog not saved or added to collection'); - } else { - success('extra dog saved and added to collection'); - runner(step, dogs); - } - }); - } - }); - -} - -function getNextDogsPage(step, dogs) { - - if (dogs.hasNextPage()) { - //there is a next page, so get it from the server - dogs.getNextPage(function(err){ - if (err) { - error('could not get next page of dogs'); - } else { - success('got next page of dogs'); - //we got the next page of data, so do something with it: - var i = 11; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs') - runner(step, dogs); - } - }); - } else { - getPreviousDogsPage(dogs); - } - -} - -function getPreviousDogsPage(step, dogs) { - - if (dogs.hasPreviousPage()) { - //there is a previous page, so get it from the server - dogs.getPreviousPage(function(err){ - if(err) { - error('could not get previous page of dogs'); - } else { - success('got next page of dogs'); - //we got the previous page of data, so do something with it: - var i = 1; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs'); - runner(step); - } - }); - } else { - getAllDogs(); - } -} - -function cleanupAllDogs(step){ - - var options = { - type:'dogs', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not get all dogs'); - } else { - success('got at most 50 dogs'); - //we got 50 dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - dogs.resetEntityPointer(); - //do doggy cleanup - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } - - //no need to wait around for dogs to be removed, so go on to next test - runner(step); - } - }); -} - - -function prepareDatabaseForNewUser(step) { - var options = { - method:'DELETE', - endpoint:'users/', - qs:{ql:"select * where username ='marty*'"} - }; - client.request(options, function (err, data) { - if (err) { - notice('database ready - no user to delete'); - runner(step); - } else { - //data will contain raw results from API call - success('database ready - user deleted worked'); - runner(step); - } - }); -} - -function createUser(step) { - client.signup(_username, _password, _email, 'Marty McFly', - function (err, response, marty) { - if (err){ - error('user not created'); - runner(step, marty); - } else { - success('user created'); - runner(step, marty); - } - } - ); -} - -function updateUser(step, marty) { - - //add properties cumulatively - marty.set('state', 'California'); - marty.set("girlfriend","Jennifer"); - marty.save(function(err){ - if (err){ - error('user not updated'); - } else { - success('user updated'); - runner(step, marty); - } - }); - -} - -function getExistingUser(step, marty) { - - var options = { - type:'users', - username:_username - } - client.getEntity(options, function(err, response, existingUser){ - if (err){ - error('existing user not retrieved'); - } else { - success('existing user was retrieved'); - - var username = existingUser.get('username'); - if (username === _username){ - success('got existing user username'); - } else { - error('could not get existing user username'); - } - runner(step, marty); - } - }); - -} - - -function refreshUser(step, marty) { - - marty.fetch(function(err){ - if (err){ - error('not refreshed'); - } else { - success('user refreshed'); - runner(step, marty); - } - }); - -} - -function loginUser(step, marty) { - username = _username; - password = _password; - client.login(username, password, - function (err, response, user) { - if (err) { - error('could not log user in'); - } else { - success('user has been logged in'); - - //the login call will return an OAuth token, which is saved - //in the client. Any calls made now will use the token. - //once a user has logged in, their user object is stored - //in the client and you can access it this way: - var token = client.token; - - //Then make calls against the API. For example, you can - //get the user entity this way: - client.getLoggedInUser(function(err, data, user) { - console.error(err, data, user); - if(err) { - error('could not get logged in user'); - } else { - success('got logged in user'); - - //you can then get info from the user entity object: - var username = user.get('username'); - notice('logged in user was: ' + username); - - runner(step, user); - } - }); - - } - } - ); -} - -function changeUsersPassword(step, marty) { - - marty.set('oldpassword', _password); - marty.set('password', _newpassword); - marty.set('newpassword', _newpassword); - marty.changePassword(function(err, response){ - if (err){ - error('user password not updated'); - } else { - success('user password updated'); - runner(step, marty); - } - }); - -} - -function logoutUser(step, marty) { - - //to log the user out, call the logout() method - client.logout(); - - //verify the logout worked - if (client.isLoggedIn()) { - error('logout failed'); - } else { - success('user has been logged out'); - } - - runner(step, marty); -} - -function reloginUser(step, marty) { - - username = _username - password = _newpassword; - client.login(username, password, - function (err, response, marty) { - if (err) { - error('could not relog user in'); - } else { - success('user has been re-logged in'); - runner(step, marty); - } - } - ); -} - - - -//TODO: currently, this code assumes permissions have been set to support user actions. need to add code to show how to add new role and permission programatically -// -//first create a new permission on the default role: -//POST "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions" -d '{"permission":"get,post,put,delete:/dogs/**"}' -//then after user actions, delete the permission on the default role: -//DELETE "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions?permission=get%2Cpost%2Cput%2Cdelete%3A%2Fdogs%2F**" - - -function createDog(step, marty) { - - var options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('POST new dog by logged in user failed'); - } else { - success('POST new dog by logged in user succeeded'); - runner(step, marty, dog); - } - }); - -} - -function userLikesDog(step, marty, dog) { - - marty.connect('likes', dog, function (err, response, data) { - if (err) { - error('connection not created'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, response, data) { - if (err) { - error('could not get connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - success('connection exists'); - } else { - error('connection does not exist'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeUserLikesDog(step, marty, dog) { - - marty.disconnect('likes', dog, function (err, data) { - if (err) { - error('connection not deleted'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, data) { - if (err) { - error('error getting connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - error('connection still exists'); - } else { - success('connection deleted'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeDog(step, marty, dog) { - - //now delete the dog from the database - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - runner(step, marty); -} - -function destroyUser(step, marty) { - - marty.destroy(function(err){ - if (err){ - error('user not deleted from database'); - } else { - success('user deleted from database'); - marty = null; //blow away the local object - runner(step); - } - }); - -} - -function createExistingEntity(step, marty) { - - var options = { - type:'dogs', - name:'einstein' - } - - client.createEntity(options, function (err, response, dog) { - if (err) { - error('Create new entity to use for existing entity failed'); - } else { - success('Create new entity to use for existing entity succeeded'); - - var uuid = dog.get('uuid'); - //now create new entity, but use same entity name of einstein. This means that - //the original einstein entity now exists. Thus, the new einstein entity should - //be the same as the original + any data differences from the options var: - - options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - client.createEntity(options, function (err, response, newdog) { - if (err) { - success('Create new entity to use for existing entity failed'); - } else { - error('Create new entity to use for existing entity succeeded'); - } - dog.destroy(function(err){ - if (err){ - error('existing entity not deleted from database'); - } else { - success('existing entity deleted from database'); - dog = null; //blow away the local object - newdog = null; //blow away the local object - runner(step); - } - }); - }); - } - }); - -} - -function createNewEntityNoName(step, marty) { - - var options = { - type:"something", - othervalue:"something else" - } - - client.createEntity(options, function (err, response, entity) { - if (err) { - error('Create new entity with no name failed'); - } else { - success('Create new entity with no name succeeded'); - - entity.destroy(); - runner(step); - } - }); - -} - -function cleanUpUsers(step){ - - var options = { - type:'users', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, users) { - if (err) { - error('could not get all users'); - } else { - success('got users'); - //do doggy cleanup - while(users.hasNextEntity()) { - //get a reference to the dog - var user = users.getNextEntity(); - var username = user.get('name'); - notice('removing dog ' + username + ' from database'); - user.destroy(function(err, data) { - if (err) { - error('user not removed'); - } else { - success('user removed'); - } - }); - } - - runner(step); - } - }); - -} - -function cleanUpDogs(step){ - - var options = { - type:'dogs', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, response, dogs) { - if (err) { - error('could not get all dogs'); - } else { - success('got at most 50 dogs'); - //we got 50 dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - dogs.resetEntityPointer(); - //do doggy cleanup - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } - - //no need to wait around for dogs to be removed, so go on to next test - runner(step); - } - }); - } -}); diff --git a/index.html b/index.html index 309d90b..627f879 100755 --- a/index.html +++ b/index.html @@ -35,7 +35,7 @@

    Javascript SDK


    Read me

    View the read me file for the SDK: - https://github.com/usergrid/usergrid/blob/master/sdks/html5-javascript/README.md. + https://github.com/apache/usergrid-javascript/README.md.

    API documentation

    @@ -44,26 +44,23 @@

    API documentation



    -

    Example Apps:

    +

    Tests:


    - All Calls example app + Mocha Tests
    - This app shows the basic method for making all call types against the API. It also shows how to log in an app user. + This is a test script that runs all of the Mocha test cases written for the Javascript SDK.

    - Dogs example app +

    Examples:


    - This app shows you how to use the Entity and Collection objects + User Example
    + This example shows the basic methods for making all REST calls against the API for creating, editing and logging in a new UsergridUser.
    - Facebook Login Example
    - This app shows you how to use Facebook to log into Usergrid. + Dogs Example
    -
    - Tests for examples in readme file -
    - This is a test script that runs all the sample code shown in the readme file. See the samples in action! + This example shows you how to POST UsergridEntity objects and page through responses.
    diff --git a/lib/Module.js b/lib/Module.js deleted file mode 100644 index 38f5047..0000000 --- a/lib/Module.js +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - //noinspection ThisExpressionReferencesGlobalObjectJS -(function (global) { - var name = 'Module', - short = '_m', - _name = global[name], - _short = (short !== undefined) ? global[short] : undefined; - - function Module() { - /* put code in here */ - - } - - global[name] = Module; - if (short !== undefined) { - global[short] = Module; - } - global[name].global[name].noConflict = function () { - if (_name) { - global[name] = _name; - } - if (short !== undefined) { - global[short] = _short; - } - return Module; - }; - if( typeof module !== "undefined" && ('exports' in module)){ - module.exports = global[name] - } - return global[name]; -}(this)); diff --git a/lib/Usergrid.js b/lib/Usergrid.js index f1bb218..819c1b9 100644 --- a/lib/Usergrid.js +++ b/lib/Usergrid.js @@ -17,307 +17,27 @@ * under the License. */ -//Hack around IE console.log -window.console = window.console || {}; -window.console.log = window.console.log || function() {}; - - -function extend(subClass, superClass) { - var F = function() {}; - F.prototype = superClass.prototype; - subClass.prototype = new F(); - subClass.prototype.constructor = subClass; - - subClass.superclass = superClass.prototype; - if (superClass.prototype.constructor == Object.prototype.constructor) { - superClass.prototype.constructor = superClass; - } - return subClass; -} - -function propCopy(from, to) { - for (var prop in from) { - if (from.hasOwnProperty(prop)) { - if ("object" === typeof from[prop] && "object" === typeof to[prop]) { - to[prop] = propCopy(from[prop], to[prop]); - } else { - to[prop] = from[prop]; - } - } - } - return to; -} - -function NOOP() {} - -function isValidUrl(url) { - if (!url) return false; - var doc, base, anchor, isValid = false; - try { - doc = document.implementation.createHTMLDocument(''); - base = doc.createElement('base'); - base.href = base || window.lo; - doc.head.appendChild(base); - anchor = doc.createElement('a'); - anchor.href = url; - doc.body.appendChild(anchor); - isValid = !(anchor.href === '') - } catch (e) { - console.error(e); - } finally { - doc.head.removeChild(base); - doc.body.removeChild(anchor); - base = null; - anchor = null; - doc = null; - return isValid; - } -} - -/* - * Tests if the string is a uuid - * - * @public - * @method isUUID - * @param {string} uuid The string to test - * @returns {Boolean} true if string is uuid - */ -var uuidValueRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; - -function isUUID(uuid) { - return (!uuid) ? false : uuidValueRegex.test(uuid); -} - -/* - * method to encode the query string parameters - * - * @method encodeParams - * @public - * @params {object} params - an object of name value pairs that will be urlencoded - * @return {string} Returns the encoded string - */ -function encodeParams(params) { - var queryString; - if (params && Object.keys(params)) { - queryString = [].slice.call(arguments) - .reduce(function(a, b) { - return a.concat((b instanceof Array) ? b : [b]); - }, []) - .filter(function(c) { - return "object" === typeof c - }) - .reduce(function(p, c) { - (!(c instanceof Array)) ? p = p.concat(Object.keys(c).map(function(key) { - return [key, c[key]] - })) : p.push(c); - return p; - }, []) - .reduce(function(p, c) { - ((c.length === 2) ? p.push(c) : p = p.concat(c)); - return p; - }, []) - .reduce(function(p, c) { - (c[1] instanceof Array) ? c[1].forEach(function(v) { - p.push([c[0], v]) - }) : p.push(c); - return p; - }, []) - .map(function(c) { - c[1] = encodeURIComponent(c[1]); - return c.join('=') - }) - .join('&'); - } - return queryString; -} - - -/* - * method to determine whether or not the passed variable is a function - * - * @method isFunction - * @public - * @params {any} f - any variable - * @return {boolean} Returns true or false - */ -function isFunction(f) { - return (f && f !== null && typeof(f) === 'function'); -} - -/* - * a safe wrapper for executing a callback - * - * @method doCallback - * @public - * @params {Function} callback - the passed-in callback method - * @params {Array} params - an array of arguments to pass to the callback - * @params {Object} context - an optional calling context for the callback - * @return Returns whatever would be returned by the callback. or false. - */ -function doCallback(callback, params, context) { - var returnValue; - if (isFunction(callback)) { - if (!params) params = []; - if (!context) context = this; - params.push(context); - //try { - returnValue = callback.apply(context, params); - /*} catch (ex) { - if (console && console.error) { - console.error("Callback error:", ex); - } - }*/ - } - return returnValue; -} - -//noinspection ThisExpressionReferencesGlobalObjectJS -(function(global) { - var name = 'Usergrid', - overwrittenName = global[name]; - var VALID_REQUEST_METHODS = ['GET', 'POST', 'PUT', 'DELETE']; - - function Usergrid() { - this.logger = new Logger(name); - } - - Usergrid.isValidEndpoint = function(endpoint) { - //TODO actually implement this - return true; - }; - - Usergrid.Request = function(method, endpoint, query_params, data, callback) { - var p = new Promise(); - /* - Create a logger - */ - this.logger = new global.Logger("Usergrid.Request"); - this.logger.time("process request " + method + " " + endpoint); - /* - Validate our input - */ - this.endpoint = endpoint + '?' + encodeParams(query_params); - this.method = method.toUpperCase(); - //this.query_params = query_params; - this.data = ("object" === typeof data) ? JSON.stringify(data) : data; - - if (VALID_REQUEST_METHODS.indexOf(this.method) === -1) { - throw new UsergridInvalidHTTPMethodError("invalid request method '" + this.method + "'"); - } - - /* - Prepare our request - */ - if (!isValidUrl(this.endpoint)) { - this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint)); - throw new UsergridInvalidURIError("The provided endpoint is not valid: " + this.endpoint); - } - /* a callback to make the request */ - var request = function() { - return Ajax.request(this.method, this.endpoint, this.data) - }.bind(this); - /* a callback to process the response */ - var response = function(err, request) { - return new Usergrid.Response(err, request) - }.bind(this); - /* a callback to clean up and return data to the client */ - var oncomplete = function(err, response) { - p.done(err, response); - this.logger.info("REQUEST", err, response); - doCallback(callback, [err, response]); - this.logger.timeEnd("process request " + method + " " + endpoint); - }.bind(this); - /* and a promise to chain them all together */ - Promise.chain([request, response]).then(oncomplete); - - return p; - }; - //TODO more granular handling of statusCodes - Usergrid.Response = function(err, response) { - var p = new Promise(); - var data = null; - try { - data = JSON.parse(response.responseText); - } catch (e) { - //this.logger.error("Error parsing response text: ",this.text); - //this.logger.error("Caught error ", e.message); - data = {} - } - Object.keys(data).forEach(function(key) { - Object.defineProperty(this, key, { - value: data[key], - enumerable: true - }); - }.bind(this)); - Object.defineProperty(this, "logger", { - enumerable: false, - configurable: false, - writable: false, - value: new global.Logger(name) - }); - Object.defineProperty(this, "success", { - enumerable: false, - configurable: false, - writable: true, - value: true - }); - Object.defineProperty(this, "err", { - enumerable: false, - configurable: false, - writable: true, - value: err - }); - Object.defineProperty(this, "status", { - enumerable: false, - configurable: false, - writable: true, - value: parseInt(response.status) - }); - Object.defineProperty(this, "statusGroup", { - enumerable: false, - configurable: false, - writable: true, - value: (this.status - this.status % 100) - }); - switch (this.statusGroup) { - case 200: //success - this.success = true; - break; - case 400: //user error - case 500: //server error - case 300: //cache and redirects - case 100: //upgrade - default: - //server error - this.success = false; - break; - } - if (this.success) { - p.done(null, this); - } else { - p.done(UsergridError.fromResponse(data), this); - } - return p; - }; - Usergrid.Response.prototype.getEntities = function() { - var entities; - if (this.success) { - entities = (this.data) ? this.data.entities : this.entities; - } - return entities || []; - } - Usergrid.Response.prototype.getEntity = function() { - var entities = this.getEntities(); - return entities[0]; - } - Usergrid.VERSION = Usergrid.USERGRID_SDK_VERSION = '0.11.0'; - - global[name] = Usergrid; - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; - } - return Usergrid; - }; - return global[name]; -}(this)); +"use strict"; + +var UsergridSDKVersion = "2.0.0"; + +var UsergridClientSharedInstance = function() { + var self = this; + self.isInitialized = false; + self.isSharedInstance = true; + return self; +}; +UsergridHelpers.inherits(UsergridClientSharedInstance, UsergridClient); + +var Usergrid = new UsergridClientSharedInstance(); +Usergrid.initSharedInstance = function(options) { + if (Usergrid.isInitialized) { + console.log("Usergrid shared instance is already initialized"); + } else { + _.assign(Usergrid, new UsergridClient(options)); + Usergrid.isInitialized = true; + Usergrid.isSharedInstance = true; + } + return Usergrid; +}; +Usergrid.init = Usergrid.initSharedInstance; diff --git a/lib/modules/Asset.js b/lib/modules/Asset.js deleted file mode 100644 index 862313a..0000000 --- a/lib/modules/Asset.js +++ /dev/null @@ -1,248 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ - - - -/* - * XMLHttpRequest.prototype.sendAsBinary polyfill - * from: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary() - * - * @method sendAsBinary - * @param {string} sData - */ -if (!XMLHttpRequest.prototype.sendAsBinary) { - XMLHttpRequest.prototype.sendAsBinary = function(sData) { - var nBytes = sData.length, - ui8Data = new Uint8Array(nBytes); - for (var nIdx = 0; nIdx < nBytes; nIdx++) { - ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff; - } - this.send(ui8Data); - }; -} - - -/* - * A class to model a Usergrid asset. - * - * @constructor - * @param {object} options {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" } - * @returns {callback} callback(err, asset) - */ -Usergrid.Asset = function(options, callback) { - var self = this, - messages = []; - self._client = options.client; - self._data = options.data || {}; - self._data.type = "assets"; - var missingData = ["name", "owner", "path"].some(function(required) { - return !(required in self._data); - }); - if (missingData) { - doCallback(callback, [new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."), null, self], self); - } else { - self.save(function(err, data) { - if (err) { - doCallback(callback, [new UsergridError(data), data, self], self); - } else { - if (data && data.entities && data.entities.length) { - self.set(data.entities[0]); - } - doCallback(callback, [null, data, self], self); - } - }); - } -}; - -/* - * Inherit from Usergrid.Entity. - */ -Usergrid.Asset.prototype = new Usergrid.Entity(); - -/* - * Add an asset to a folder. - * - * @method connect - * @public - * @param {object} options {folder:"F01DE600-0000-0000-0000-000000000000"} - * @returns {callback} callback(err, asset) - */ - -Usergrid.Asset.prototype.addToFolder = function(options, callback) { - var self = this, - error = null; - if (('folder' in options) && isUUID(options.folder)) { - //we got a valid UUID - var folder = Usergrid.Folder({ - uuid: options.folder - }, function(err, folder) { - if (err) { - doCallback(callback, [UsergridError.fromResponse(folder), folder, self], self); - } else { - var endpoint = ["folders", folder.get("uuid"), "assets", self.get("uuid")].join('/'); - var options = { - method: 'POST', - endpoint: endpoint - }; - this._client.request(options, function(err, response) { - if (err) { - doCallback(callback, [UsergridError.fromResponse(folder), response, self], self); - } else { - doCallback(callback, [null, folder, self], self); - } - - - }); - } - }); - } else { - doCallback(callback, [new UsergridError('folder not specified'), null, self], self); - } -}; - -Usergrid.Entity.prototype.attachAsset = function (file, callback) { - - if (!(window.File && window.FileReader && window.FileList && window.Blob)) { - doCallback(callback, [ new UsergridError("The File APIs are not fully supported by your browser."), null, this ], this); - return; - } - var self = this; - var args = arguments; - var type = this._data.type; - var attempts = self.get("attempts"); - if (isNaN(attempts)) { - attempts = 3; - } - - if(type != 'assets' && type != 'asset') { - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); - } else { - self.set("content-type", file.type); - self.set("size", file.size); - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); - } - - var xhr = new XMLHttpRequest(); - xhr.open("POST", endpoint, true); - xhr.onerror = function(err) { - doCallback(callback, [ new UsergridError("The File APIs are not fully supported by your browser.") ], xhr, self); - }; - xhr.onload = function(ev) { - if (xhr.status >= 500 && attempts > 0) { - self.set("attempts", --attempts); - setTimeout(function() { - self.attachAsset.apply(self, args); - }, 100); - } else if (xhr.status >= 300) { - self.set("attempts"); - doCallback(callback, [ new UsergridError(JSON.parse(xhr.responseText)), xhr, self ], self); - } else { - self.set("attempts"); - self.fetch(); - doCallback(callback, [ null, xhr, self ], self); - } - }; - var fr = new FileReader(); - fr.onload = function() { - var binary = fr.result; - if (type === 'assets' || type === 'asset') { - xhr.overrideMimeType("application/octet-stream"); - xhr.setRequestHeader("Content-Type", "application/octet-stream"); - } - xhr.sendAsBinary(binary); - }; - fr.readAsBinaryString(file); - -}; - -/* - * Upload Asset data - * - * @method upload - * @public - * @param {object} data Can be a javascript Blob or File object - * @returns {callback} callback(err, asset) - */ -Usergrid.Asset.prototype.upload = function(data, callback) { - this.attachAsset(data, function(err, response) { - if(!err){ - doCallback(callback, [ null, response, self ], self); - } else { - doCallback(callback, [ new UsergridError(err), response, self ], self); - } - }); -}; - -/* - * Download Asset data - * - * @method download - * @public - * @returns {callback} callback(err, blob) blob is a javascript Blob object. - */ -Usergrid.Entity.prototype.downloadAsset = function(callback) { - var self = this; - var endpoint; - var type = this._data.type; - - var xhr = new XMLHttpRequest(); - if(type != "assets" && type != 'asset') { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); - } else { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); - } - xhr.open("GET", endpoint, true); - xhr.responseType = "blob"; - xhr.onload = function(ev) { - var blob = xhr.response; - if(type != "assets" && type != 'asset') { - doCallback(callback, [ null, blob, xhr ], self); - } else { - doCallback(callback, [ null, xhr, self ], self); - } - }; - xhr.onerror = function(err) { - callback(true, err); - doCallback(callback, [ new UsergridError(err), xhr, self ], self); - }; - - if(type != "assets" && type != 'asset') { - xhr.setRequestHeader("Accept", self._data["file-metadata"]["content-type"]); - } else { - xhr.overrideMimeType(self.get("content-type")); - } - xhr.send(); -}; - -/* - * Download Asset data - * - * @method download - * @public - * @returns {callback} callback(err, blob) blob is a javascript Blob object. - */ -Usergrid.Asset.prototype.download = function(callback) { - this.downloadAsset(function(err, response) { - if(!err){ - doCallback(callback, [ null, response, self ], self); - } else { - doCallback(callback, [ new UsergridError(err), response, self ], self); - } - }); -}; \ No newline at end of file diff --git a/lib/modules/Client.js b/lib/modules/Client.js deleted file mode 100644 index e27ae65..0000000 --- a/lib/modules/Client.js +++ /dev/null @@ -1,883 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -(function() { - var name = 'Client', - global = this, - overwrittenName = global[name], - exports; - var AUTH_ERRORS = [ - "auth_expired_session_token", - "auth_missing_credentials", - "auth_unverified_oath", - "expired_token", - "unauthorized", - "auth_invalid" - ]; - Usergrid.Client = function(options) { - //usergrid endpoint - this.URI = options.URI || 'https://api.usergrid.com'; - - //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid) - if (options.orgName) { - this.set('orgName', options.orgName); - } - if (options.appName) { - this.set('appName', options.appName); - } - if (options.qs) { - this.setObject('default_qs', options.qs); - } - //other options - this.buildCurl = options.buildCurl || false; - this.logging = options.logging || false; - - //timeout and callbacks - // this.logoutCallback = options.logoutCallback || null; - }; - - /* - * Main function for making requests to the API. Can be called directly. - * - * options object: - * `method` - http method (GET, POST, PUT, or DELETE), defaults to GET - * `qs` - object containing querystring values to be appended to the uri - * `body` - object containing entity body for POST and PUT requests - * `endpoint` - API endpoint, for example 'users/fred' - * `mQuery` - boolean, set to true if running management query, defaults to false - * - * @method request - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.request = function(options, callback) { - var method = options.method || 'GET'; - var endpoint = options.endpoint; - var body = options.body || {}; - var qs = options.qs || {}; - var mQuery = options.mQuery || false; //is this a query to the management endpoint? - var orgName = this.get('orgName'); - var appName = this.get('appName'); - var default_qs = this.getObject('default_qs'); - var uri; - /*var logoutCallback=function(){ - if (typeof(this.logoutCallback) === 'function') { - return this.logoutCallback(true, 'no_org_or_app_name_specified'); - } - }.bind(this);*/ - if (!mQuery && !orgName && !appName) { - return logoutCallback(); - } - if (mQuery) { - uri = this.URI + '/' + endpoint; - } else { - uri = this.URI + '/' + orgName + '/' + appName + '/' + endpoint; - } - if (this.getToken()) { - qs.access_token = this.getToken(); - /* - **NOTE** The token can also be passed as a header on the request - - xhr.setRequestHeader("Authorization", "Bearer " + self.getToken()); - xhr.withCredentials = true; - */ - } - if (default_qs) { - qs = propCopy(qs, default_qs); - } - var self=this; - var req = new Usergrid.Request(method, uri, qs, body, function(err, response) { - /*if (AUTH_ERRORS.indexOf(response.error) !== -1) { - return logoutCallback(); - }*/ - if(err){ - doCallback(callback, [err, response, self], self); - }else{ - doCallback(callback, [null, response, self], self); - } - //p.done(err, response); - }); - }; - - /* - * function for building asset urls - * - * @method buildAssetURL - * @public - * @params {string} uuid - * @return {string} assetURL - */ - Usergrid.Client.prototype.buildAssetURL = function(uuid) { - var self = this; - var qs = {}; - var assetURL = this.URI + '/' + this.orgName + '/' + this.appName + '/assets/' + uuid + '/data'; - - if (self.getToken()) { - qs.access_token = self.getToken(); - } - - //append params to the path - var encoded_params = encodeParams(qs); - if (encoded_params) { - assetURL += "?" + encoded_params; - } - - return assetURL; - }; - - /* - * Main function for creating new groups. Call this directly. - * - * @method createGroup - * @public - * @params {string} path - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createGroup = function(options, callback) { - var group = new Usergrid.Group({ - path: options.path, - client: this, - data: options - }); - group.save(function(err, response) { - doCallback(callback, [err, response, group], group); - }); - }; - - /* - * Main function for creating new entities - should be called directly. - * - * options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}} - * - * @method createEntity - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createEntity = function(options, callback) { - var entity = new Usergrid.Entity({ - client: this, - data: options - }); - entity.save(function(err, response) { - doCallback(callback, [err, response, entity], entity); - }); - }; - /* - * Main function for getting existing entities - should be called directly. - * - * You must supply a uuid or (username or name). Username only applies to users. - * Name applies to all custom entities - * - * options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}} - * - * @method createEntity - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.getEntity = function(options, callback) { - var entity = new Usergrid.Entity({ - client: this, - data: options - }); - entity.fetch(function(err, response) { - doCallback(callback, [err, response, entity], entity); - }); - }; - - /* - * Main function for restoring an entity from serialized data. - * - * serializedObject should have come from entityObject.serialize(); - * - * @method restoreEntity - * @public - * @param {string} serializedObject - * @return {object} Entity Object - */ - Usergrid.Client.prototype.restoreEntity = function(serializedObject) { - var data = JSON.parse(serializedObject); - var options = { - client: this, - data: data - }; - var entity = new Usergrid.Entity(options); - return entity; - }; - /* - * Main function for creating new counters - should be called directly. - * - * options object: options {timestamp:0, category:'value', counters:{name : value}} - * - * @method createCounter - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, response, counter) - */ - Usergrid.Client.prototype.createCounter = function(options, callback) { - var counter = new Usergrid.Counter({ - client: this, - data: options - }); - counter.save(callback); - }; - /* - * Main function for creating new assets - should be called directly. - * - * options object: options {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000", file: FileOrBlobObject } - * - * @method createCounter - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, response, counter) - */ - Usergrid.Client.prototype.createAsset = function(options, callback) { - var file=options.file; - if(file){ - options.name=options.name||file.name; - options['content-type']=options['content-type']||file.type; - options.path=options.path||'/'; - delete options.file; - } - var asset = new Usergrid.Asset({ - client: this, - data: options - }); - asset.save(function(err, response, asset){ - if(file && !err){ - asset.upload(file, callback); - }else{ - doCallback(callback, [err, response, asset], asset); - } - }); - }; - - /* - * Main function for creating new collections - should be called directly. - * - * options object: options {client:client, type: type, qs:qs} - * - * @method createCollection - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createCollection = function (options, callback) { - options.client = this; - return new Usergrid.Collection(options, function(err, data, collection) { - console.log("createCollection", arguments); - doCallback(callback, [err, collection, data]); - }); - }; - - /* - * Main function for restoring a collection from serialized data. - * - * serializedObject should have come from collectionObject.serialize(); - * - * @method restoreCollection - * @public - * @param {string} serializedObject - * @return {object} Collection Object - */ - Usergrid.Client.prototype.restoreCollection = function(serializedObject) { - var data = JSON.parse(serializedObject); - data.client = this; - var collection = new Usergrid.Collection(data); - return collection; - }; - - /* - * Main function for retrieving a user's activity feed. - * - * @method getFeedForUser - * @public - * @params {string} username - * @param {function} callback - * @return {callback} callback(err, data, activities) - */ - Usergrid.Client.prototype.getFeedForUser = function(username, callback) { - var options = { - method: "GET", - endpoint: "users/" + username + "/feed" - }; - - this.request(options, function(err, data) { - if (err) { - doCallback(callback, [err]); - } else { - doCallback(callback, [err, data, data.getEntities()]); - } - }); - }; - - /* - * Function for creating new activities for the current user - should be called directly. - * - * //user can be any of the following: "me", a uuid, a username - * Note: the "me" alias will reference the currently logged in user (e.g. 'users/me/activties') - * - * //build a json object that looks like this: - * var options = - * { - * "actor" : { - * "displayName" :"myusername", - * "uuid" : "myuserid", - * "username" : "myusername", - * "email" : "myemail", - * "picture": "http://path/to/picture", - * "image" : { - * "duration" : 0, - * "height" : 80, - * "url" : "http://www.gravatar.com/avatar/", - * "width" : 80 - * }, - * }, - * "verb" : "post", - * "content" : "My cool message", - * "lat" : 48.856614, - * "lon" : 2.352222 - * } - * - * @method createEntity - * @public - * @params {string} user // "me", a uuid, or a username - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createUserActivity = function(user, options, callback) { - options.type = 'users/' + user + '/activities'; - options = { - client: this, - data: options - }; - var entity = new Usergrid.Entity(options); - entity.save(function(err, data) { - doCallback(callback, [err, data, entity]); - }); - }; - - /* - * Function for creating user activities with an associated user entity. - * - * user object: - * The user object passed into this function is an instance of Usergrid.Entity. - * - * @method createUserActivityWithEntity - * @public - * @params {object} user - * @params {string} content - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createUserActivityWithEntity = function(user, content, callback) { - var username = user.get("username"); - var options = { - actor: { - "displayName": username, - "uuid": user.get("uuid"), - "username": username, - "email": user.get("email"), - "picture": user.get("picture"), - "image": { - "duration": 0, - "height": 80, - "url": user.get("picture"), - "width": 80 - } - }, - "verb": "post", - "content": content - }; - - this.createUserActivity(username, options, callback); - - }; - - /* - * A private method to get call timing of last call - */ - Usergrid.Client.prototype.calcTimeDiff = function() { - var seconds = 0; - var time = this._end - this._start; - try { - seconds = ((time / 10) / 60).toFixed(2); - } catch (e) { - return 0; - } - return seconds; - }; - - /* - * A public method to store the OAuth token for later use - uses localstorage if available - * - * @method setToken - * @public - * @params {string} token - * @return none - */ - Usergrid.Client.prototype.setToken = function(token) { - this.set('token', token); - }; - - /* - * A public method to get the OAuth token - * - * @method getToken - * @public - * @return {string} token - */ - Usergrid.Client.prototype.getToken = function() { - return this.get('token'); - }; - - Usergrid.Client.prototype.setObject = function(key, value) { - if (value) { - value = JSON.stringify(value); - } - this.set(key, value); - }; - - Usergrid.Client.prototype.set = function(key, value) { - var keyStore = 'apigee_' + key; - this[key] = value; - if (typeof(Storage) !== "undefined") { - if (value) { - localStorage.setItem(keyStore, value); - } else { - localStorage.removeItem(keyStore); - } - } - }; - - Usergrid.Client.prototype.getObject = function(key) { - return JSON.parse(this.get(key)); - }; - - Usergrid.Client.prototype.get = function(key) { - var keyStore = 'apigee_' + key; - var value = null; - if (this[key]) { - value = this[key]; - } else if (typeof(Storage) !== "undefined") { - value = localStorage.getItem(keyStore); - } - return value; - }; - - /* - * A public facing helper method for signing up users - * - * @method signup - * @public - * @params {string} username - * @params {string} password - * @params {string} email - * @params {string} name - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.signup = function(username, password, email, name, callback) { - var self = this; - var options = { - type: "users", - username: username, - password: password, - email: email, - name: name - }; - - this.createEntity(options, callback); - }; - - /* - * - * A public method to log in an app user - stores the token for later use - * - * @method login - * @public - * @params {string} username - * @params {string} password - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.login = function(username, password, callback) { - var self = this; - var options = { - method: 'POST', - endpoint: 'token', - body: { - username: username, - password: password, - grant_type: 'password' - } - }; - self.request(options, function(err, response) { - var user = {}; - if (err) { - if (self.logging) console.log('error trying to log user in'); - } else { - var options = { - client: self, - data: response.user - }; - user = new Usergrid.Entity(options); - self.setToken(response.access_token); - } - doCallback(callback, [err, response, user]); - }); - }; - - Usergrid.Client.prototype.adminlogin = function(username, password, callback) { - var self = this; - var options = { - method: "POST", - endpoint:'management/token', - body: { - username: username, - password: password, - grant_type: "password" - }, - mQuery:true - }; - self.request(options, function(err, response) { - var user = {}; - if (err) { - if (self.logging) console.log("error trying to log adminuser in"); - } else { - var options = { - client: self, - data: response.user - }; - user = new Usergrid.Entity(options); - self.setToken(response.access_token); - } - doCallback(callback, [ err, response, user ]); - }); - }; - - Usergrid.Client.prototype.reAuthenticateLite = function(callback) { - var self = this; - var options = { - method: 'GET', - endpoint: 'management/me', - mQuery: true - }; - this.request(options, function(err, response) { - if (err && self.logging) { - console.log('error trying to re-authenticate user'); - } else { - - //save the re-authed token and current email/username - self.setToken(response.data.access_token); - - } - doCallback(callback, [err]); - - }); - }; - - - Usergrid.Client.prototype.reAuthenticate = function(email, callback) { - var self = this; - var options = { - method: 'GET', - endpoint: 'management/users/' + email, - mQuery: true - }; - this.request(options, function(err, response) { - var organizations = {}; - var applications = {}; - var user = {}; - var data; - if (err && self.logging) { - console.log('error trying to full authenticate user'); - } else { - data = response.data; - self.setToken(data.token); - self.set('email', data.email); - - //delete next block and corresponding function when iframes are refactored - localStorage.setItem('accessToken', data.token); - localStorage.setItem('userUUID', data.uuid); - localStorage.setItem('userEmail', data.email); - //end delete block - - - var userData = { - "username": data.username, - "email": data.email, - "name": data.name, - "uuid": data.uuid - }; - var options = { - client: self, - data: userData - }; - user = new Usergrid.Entity(options); - - organizations = data.organizations; - var org = ''; - try { - //if we have an org stored, then use that one. Otherwise, use the first one. - var existingOrg = self.get('orgName'); - org = (organizations[existingOrg]) ? organizations[existingOrg] : organizations[Object.keys(organizations)[0]]; - self.set('orgName', org.name); - } catch (e) { - err = true; - if (self.logging) { - console.log('error selecting org'); - } - } //should always be an org - - applications = self.parseApplicationsArray(org); - self.selectFirstApp(applications); - - self.setObject('organizations', organizations); - self.setObject('applications', applications); - - } - doCallback(callback, [err, data, user, organizations, applications], self); - }); - }; - - /* - * A public method to log in an app user with facebook - stores the token for later use - * - * @method loginFacebook - * @public - * @params {string} username - * @params {string} password - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.loginFacebook = function(facebookToken, callback) { - var self = this; - var options = { - method: 'GET', - endpoint: 'auth/facebook', - qs: { - fb_access_token: facebookToken - } - }; - this.request(options, function(err, data) { - var user = {}; - if (err && self.logging) { - console.log('error trying to log user in'); - } else { - var options = { - client: self, - data: data.user - }; - user = new Usergrid.Entity(options); - self.setToken(data.access_token); - } - doCallback(callback, [err, data, user], self); - }); - }; - - /* - * A public method to get the currently logged in user entity - * - * @method getLoggedInUser - * @public - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.getLoggedInUser = function(callback) { - var self = this; - if (!this.getToken()) { - doCallback(callback, [new UsergridError("Access Token not set"), null, self], self); - } else { - var options = { - method: 'GET', - endpoint: 'users/me' - }; - this.request(options, function(err, response) { - if (err) { - if (self.logging) { - console.log('error trying to log user in'); - } - console.error(err, response); - doCallback(callback, [err, response, self], self); - } else { - var options = { - client: self, - data: response.getEntity() - }; - var user = new Usergrid.Entity(options); - doCallback(callback, [null, response, user], self); - } - }); - } - }; - - /* - * A public method to test if a user is logged in - does not guarantee that the token is still valid, - * but rather that one exists - * - * @method isLoggedIn - * @public - * @return {boolean} Returns true the user is logged in (has token and uuid), false if not - */ - Usergrid.Client.prototype.isLoggedIn = function() { - var token = this.getToken(); - return "undefined" !== typeof token && token !== null; - }; - - /* - * A public method to log out an app user - clears all user fields from client - * - * @method logout - * @public - * @return none - */ - Usergrid.Client.prototype.logout = function() { - this.setToken(); - }; - - /* - * A public method to destroy access tokens on the server - * - * @method logout - * @public - * @param {string} username the user associated with the token to revoke - * @param {string} token set to 'null' to revoke the token of the currently logged in user - * or set to token value to revoke a specific token - * @param {string} revokeAll set to 'true' to revoke all tokens for the user - * @return none - */ - Usergrid.Client.prototype.destroyToken = function(username, token, revokeAll, callback) { - var options = { - client: self, - method: 'PUT', - }; - - if (revokeAll === true) { - options.endpoint = 'users/' + username + '/revoketokens'; - } else if (token === null) { - options.endpoint = 'users/' + username + '/revoketoken?token=' + this.getToken(); - } else { - options.endpoint = 'users/' + username + '/revoketoken?token=' + token; - } - this.request(options, function(err, data) { - if (err) { - if (self.logging) { - console.log('error destroying access token'); - } - doCallback(callback, [err, data, null], self); - } else { - if (revokeAll === true) { - console.log('all user tokens invalidated'); - } else { - console.log('token invalidated'); - } - doCallback(callback, [err, data, null], self); - } - }); - }; - - /* - * A public method to log out an app user - clears all user fields from client - * and destroys the access token on the server. - * - * @method logout - * @public - * @param {string} username the user associated with the token to revoke - * @param {string} token set to 'null' to revoke the token of the currently logged in user - * or set to token value to revoke a specific token - * @param {string} revokeAll set to 'true' to revoke all tokens for the user - * @return none - */ - Usergrid.Client.prototype.logoutAndDestroyToken = function(username, token, revokeAll, callback) { - if (username === null) { - console.log('username required to revoke tokens'); - } else { - this.destroyToken(username, token, revokeAll, callback); - if (revokeAll === true || token === this.getToken() || token === null) { - this.setToken(null); - } - } - }; - - /* - * A private method to build the curl call to display on the command line - * - * @method buildCurlCall - * @private - * @param {object} options - * @return {string} curl - */ - Usergrid.Client.prototype.buildCurlCall = function(options) { - var curl = ['curl']; - var method = (options.method || 'GET').toUpperCase(); - var body = options.body; - var uri = options.uri; - - //curl - add the method to the command (no need to add anything for GET) - curl.push('-X'); - curl.push((['POST', 'PUT', 'DELETE'].indexOf(method) >= 0) ? method : 'GET'); - - //curl - append the path - curl.push(uri); - - if ("object" === typeof body && Object.keys(body).length > 0 && ['POST', 'PUT'].indexOf(method) !== -1) { - curl.push('-d'); - curl.push("'" + JSON.stringify(body) + "'"); - } - curl = curl.join(' '); - //log the curl command to the console - console.log(curl); - - return curl; - }; - - Usergrid.Client.prototype.getDisplayImage = function(email, picture, size) { - size = size || 50; - var image = 'https://apigee.com/usergrid/images/user_profile.png'; - try { - if (picture) { - image = picture; - } else if (email.length) { - image = 'https://secure.gravatar.com/avatar/' + MD5(email) + '?s=' + size + encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"); - } - } catch (e) { - //TODO do something with this error? - } finally { - return image; - } - }; - global[name] = Usergrid.Client; - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; - } - return exports; - }; - return global[name]; -}()); diff --git a/lib/modules/Collection.js b/lib/modules/Collection.js deleted file mode 100644 index d137125..0000000 --- a/lib/modules/Collection.js +++ /dev/null @@ -1,483 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ - - -/* - * The Collection class models Usergrid Collections. It essentially - * acts as a container for holding Entity objects, while providing - * additional funcitonality such as paging, and saving - * - * @constructor - * @param {string} options - configuration object - * @return {Collection} collection - */ -Usergrid.Collection = function(options) { - - if (options) { - this._client = options.client; - this._type = options.type; - this.qs = options.qs || {}; - - //iteration - this._list = options.list || []; - this._iterator = options.iterator || -1; //first thing we do is increment, so set to -1 - - //paging - this._previous = options.previous || []; - this._next = options.next || null; - this._cursor = options.cursor || null; - - //restore entities if available - if (options.list) { - var count = options.list.length; - for (var i = 0; i < count; i++) { - //make new entity with - var entity = this._client.restoreEntity(options.list[i]); - this._list[i] = entity; - } - } - } - /*if (callback) { - //populate the collection - this.fetch(callback); - }*/ - -}; - - -/* - * method to determine whether or not the passed variable is a Usergrid Collection - * - * @method isCollection - * @public - * @params {any} obj - any variable - * @return {boolean} Returns true or false - */ -Usergrid.isCollection = function(obj) { - return (obj && obj instanceof Usergrid.Collection); -}; - - -/* - * gets the data from the collection object for serialization - * - * @method serialize - * @return {object} data - */ -Usergrid.Collection.prototype.serialize = function() { - - //pull out the state from this object and return it - var data = {}; - data.type = this._type; - data.qs = this.qs; - data.iterator = this._iterator; - data.previous = this._previous; - data.next = this._next; - data.cursor = this._cursor; - - this.resetEntityPointer(); - var i = 0; - data.list = []; - while (this.hasNextEntity()) { - var entity = this.getNextEntity(); - data.list[i] = entity.serialize(); - i++; - } - - data = JSON.stringify(data); - return data; -}; -//addCollection is deprecated? -/*Usergrid.Collection.prototype.addCollection = function (collectionName, options, callback) { - self = this; - options.client = this._client; - var collection = new Usergrid.Collection(options, function(err, data) { - if (typeof(callback) === 'function') { - - collection.resetEntityPointer(); - while(collection.hasNextEntity()) { - var user = collection.getNextEntity(); - var email = user.get('email'); - var image = self._client.getDisplayImage(user.get('email'), user.get('picture')); - user._portal_image_icon = image; - } - - self[collectionName] = collection; - doCallback(callback, [err, collection], self); - } - }); -};*/ - -/* - * Populates the collection from the server - * - * @method fetch - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.fetch = function(callback) { - var self = this; - var qs = this.qs; - - //add in the cursor if one is available - if (this._cursor) { - qs.cursor = this._cursor; - } else { - delete qs.cursor; - } - var options = { - method: 'GET', - endpoint: this._type, - qs: this.qs - }; - this._client.request(options, function(err, response) { - if (err && self._client.logging) { - console.log('error getting collection'); - } else { - //save the cursor if there is one - self.saveCursor(response.cursor || null); - self.resetEntityPointer(); - //save entities locally - self._list = response.getEntities() - .filter(function(entity) { - return isUUID(entity.uuid); - }) - .map(function(entity) { - var ent = new Usergrid.Entity({ - client: self._client - }); - ent.set(entity); - ent.type = self._type; - //ent._json = JSON.stringify(entity, null, 2); - return ent; - }); - } - doCallback(callback, [err, response, self], self); - }); -}; - -/* - * Adds a new Entity to the collection (saves, then adds to the local object) - * - * @method addNewEntity - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data, entity) - */ -Usergrid.Collection.prototype.addEntity = function(entityObject, callback) { - var self = this; - entityObject.type = this._type; - - //create the new entity - this._client.createEntity(entityObject, function(err, response, entity) { - if (!err) { - //then add the entity to the list - self.addExistingEntity(entity); - } - doCallback(callback, [err, response, self], self); - }); -}; - -Usergrid.Collection.prototype.addExistingEntity = function(entity) { - //entity should already exist in the db, so just add it to the list - var count = this._list.length; - this._list[count] = entity; -}; - -/* - * Removes the Entity from the collection, then destroys the object on the server - * - * @method destroyEntity - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.destroyEntity = function(entity, callback) { - var self = this; - entity.destroy(function(err, response) { - if (err) { - if (self._client.logging) { - console.log('could not destroy entity'); - } - doCallback(callback, [err, response, self], self); - } else { - //destroy was good, so repopulate the collection - self.fetch(callback); - } - //remove entity from the local store - self.removeEntity(entity); - }); -}; - -/* - * Filters the list of entities based on the supplied criteria function - * works like Array.prototype.filter - * - * @method getEntitiesByCriteria - * @param {function} criteria A function that takes each entity as an argument and returns true or false - * @return {Entity[]} returns a list of entities that caused the criteria function to return true - */ -Usergrid.Collection.prototype.getEntitiesByCriteria = function(criteria) { - return this._list.filter(criteria); -}; -/* - * Returns the first entity from the list of entities based on the supplied criteria function - * works like Array.prototype.filter - * - * @method getEntitiesByCriteria - * @param {function} criteria A function that takes each entity as an argument and returns true or false - * @return {Entity[]} returns a list of entities that caused the criteria function to return true - */ -Usergrid.Collection.prototype.getEntityByCriteria = function(criteria) { - return this.getEntitiesByCriteria(criteria).shift(); -}; -/* - * Removed an entity from the collection without destroying it on the server - * - * @method removeEntity - * @param {object} entity - * @return {Entity} returns the removed entity or undefined if it was not found - */ -Usergrid.Collection.prototype.removeEntity = function(entity) { - var removedEntity = this.getEntityByCriteria(function(item) { - return entity.uuid === item.get('uuid'); - }); - delete this._list[this._list.indexOf(removedEntity)]; - return removedEntity; -}; - -/* - * Looks up an Entity by UUID - * - * @method getEntityByUUID - * @param {string} UUID - * @param {function} callback - * @return {callback} callback(err, data, entity) - */ -Usergrid.Collection.prototype.getEntityByUUID = function(uuid, callback) { - var entity = this.getEntityByCriteria(function(item) { - return item.get('uuid') === uuid; - }); - if (entity) { - doCallback(callback, [null, entity, entity], this); - } else { - //get the entity from the database - var options = { - data: { - type: this._type, - uuid: uuid - }, - client: this._client - }; - entity = new Usergrid.Entity(options); - entity.fetch(callback); - } -}; - -/* - * Returns the first Entity of the Entity list - does not affect the iterator - * - * @method getFirstEntity - * @return {object} returns an entity object - */ -Usergrid.Collection.prototype.getFirstEntity = function() { - var count = this._list.length; - if (count > 0) { - return this._list[0]; - } - return null; -}; - -/* - * Returns the last Entity of the Entity list - does not affect the iterator - * - * @method getLastEntity - * @return {object} returns an entity object - */ -Usergrid.Collection.prototype.getLastEntity = function() { - var count = this._list.length; - if (count > 0) { - return this._list[count - 1]; - } - return null; -}; - -/* - * Entity iteration -Checks to see if there is a "next" entity - * in the list. The first time this method is called on an entity - * list, or after the resetEntityPointer method is called, it will - * return true referencing the first entity in the list - * - * @method hasNextEntity - * @return {boolean} true if there is a next entity, false if not - */ -Usergrid.Collection.prototype.hasNextEntity = function() { - var next = this._iterator + 1; - var hasNextElement = (next >= 0 && next < this._list.length); - if (hasNextElement) { - return true; - } - return false; -}; - -/* - * Entity iteration - Gets the "next" entity in the list. The first - * time this method is called on an entity list, or after the method - * resetEntityPointer is called, it will return the, - * first entity in the list - * - * @method hasNextEntity - * @return {object} entity - */ -Usergrid.Collection.prototype.getNextEntity = function() { - this._iterator++; - var hasNextElement = (this._iterator >= 0 && this._iterator <= this._list.length); - if (hasNextElement) { - return this._list[this._iterator]; - } - return false; -}; - -/* - * Entity iteration - Checks to see if there is a "previous" - * entity in the list. - * - * @method hasPrevEntity - * @return {boolean} true if there is a previous entity, false if not - */ -Usergrid.Collection.prototype.hasPrevEntity = function() { - var previous = this._iterator - 1; - var hasPreviousElement = (previous >= 0 && previous < this._list.length); - if (hasPreviousElement) { - return true; - } - return false; -}; - -/* - * Entity iteration - Gets the "previous" entity in the list. - * - * @method getPrevEntity - * @return {object} entity - */ -Usergrid.Collection.prototype.getPrevEntity = function() { - this._iterator--; - var hasPreviousElement = (this._iterator >= 0 && this._iterator <= this._list.length); - if (hasPreviousElement) { - return this._list[this._iterator]; - } - return false; -}; - -/* - * Entity iteration - Resets the iterator back to the beginning - * of the list - * - * @method resetEntityPointer - * @return none - */ -Usergrid.Collection.prototype.resetEntityPointer = function() { - this._iterator = -1; -}; - -/* - * Method to save off the cursor just returned by the last API call - * - * @public - * @method saveCursor - * @return none - */ -Usergrid.Collection.prototype.saveCursor = function(cursor) { - //if current cursor is different, grab it for next cursor - if (this._next !== cursor) { - this._next = cursor; - } -}; - -/* - * Resets the paging pointer (back to original page) - * - * @public - * @method resetPaging - * @return none - */ -Usergrid.Collection.prototype.resetPaging = function() { - this._previous = []; - this._next = null; - this._cursor = null; -}; - -/* - * Paging - checks to see if there is a next page od data - * - * @method hasNextPage - * @return {boolean} returns true if there is a next page of data, false otherwise - */ -Usergrid.Collection.prototype.hasNextPage = function() { - return (this._next); -}; - -/* - * Paging - advances the cursor and gets the next - * page of data from the API. Stores returned entities - * in the Entity list. - * - * @method getNextPage - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.getNextPage = function(callback) { - if (this.hasNextPage()) { - //set the cursor to the next page of data - this._previous.push(this._cursor); - this._cursor = this._next; - //empty the list - this._list = []; - this.fetch(callback); - } -}; - -/* - * Paging - checks to see if there is a previous page od data - * - * @method hasPreviousPage - * @return {boolean} returns true if there is a previous page of data, false otherwise - */ -Usergrid.Collection.prototype.hasPreviousPage = function() { - return (this._previous.length > 0); -}; - -/* - * Paging - reverts the cursor and gets the previous - * page of data from the API. Stores returned entities - * in the Entity list. - * - * @method getPreviousPage - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.getPreviousPage = function(callback) { - if (this.hasPreviousPage()) { - this._next = null; //clear out next so the comparison will find the next item - this._cursor = this._previous.pop(); - //empty the list - this._list = []; - this.fetch(callback); - } -}; diff --git a/lib/modules/Counter.js b/lib/modules/Counter.js deleted file mode 100644 index 7b120cc..0000000 --- a/lib/modules/Counter.js +++ /dev/null @@ -1,196 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ - - -/* - * A class to model a Usergrid event. - * - * @constructor - * @param {object} options {timestamp:0, category:'value', counters:{name : value}} - * @returns {callback} callback(err, event) - */ -Usergrid.Counter = function(options) { - // var self=this; - this._client = options.client; - this._data = options.data || {}; - this._data.category = options.category || "UNKNOWN"; - this._data.timestamp = options.timestamp || 0; - this._data.type = "events"; - this._data.counters = options.counters || {}; - // doCallback(callback, [false, this], this); - //this.save(callback); -}; -var COUNTER_RESOLUTIONS = [ - 'all', 'minute', 'five_minutes', 'half_hour', - 'hour', 'six_day', 'day', 'week', 'month' -]; -/* - * Inherit from Usergrid.Entity. - * Note: This only accounts for data on the group object itself. - * You need to use add and remove to manipulate group membership. - */ -Usergrid.Counter.prototype = new Usergrid.Entity(); - -/* - * overrides Entity.prototype.fetch. Returns all data for counters - * associated with the object as specified in the constructor - * - * @public - * @method increment - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.fetch = function(callback) { - this.getData({}, callback); -}; -/* - * increments the counter for a specific event - * - * options object: {name: counter_name} - * - * @public - * @method increment - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.increment = function(options, callback) { - var self = this, - name = options.name, - value = options.value; - if (!name) { - return doCallback(callback, [new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"), null, self], self); - } else if (isNaN(value)) { - return doCallback(callback, [new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"), null, self], self); - } else { - self._data.counters[name] = (parseInt(value)) || 1; - return self.save(callback); - } -}; -/* - * decrements the counter for a specific event - * - * options object: {name: counter_name} - * - * @public - * @method decrement - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ - -Usergrid.Counter.prototype.decrement = function(options, callback) { - var self = this, - name = options.name, - value = options.value; - self.increment({ - name: name, - value: -((parseInt(value)) || 1) - }, callback); -}; -/* - * resets the counter for a specific event - * - * options object: {name: counter_name} - * - * @public - * @method reset - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ - -Usergrid.Counter.prototype.reset = function(options, callback) { - var self = this, - name = options.name; - self.increment({ - name: name, - value: 0 - }, callback); -}; - -/* - * gets data for one or more counters over a given - * time period at a specified resolution - * - * options object: { - * counters: ['counter1', 'counter2', ...], - * start: epoch timestamp or ISO date string, - * end: epoch timestamp or ISO date string, - * resolution: one of ('all', 'minute', 'five_minutes', 'half_hour', 'hour', 'six_day', 'day', 'week', or 'month') - * } - * - * @public - * @method getData - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.getData = function(options, callback) { - var start_time, - end_time, - start = options.start || 0, - end = options.end || Date.now(), - resolution = (options.resolution || 'all').toLowerCase(), - counters = options.counters || Object.keys(this._data.counters), - res = (resolution || 'all').toLowerCase(); - if (COUNTER_RESOLUTIONS.indexOf(res) === -1) { - res = 'all'; - } - start_time = getSafeTime(start); - end_time = getSafeTime(end); - var self = this; - //https://api.usergrid.com/yourorgname/sandbox/counters?counter=test_counter - var params = Object.keys(counters).map(function(counter) { - return ["counter", encodeURIComponent(counters[counter])].join('='); - }); - params.push('resolution=' + res); - params.push('start_time=' + String(start_time)); - params.push('end_time=' + String(end_time)); - - var endpoint = "counters?" + params.join('&'); - this._client.request({ - endpoint: endpoint - }, function(err, data) { - if (data.counters && data.counters.length) { - data.counters.forEach(function(counter) { - self._data.counters[counter.name] = counter.value || counter.values; - }); - } - return doCallback(callback, [err, data, self], self); - }); -}; - -function getSafeTime(prop) { - var time; - switch (typeof prop) { - case "undefined": - time = Date.now(); - break; - case "number": - time = prop; - break; - case "string": - time = (isNaN(prop)) ? Date.parse(prop) : parseInt(prop); - break; - default: - time = Date.parse(prop.toString()); - } - return time; -} diff --git a/lib/modules/Entity.js b/lib/modules/Entity.js deleted file mode 100644 index 029951c..0000000 --- a/lib/modules/Entity.js +++ /dev/null @@ -1,767 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ - - -var ENTITY_SYSTEM_PROPERTIES = ['metadata', 'created', 'modified', 'oldpassword', 'newpassword', 'type', 'activated', 'uuid']; - -/* - * A class to Model a Usergrid Entity. - * Set the type and uuid of entity in the 'data' json object - * - * @constructor - * @param {object} options {client:client, data:{'type':'collection_type', uuid:'uuid', 'key':'value'}} - */ -Usergrid.Entity = function(options) { - this._data={}; - this._client=undefined; - if (options) { - //this._data = options.data || {}; - this.set(options.data || {}); - this._client = options.client || {}; - } -}; - -/* - * method to determine whether or not the passed variable is a Usergrid Entity - * - * @method isEntity - * @public - * @params {any} obj - any variable - * @return {boolean} Returns true or false - */ -Usergrid.Entity.isEntity = function(obj) { - return (obj && obj instanceof Usergrid.Entity); -}; - -/* - * method to determine whether or not the passed variable is a Usergrid Entity - * That has been saved. - * - * @method isPersistedEntity - * @public - * @params {any} obj - any variable - * @return {boolean} Returns true or false - */ -Usergrid.Entity.isPersistedEntity = function(obj) { - return (isEntity(obj) && isUUID(obj.get('uuid'))); -}; - -/* - * returns a serialized version of the entity object - * - * Note: use the client.restoreEntity() function to restore - * - * @method serialize - * @return {string} data - */ -Usergrid.Entity.prototype.serialize = function() { - return JSON.stringify(this._data); -}; - -/* - * gets a specific field or the entire data object. If null or no argument - * passed, will return all data, else, will return a specific field - * - * @method get - * @param {string} field - * @return {string} || {object} data - */ -Usergrid.Entity.prototype.get = function(key) { - var value; - if (arguments.length === 0) { - value = this._data; - } else if (arguments.length > 1) { - key = [].slice.call(arguments).reduce(function(p, c, i, a) { - if (c instanceof Array) { - p = p.concat(c); - } else { - p.push(c); - } - return p; - }, []); - } - if (key instanceof Array) { - var self = this; - value = key.map(function(k) { - return self.get(k); - }); - } else if ("undefined" !== typeof key) { - value = this._data[key]; - } - return value; -}; -/* - * adds a specific key value pair or object to the Entity's data - * is additive - will not overwrite existing values unless they - * are explicitly specified - * - * @method set - * @param {string} key || {object} - * @param {string} value - * @return none - */ -Usergrid.Entity.prototype.set = function(key, value) { - if (typeof key === 'object') { - for (var field in key) { - this._data[field] = key[field]; - } - } else if (typeof key === 'string') { - if (value === null) { - delete this._data[key]; - } else { - this._data[key] = value; - } - } else { - this._data = {}; - } -}; - -Usergrid.Entity.prototype.getEndpoint = function() { - var type = this.get('type'), - nameProperties = ['uuid', 'name'], - name; - if (type === undefined) { - throw new UsergridError('cannot fetch entity, no entity type specified', 'no_type_specified'); - } else if (/^users?$/.test(type)) { - nameProperties.unshift('username'); - } - name = this.get(nameProperties) - .filter(function(x) { - return (x !== null && "undefined" !== typeof x); - }) - .shift(); - return (name) ? [type, name].join('/') : type; -}; -/* - * Saves the entity back to the database - * - * @method save - * @public - * @param {function} callback - * @return {callback} callback(err, response, self) - */ -Usergrid.Entity.prototype.save = function(callback) { - var self = this, - type = this.get('type'), - method = 'POST', - entityId = this.get("uuid"), - changePassword, - entityData = this.get(), - options = { - method: method, - endpoint: type - }; - //update the entity if the UUID is present - if (entityId) { - options.method = 'PUT'; - options.endpoint += '/' + entityId; - } - //remove system-specific properties - options.body = Object.keys(entityData) - .filter(function(key) { - return (ENTITY_SYSTEM_PROPERTIES.indexOf(key) === -1); - }) - .reduce(function(data, key) { - data[key] = entityData[key]; - return data; - }, {}); - self._client.request(options, function(err, response) { - var entity = response.getEntity(); - if (entity) { - self.set(entity); - self.set('type', (/^\//.test(response.path)) ? response.path.substring(1) : response.path); - } - if (err && self._client.logging) { - console.log('could not save entity'); - } - doCallback(callback, [err, response, self], self); - }); -}; - -/* - * - * Updates the user's password - */ -Usergrid.Entity.prototype.changePassword = function(oldpassword, newpassword, callback) { - //Note: we have a ticket in to change PUT calls to /users to accept the password change - // once that is done, we will remove this call and merge it all into one - var self = this; - if ("function" === typeof oldpassword && callback === undefined) { - callback = oldpassword; - oldpassword = self.get("oldpassword"); - newpassword = self.get("newpassword"); - } - //clear out pw info if present - self.set({ - 'password': null, - 'oldpassword': null, - 'newpassword': null - }); - if ((/^users?$/.test(self.get('type'))) && oldpassword && newpassword) { - var options = { - method: 'PUT', - endpoint: 'users/' + self.get("uuid") + '/password', - body: { - uuid: self.get("uuid"), - username: self.get("username"), - oldpassword: oldpassword, - newpassword: newpassword - } - }; - self._client.request(options, function(err, response) { - if (err && self._client.logging) { - console.log('could not update user'); - } - //remove old and new password fields so they don't end up as part of the entity object - doCallback(callback, [err, response, self], self); - }); - } else { - throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'"); - } -}; -/* - * refreshes the entity by making a GET call back to the database - * - * @method fetch - * @public - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Entity.prototype.fetch = function(callback) { - var endpoint, self = this; - endpoint = this.getEndpoint(); - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, response) { - var entity = response.getEntity(); - if (entity) { - self.set(entity); - } - doCallback(callback, [err, response, self], self); - }); -}; - -/* - * deletes the entity from the database - will only delete - * if the object has a valid uuid - * - * @method destroy - * @public - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.destroy = function(callback) { - var self = this; - var endpoint = this.getEndpoint(); - - var options = { - method: 'DELETE', - endpoint: endpoint - }; - this._client.request(options, function(err, response) { - if (!err) { - self.set(null); - } - doCallback(callback, [err, response, self], self); - }); -}; - -/* - * connects one entity to another - * - * @method connect - * @public - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.connect = function(connection, entity, callback) { - this.addOrRemoveConnection("POST", connection, entity, callback); -}; - -/* - * disconnects one entity from another - * - * @method disconnect - * @public - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.disconnect = function(connection, entity, callback) { - this.addOrRemoveConnection("DELETE", connection, entity, callback); -}; -/* - * adds or removes a connection between two entities - * - * @method addOrRemoveConnection - * @public - * @param {string} method - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.addOrRemoveConnection = function(method, connection, entity, callback) { - var self = this; - if (['POST', 'DELETE'].indexOf(method.toUpperCase()) == -1) { - throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'"); - } - //connectee info - var connecteeType = entity.get('type'); - var connectee = this.getEntityId(entity); - if (!connectee) { - throw new UsergridInvalidArgumentError("connectee could not be identified"); - } - - //connector info - var connectorType = this.get('type'); - var connector = this.getEntityId(this); - if (!connector) { - throw new UsergridInvalidArgumentError("connector could not be identified"); - } - - var endpoint = [connectorType, connector, connection, connecteeType, connectee].join('/'); - var options = { - method: method, - endpoint: endpoint - }; - this._client.request(options, function(err, response) { - if (err && self._client.logging) { - console.log('There was an error with the connection call'); - } - doCallback(callback, [err, response, self], self); - }); -}; - -/* - * returns a unique identifier for an entity - * - * @method connect - * @public - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.getEntityId = function(entity) { - var id; - if (isUUID(entity.get("uuid"))) { - id = entity.get("uuid"); - } else if (this.get("type") === "users" || this.get("type") === "user") { - id = entity.get("username"); - } else { - id = entity.get("name"); - } - return id; -}; - -/* - * gets an entities connections - * - * @method getConnections - * @public - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data, connections) - * - */ -Usergrid.Entity.prototype.getConnections = function(connection, callback) { - - var self = this; - - //connector info - var connectorType = this.get('type'); - var connector = this.getEntityId(this); - if (!connector) { - if (typeof(callback) === 'function') { - var error = 'Error in getConnections - no uuid specified.'; - if (self._client.logging) { - console.log(error); - } - doCallback(callback, [true, error], self); - } - return; - } - - var endpoint = connectorType + '/' + connector + '/' + connection + '/'; - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('entity could not be connected'); - } - - self[connection] = {}; - - var length = (data && data.entities) ? data.entities.length : 0; - for (var i = 0; i < length; i++) { - if (data.entities[i].type === 'user') { - self[connection][data.entities[i].username] = data.entities[i]; - } else { - self[connection][data.entities[i].name] = data.entities[i]; - } - } - - doCallback(callback, [err, data, data.entities], self); - }); - -}; - -Usergrid.Entity.prototype.getGroups = function(callback) { - - var self = this; - - var endpoint = 'users' + '/' + this.get('uuid') + '/groups'; - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('entity could not be connected'); - } - - self.groups = data.entities; - - doCallback(callback, [err, data, data.entities], self); - }); - -}; - -Usergrid.Entity.prototype.getActivities = function(callback) { - - var self = this; - - var endpoint = this.get('type') + '/' + this.get('uuid') + '/activities'; - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('entity could not be connected'); - } - - for (var entity in data.entities) { - data.entities[entity].createdDate = (new Date(data.entities[entity].created)).toUTCString(); - } - - self.activities = data.entities; - - doCallback(callback, [err, data, data.entities], self); - }); - -}; - -Usergrid.Entity.prototype.getFollowing = function(callback) { - - var self = this; - - var endpoint = 'users' + '/' + this.get('uuid') + '/following'; - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('could not get user following'); - } - - for (var entity in data.entities) { - data.entities[entity].createdDate = (new Date(data.entities[entity].created)).toUTCString(); - var image = self._client.getDisplayImage(data.entities[entity].email, data.entities[entity].picture); - data.entities[entity]._portal_image_icon = image; - } - - self.following = data.entities; - - doCallback(callback, [err, data, data.entities], self); - }); - -}; - - -Usergrid.Entity.prototype.getFollowers = function(callback) { - - var self = this; - - var endpoint = 'users' + '/' + this.get('uuid') + '/followers'; - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('could not get user followers'); - } - - for (var entity in data.entities) { - data.entities[entity].createdDate = (new Date(data.entities[entity].created)).toUTCString(); - var image = self._client.getDisplayImage(data.entities[entity].email, data.entities[entity].picture); - data.entities[entity]._portal_image_icon = image; - } - - self.followers = data.entities; - - doCallback(callback, [err, data, data.entities], self); - }); - -}; - -Usergrid.Client.prototype.createRole = function(roleName, permissions, callback) { - - var options = { - type: 'role', - name: roleName - }; - - this.createEntity(options, function(err, response, entity) { - if (err) { - doCallback(callback, [ err, response, self ]); - } else { - entity.assignPermissions(permissions, function (err, data) { - if (err) { - doCallback(callback, [ err, response, self ]); - } else { - doCallback(callback, [ err, data, data.data ], self); - } - }) - } - }); - -}; - -Usergrid.Entity.prototype.getRoles = function(callback) { - var self = this; - var endpoint = this.get("type") + "/" + this.get("uuid") + "/roles"; - var options = { - method: "GET", - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not get user roles"); - } - self.roles = data.entities; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Entity.prototype.assignRole = function(roleName, callback) { - - var self = this; - var type = self.get('type'); - var collection = type + 's'; - var entityID; - - if (type == 'user' && this.get('username') != null) { - entityID = self.get('username'); - } else if (type == 'group' && this.get('name') != null) { - entityID = self.get('name'); - } else if (this.get('uuid') != null) { - entityID = self.get('uuid'); - } - - if (type != 'users' && type != 'groups') { - doCallback(callback, [ new UsergridError('entity must be a group or user', 'invalid_entity_type'), null, this ], this); - } - - var endpoint = 'roles/' + roleName + '/' + collection + '/' + entityID; - var options = { - method: 'POST', - endpoint: endpoint - }; - - this._client.request(options, function(err, response) { - if (err) { - console.log('Could not assign role.'); - } - doCallback(callback, [ err, response, self ]); - }); - -}; - -Usergrid.Entity.prototype.removeRole = function(roleName, callback) { - - var self = this; - var type = self.get('type'); - var collection = type + 's'; - var entityID; - - if (type == 'user' && this.get('username') != null) { - entityID = this.get('username'); - } else if (type == 'group' && this.get('name') != null) { - entityID = this.get('name'); - } else if (this.get('uuid') != null) { - entityID = this.get('uuid'); - } - - if (type != 'users' && type != 'groups') { - doCallback(callback, [ new UsergridError('entity must be a group or user', 'invalid_entity_type'), null, this ], this); - } - - var endpoint = 'roles/' + roleName + '/' + collection + '/' + entityID; - var options = { - method: 'DELETE', - endpoint: endpoint - }; - - this._client.request(options, function(err, response) { - if (err) { - console.log('Could not assign role.'); - } - doCallback(callback, [ err, response, self ]); - }); - -}; - -Usergrid.Entity.prototype.assignPermissions = function(permissions, callback) { - var self = this; - var entityID; - var type = this.get('type'); - - if (type != 'user' && type != 'users' && type != 'group' && type != 'groups' && type != 'role' && type != 'roles') { - doCallback(callback, [ new UsergridError('entity must be a group, user, or role', 'invalid_entity_type'), null, this ], this); - } - - if (type == 'user' && this.get('username') != null) { - entityID = this.get('username'); - } else if (type == 'group' && this.get('name') != null) { - entityID = this.get('name'); - } else if (this.get('uuid') != null) { - entityID = this.get('uuid'); - } - - var endpoint = type + '/' + entityID + '/permissions'; - var options = { - method: 'POST', - endpoint: endpoint, - body: { - 'permission': permissions - } - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('could not assign permissions'); - } - doCallback(callback, [ err, data, data.data ], self); - }); -}; - -Usergrid.Entity.prototype.removePermissions = function(permissions, callback) { - var self = this; - var entityID; - var type = this.get('type'); - - if (type != 'user' && type != 'users' && type != 'group' && type != 'groups' && type != 'role' && type != 'roles') { - doCallback(callback, [ new UsergridError('entity must be a group, user, or role', 'invalid_entity_type'), null, this ], this); - } - - if (type == 'user' && this.get('username') != null) { - entityID = this.get('username'); - } else if (type == 'group' && this.get('name') != null) { - entityID = this.get('name'); - } else if (this.get('uuid') != null) { - entityID = this.get('uuid'); - } - - var endpoint = type + '/' + entityID + '/permissions'; - var options = { - method: 'DELETE', - endpoint: endpoint, - qs: { - 'permission': permissions - } - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('could not remove permissions'); - } - doCallback(callback, [ err, data, data.params.permission ], self); - }); -}; - -Usergrid.Entity.prototype.getPermissions = function(callback) { - - var self = this; - - var endpoint = this.get('type') + '/' + this.get('uuid') + '/permissions'; - var options = { - method: 'GET', - endpoint: endpoint - }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log('could not get user permissions'); - } - - var permissions = []; - if (data.data) { - var perms = data.data; - var count = 0; - - for (var i in perms) { - count++; - var perm = perms[i]; - var parts = perm.split(':'); - var ops_part = ""; - var path_part = parts[0]; - - if (parts.length > 1) { - ops_part = parts[0]; - path_part = parts[1]; - } - - ops_part=ops_part.replace("*", "get,post,put,delete"); - var ops = ops_part.split(','); - var ops_object = {}; - ops_object.get = 'no'; - ops_object.post = 'no'; - ops_object.put = 'no'; - ops_object.delete = 'no'; - for (var j in ops) { - ops_object[ops[j]] = 'yes'; - } - - permissions.push({ - operations: ops_object, - path: path_part, - perm: perm - }); - } - } - - self.permissions = permissions; - - doCallback(callback, [err, data, data.entities], self); - }); - -}; diff --git a/lib/modules/Error.js b/lib/modules/Error.js deleted file mode 100644 index 5cc5807..0000000 --- a/lib/modules/Error.js +++ /dev/null @@ -1,155 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -//noinspection ThisExpressionReferencesGlobalObjectJS - -/** - * Created by ryan bridges on 2014-02-05. - */ -(function(global) { - //noinspection JSUnusedAssignment - var name = 'UsergridError', - short, - _name = global[name], - _short = (short && short !== undefined) ? global[short] : undefined; - - /* - * Instantiates a new UsergridError - * - * @method UsergridError - * @public - * @params {} message - * @params {} id - the error code, id, or name - * @params {} timestamp - * @params {} duration - * @params {} exception - the Java exception from Usergrid - * @return Returns - a new UsergridError object - * - * Example: - * - * UsergridError(message); - */ - - function UsergridError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridError.prototype = new Error(); - UsergridError.prototype.constructor = UsergridError; - /* - * Creates a UsergridError from the JSON response returned from the backend - * - * @method fromResponse - * @public - * @params {object} response - the deserialized HTTP response from the Usergrid API - * @return Returns a new UsergridError object. - * - * Example: - * { - * "error":"organization_application_not_found", - * "timestamp":1391618508079, - * "duration":0, - * "exception":"org.usergrid.rest.exceptions.OrganizationApplicationNotFoundException", - * "error_description":"Could not find application for yourorgname/sandboxxxxx from URI: yourorgname/sandboxxxxx" - * } - */ - UsergridError.fromResponse = function(response) { - if (response && "undefined" !== typeof response) { - return new UsergridError(response.error_description, response.error, response.timestamp, response.duration, response.exception); - } else { - return new UsergridError(); - } - }; - UsergridError.createSubClass = function(name) { - if (name in global && global[name]) return global[name]; - global[name] = function() {}; - global[name].name = name; - global[name].prototype = new UsergridError(); - return global[name]; - }; - - function UsergridHTTPResponseError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridHTTPResponseError.prototype = new UsergridError(); - - function UsergridInvalidHTTPMethodError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name || 'invalid_http_method'; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridInvalidHTTPMethodError.prototype = new UsergridError(); - - function UsergridInvalidURIError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name || 'invalid_uri'; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridInvalidURIError.prototype = new UsergridError(); - - function UsergridInvalidArgumentError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name || 'invalid_argument'; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridInvalidArgumentError.prototype = new UsergridError(); - - function UsergridKeystoreDatabaseUpgradeNeededError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridKeystoreDatabaseUpgradeNeededError.prototype = new UsergridError(); - - global.UsergridHTTPResponseError = UsergridHTTPResponseError; - global.UsergridInvalidHTTPMethodError = UsergridInvalidHTTPMethodError; - global.UsergridInvalidURIError = UsergridInvalidURIError; - global.UsergridInvalidArgumentError = UsergridInvalidArgumentError; - global.UsergridKeystoreDatabaseUpgradeNeededError = UsergridKeystoreDatabaseUpgradeNeededError; - - global[name] = UsergridError; - if (short !== undefined) { - //noinspection JSUnusedAssignment - global[short] = UsergridError; - } - global[name].noConflict = function() { - if (_name) { - global[name] = _name; - } - if (short !== undefined) { - global[short] = _short; - } - return UsergridError; - }; - return global[name]; -}(this)); diff --git a/lib/modules/Folder.js b/lib/modules/Folder.js deleted file mode 100644 index 9d13155..0000000 --- a/lib/modules/Folder.js +++ /dev/null @@ -1,190 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ - -/* - * A class to model a Usergrid folder. - * - * @constructor - * @param {object} options {name:"MyPhotos", path:"/user/uploads", owner:"00000000-0000-0000-0000-000000000000" } - * @returns {callback} callback(err, folder) - */ -Usergrid.Folder = function(options, callback) { - var self = this, - messages = []; - console.log("FOLDER OPTIONS", options); - self._client = options.client; - self._data = options.data || {}; - self._data.type = "folders"; - var missingData = ["name", "owner", "path"].some(function(required) { - return !(required in self._data); - }); - if (missingData) { - return doCallback(callback, [new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."), null, self], self); - } - self.save(function(err, response) { - if (err) { - doCallback(callback, [new UsergridError(response), response, self], self); - } else { - if (response && response.entities && response.entities.length) { - self.set(response.entities[0]); - } - doCallback(callback, [null, response, self], self); - } - }); -}; -/* - * Inherit from Usergrid.Entity. - */ -Usergrid.Folder.prototype = new Usergrid.Entity(); - - -/* - * fetch the folder and associated assets - * - * @method fetch - * @public - * @param {function} callback(err, self) - * @returns {callback} callback(err, self) - */ -Usergrid.Folder.prototype.fetch = function(callback) { - var self = this; - Usergrid.Entity.prototype.fetch.call(self, function(err, data) { - console.log("self", self.get()); - console.log("data", data); - if (!err) { - self.getAssets(function(err, response) { - if (err) { - doCallback(callback, [new UsergridError(response), resonse, self], self); - } else { - doCallback(callback, [null, self], self); - } - }); - } else { - doCallback(callback, [null, data, self], self); - } - }); -}; -/* - * Add an asset to the folder. - * - * @method addAsset - * @public - * @param {object} options {asset:(uuid || Usergrid.Asset || {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" }) } - * @returns {callback} callback(err, folder) - */ -Usergrid.Folder.prototype.addAsset = function(options, callback) { - var self = this; - if (('asset' in options)) { - var asset = null; - switch (typeof options.asset) { - case 'object': - asset = options.asset; - if (!(asset instanceof Usergrid.Entity)) { - asset = new Usergrid.Asset(asset); - } - break; - case 'string': - if (isUUID(options.asset)) { - asset = new Usergrid.Asset({ - client: self._client, - data: { - uuid: options.asset, - type: "assets" - } - }); - } - break; - } - if (asset && asset instanceof Usergrid.Entity) { - asset.fetch(function(err, data) { - if (err) { - doCallback(callback, [new UsergridError(data), data, self], self); - } else { - var endpoint = ["folders", self.get("uuid"), "assets", asset.get("uuid")].join('/'); - var options = { - method: 'POST', - endpoint: endpoint - }; - self._client.request(options, callback); - } - }); - } - } else { - //nothing to add - doCallback(callback, [new UsergridInvalidArgumentError("No asset specified"), null, self], self); - } -}; - -/* - * Remove an asset from the folder. - * - * @method removeAsset - * @public - * @param {object} options {asset:(uuid || Usergrid.Asset || {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" }) } - * @returns {callback} callback(err, folder) - */ -Usergrid.Folder.prototype.removeAsset = function(options, callback) { - var self = this; - if (('asset' in options)) { - var asset = null; - switch (typeof options.asset) { - case 'object': - asset = options.asset; - break; - case 'string': - if (isUUID(options.asset)) { - asset = new Usergrid.Asset({ - client: self._client, - data: { - uuid: options.asset, - type: "assets" - } - }); - } - break; - } - if (asset && asset !== null) { - var endpoint = ["folders", self.get("uuid"), "assets", asset.get("uuid")].join('/'); - self._client.request({ - method: 'DELETE', - endpoint: endpoint - }, function(err, response) { - if (err) { - doCallback(callback, [new UsergridError(response), response, self], self); - } else { - doCallback(callback, [null, response, self], self); - } - }); - } - } else { - //nothing to add - doCallback(callback, [new UsergridInvalidArgumentError("No asset specified"), null, self], self); - } -}; - -/* - * List the assets in the folder. - * - * @method getAssets - * @public - * @returns {callback} callback(err, assets) - */ -Usergrid.Folder.prototype.getAssets = function(callback) { - return this.getConnections("assets", callback); -}; diff --git a/lib/modules/Group.js b/lib/modules/Group.js deleted file mode 100644 index 1ea27c2..0000000 --- a/lib/modules/Group.js +++ /dev/null @@ -1,231 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ - - -/* - * A class to model a Usergrid group. - * Set the path in the options object. - * - * @constructor - * @param {object} options {client:client, data: {'key': 'value'}, path:'path'} - */ -Usergrid.Group = function(options, callback) { - this._path = options.path; - this._list = []; - this._client = options.client; - this._data = options.data || {}; - this._data.type = "groups"; -}; - -/* - * Inherit from Usergrid.Entity. - * Note: This only accounts for data on the group object itself. - * You need to use add and remove to manipulate group membership. - */ -Usergrid.Group.prototype = new Usergrid.Entity(); - -/* - * Fetches current group data, and members. - * - * @method fetch - * @public - * @param {function} callback - * @returns {function} callback(err, data) - */ -Usergrid.Group.prototype.fetch = function(callback) { - var self = this; - var groupEndpoint = 'groups/' + this._path; - var memberEndpoint = 'groups/' + this._path + '/users'; - - var groupOptions = { - method: 'GET', - endpoint: groupEndpoint - }; - - var memberOptions = { - method: 'GET', - endpoint: memberEndpoint - }; - - this._client.request(groupOptions, function(err, response) { - if (err) { - if (self._client.logging) { - console.log('error getting group'); - } - doCallback(callback, [err, response], self); - } else { - var entities = response.getEntities(); - if (entities && entities.length) { - var groupresponse = entities.shift(); - //self._response = groupresponse || {}; - self._client.request(memberOptions, function(err, response) { - if (err && self._client.logging) { - console.log('error getting group users'); - } else { - self._list = response.getEntities() - .filter(function(entity) { - return isUUID(entity.uuid); - }) - .map(function(entity) { - return new Usergrid.Entity({ - type: entity.type, - client: self._client, - uuid: entity.uuid, - response: entity //TODO: deprecate this property - }); - }); - } - doCallback(callback, [err, response, self], self); - }); - } - } - }); -}; - -/* - * Retrieves the members of a group. - * - * @method members - * @public - * @param {function} callback - * @return {function} callback(err, data); - */ -Usergrid.Group.prototype.members = function(callback) { - //doCallback(callback, [null, this._list, this], this); - return this._list; -}; - -/* - * Adds an existing user to the group, and refreshes the group object. - * - * Options object: {user: user_entity} - * - * @method add - * @public - * @params {object} options - * @param {function} callback - * @return {function} callback(err, data) - */ -Usergrid.Group.prototype.add = function(options, callback) { - var self = this; - if (options.user) { - options = { - method: "POST", - endpoint: "groups/" + this._path + "/users/" + options.user.get('username') - }; - this._client.request(options, function(error, response) { - if (error) { - doCallback(callback, [error, response, self], self); - } else { - self.fetch(callback); - } - }); - } else { - doCallback(callback, [new UsergridError("no user specified", 'no_user_specified'), null, this], this); - } -}; - -/* - * Removes a user from a group, and refreshes the group object. - * - * Options object: {user: user_entity} - * - * @method remove - * @public - * @params {object} options - * @param {function} callback - * @return {function} callback(err, data) - */ -Usergrid.Group.prototype.remove = function(options, callback) { - var self = this; - if (options.user) { - options = { - method: "DELETE", - endpoint: "groups/" + this._path + "/users/" + options.user.username - }; - this._client.request(options, function(error, response) { - if (error) { - doCallback(callback, [error, response, self], self); - } else { - self.fetch(callback); - } - }); - } else { - doCallback(callback, [new UsergridError("no user specified", 'no_user_specified'), null, this], this); - } -}; - -/* - * Gets feed for a group. - * - * @public - * @method feed - * @param {function} callback - * @returns {callback} callback(err, data, activities) - */ -Usergrid.Group.prototype.feed = function(callback) { - var self = this; - var options = { - method: "GET", - endpoint: "groups/" + this._path + "/feed" - }; - this._client.request(options, function(err, response) { - doCallback(callback, [err, response, self], self); - }); -}; - -/* - * Creates activity and posts to group feed. - * - * options object: {user: user_entity, content: "activity content"} - * - * @public - * @method createGroupActivity - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, entity) - */ -Usergrid.Group.prototype.createGroupActivity = function(options, callback) { - var self = this; - var user = options.user; - var entity = new Usergrid.Entity({ - client: this._client, - data: { - actor: { - "displayName": user.get("username"), - "uuid": user.get("uuid"), - "username": user.get("username"), - "email": user.get("email"), - "picture": user.get("picture"), - "image": { - "duration": 0, - "height": 80, - "url": user.get("picture"), - "width": 80 - }, - }, - "verb": "post", - "content": options.content, - "type": 'groups/' + this._path + '/activities' - } - }); - entity.save(function(err, response, entity) { - doCallback(callback, [err, response, self]); - }); -}; diff --git a/lib/modules/UsergridAsset.js b/lib/modules/UsergridAsset.js new file mode 100644 index 0000000..5bd3b59 --- /dev/null +++ b/lib/modules/UsergridAsset.js @@ -0,0 +1,29 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridAssetDefaultFileName = "file"; + +var UsergridAsset = function(fileOrBlob) { + if( !fileOrBlob instanceof File || !fileOrBlob instanceof Blob ) { + throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'"); + } + var self = this; + self.data = fileOrBlob; + self.filename = fileOrBlob.name || UsergridAssetDefaultFileName; + self.contentLength = fileOrBlob.size; + self.contentType = fileOrBlob.type; + return self; +}; \ No newline at end of file diff --git a/lib/modules/UsergridAuth.js b/lib/modules/UsergridAuth.js new file mode 100644 index 0000000..0c4aabd --- /dev/null +++ b/lib/modules/UsergridAuth.js @@ -0,0 +1,96 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridAuth = function(token, expiry) { + var self = this; + + self.token = token; + self.expiry = expiry || 0; + + var usingToken = (token) ? true : false; + + Object.defineProperty(self, "hasToken", { + get: function() { + return self.token !== undefined; + }, + configurable: true + }); + + Object.defineProperty(self, "isExpired", { + get: function() { + return (usingToken) ? false : (Date.now() >= self.expiry); + }, + configurable: true + }); + + Object.defineProperty(self, "isValid", { + get: function() { + return (!self.isExpired && self.hasToken); + }, + configurable: true + }); + + Object.defineProperty(self, "tokenTtl", { + configurable: true, + writable: true + }); + + _.assign(self, { + destroy: function() { + self.token = undefined; + self.expiry = 0; + self.tokenTtl = undefined; + } + }); + + return self; +}; + +var UsergridAppAuth = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + if (_.isPlainObject(args[0])) { + self.clientId = args[0].clientId; + self.clientSecret = args[0].clientSecret; + self.tokenTtl = args[0].tokenTtl; + } else { + self.clientId = args[0]; + self.clientSecret = args[1]; + self.tokenTtl = args[2]; + } + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; +}; +UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth); + +var UsergridUserAuth = function(options) { + var self = this; + var args = _.flattenDeep(UsergridHelpers.flattenArgs(arguments)); + if (_.isPlainObject(args[0])) { + options = args[0]; + } + self.username = options.username || args[0]; + self.email = options.email; + if (options.password || args[1]) { + self.password = options.password || args[1]; + } + self.tokenTtl = options.tokenTtl || args[2]; + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; +}; +UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth); \ No newline at end of file diff --git a/lib/modules/UsergridClient.js b/lib/modules/UsergridClient.js new file mode 100644 index 0000000..255925e --- /dev/null +++ b/lib/modules/UsergridClient.js @@ -0,0 +1,193 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridClientDefaultOptions = { + baseUrl: "https://api.usergrid.com", + authMode: UsergridAuthMode.USER +}; + +var UsergridClient = function(options) { + var self = this; + + var __appAuth; + self.tempAuth = undefined; + self.isSharedInstance = false; + + if (arguments.length === 2) { + self.orgId = arguments[0]; + self.appId = arguments[1]; + } + + _.defaults(self, options, UsergridClientDefaultOptions); + + if (!self.orgId || !self.appId) { + throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient"); + } + + Object.defineProperty(self, "clientId", { + enumerable: false + }); + + Object.defineProperty(self, "clientSecret", { + enumerable: false + }); + + Object.defineProperty(self, "appAuth", { + get: function() { + return __appAuth; + }, + set: function(options) { + if (options instanceof UsergridAppAuth) { + __appAuth = options; + } else if (typeof options !== "undefined") { + __appAuth = new UsergridAppAuth(options); + } + } + }); + + // if client ID and secret are defined on initialization, initialize appAuth + if (self.clientId && self.clientSecret) { + self.setAppAuth(self.clientId, self.clientSecret); + } + return self; +}; + +UsergridClient.prototype = { + sendRequest: function(usergridRequest) { + return usergridRequest.sendRequest(); + }, + GET: function() { + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + PUT: function() { + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + POST: function() { + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + DELETE: function() { + var usergridRequest = UsergridHelpers.buildRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + connect: function() { + var usergridRequest = UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + disconnect: function() { + var usergridRequest = UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + getConnections: function() { + var usergridRequest = UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + usingAuth: function(auth) { + var self = this; + if( _.isString(auth) ) { self.tempAuth = new UsergridAuth(auth); } + else if( auth instanceof UsergridAuth ) { self.tempAuth = auth; } + else { self.tempAuth = undefined; } + return self; + }, + setAppAuth: function() { + this.appAuth = new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments)); + }, + authenticateApp: function(options) { + var self = this; + var authenticateAppCallback = UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)); + var auth = _.first([options, self.appAuth, new UsergridAppAuth(options), new UsergridAppAuth(self.clientId, self.clientSecret)].filter(function(p) { + return p instanceof UsergridAppAuth; + })); + + if (!(auth instanceof UsergridAppAuth)) { + throw new Error("App auth context was not defined when attempting to call .authenticateApp()"); + } else if (!auth.clientId || !auth.clientSecret) { + throw new Error("authenticateApp() failed because clientId or clientSecret are missing"); + } + + var callback = function(error,usergridResponse) { + var token = _.get(usergridResponse.responseJSON,"access_token"); + var expiresIn = _.get(usergridResponse.responseJSON,"expires_in"); + if (usergridResponse.ok) { + if (!self.appAuth) { + self.appAuth = auth; + } + self.appAuth.token = token; + self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn); + self.appAuth.tokenTtl = expiresIn; + } + authenticateAppCallback(error,usergridResponse,token); + }; + + var usergridRequest = UsergridHelpers.buildAppAuthRequest(self,auth,callback); + return self.sendRequest(usergridRequest); + }, + authenticateUser: function(options) { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var setAsCurrentUser = (_.last(args.filter(_.isBoolean))) !== undefined ? _.last(args.filter(_.isBoolean)) : true; + + var userToAuthenticate = new UsergridUser(options); + userToAuthenticate.login(self, function(error, usergridResponse, token) { + if (usergridResponse.ok && setAsCurrentUser) { + self.currentUser = userToAuthenticate; + } + callback(usergridResponse.error,usergridResponse,token); + }); + }, + downloadAsset: function() { + var self = this; + var usergridRequest = UsergridHelpers.buildRequest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)); + var assetContentType = _.get(usergridRequest,"entity.file-metadata.content-type"); + if( assetContentType !== undefined ) { + _.assign(usergridRequest.headers,{"Accept":assetContentType}); + } + var realDownloadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function (error,usergridResponse) { + var entity = usergridRequest.entity; + entity.asset = usergridResponse.asset; + realDownloadAssetCallback(error,usergridResponse,entity); + }; + return self.sendRequest(usergridRequest); + }, + uploadAsset: function() { + var self = this; + var usergridRequest = UsergridHelpers.buildRequest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments)); + if (usergridRequest.asset === undefined) { + throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()"); + } + + var realUploadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function (error,usergridResponse) { + var requestEntity = usergridRequest.entity; + var responseEntity = usergridResponse.entity; + var requestAsset = usergridRequest.asset; + + if( usergridResponse.ok && responseEntity !== undefined ) { + UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse); + requestEntity.asset = requestAsset; + if( responseEntity ) { + responseEntity.asset = requestAsset; + } + } + realUploadAssetCallback(error,usergridResponse,requestEntity); + }; + return self.sendRequest(usergridRequest); + } +}; \ No newline at end of file diff --git a/lib/modules/UsergridEntity.js b/lib/modules/UsergridEntity.js new file mode 100644 index 0000000..98f3c36 --- /dev/null +++ b/lib/modules/UsergridEntity.js @@ -0,0 +1,194 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +"use strict"; + +var UsergridEntity = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + + if (args.length === 0) { + throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments"); + } + + self.asset = undefined; + + if (_.isPlainObject(args[0])) { + _.assign(self, args[0]); + } else { + if( !self.type ) { + self.type = _.isString(args[0]) ? args[0] : undefined; + } + if( !self.name ) { + self.name = _.isString(args[1]) ? args[1] : undefined; + } + } + + if (!_.isString(self.type)) { + throw new Error("'type' (or 'collection') parameter is required when initializing a UsergridEntity object"); + } + + Object.defineProperty(self, "isUser", { + get: function() { + return (self.type.toLowerCase() === "user"); + } + }); + + Object.defineProperty(self, "hasAsset", { + get: function() { + return _.has(self, "file-metadata"); + } + }); + + UsergridHelpers.setReadOnly(self, ["uuid", "name", "type", "created"]); + + return self; +}; + +UsergridEntity.prototype = { + jsonValue: function() { + var jsonValue = {}; + _.forOwn(this, function(value,key) { + jsonValue[key] = value; + }); + return jsonValue; + }, + putProperty: function(key, value) { + this[key] = value; + }, + putProperties: function(obj) { + _.assign(this, obj); + }, + removeProperty: function(key) { + this.removeProperties([key]); + }, + removeProperties: function(keys) { + var self = this; + keys.forEach(function(key) { + delete self[key]; + }); + }, + insert: function(key, value, idx) { + if (!_.isArray(this[key])) { + this[key] = this[key] ? [this[key]] : []; + } + this[key].splice.apply(this[key], [idx, 0].concat(value)); + }, + append: function(key, value) { + this.insert(key, value, Number.MAX_VALUE); + }, + prepend: function(key, value) { + this.insert(key, value, 0); + }, + pop: function(key) { + if (_.isArray(this[key])) { + this[key].pop(); + } + }, + shift: function(key) { + if (_.isArray(this[key])) { + this[key].shift(); + } + }, + reload: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + client.GET(self, function(error,usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + callback(error,usergridResponse,self); + }.bind(self)); + }, + save: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + var currentAsset = self.asset; + client.PUT(self, function(error,usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if( self.hasAsset ) { + self.asset = currentAsset; + } + callback(error,usergridResponse,self); + }.bind(self)); + }, + remove: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + client.DELETE(self, function(error,usergridResponse) { + callback(error,usergridResponse,self); + }.bind(self)); + }, + attachAsset: function(asset) { + this.asset = asset; + }, + uploadAsset: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + if( _.has(self,"asset.contentType") ) { + client.uploadAsset(self,callback); + } else { + var response = UsergridResponse.responseWithError({ + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }); + callback(response.error,response,self); + } + }, + downloadAsset: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + if( _.has(self,"asset.contentType") ) { + client.downloadAsset(self,callback); + } else { + var response = UsergridResponse.responseWithError({ + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }); + callback(response.error,response,self); + } + }, + connect: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args[0] = this; + return client.connect.apply(client, args); + }, + disconnect: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args[0] = this; + return client.disconnect.apply(client, args); + }, + getConnections: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args.shift(); + args.splice(1, 0, this); + return client.getConnections.apply(client, args); + } +}; diff --git a/lib/modules/UsergridEnums.js b/lib/modules/UsergridEnums.js new file mode 100644 index 0000000..1d11d96 --- /dev/null +++ b/lib/modules/UsergridEnums.js @@ -0,0 +1,46 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridAuthMode = Object.freeze({ + NONE: "none", + USER: "user", + APP: "app" +}); + +var UsergridDirection = Object.freeze({ + IN: "connecting", + OUT: "connections" +}); + +var UsergridHttpMethod = Object.freeze({ + GET: "GET", + PUT: "PUT", + POST: "POST", + DELETE: "DELETE" +}); + +var UsergridQueryOperator = Object.freeze({ + EQUAL: "=", + GREATER_THAN: ">", + GREATER_THAN_EQUAL_TO: ">=", + LESS_THAN: "<", + LESS_THAN_EQUAL_TO: "<=" +}); + +var UsergridQuerySortOrder = Object.freeze({ + ASC: "asc", + DESC: "desc" +}); diff --git a/lib/modules/UsergridQuery.js b/lib/modules/UsergridQuery.js new file mode 100644 index 0000000..6f551c4 --- /dev/null +++ b/lib/modules/UsergridQuery.js @@ -0,0 +1,208 @@ +/* + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * @author ryan bridges (rbridges@apigee.com) + */ + +"use strict"; + +var UsergridQuery = function(type) { + + var self = this; + + var query = "", + queryString, + sort, + urlTerms = {}, + __nextIsNot = false; + + self._type = type; + + // builder pattern + _.assign(self, { + type: function(value) { + self._type = value; + return self; + }, + collection: function(value) { + self._type = value; + return self; + }, + limit: function(value) { + self._limit = value; + return self; + }, + cursor: function(value) { + self._cursor = value; + return self; + }, + eq: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.EQUAL + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + equal: this.eq, + gt: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.GREATER_THAN + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + greaterThan: this.gt, + gte: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.GREATER_THAN_EQUAL_TO + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + greaterThanOrEqual: this.gte, + lt: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.LESS_THAN + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + lessThan: this.lt, + lte: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.LESS_THAN_EQUAL_TO + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + lessThanOrEqual: this.lte, + contains: function(key, value) { + query = self.andJoin(key + " contains " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + locationWithin: function(distanceInMeters, lat, lng) { + query = self.andJoin("location within " + distanceInMeters + " of " + lat + ", " + lng); + return self; + }, + asc: function(key) { + self.sort(key, UsergridQuerySortOrder.ASC); + return self; + }, + desc: function(key) { + self.sort(key, UsergridQuerySortOrder.DESC); + return self; + }, + sort: function(key, order) { + sort = (key && order) ? (" order by " + key + " " + order) : ""; + return self; + }, + fromString: function(string) { + queryString = string; + return self; + }, + urlTerm: function(key,value) { + if( key === "ql" ) { + self.fromString(); + } else { + urlTerms[key] = value; + } + return self; + }, + andJoin: function(append) { + if (__nextIsNot) { + append = "not " + append; + __nextIsNot = false; + } + if (!append) { + return query; + } else if (query.length === 0) { + return append; + } else { + return (_.endsWith(query, "and") || _.endsWith(query, "or")) ? (query + " " + append) : (query + " and " + append); + } + }, + orJoin: function() { + return (query.length > 0 && !_.endsWith(query, "or")) ? (query + " or") : query; + } + }); + + // public accessors + Object.defineProperty(self, "_ql", { + get: function() { + var ql = "select * "; + if (queryString !== undefined) { + ql = queryString; + } else { + ql += ((query.length > 0) ? "where " + (query || "") : ""); + ql += ((sort !== undefined) ? sort : ""); + } + return ql; + } + }); + + Object.defineProperty(self, "encodedStringValue", { + get: function() { + var self = this; + var limit = self._limit; + var cursor = self._cursor; + var requirementsString = self._ql; + var returnString = undefined; + + if( limit !== undefined ) { + returnString = "limit" + UsergridQueryOperator.EQUAL + limit; + } + if( !_.isEmpty(cursor) ) { + var cursorString = "cursor" + UsergridQueryOperator.EQUAL + cursor; + if( _.isEmpty(returnString) ) { + returnString = cursorString; + } else { + returnString += "&" + cursorString; + } + } + _.forEach(urlTerms,function(value,key) { + var encodedURLTermString = encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); + if( _.isEmpty(returnString) ) { + returnString = encodedURLTermString; + } else { + returnString += "&" + encodedURLTermString; + } + }); + if( !_.isEmpty(requirementsString) ) { + var qLString = "ql=" + encodeURIComponent(requirementsString); + if( _.isEmpty(returnString) ) { + returnString = qLString; + } else { + returnString += "&" + qLString; + } + } + + if( !_.isEmpty(returnString) ) { + returnString = "?" + returnString; + } + return !_.isEmpty(returnString) ? returnString : undefined; + } + }); + + Object.defineProperty(self, "and", { + get: function() { + query = self.andJoin(""); + return self; + } + }); + + Object.defineProperty(self, "or", { + get: function() { + query = self.orJoin(); + return self; + } + }); + + Object.defineProperty(self, "not", { + get: function() { + __nextIsNot = true; + return self; + } + }); + + return self; +}; diff --git a/lib/modules/UsergridRequest.js b/lib/modules/UsergridRequest.js new file mode 100644 index 0000000..5152622 --- /dev/null +++ b/lib/modules/UsergridRequest.js @@ -0,0 +1,107 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridRequest = function(options) { + var self = this; + var client = UsergridHelpers.validateAndRetrieveClient(options); + + if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { + throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest"); + } + + if (!_.includes(["GET", "PUT", "POST", "DELETE"], options.method)) { + throw new Error("'method' parameter is required when initializing a UsergridRequest"); + } + + self.method = options.method; + self.callback = options.callback; + self.uri = options.uri || UsergridHelpers.uri(client, options); + self.entity = options.entity; + self.body = options.body; + self.asset = options.asset; + self.query = options.query; + self.queryParams = options.queryParams || options.qs; + + var defaultHeadersToUse = !self.asset ? UsergridHelpers.DefaultHeaders : {}; + self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); + + if( self.query !== undefined ) { + self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}); + } + + if( self.queryParams ) { + _.forOwn(self.queryParams, function(value,key){ + self.uri += "?" + encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); + }); + self.uri = UsergridHelpers.normalize(self.uri,{}); + } + + if( self.asset ) { + self.body = new FormData(); + self.body.append(self.asset.filename, self.asset.data); + } else { + try{ + if( _.isPlainObject(self.body) ) { + self.body = JSON.stringify(self.body); + } else if( _.isArray(self.body) ) { + self.body = JSON.stringify(self.body); + } + } catch( exception ) { + console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: " + exception); + } + } + + return self; +}; + +UsergridRequest.prototype.sendRequest = function() { + var self = this; + + var requestPromise = function() { + var promise = new Promise(); + + var xmlHttpRequest = new XMLHttpRequest(); + xmlHttpRequest.open(self.method, self.uri,true); + xmlHttpRequest.onload = function() { promise.done(xmlHttpRequest); }; + + // Add any request headers + _.forOwn(self.headers, function(value,key) { + xmlHttpRequest.setRequestHeader(key, value); + }); + + // If we are getting something that is not JSON we must be getting an asset so set the responseType to 'blob'. + if ( self.method === UsergridHttpMethod.GET && _.get(self.headers, "Accept") !== UsergridApplicationJSONHeaderValue) { + xmlHttpRequest.responseType = "blob"; + } + + xmlHttpRequest.send(self.body); + return promise; + }; + + var responsePromise = function(xmlRequest) { + var promise = new Promise(); + var usergridResponse = new UsergridResponse(xmlRequest,self); + promise.done(usergridResponse); + return promise; + }; + + var onCompletePromise = function(usergridResponse) { + self.callback(usergridResponse.error,usergridResponse); + }; + + Promise.chain([requestPromise, responsePromise]).then(onCompletePromise); + return self; +}; \ No newline at end of file diff --git a/lib/modules/UsergridResponse.js b/lib/modules/UsergridResponse.js new file mode 100644 index 0000000..41d6038 --- /dev/null +++ b/lib/modules/UsergridResponse.js @@ -0,0 +1,125 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridResponseError = function(options) { + var self = this; + _.assign(self, options); + return self; +}; + +UsergridResponseError.fromJSON = function(responseErrorObject) { + var usergridResponseError; + var error = { name: _.get(responseErrorObject,"error") }; + if ( error.name ) { + _.assign(error, { + exception: _.get(responseErrorObject,"exception"), + description: _.get(responseErrorObject,"error_description") || _.get(responseErrorObject,"description") + }); + usergridResponseError = new UsergridResponseError(error); + } + return usergridResponseError; +}; + +var UsergridResponse = function(xmlRequest,usergridRequest) { + var self = this; + self.ok = false; + self.request = usergridRequest; + + if( xmlRequest ) { + self.statusCode = parseInt(xmlRequest.status); + self.ok = (self.statusCode < 400); + self.headers = UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders()); + + var responseContentType = _.get(self.headers,"content-type"); + if( responseContentType === UsergridApplicationJSONHeaderValue ) { + try { + var responseJSON = JSON.parse(xmlRequest.responseText); + if( responseJSON ) { + self.parseResponseJSON(responseJSON); + } + } catch (e) {} + } else { + self.asset = new UsergridAsset(xmlRequest.response); + } + } + return self; +}; + +UsergridResponse.responseWithError = function(options) { + var usergridResponse = new UsergridResponse(); + usergridResponse.error = new UsergridResponseError(options); + return usergridResponse; +}; + +UsergridResponse.prototype = { + parseResponseJSON: function(responseJSON) { + var self = this; + self.responseJSON = _.cloneDeep(responseJSON); + if (self.ok) { + self.cursor = _.get(self,"responseJSON.cursor"); + self.hasNextPage = (!_.isNil(self.cursor)); + var entitiesJSON = _.get(responseJSON,"entities"); + if (entitiesJSON) { + self.parseResponseEntities(entitiesJSON); + delete self.responseJSON.entities; + } + } else { + self.error = UsergridResponseError.fromJSON(responseJSON); + } + UsergridHelpers.setReadOnly(self.responseJSON); + }, + parseResponseEntities: function(entitiesJSON) { + var self = this; + self.entities = _.map(entitiesJSON,function(entityJSON) { + var entity = new UsergridEntity(entityJSON); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + + self.first = _.first(self.entities); + self.entity = self.first; + self.last = _.last(self.entities); + + if (_.get(self, "responseJSON.path") === "/users") { + self.user = self.first; + self.users = self.entities; + } + }, + loadNextPage: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var cursor = self.cursor; + + if (!cursor) { + callback(UsergridResponse.responseWithError({ + name:"cursor_not_found", + description:"Cursor must be present in order perform loadNextPage()."}) + ); + } else { + var client = UsergridHelpers.validateAndRetrieveClient(args); + + var type = _.last(_.get(self,"responseJSON.path").split("/")); + var limit = _.first(_.get(self,"responseJSON.params.limit")); + var ql = _.first(_.get(self,"responseJSON.params.ql")); + + var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); + client.GET(query, callback); + } + } +}; \ No newline at end of file diff --git a/lib/modules/UsergridUser.js b/lib/modules/UsergridUser.js new file mode 100644 index 0000000..7c0337c --- /dev/null +++ b/lib/modules/UsergridUser.js @@ -0,0 +1,151 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +"use strict"; + +var UsergridUser = function(obj) { + + if (! _.has(obj,"email") && !_.has(obj,"username")) { + // This is not a user entity + throw new Error("'email' or 'username' property is required when initializing a UsergridUser object"); + } + + var self = this; + + _.assign(self, obj, UsergridEntity); + UsergridEntity.call(self, "user"); + + UsergridHelpers.setWritable(self, "name"); + return self; +}; + +UsergridUser.CheckAvailable = function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + var username = args[0].username || args[1].username; + var email = args[0].email || args[1].email; + + if( !username && !email ) { + throw new Error("'username' or 'email' property is required when checking for available users"); + } else { + var checkQuery = new UsergridQuery("users"); + if (username) { + checkQuery.eq("username", username); + } + if (email) { + checkQuery.or.eq("email", email); + } + client.GET(checkQuery, function(error,usergridResponse) { + callback(error, usergridResponse, usergridResponse.entities.length > 0); + }); + } +}; +UsergridHelpers.inherits(UsergridUser, UsergridEntity); + +UsergridUser.prototype.uniqueId = function() { + var self = this; + return _.first([self.uuid, self.username, self.email].filter(_.isString)); +}; + +UsergridUser.prototype.create = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + client.POST(self, function(error,usergridResponse) { + delete self.password; + _.assign(self, usergridResponse.user); + callback(error, usergridResponse, self); + }.bind(self)); +}; + +UsergridUser.prototype.login = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + client.POST("token", UsergridHelpers.userLoginBody(self), function (error,usergridResponse) { + delete self.password; + + var responseJSON = usergridResponse.responseJSON; + var token = _.get(responseJSON,"access_token"); + var expiresIn = _.get(responseJSON,"expires_in"); + + if (usergridResponse.ok) { + self.auth = new UsergridUserAuth(self); + self.auth.token = token; + self.auth.expiry = UsergridHelpers.calculateExpiry(expiresIn); + self.auth.tokenTtl = expiresIn; + } + callback(error,usergridResponse,token); + }); +}; + +UsergridUser.prototype.logout = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + if (!self.auth || !self.auth.isValid) { + var response = UsergridResponse.responseWithError({ + name: "no_valid_token", + description: "this user does not have a valid token" + }); + callback(response.error,response); + } else { + var revokeAll = _.first(args.filter(_.isBoolean)) || false; + var requestOptions = { + client: client, + path: ["users", self.uniqueId(), ("revoketoken" + ((revokeAll) ? "s" : ""))].join("/"), + method: UsergridHttpMethod.PUT, + callback: function (error,usergridResponse) { + self.auth.destroy(); + callback(error,usergridResponse,usergridResponse.ok); + }.bind(self) + }; + if (!revokeAll) { + requestOptions.queryParams = {token: self.auth.token}; + } + var request = new UsergridRequest(requestOptions); + client.sendRequest(request); + } +}; + +UsergridUser.prototype.logoutAllSessions = function() { + var args = UsergridHelpers.flattenArgs(arguments); + args = _.concat([UsergridHelpers.validateAndRetrieveClient(args), true], args); + return this.logout.apply(this, args); +}; + +UsergridUser.prototype.resetPassword = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + + if (args[0] instanceof UsergridClient) { + args.shift(); + } + + var body = UsergridHelpers.userResetPasswordBody(args); + if (!body.oldpassword || !body.newpassword) { + throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password"); + } + client.PUT(["users",self.uniqueId(),"password"].join("/"), body, callback); +}; \ No newline at end of file diff --git a/lib/modules/util/Ajax.js b/lib/modules/util/Ajax.js deleted file mode 100644 index 4b8a381..0000000 --- a/lib/modules/util/Ajax.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - * - * @author ryan bridges (rbridges@apigee.com) - */ - -//Ajax -(function() { - var name = 'Ajax', global = this, overwrittenName = global[name], exports; - - function partial(){ - var args = Array.prototype.slice.call(arguments); - var fn=args.shift(); - return fn.bind(this, args); - } - function Ajax() { - this.logger=new global.Logger(name); - var self=this; - function encode(data) { - var result = ""; - if (typeof data === "string") { - result = data; - } else { - var e = encodeURIComponent; - for (var i in data) { - if (data.hasOwnProperty(i)) { - result += '&' + e(i) + '=' + e(data[i]); - } - } - } - return result; - } - function request(m, u, d) { - var p = new Promise(), timeout; - self.logger.time(m + ' ' + u); - (function(xhr) { - xhr.onreadystatechange = function() { - if(this.readyState === 4){ - self.logger.timeEnd(m + ' ' + u); - clearTimeout(timeout); - p.done(null, this); - } - }; - xhr.onerror=function(response){ - clearTimeout(timeout); - p.done(response, null); - }; - xhr.oncomplete=function(response){ - clearTimeout(timeout); - self.logger.timeEnd(m + ' ' + u); - self.info("%s request to %s returned %s", m, u, this.status ); - }; - xhr.open(m, u); - if (d) { - if("object"===typeof d){ - d=JSON.stringify(d); - } - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Accept", "application/json"); - } - timeout = setTimeout(function() { - xhr.abort(); - p.done("API Call timed out.", null); - }, 30000); - //TODO stick that timeout in a config variable - xhr.send(encode(d)); - }(new XMLHttpRequest())); - return p; - } - this.request=request; - this.get = partial(request,'GET'); - this.post = partial(request,'POST'); - this.put = partial(request,'PUT'); - this.delete = partial(request,'DELETE'); - } - global[name] = new Ajax(); - global[name].noConflict = function() { - if(overwrittenName){ - global[name] = overwrittenName; - } - return exports; - }; - return global[name]; -}()); diff --git a/lib/modules/util/Event.js b/lib/modules/util/Event.js deleted file mode 100644 index d826e04..0000000 --- a/lib/modules/util/Event.js +++ /dev/null @@ -1,33 +0,0 @@ -var UsergridEventable = function(){ - throw Error("'UsergridEventable' is not intended to be invoked directly"); -}; -UsergridEventable.prototype = { - bind : function(event, fn){ - this._events = this._events || {}; - this._events[event] = this._events[event] || []; - this._events[event].push(fn); - }, - unbind : function(event, fn){ - this._events = this._events || {}; - if( event in this._events === false ) return; - this._events[event].splice(this._events[event].indexOf(fn), 1); - }, - trigger : function(event /* , args... */){ - this._events = this._events || {}; - if( event in this._events === false ) return; - for(var i = 0; i < this._events[event].length; i++){ - this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); - } - } -}; -UsergridEventable.mixin = function(destObject){ - var props = ['bind', 'unbind', 'trigger']; - for(var i = 0; i < props.length; i ++){ - if(props[i] in destObject.prototype){ - console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."); - console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."); - destObject.prototype['_'+props[i]]=destObject.prototype[props[i]]; - } - destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]]; - } -}; diff --git a/lib/modules/util/Logger.js b/lib/modules/util/Logger.js deleted file mode 100644 index c3cf579..0000000 --- a/lib/modules/util/Logger.js +++ /dev/null @@ -1,89 +0,0 @@ -/* - *Licensed to the Apache Software Foundation (ASF) under one - *or more contributor license agreements. See the NOTICE file - *distributed with this work for additional information - *regarding copyright ownership. The ASF licenses this file - *to you under the Apache License, Version 2.0 (the - *"License"); you may not use this file except in compliance - *with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - * - * @author ryan bridges (rbridges@apigee.com) - */ - -//Logger -(function() { - var name = 'Logger', global = this, overwrittenName = global[name], exports; - /* logging */ - function Logger(name) { - this.logEnabled = true; - this.init(name, true); - } - Logger.METHODS=[ - "log", "error", "warn", "info", "debug", "assert", "clear", "count", - "dir", "dirxml", "exception", "group", "groupCollapsed", "groupEnd", - "profile", "profileEnd", "table", "time", "timeEnd", "trace" - ]; - Logger.prototype.init=function(name, logEnabled){ - this.name=name||"UNKNOWN"; - this.logEnabled=logEnabled||true; - var addMethod=function(method){this[method]=this.createLogMethod(method);}.bind(this); - Logger.METHODS.forEach(addMethod); - }; - Logger.prototype.createLogMethod=function(method){ - return Logger.prototype.log.bind(this, method); - }; - Logger.prototype.prefix=function(method, args){ - var prepend='['+method.toUpperCase()+']['+name+"]:\t"; - if(['log', 'error', 'warn', 'info'].indexOf(method)!==-1){ - if("string"===typeof args[0]){ - args[0]=prepend+args[0]; - }else{ - args.unshift(prepend); - } - } - return args; - }; - Logger.prototype.log=function(){ - var args=[].slice.call(arguments); - method=args.shift(); - if(Logger.METHODS.indexOf(method)===-1){ - method="log"; - } - if(!(this.logEnabled && console && console[method]))return; - args=this.prefix(method, args); - console[method].apply(console, args); - }; - Logger.prototype.setLogEnabled=function(logEnabled){ - this.logEnabled=logEnabled||true; - }; - - Logger.mixin = function(destObject){ - destObject.__logger=new Logger(destObject.name||"UNKNOWN"); - var addMethod=function(method){ - if(method in destObject.prototype){ - console.warn("overwriting '"+method+"' on '"+destObject.name+"'."); - console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."); - destObject.prototype['_'+method]=destObject.prototype[method]; - } - destObject.prototype[method]=destObject.__logger.createLogMethod(method); - }; - Logger.METHODS.forEach(addMethod); - }; - global[name] = Logger; - global[name].noConflict = function() { - if(overwrittenName){ - global[name] = overwrittenName; - } - return Logger; - }; - return global[name]; -}()); diff --git a/lib/modules/util/Promise.js b/lib/modules/util/Promise.js index 76d0d04..a4e1b21 100644 --- a/lib/modules/util/Promise.js +++ b/lib/modules/util/Promise.js @@ -19,13 +19,13 @@ * @author ryan bridges (rbridges@apigee.com) */ -//Promise +"use strict"; + (function(global) { - var name = 'Promise', overwrittenName = global[name], exports; + var name = "Promise", overwrittenName = global[name]; function Promise() { this.complete = false; - this.error = null; this.result = null; this.callbacks = []; } @@ -34,17 +34,18 @@ return callback.apply(context, arguments); }; if (this.complete) { - f(this.error, this.result); + f(this.result); } else { this.callbacks.push(f); } }; - Promise.prototype.done = function(error, result) { + Promise.prototype.done = function(result) { this.complete = true; - this.error = error; this.result = result; if(this.callbacks){ - for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](error, result); + _.forEach(this.callbacks,function(callback){ + callback(result); + }); this.callbacks.length = 0; } }; @@ -52,16 +53,14 @@ var p = new Promise(), total = promises.length, completed = 0, - errors = [], results = []; function notifier(i) { - return function(error, result) { + return function(result) { completed += 1; - errors[i] = error; results[i] = result; if (completed === total) { - p.done(errors, results); + p.done(results); } }; } @@ -70,20 +69,19 @@ } return p; }; - Promise.chain = function(promises, error, result) { + Promise.chain = function(promises, result) { var p = new Promise(); if (promises===null||promises.length === 0) { - p.done(error, result); + p.done(result); } else { - promises[0](error, result).then(function(res, err) { + promises[0](result).then(function(res) { promises.splice(0, 1); - //self.logger.info(promises.length) if(promises){ - Promise.chain(promises, res, err).then(function(r, e) { - p.done(r, e); + Promise.chain(promises, res).then(function(r) { + p.done(r); }); }else{ - p.done(res, err); + p.done(res); } }); } diff --git a/lib/modules/util/UsergridHelpers.js b/lib/modules/util/UsergridHelpers.js new file mode 100644 index 0000000..7e963ce --- /dev/null +++ b/lib/modules/util/UsergridHelpers.js @@ -0,0 +1,518 @@ +/* + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * @author ryan bridges (rbridges@apigee.com) + */ + +"use strict"; + +var UsergridApplicationJSONHeaderValue = "application/json"; + +(function(global) { + var name = "UsergridHelpers", overwrittenName = global[name]; + + function UsergridHelpers() { } + + UsergridHelpers.DefaultHeaders = Object.freeze({ + "Content-Type": UsergridApplicationJSONHeaderValue, + "Accept": UsergridApplicationJSONHeaderValue + }); + + UsergridHelpers.validateAndRetrieveClient = function(args) { + var client = _.first([args, args[0], _.get(args,"client"), (Usergrid.isInitialized) ? Usergrid : undefined].filter(function(client) { + return client instanceof UsergridClient; + })); + if( !client ) { + throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); + } + return client; + }; + + UsergridHelpers.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + + UsergridHelpers.flattenArgs = function(args) { + return _.flattenDeep(Array.prototype.slice.call(args)); + }; + + UsergridHelpers.callback = function() { + var args = UsergridHelpers.flattenArgs(arguments).reverse(); + var emptyFunc = function() {}; + return _.first(_.flattenDeep([args, _.get(args,"0.callback"), emptyFunc]).filter(_.isFunction)); + }; + + UsergridHelpers.authForRequests = function(client) { + var authForRequests = undefined; + if( _.get(client,"tempAuth.isValid") ) { + authForRequests = client.tempAuth; + client.tempAuth = undefined; + } else if( _.get(client,"currentUser.auth.isValid") && client.authMode === UsergridAuthMode.USER ) { + authForRequests = client.currentUser.auth; + } else if( _.get(client,"appAuth.isValid") && client.authMode === UsergridAuthMode.APP ) { + authForRequests = client.appAuth; + } + return authForRequests; + }; + + UsergridHelpers.userLoginBody = function(options) { + var body = { + grant_type: "password", + password: options.password + }; + if (options.tokenTtl) { + body.ttl = options.tokenTtl; + } + body[(options.username) ? "username" : "email"] = (options.username) ? options.username : options.email; + return body; + }; + + UsergridHelpers.appLoginBody = function(options) { + var body = { + grant_type: "client_credentials", + client_id: options.clientId, + client_secret: options.clientSecret + }; + if (options.tokenTtl) { + body.ttl = options.tokenTtl; + } + return body; + }; + + UsergridHelpers.userResetPasswordBody = function(args) { + return { + oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, + newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined + }; + }; + + UsergridHelpers.calculateExpiry = function(expires_in) { + return Date.now() + ((expires_in ? expires_in - 5 : 0) * 1000); + }; + + var uuidValueRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; + UsergridHelpers.isUUID = function(uuid) { + return (!uuid) ? false : uuidValueRegex.test(uuid); + }; + + UsergridHelpers.useQuotesIfRequired = function(value) { + return (_.isFinite(value) || UsergridHelpers.isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value)) ? value : ("'" + value + "'"); + }; + + UsergridHelpers.setReadOnly = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { UsergridHelpers.setReadOnly(obj, k); }); + } else if (_.isPlainObject(obj[key])) { + return Object.freeze(obj[key]); + } else if (_.isPlainObject(obj) && key === undefined) { + return Object.freeze(obj); + } else if (_.has(obj,key)) { + return Object.defineProperty(obj, key, { writable: false }); + } else { + return obj; + } + }; + + UsergridHelpers.setWritable = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setWritable(obj, k) + }); + // Note that once Object.freeze is called on an object, it cannot be unfrozen, so we need to clone it + } else if (_.isPlainObject(obj[key])) { + return _.clone(obj[key]) + } else if (_.isPlainObject(obj) && key === undefined) { + return _.clone(obj) + } else if (_.has(obj,key)) { + return Object.defineProperty(obj, key, { + writable: true + }) + } else { + return obj + } + }; + + UsergridHelpers.assignPrefabOptions = function(args) { + // if a pre-formatted options argument passed, assign it to options + if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.has(args,"method")) { + _.assign(this, args[0]) + } + return this + }; + + UsergridHelpers.normalize = function(str) { + + // remove consecutive slashes + str = str.replace(/\/+/g, "/"); + + // make sure protocol is followed by two slashes + str = str.replace(/:\//g, "://"); + + // remove trailing slash before parameters or hash + str = str.replace(/\/(\?|&|#[^!])/g, "$1"); + + // replace ? in parameters with & + str = str.replace(/(\?.+)\?/g, "$1&"); + + return str; + }; + + UsergridHelpers.urljoin = function() { + var input = arguments; + var options = {}; + + if (typeof arguments[0] === "object") { + // new syntax with array and options + input = arguments[0]; + options = arguments[1] || {}; + } + + var joined = [].slice.call(input, 0).join("/"); + return UsergridHelpers.normalize(joined, options); + }; + + UsergridHelpers.parseResponseHeaders = function(headerStr) { + var headers = {}; + if (headerStr) { + var headerPairs = headerStr.split("\u000d\u000a"); + for (var i = 0; i < headerPairs.length; i++) { + + // Can"t use split() here because it does the wrong thing + // if the header value has the string ": " in it. + + var headerPair = headerPairs[i]; + var index = headerPair.indexOf("\u003a\u0020"); + if (index > 0) { + var key = headerPair.substring(0, index).toLowerCase(); + headers[key] = headerPair.substring(index + 2); + } + } + } + return headers; + }; + + UsergridHelpers.uri = function(client, options) { + var path = ""; + if( options instanceof UsergridEntity ) { + path = options.type + } else if( options instanceof UsergridQuery ) { + path = options._type + } else if( _.isString(options) ) { + path = options + } else if( _.isArray(options) ) { + path = _.get(options,"0.type") || _.get(options,"0.path") + } else { + path = options.path || options.type || _.get(options,"entity.type") || _.get(options,"query._type") || _.get(options,"body.type") || _.get(options,"body.path") + } + + var uuidOrName = ""; + if( options.method !== UsergridHttpMethod.POST ) { + uuidOrName = _.first([ + options.uuidOrName, + options.uuid, + options.name, + _.get(options,"entity.uuid"), + _.get(options,"entity.name"), + _.get(options,"body.uuid"), + _.get(options,"body.name"), + "" + ].filter(_.isString)); + } + return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName); + }; + + UsergridHelpers.updateEntityFromRemote = function(entity,usergridResponse) { + UsergridHelpers.setWritable(entity, ["uuid", "name", "type", "created"]); + _.assign(entity, usergridResponse.entity); + UsergridHelpers.setReadOnly(entity, ["uuid", "name", "type", "created"]); + }; + + UsergridHelpers.headers = function(client, options, defaultHeaders) { + var returnHeaders = {}; + _.defaults(returnHeaders, options.headers, defaultHeaders); + _.assign(returnHeaders, { "User-Agent":"usergrid-js/v" + UsergridSDKVersion } ); + + var authForRequests = UsergridHelpers.authForRequests(client); + if (authForRequests) { + _.assign(returnHeaders, { authorization: "Bearer " + authForRequests.token }); + } + return returnHeaders; + }; + + UsergridHelpers.setEntity = function(options,args) { + options.entity = _.first([options.entity, args[0]].filter(function(property) { + return (property instanceof UsergridEntity); + })); + if (options.entity !== undefined) { + options.type = options.entity.type; + } + return options; + }; + + UsergridHelpers.setAsset = function(options,args) { + options.asset = _.first([options.asset, _.get(options,"entity.asset"), args[1], args[0]].filter(function(property) { + return (property instanceof UsergridAsset); + })); + return options; + }; + + UsergridHelpers.setUuidOrName = function(options,args) { + options.uuidOrName = _.first([ + options.uuidOrName, + options.uuid, + options.name, + _.get(options,"entity.uuid"), + _.get(options,"body.uuid"), + _.get(options,"entity.name"), + _.get(options,"body.name"), + _.get(args,"0.uuid"), + _.get(args,"0.name"), + _.get(args,"2"), + _.get(args,"1") + ].filter(_.isString)); + return options; + }; + + UsergridHelpers.setPathOrType = function(options,args) { + var pathOrType = _.first([ + args.type, + _.get(args,"0.type"), + _.get(options,"entity.type"), + _.get(args,"body.type"), + _.get(options,"body.0.type"), + _.isArray(args) ? args[0] : undefined + ].filter(_.isString)); + options[(/\//.test(pathOrType)) ? "path" : "type"] = pathOrType; + return options; + }; + + UsergridHelpers.setQs = function(options,args) { + if (options.path) { + options.qs = _.first([options.qs, args[2], args[1], args[0]].filter(_.isPlainObject)); + } + return options; + }; + + UsergridHelpers.setQuery = function(options,args) { + options.query = _.first([options,options.query, args[0]].filter(function(property) { + return (property instanceof UsergridQuery); + })); + return options; + }; + + UsergridHelpers.setAsset = function(options,args) { + options.asset = _.first([options.asset, _.get(options,"entity.asset"), args[1], args[0]].filter(function(property) { + return (property instanceof UsergridAsset); + })); + return options; + }; + + UsergridHelpers.setBody = function(options,args) { + var body = _.first([args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0]].filter(function(property) { + return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset); + })); + + if( body instanceof UsergridEntity ) { + body = body.jsonValue(); + } else if( _.isArray(body) ) { + if( body[0] instanceof UsergridEntity ) { + body = _.map(body, function(entity){ + return entity.jsonValue(); + }); + } + } + + options.body = body; + return options; + }; + + UsergridHelpers.buildRequest = function(client, method, args) { + var options = { + client: client, + method: method, + queryParams: args.queryParams || _.get(args,"0.queryParams"), + callback: UsergridHelpers.callback(args) + }; + + UsergridHelpers.assignPrefabOptions(options, args); + UsergridHelpers.setEntity(options, args); + + if( method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT ) { + UsergridHelpers.setAsset(options, args); + if( !options.asset ) { + UsergridHelpers.setBody(options, args); + if ( !options.body ) { + throw new Error("'body' is required when making a " + options.method + " request"); + } + } + } + + UsergridHelpers.setUuidOrName(options, args); + UsergridHelpers.setPathOrType(options, args); + UsergridHelpers.setQs(options, args); + UsergridHelpers.setQuery(options, args); + + options.uri = UsergridHelpers.uri(client,options); + + return new UsergridRequest(options); + }; + + UsergridHelpers.buildAppAuthRequest = function(client,auth,callback) { + var requestOptions = { + client: client, + method: UsergridHttpMethod.POST, + uri: UsergridHelpers.uri(client, {path: "token"} ), + body: UsergridHelpers.appLoginBody(auth), + callback: callback + }; + return new UsergridRequest(requestOptions); + }; + + UsergridHelpers.buildConnectionRequest = function(client,method,args) { + var options = { + client: client, + method: method, + entity: {}, + to: {}, + callback: UsergridHelpers.callback(args) + }; + + UsergridHelpers.assignPrefabOptions.call(options, args); + + // handle DELETE using "from" preposition + if (_.isObject(options.from)) { + options.to = options.from; + } + + if( _.isObject(args[0]) && _.has(args[0],"entity") && _.has(args[0],"to") ) { + _.assign(options.entity,args[0].entity); + options.relationship = _.get(args,"0.relationship"); + _.assign(options.to,args[0].to); + } + + // if an entity object or UsergridEntity instance is the first argument (source) + if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.isString(args[1])) { + _.assign(options.entity, args[0]); + options.relationship = _.first([options.relationship, args[1]].filter(_.isString)); + } + + // if an entity object or UsergridEntity instance is the third argument (target) + if (_.isObject(args[2]) && !_.isFunction(args[2])) { + _.assign(options.to, args[2]); + } + + options.entity.uuidOrName = _.first([options.entity.uuidOrName, options.entity.uuid, options.entity.name, args[1]].filter(_.isString)); + if (!options.entity.type) { + options.entity.type = _.first([options.entity.type, args[0]].filter(_.isString)); + } + options.relationship = _.first([options.relationship, args[2]].filter(_.isString)); + + if (_.isString(args[3]) && !UsergridHelpers.isUUID(args[3]) && _.isString(args[4])) { + options.to.type = args[3]; + } else if (_.isString(args[2]) && !UsergridHelpers.isUUID(args[2]) && _.isString(args[3]) && _.isObject(args[0]) && !_.isFunction(args[0])) { + options.to.type = args[2]; + } + + options.to.uuidOrName = _.first([options.to.uuidOrName, options.to.uuid, options.to.name, args[4], args[3], args[2]].filter(function(property) { + return (_.isString(options.to.type) && _.isString(property) || UsergridHelpers.isUUID(property)); + })); + + if (!_.isString(options.entity.uuidOrName)) { + throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities"); + } + + if (!_.isString(options.to.uuidOrName)) { + throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities"); + } + + if (!_.isString(options.to.type) && !UsergridHelpers.isUUID(options.to.uuidOrName)) { + throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name"); + } + + options.uri = UsergridHelpers.urljoin( + client.baseUrl, + client.orgId, + client.appId, + _.isString(options.entity.type) ? options.entity.type : "", + _.isString(options.entity.uuidOrName) ? options.entity.uuidOrName : "", + options.relationship, + _.isString(options.to.type) ? options.to.type : "", + _.isString(options.to.uuidOrName) ? options.to.uuidOrName : "" + ); + + return new UsergridRequest(options); + }; + + UsergridHelpers.buildGetConnectionRequest = function(client,args) { + var options = { + client: client, + method: "GET", + callback: UsergridHelpers.callback(args) + }; + + UsergridHelpers.assignPrefabOptions.call(options, args); + if (_.isObject(args[1]) && !_.isFunction(args[1])) { + _.assign(options, args[1]); + } + + options.direction = _.first([options.direction, args[0]].filter(function(property) { + return (property === UsergridDirection.IN || property === UsergridDirection.OUT); + })); + + options.relationship = _.first([options.relationship, args[3], args[2]].filter(_.isString)); + options.uuidOrName = _.first([options.uuidOrName, options.uuid, options.name, args[2]].filter(_.isString)); + options.type = _.first([options.type, args[1]].filter(_.isString)); + + if (!_.isString(options.type)) { + throw new Error("'type' (collection name) parameter is required when retrieving connections"); + } + + if (!_.isString(options.uuidOrName)) { + throw new Error("target entity 'uuidOrName' is required when retrieving connections"); + } + + options.uri = UsergridHelpers.urljoin( + client.baseUrl, + client.orgId, + client.appId, + _.isString(options.type) ? options.type : "", + _.isString(options.uuidOrName) ? options.uuidOrName : "", + options.direction, + options.relationship + ); + + return new UsergridRequest(options); + }; + + global[name] = UsergridHelpers; + global[name].noConflict = function() { + if (overwrittenName) { + global[name] = overwrittenName; + } + return UsergridHelpers; + }; + return global[name]; +}(this)); diff --git a/lib/modules/util/lodash.js b/lib/modules/util/lodash.js new file mode 100644 index 0000000..39b5e87 --- /dev/null +++ b/lib/modules/util/lodash.js @@ -0,0 +1,16984 @@ +/** + * @license + * lodash (Custom Build) + * Build: `lodash strict` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + 'use strict'; + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.16.4'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://github.com/es-shims.', + FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for function metadata. */ + var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + CURRY_BOUND_FLAG = 4, + CURRY_FLAG = 8, + CURRY_RIGHT_FLAG = 16, + PARTIAL_FLAG = 32, + PARTIAL_RIGHT_FLAG = 64, + ARY_FLAG = 128, + REARG_FLAG = 256, + FLIP_FLAG = 512; + + /** Used to compose bitmasks for comparison styles. */ + var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 500, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', ARY_FLAG], + ['bind', BIND_FLAG], + ['bindKey', BIND_KEY_FLAG], + ['curry', CURRY_FLAG], + ['curryRight', CURRY_RIGHT_FLAG], + ['flip', FLIP_FLAG], + ['partial', PARTIAL_FLAG], + ['partialRight', PARTIAL_RIGHT_FLAG], + ['rearg', REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', + rsComboSymbolsRange = '\\u20d0-\\u20f0', + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', + rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', + rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, + rsUpper + '+' + rsOptUpperContr, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ + function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; + } + + /** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ + function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; + } + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array ? array.length : 0; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array ? array.length : 0, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array ? array.length : 0; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array ? array.length : 0; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array ? array.length : 0; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var objectToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + iteratorSymbol = Symbol ? Symbol.iterator : undefined, + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array of at least `200` elements + * and any iteratees accept only one argument. The heuristic for whether a + * section qualifies for shortcut fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB). Change the following template settings to use + * alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || arrLength < LARGE_ARRAY_SIZE || + (arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values ? values.length : 0; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths of elements to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + isNil = object == null, + length = paths.length, + result = Array(length); + + while (++index < length) { + result[index] = isNil ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {boolean} [isFull] Specify a clone including symbols. + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, isFull, customizer, key, object, stack) { + var result; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + var props = isArr ? undefined : (isFull ? getAllKeys : keys)(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + return objectToString.call(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + if (!isKey(path, object)) { + path = castPath(path); + object = parent(object, path); + path = last(path); + } + var func = object == null ? object : object[toKey(path)]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && objectToString.call(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && objectToString.call(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = getTag(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = getTag(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) + : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, equalFunc, customizer, bitmask, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObject(value) && objectToString.call(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(object[key], srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = object[key], + srcValue = source[key], + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property identifiers to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, props) { + object = Object(object); + return basePickBy(object, props, function(value, key) { + return key in object; + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property identifiers to pick from. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, props, predicate) { + var index = -1, + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index], + value = object[key]; + + if (predicate(value, key)) { + baseAssignValue(result, key, value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } + else if (!isKey(index, array)) { + var path = castPath(index), + object = parent(array, path); + + if (object != null) { + delete object[toKey(last(path))]; + } + } + else { + delete array[toKey(index)]; + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = isKey(path, object) ? [path] : castPath(path); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array ? array.length : low; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array ? array.length : 0, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + object = parent(object, path); + + var key = toKey(last(path)); + return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var index = -1, + length = arrays.length; + + while (++index < length) { + var result = result + ? arrayPush( + baseDifference(result, arrays[index], iteratee, comparator), + baseDifference(arrays[index], result, iteratee, comparator) + ) + : arrays[index]; + } + return (result && result.length) ? baseUniq(result, iteratee, comparator) : []; + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value) { + return isArray(value) ? value : stringToPath(value); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `map`. + * + * @private + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */ + function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ + function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbol properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && + isArray(value) && value.length >= LARGE_ARRAY_SIZE) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & ARY_FLAG, + isBind = bitmask & BIND_FLAG, + isBindKey = bitmask & BIND_KEY_FLAG, + isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), + isFlip = bitmask & FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); + + if (!(bitmask & CURRY_BOUND_FLAG)) { + bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = nativeMin(toInteger(precision), 292); + if (precision) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] == null + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) { + bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, customizer, bitmask, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & PARTIAL_COMPARE_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= UNORDERED_COMPARE_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * Creates an array of the own enumerable symbol properties of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; + + /** + * Creates an array of the own and inherited enumerable symbol properties + * of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object ? object.length : 0; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG); + + var isCombo = + ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) || + ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function mergeDefaults(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, mergeDefaults, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + string = toString(string); + + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array ? array.length : 0; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs ? pairs.length : 0, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array ? array.length : 0; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (comparator === last(mapped)) { + comparator = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array ? nativeJoin.call(array, separator) : ''; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array ? array.length : 0, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array ? nativeReverse.call(array) : array; + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array ? array.length : 0; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false}, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) + ? baseUniq(array) + : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) + ? baseUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + return (array && array.length) + ? baseUniq(array, undefined, comparator) + : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] + * The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths of elements to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] + * The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + isProp = isKey(path), + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); + result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] + * The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

    ' + func(text) + '

    '; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

    fred, barney, & pebbles

    ' + */ + function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return partial(wrapper, value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, false, true); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + return baseClone(value, false, true, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, true, true); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + return baseClone(value, true, true, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return value != null && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are **not** supported. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + return (objectToString.call(value) == errorTag) || + (typeof value.message == 'string' && typeof value.name == 'string'); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || objectToString.call(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && objectToString.call(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (iteratorSymbol && value[iteratorSymbol]) { + return iteratorToArray(value[iteratorSymbol]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths of elements to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? baseAssign(result, properties) : result; + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return apply(assignInWith, undefined, args); + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, mergeDefaults); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable string keyed properties of `object` that are + * not omitted. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [props] The property identifiers to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, props) { + if (object == null) { + return {}; + } + props = arrayMap(props, toKey); + return basePick(object, baseDifference(getAllKeysIn(object), props)); + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [props] The property identifiers to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, props) { + return object == null ? {} : basePick(object, arrayMap(props, toKey)); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + return object == null ? {} : basePickBy(object, getAllKeysIn(object), getIteratee(predicate)); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + object = undefined; + length = 1; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object ? baseValues(object, keys(object)) : []; + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = baseClamp(toInteger(position), 0, string.length); + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - -
    diff --git a/tests/mocha/test.js b/tests/mocha/test.js deleted file mode 100644 index ef4ff54..0000000 --- a/tests/mocha/test.js +++ /dev/null @@ -1,1078 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/* - Creates a generic usergrid client with logging and buildCurl disabled - - */ -function getClient() { - return new Usergrid.Client({ - orgName: 'yourorgname', - appName: 'sandbox', - logging: false, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default - }); -} -/* - A convenience function that will test for the presence of an API error - and run any number of additional tests - */ -function usergridTestHarness(err, data, done, tests, ignoreError) { - if (!ignoreError) assert(!err, (err)?err.error_description:"unknown"); - if (tests) { - if ("function" === typeof tests) { - tests(err, data); - } else if (tests.length) { - tests.forEach(function(test) { - if ("function" === typeof test) { - test(err, data); - } - }) - } - } - done(); -} -describe('Ajax', function() { - var dogName="dog"+Math.floor(Math.random()*10000); - var dogData=JSON.stringify({type:"dog",name:dogName}); - var dogURI='https://api.usergrid.com/yourorgname/sandbox/dogs' - it('should POST to a URI',function(done){ - Ajax.post(dogURI, dogData).then(function(err, data){ - assert(!err, err); - done(); - }) - }) - it('should GET a URI',function(done){ - Ajax.get(dogURI+'/'+dogName).then(function(err, data){ - assert(!err, err); - done(); - }) - }) - it('should PUT to a URI',function(done){ - Ajax.put(dogURI+'/'+dogName, {"favorite":true}).then(function(err, data){ - assert(!err, err); - done(); - }) - }) - it('should DELETE a URI',function(done){ - Ajax.delete(dogURI+'/'+dogName, dogData).then(function(err, data){ - assert(!err, err); - done(); - }) - }) -}); -describe('UsergridError', function() { - var errorResponse={ - "error":"service_resource_not_found", - "timestamp":1392067967144, - "duration":0, - "exception":"org.usergrid.services.exceptions.ServiceResourceNotFoundException", - "error_description":"Service resource not found" - }; - it('should unmarshal a response from Usergrid into a proper Javascript error',function(done){ - var error = UsergridError.fromResponse(errorResponse); - assert(error.name===errorResponse.error, "Error name not set correctly"); - assert(error.message===errorResponse.error_description, "Error message not set correctly"); - done(); - }); -}); -describe('Usergrid', function(){ - describe('SDK Version', function(){ - it('should contain a minimum SDK version',function(){ - var parts=Usergrid.VERSION.split('.').map(function(i){return i.replace(/^0+/,'')}).map(function(i){return parseInt(i)}); - - assert(parts[1]>=10, "expected minor version >=10"); - assert(parts[1]>10||parts[2]>=8, "expected minimum version >=8"); - }); - }); - describe('Usergrid Request/Response', function() { - var dogName="dog"+Math.floor(Math.random()*10000); - var dogData=JSON.stringify({type:"dog",name:dogName}); - var dogURI='https://api.usergrid.com/yourorgname/sandbox/dogs' - it('should POST to a URI',function(done){ - var req=new Usergrid.Request("POST", dogURI, {}, dogData, function(err, response){ - console.error(err, response); - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - done(); - }) - }) - it('should GET a URI',function(done){ - var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - done(); - }) - }) - it('should GET an array of entity data from the Usergrid.Response object',function(done){ - var req=new Usergrid.Request("GET", dogURI, {}, null, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - var entities=response.getEntities(); - assert(entities && entities.length, "Nothing was returned") - done(); - }) - }) - it('should GET entity data from the Usergrid.Response object',function(done){ - var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(err, response){ - var entity=response.getEntity(); - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - assert(entity, "Nothing was returned") - done(); - }) - }) - it('should PUT to a URI',function(done){ - var req=new Usergrid.Request("PUT", dogURI+'/'+dogName, {}, {favorite:true}, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - done(); - }) - }) - it('should DELETE a URI',function(done){ - var req=new Usergrid.Request("DELETE", dogURI+'/'+dogName, {}, null, function(err, response){ - assert(!err, err); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - done(); - }) - }) - it('should NOT allow an invalid method',function(done){ - try{ - var req=new Usergrid.Request("INVALID", dogURI+'/'+dogName, {}, null, function(err, response){ - assert(true, "Should have thrown an UsergridInvalidHTTPMethodError"); - done(); - }) - }catch(e){ - assert(e instanceof UsergridInvalidHTTPMethodError, "Error is not and instance of UsergridInvalidHTTPMethodError"); - done() - } - }) - it('should NOT allow an invalid URI',function(done){ - try{ - var req=new Usergrid.Request("GET", "://apigee.com", {}, null, function(err, response){ - assert(true, "Should have thrown an UsergridInvalidURIError"); - done(); - }) - }catch(e){ - assert(e instanceof UsergridInvalidURIError, "Error is not and instance of UsergridInvalidURIError"); - done() - } - }) - it('should return a UsergridError object on an invalid URI',function(done){ - var req=new Usergrid.Request("GET", dogURI+'/'+dogName+'zzzzz', {}, null, function(err, response){ - assert(err, "Should have returned an error"); - assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response"); - assert(err instanceof UsergridError, "Error is not and instance of UsergridError"); - done(); - }) - }) - }); - describe('Usergrid Client', function() { - var client = getClient(); - describe('Usergrid CRUD request', function() { - before(function(done) { - this.timeout(10000); - //Make sure our dog doesn't already exist - client.request({ - method: 'DELETE', - endpoint: 'users/fred' - }, function(err, data) { - done(); - }); - }); - var options = { - method: 'GET', - endpoint: 'users' - }; - it('should persist default query parameters', function(done) { - //create new client with default params - var client=new Usergrid.Client({ - orgName: 'yourorgname', - appName: 'sandbox', - logging: false, //optional - turn on logging, off by default - buildCurl: true, //optional - turn on curl commands, off by default - qs:{ - test1:'test1', - test2:'test2' - } - }); - var default_qs=client.getObject('default_qs'); - assert(default_qs.test1==='test1', "the default query parameters were not persisted"); - assert(default_qs.test2==='test2', "the default query parameters were not persisted"); - client.request({ - method: 'GET', - endpoint: 'users' - }, function(err, data) { - assert(data.params.test2[0]==='test2', "the default query parameters were not sent to the backend"); - assert(data.params.test1[0]==='test1', "the default query parameters were not sent to the backend"); - done(); - }); - }); - it('should CREATE a new user', function(done) { - client.request({ - method: 'POST', - endpoint: 'users', - body: { - username: 'fred', - password: 'secret' - } - }, function(err, data) { - usergridTestHarness(err, data, done, [ - function(err, data) { - assert(!err) - } - ]); - }); - }); - it('should RETRIEVE an existing user', function(done) { - client.request({ - method: 'GET', - endpoint: 'users/fred', - body: {} - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(true) - } - ]); - }); - }); - it('should UPDATE an existing user', function(done) { - client.request({ - method: 'PUT', - endpoint: 'users/fred', - body: { - newkey: 'newvalue' - } - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(true) - } - ]); - }); - }); - it('should DELETE the user from the database', function(done) { - client.request({ - method: 'DELETE', - endpoint: 'users/fred' - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(true) - } - ]); - }); - }); - }); - describe('Usergrid REST', function() { - it('should return a list of users', function(done) { - client.request({ - method: 'GET', - endpoint: 'users' - }, function(err, data) { - usergridTestHarness(err, data, done, [ - function(err, data) { - assert(data.entities.length>=0, "Request should return at least one user"); - } - ]); - }); - }); - it('should return no entities when an endpoint does not exist', function(done) { - client.request({ - method: 'GET', - endpoint: 'nonexistantendpoint' - }, function(err, data) { - usergridTestHarness(err, data, done, [ - - function(err, data) { - assert(data.entities.length===0, "Request should return no entities"); - } - ]); - }); - }); - }); - describe('Usergrid convenience methods', function(){ - before(function(){ client.logout();}); - it('createEntity',function(done){ - client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - console.warn(err, response, dog); - assert(!err, "createEntity returned an error") - assert(dog, "createEntity did not return a dog") - assert(dog.get("name")==='createEntityTestDog', "The dog's name is not 'createEntityTestDog'") - done(); - }) - }) - it('createEntity - existing entity',function(done){ - client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - try{ - assert(err, "createEntity should return an error") - }catch(e){ - assert(true, "trying to create an entity that already exists throws an error"); - }finally{ - done(); - } - }); - }) - var testGroup; - it('createGroup',function(done){ - client.createGroup({path:'dogLovers'},function(err, response, group){ - try{ - assert(!err, "createGroup returned an error") - }catch(e){ - assert(true, "trying to create a group that already exists throws an error"); - }finally{ - done(); - } - /*assert(!err, "createGroup returned an error: "+err); - assert(group, "createGroup did not return a group"); - assert(group instanceof Usergrid.Group, "createGroup did not return a Usergrid.Group"); - testGroup=group; - done();*/ - }) - done(); - }) - it('buildAssetURL',function(done){ - var assetURL='https://api.usergrid.com/yourorgname/sandbox/assets/00000000-0000-0000-000000000000/data'; - assert(assetURL===client.buildAssetURL('00000000-0000-0000-000000000000'), "buildAssetURL doesn't work") - done(); - }) - var dogEntity; - it('getEntity',function(done){ - client.getEntity({type:'dog',name:'createEntityTestDog'}, function(err, response, dog){ - assert(!err, "createEntity returned an error") - assert(dog, "createEntity returned a dog") - assert(dog.get("uuid")!==null, "The dog's UUID was not returned") - dogEntity=dog; - done(); - }) - }) - it('restoreEntity',function(done){ - var serializedDog=dogEntity.serialize(); - var dog=client.restoreEntity(serializedDog); - assert(dog, "restoreEntity did not return a dog") - assert(dog.get("uuid")===dogEntity.get("uuid"), "The dog's UUID was not the same as the serialized dog") - assert(dog.get("type")===dogEntity.get("type"), "The dog's type was not the same as the serialized dog") - assert(dog.get("name")===dogEntity.get("name"), "The dog's name was not the same as the serialized dog") - - done(); - }) - var dogCollection; - it('createCollection',function(done){ - client.createCollection({type:'dogs'},function(err, response, dogs){ - assert(!err, "createCollection returned an error"); - assert(dogs, "createCollection did not return a dogs collection"); - dogCollection=dogs; - done(); - }) - }) - it('restoreCollection',function(done){ - var serializedDogs=dogCollection.serialize(); - var dogs=client.restoreCollection(serializedDogs); - console.warn('restoreCollection',dogs, dogCollection); - assert(dogs._type===dogCollection._type, "The dog collection type was not the same as the serialized dog collection") - assert(dogs._qs==dogCollection._qs, "The query strings do not match") - assert(dogs._list.length===dogCollection._list.length, "The collections have a different number of entities") - done(); - }) - var activityUser; - before(function(done){ - activityUser=new Usergrid.Entity({client:client,data:{"type":"user",'username':"testActivityUser"}}); - console.warn(activityUser); - activityUser.fetch(function(err, data){ - console.warn(err, data, activityUser); - if(err){ - activityUser.save(function(err, data){ - activityUser.set(data); - done(); - }); - }else{ - activityUser.set(data); - done(); - } - }) - }) - it('createUserActivity',function(done){ - var options = { - "actor" : { - "displayName" :"Test Activity User", - "uuid" : activityUser.get("uuid"), - "username" : "testActivityUser", - "email" : "usergrid@apigee.com", - "image" : { - "height" : 80, - "url" : "http://placekitten.com/80/80", - "width" : 80 - } - }, - "verb" : "post", - "content" : "test post for createUserActivity", - "lat" : 48.856614, - "lon" : 2.352222 - }; - client.createUserActivity("testActivityUser", options, function(err, activity){ - assert(!err, "createUserActivity returned an error"); - assert(activity, "createUserActivity returned no activity object") - done(); - }) - }) - it('createUserActivityWithEntity',function(done){ - client.createUserActivityWithEntity(activityUser, "Another test activity with createUserActivityWithEntity", function(err, activity){ - assert(!err, "createUserActivityWithEntity returned an error "+err); - assert(activity, "createUserActivityWithEntity returned no activity object") - done(); - }) - }) - it('getFeedForUser',function(done){ - client.getFeedForUser('testActivityUser', function(err, data, items){ - assert(!err, "getFeedForUser returned an error"); - assert(data, "getFeedForUser returned no data object") - assert(items, "getFeedForUser returned no items array") - done(); - }) - }) - var testProperty="____test_item"+Math.floor(Math.random()*10000), - testPropertyValue="test"+Math.floor(Math.random()*10000), - testPropertyObjectValue={test:testPropertyValue}; - it('set',function(done){ - client.set(testProperty, testPropertyValue); - done(); - }) - it('get',function(done){ - var retrievedValue=client.get(testProperty); - assert(retrievedValue===testPropertyValue, "Get is not working properly"); - done(); - }) - it('setObject',function(done){ - client.set(testProperty, testPropertyObjectValue); - done(); - }) - it('getObject',function(done){ - var retrievedValue=client.get(testProperty); - assert(retrievedValue==testPropertyObjectValue, "getObject is not working properly"); - done(); - }) - /*it('setToken',function(done){ - client.setToken("dummytoken"); - done(); - }) - it('getToken',function(done){ - assert(client.getToken()==="dummytoken"); - done(); - })*/ - it('remove property',function(done){ - client.set(testProperty); - assert(client.get(testProperty)===null); - done(); - }) - var newUser; - it('signup',function(done){ - client.signup("newUsergridUser", "Us3rgr1d15Aw3s0m3!", "usergrid@apigee.com", "Another Satisfied Developer", function(err, user){ - assert(!err, "signup returned an error"); - assert(user, "signup returned no user object") - newUser=user; - done(); - }) - }) - it('login',function(done){ - client.login("newUsergridUser", "Us3rgr1d15Aw3s0m3!", function(err, data, user){ - assert(!err, "login returned an error"); - assert(user, "login returned no user object") - done(); - }) - }) - /*it('reAuthenticateLite',function(done){ - client.reAuthenticateLite(function(err){ - assert(!err, "reAuthenticateLite returned an error"); - done(); - }) - })*/ - /*it('reAuthenticate',function(done){ - client.reAuthenticate("usergrid@apigee.com", function(err, data, user, organizations, applications){ - assert(!err, "reAuthenticate returned an error"); - done(); - }) - })*/ - /*it('loginFacebook',function(done){ - assert(true, "Not sure how feasible it is to test this with Mocha") - done(); - })*/ - it('isLoggedIn',function(done){ - assert(client.isLoggedIn()===true, "isLoggedIn is not detecting that we have logged in.") - done(); - }) - it('getLoggedInUser',function(done){ - setTimeout(function(){ - client.getLoggedInUser(function(err, data, user){ - assert(!err, "getLoggedInUser returned an error"); - assert(user, "getLoggedInUser returned no user object") - done(); - }) - },1000); - }) - before(function(done){ - //please enjoy this musical interlude. - setTimeout(function(){done()},1000); - }) - it('logout',function(done){ - client.logout(); - assert(null===client.getToken(), "we logged out, but the token still remains.") - done(); - }) - it('getLoggedInUser',function(done){ - client.getLoggedInUser(function(err, data, user){ - assert(err, "getLoggedInUser should return an error after logout"); - assert(user, "getLoggedInUser should not return data after logout") - done(); - }) - }) - it('isLoggedIn',function(done){ - assert(client.isLoggedIn()===false, "isLoggedIn still returns true after logout.") - done(); - }) - after(function (done) { - client.request({ - method: 'DELETE', - endpoint: 'users/newUsergridUser' - }, function (err, data) { - done(); - }); - - }) - it('buildCurlCall',function(done){ - done(); - }) - it('getDisplayImage',function(done){ - done(); - }) - after(function(done){ - dogEntity.destroy(); - //dogCollection.destroy(); - //testGroup.destroy(); - done(); - }) - }); - }); - describe('Usergrid Entity', function() { - var client = getClient(); - var dog; - before(function(done) { - //Make sure our dog doesn't already exist - client.request({ - method: 'DELETE', - endpoint: 'dogs/Rocky' - }, function(err, data) { - assert(true); - done(); - }); - }); - it('should CREATE a new dog', function(done) { - var options = { - type: 'dogs', - name: 'Rocky' - } - dog=new Usergrid.Entity({client:client,data:options}); - dog.save(function(err, entity) { - assert(!err, "dog not created"); - done(); - }); - }); - it('should RETRIEVE the dog', function(done) { - if (!dog) { - assert(false, "dog not created"); - done(); - return; - } - //once the dog is created, you can set single properties: - dog.fetch(function(err) { - assert(!err, "dog not fetched"); - done(); - }); - }); - it('should UPDATE the dog', function(done) { - if (!dog) { - assert(false, "dog not created"); - done(); - return; - } - //once the dog is created, you can set single properties: - dog.set('breed', 'Dinosaur'); - - //the set function can also take a JSON object: - var data = { - master: 'Fred', - state: 'hungry' - } - //set is additive, so previously set properties are not overwritten - dog.set(data); - //finally, call save on the object to save it back to the database - dog.save(function(err) { - assert(!err, "dog not saved"); - done(); - }); - }); - it('should DELETE the dog', function(done) { - if (!dog) { - assert(false, "dog not created"); - done(); - return; - } - //once the dog is created, you can set single properties: - dog.destroy(function(err) { - assert(!err, "dog not removed"); - done(); - }); - }); - }); - describe('Usergrid Collections', function() { - var client = getClient(); - var dog, dogs = {}; - - before(function(done) { - //Make sure our dog doesn't already exist - var options = { - type: 'dogs', - qs: { - limit: 50 - } //limit statement set to 50 - } - - client.createCollection(options, function(err, response, dogs) { - if (!err) { - assert(!err, "could not retrieve list of dogs: " + dogs.error_description); - //we got 50 dogs, now display the Entities: - //do doggy cleanup - //if (dogs.hasNextEntity()) { - while (dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - console.warn(dog); - //notice('removing dog ' + dogname + ' from database'); - if(dog === null) continue; - dog.destroy(function(err, data) { - assert(!err, dog.get('name') + " not removed: " + data.error_description); - if (!dogs.hasNextEntity()) { - done(); - } - }); - } - //} else { - done(); - //} - } - }); - }); - it('should CREATE a new dogs collection', function(done) { - var options = { - client:client, - type: 'dogs', - qs: { - ql: 'order by index' - } - } - dogs=new Usergrid.Collection(options); - assert(dogs!==undefined&&dogs!==null, "could not create dogs collection"); - done(); - }); - it('should CREATE dogs in the collection', function(done) { - this.timeout(10000); - var totalDogs = 30; - Array.apply(0, Array(totalDogs)).forEach(function(x, y) { - var dogNum = y + 1; - var options = { - type: 'dogs', - name: 'dog' + dogNum, - index: y - } - dogs.addEntity(options, function(err, dog) { - assert(!err, "dog not created"); - if (dogNum === totalDogs) { - done(); - } - }); - }) - }); - it('should RETRIEVE dogs from the collection', function(done) { - while (dogs.hasNextEntity()) { - //get a reference to the dog - dog = dogs.getNextEntity(); - } - if (done) done(); - }); - it('should RETRIEVE the next page of dogs from the collection', function(done) { - if (dogs.hasNextPage()) { - dogs.getNextPage(function(err) { - loop(done); - }); - } else { - done(); - } - }); - it('should RETRIEVE the previous page of dogs from the collection', function(done) { - if (dogs.hasPreviousPage()) { - dogs.getPreviousPage(function(err) { - loop(done); - }); - } else { - done(); - } - }); - it('should RETRIEVE an entity by UUID.', function(done) { - var uuid=dogs.getFirstEntity().get("uuid") - dogs.getEntityByUUID(uuid,function(err, data){ - assert(!err, "getEntityByUUID returned an error."); - assert(uuid==data.get("uuid"), "We didn't get the dog we asked for."); - done(); - }) - }); - it('should RETRIEVE the first entity from the collection', function() { - assert(dogs.getFirstEntity(), "Could not retrieve the first dog"); - }); - it('should RETRIEVE the last entity from the collection', function() { - assert(dogs.getLastEntity(), "Could not retrieve the last dog"); - }); - it('should reset the paging', function() { - dogs.resetPaging(); - assert(!dogs.hasPreviousPage(), "Could not resetPaging"); - }); - it('should reset the entity pointer', function() { - dogs.resetEntityPointer(); - assert(!dogs.hasPrevEntity(), "Could not reset the pointer"); - assert(dogs.hasNextEntity(), "Dog has no more entities"); - assert(dogs.getNextEntity(), "Could not retrieve the next dog"); - }); - it('should RETRIEVE the next entity from the collection', function() { - assert(dogs.hasNextEntity(), "Dog has no more entities"); - assert(dogs.getNextEntity(), "Could not retrieve the next dog"); - }); - it('should RETRIEVE the previous entity from the collection', function() { - assert(dogs.getNextEntity(), "Could not retrieve the next dog"); - assert(dogs.hasPrevEntity(), "Dogs has no previous entities"); - assert(dogs.getPrevEntity(), "Could not retrieve the previous dog"); - }); - it('should DELETE the entities from the collection', function(done) { - this.timeout(20000); - function remove(){ - if(dogs.hasNextEntity()){ - dogs.destroyEntity(dogs.getNextEntity(),function(err, data){ - assert(!err, "Could not destroy dog."); - remove(); - }) - }else if(dogs.hasNextPage()){ - dogs.getNextPage(); - remove(); - }else{ - done(); - } - } - remove(); - }); - }); - describe('Usergrid Counters', function() { - var client = getClient(); - var counter; - var MINUTE = 1000 * 60; - var HOUR = MINUTE * 60; - var time = Date.now() - HOUR; - - it('should CREATE a counter', function(done) { - counter = new Usergrid.Counter({ - client: client, - data: { - category: 'mocha_test', - timestamp: time, - name: "test", - counters: { - test: 0, - test_counter: 0 - } - } - }); - assert(counter, "Counter not created"); - done(); - }); - it('should save a counter', function(done) { - counter.save(function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it('should reset a counter', function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.reset({ - name: 'test' - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it("should increment 'test' counter", function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.increment({ - name: 'test', - value: 1 - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it("should increment 'test_counter' counter by 4", function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.increment({ - name: 'test_counter', - value: 4 - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it("should decrement 'test' counter", function(done) { - time += MINUTE * 10 - counter.set("timestamp", time); - counter.decrement({ - name: 'test', - value: 1 - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it('should fetch the counter', function(done) { - counter.fetch(function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - it('should fetch counter data', function(done) { - counter.getData({ - resolution: 'all', - counters: ['test', 'test_counter'] - }, function(err, data) { - assert(!err, data.error_description); - done(); - }); - }); - }); - describe('Usergrid Folders and Assets', function() { - var client = getClient(); - var folder, - asset, - user, - image_type, - image_url = 'http://placekitten.com/160/90', - // image_url="https://api.usergrid.com/yourorgname/sandbox/assets/a4025e7a-8ab1-11e3-b56c-5d3c6e4ca93f/data", - test_image, - filesystem, - file_url, - filename = "kitten.jpg", - foldername = "kittens", - folderpath = '/test/' + Math.round(10000 * Math.random()), - filepath = [folderpath, foldername, filename].join('/'); - before(function(done) { - var req = new XMLHttpRequest(); - req.open('GET', image_url, true); - req.responseType = 'blob'; - req.onload = function() { - test_image = req.response; - image_type = req.getResponseHeader('Content-Type'); - done(); - } - req.onerror = function(err) { - console.error(err); - done(); - }; - req.send(null); - }); - before(function(done) { - this.timeout(10000); - client.request({ - method: 'GET', - endpoint: 'Assets' - }, function(err, data) { - var assets = []; - if(data && data.entities && data.entities.length){ - assets.concat(data.entities.filter(function(asset) { - return asset.name === filename - })); - } - if (assets.length) { - assets.forEach(function(asset) { - client.request({ - method: 'DELETE', - endpoint: 'assets/' + asset.uuid - }); - }); - done(); - } else { - done(); - } - }); - }); - before(function(done) { - this.timeout(10000); - client.request({ - method: 'GET', - endpoint: 'folders' - }, function(err, data) { - var folders = []; - if(data && data.entities && data.entities.length){ - folders.concat(data.entities.filter(function(folder) { - return folder.name === foldername - })); - } - if (folders.length) { - folders.forEach(function(folder) { - client.request({ - method: 'DELETE', - endpoint: 'folders/' + folder.uuid - }); - }); - done(); - } else { - done(); - } - }); - }); - before(function(done) { - this.timeout(10000); - user = new Usergrid.Entity({ - client: client, - data: { - type: 'users', - username: 'assetuser' - } - }); - user.fetch(function(err, data) { - if (err) { - user.save(function() { - done(); - }) - } else { - done(); - } - }) - }); - it('should CREATE a folder', function(done) { - folder = new Usergrid.Folder({ - client: client, - data: { - name: foldername, - owner: user.get("uuid"), - path: folderpath - } - }, function(err, response, folder) { - assert(!err, err); - done(); - }); - }); - it('should CREATE an asset', function(done) { - asset = new Usergrid.Asset({ - client: client, - data: { - name: filename, - owner: user.get("uuid"), - path: filepath - } - }, function(err, response, asset) { - if(err){ - assert(false, err); - } - done(); - }); - }); - it('should RETRIEVE an asset', function(done) { - asset.fetch(function(err, response, entity){ - if(err){ - assert(false, err); - }else{ - asset=entity; - } - done(); - }) - }); - it('should upload asset data', function(done) { - this.timeout(5000); - asset.upload(test_image, function(err, response, asset) { - if(err){ - assert(false, err.error_description); - } - done(); - }); - }); - it('should retrieve asset data', function(done) { - this.timeout(5000); - asset.download(function(err, response, asset) { - if(err){ - assert(false, err.error_description); - } - assert(asset.get('content-type') == test_image.type, "MIME types don't match"); - assert(asset.get('size') == test_image.size, "sizes don't match"); - done(); - }); - }); - it('should add the asset to a folder', function(done) { - folder.addAsset({ - asset: asset - }, function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - it('should list the assets from a folder', function(done) { - folder.getAssets(function(err, assets) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - it('should remove the asset from a folder', function(done) { - folder.removeAsset({ - asset: asset - }, function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - after(function(done) { - asset.destroy(function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - after(function(done) { - folder.destroy(function(err, data) { - if(err){ - assert(false, err.error_description); - } - done(); - }) - }); - }); -}); diff --git a/tests/mocha/test_asset.js b/tests/mocha/test_asset.js new file mode 100644 index 0000000..45ae1b1 --- /dev/null +++ b/tests/mocha/test_asset.js @@ -0,0 +1,143 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('UsergridAsset ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + var asset; + + before(function (done) { + var req = new XMLHttpRequest(); + req.open('GET', testFile.uri, true); + req.responseType = 'blob'; + req.onload = function () { + asset = new UsergridAsset(req.response); + done(); + }; + req.onerror = function (err) { + console.error(err); + done(); + }; + req.send(null); + }); + + describe('init from XMLHTTPRequest', function () { + + it('asset.data should be a Javascript Blob', function () { + asset.data.should.be.an.instanceOf(Blob) + }); + + it('asset.contentType should be inferred from Blob', function () { + asset.contentType.should.equal(testFile.contentType) + }); + + it('asset.contentLength should be ' + testFile.contentLength + ' bytes', function () { + asset.contentLength.should.equal(testFile.contentLength) + }) + }); + + describe('upload via UsergridClient.uploadAsset() to a specific entity', function () { + var entity = new UsergridEntity({ + type: config.test.collection, + name: "TestClientUploadAsset" + }); + + before(function (done) { + entity.save(client, function (error,response) { + response.ok.should.be.true(); + entity.should.have.property('uuid'); + done() + }) + }); + after(function (done) { + entity.remove(client, function (error,response) { + response.ok.should.be.true(); + entity.uuid.should.be.equal(response.entity.uuid); + entity.name.should.be.equal(response.entity.name); + done() + }) + }); + it('should upload a binary asset to an entity', function (done) { + client.uploadAsset(entity, asset, function (error, assetResponse, entityWithAsset) { + assetResponse.statusCode.should.equal(200); + entityWithAsset.uuid.should.be.equal(entity.uuid); + entityWithAsset.name.should.be.equal(entity.name); + entityWithAsset.should.have.property('file-metadata'); + entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType); + entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength); + done() + }) + }) + }); + + describe('upload via entity.uploadAsset() to a specific entity', function () { + var entity = new UsergridEntity({ + type: config.test.collection, + name: "TestEntityUploadAsset" + }); + + before(function (done) { + entity.save(client, function (error,response) { + response.ok.should.be.true(); + entity.should.have.property('uuid'); + done() + }) + }); + + after(function (done) { + + entity.remove(client, function (error,response) { + response.ok.should.be.true(); + entity.uuid.should.be.equal(response.entity.uuid); + entity.name.should.be.equal(response.entity.name); + done() + }) + }); + + it('should upload a binary asset to an existing entity', function (done) { + + entity.attachAsset(asset); + entity.save(client, function () { + entity.uploadAsset(client, function (error, assetResponse, entityWithAsset) { + assetResponse.statusCode.should.equal(200); + entityWithAsset.uuid.should.be.equal(entity.uuid); + entityWithAsset.name.should.be.equal(entity.name); + entityWithAsset.should.have.property('file-metadata'); + entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType); + entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength); + done() + }) + }) + }); + it('should download a binary asset to an existing entity', function (done) { + entity.downloadAsset(client, function (error, assetResponse, entityWithAsset) { + assetResponse.statusCode.should.equal(200); + entityWithAsset.uuid.should.be.equal(entity.uuid); + entityWithAsset.name.should.be.equal(entity.name); + entityWithAsset.should.have.property('file-metadata'); + entityWithAsset['file-metadata'].should.have.property('content-type').equal(testFile.contentType); + entityWithAsset['file-metadata'].should.have.property('content-length').equal(testFile.contentLength); + done() + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_client_auth.js b/tests/mocha/test_client_auth.js new file mode 100644 index 0000000..0f2644b --- /dev/null +++ b/tests/mocha/test_client_auth.js @@ -0,0 +1,358 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + describe('Client Auth Tests ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + function getClient() { + return new UsergridClient(config); + } + + describe('authFallback', function () { + var token, + client = getClient(); + + before(function (done) { + // authenticate app and remove sandbox permissions + client.setAppAuth(config.clientId, config.clientSecret); + client.authenticateApp(function () { + token = client.appAuth.token; + var permissionsQuery = new UsergridQuery('roles/guest/permissions').urlTerm('permission', 'get,post,put,delete:/**'); + client.usingAuth(client.appAuth).DELETE(permissionsQuery, function () { + done() + }) + }) + }); + + it('should fall back to using no authentication when currentUser is not authenticated and authFallback is set to NONE', function (done) { + client.authMode = UsergridAuthMode.NONE; + client.GET('users', function (error,usergridResponse) { + should(client.currentUser).be.undefined(); + usergridResponse.request.headers.should.not.have.property('authorization'); + usergridResponse.error.name.should.equal('unauthorized'); + usergridResponse.ok.should.be.false(); + done() + }) + }); + + it('should fall back to using the app token when currentUser is not authenticated and authFallback is set to APP', function (done) { + client.authMode = UsergridAuthMode.APP; + client.GET('users', function (error,usergridResponse) { + should(client.currentUser).be.undefined(); + usergridResponse.request.headers.should.have.property('authorization').equal('Bearer ' + token); + usergridResponse.ok.should.be.true(); + usergridResponse.user.should.be.an.instanceof(UsergridUser); + done() + }) + }); + + after(function (done) { + client.authMode = UsergridAuthMode.NONE; + client.usingAuth(client.appAuth).POST('roles/guest/permissions', {'permission': 'get,post,put,delete:/**'}, function () { + done() + }) + }) + }); + + describe('authenticateApp()', function () { + + var response, token, client = getClient(); + before(function (done) { + client.setAppAuth(config.clientId, config.clientSecret); + client.authenticateApp(function (error,usergridResponse) { + response = usergridResponse; + token = client.appAuth.token; + done() + }) + }); + + it('response.ok should be true', function () { + response.ok.should.be.true() + }); + + it('should have a valid token', function () { + token.should.be.a.String(); + token.length.should.be.greaterThan(10) + }); + + it('client.appAuth.token should be set to the token returned from Usergrid', function () { + client.appAuth.should.have.property('token').equal(token) + }); + + it('client.appAuth.isValid should be true', function () { + client.appAuth.should.have.property('isValid').which.is.true() + }); + + it('client.appAuth.expiry should be set to a future date', function () { + client.appAuth.should.have.property('expiry').greaterThan(Date.now()) + }); + + it('should fail when called without a clientId and clientSecret', function () { + should(function () { + var client = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); + client.setAppAuth(undefined, undefined, 0); + client.authenticateApp() + }).throw() + }); + + it('should authenticate by passing clientId and clientSecret in an object', function (done) { + var isolatedClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }); + isolatedClient.authenticateApp({ + clientId: config.clientId, + clientSecret: config.clientSecret + }, function () { + isolatedClient.appAuth.should.have.property('token'); + done() + }) + }); + + it('should authenticate by passing a UsergridAppAuth instance with a custom ttl', function (done) { + var isolatedClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }); + var ttlInMilliseconds = 500000; + var appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, ttlInMilliseconds); + isolatedClient.authenticateApp(appAuth, function (error,response) { + isolatedClient.appAuth.should.have.property('token'); + response.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000); + done() + }) + }); + + it('should not set client.appAuth when authenticating with a bad clientId and clientSecret in an object', function (done) { + var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); + failClient.authenticateApp({ + clientId: 'BADCLIENTID', + clientSecret: 'BADCLIENTSECRET' + }, function (error,response) { + error.should.containDeep({ + name: 'invalid_grant', + description: 'invalid username or password' + }); + should(failClient.appAuth).be.undefined(); + done() + }) + }); + + it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using an object)', function (done) { + var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); + failClient.authenticateApp(new UsergridAppAuth({ + clientId: 'BADCLIENTID', + clientSecret: 'BADCLIENTSECRET' + }), function (error,response) { + error.should.containDeep({ + name: 'invalid_grant', + description: 'invalid username or password' + }); + should(failClient.appAuth).be.undefined(); + done() + }) + }); + + + it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using arguments)', function (done) { + var failClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); + failClient.authenticateApp(new UsergridAppAuth('BADCLIENTID', 'BADCLIENTSECRET'), function (error,response) { + error.should.containDeep({ + name: 'invalid_grant', + description: 'invalid username or password' + }); + should(failClient.appAuth).be.undefined(); + done() + }) + }) + }); + + describe('authenticateUser()', function () { + + var response, token, email = randomWord() + '@' + randomWord() + '.com'; + var client = getClient(); + before(function (done) { + client.authenticateUser({ + username: config.test.username, + password: config.test.password, + email: email + }, function (error, usergridResponse, authToken) { + response = usergridResponse; + token = authToken + done() + }) + }); + + it('should fail when called without a email (or username) and password', function () { + should(function () { + var badClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }); + badClient.authenticateUser({}) + }).throw() + }); + + it('response.ok should be true', function () { + response.ok.should.be.true() + }); + + it('should have a valid token', function () { + token.should.be.a.String(); + token.length.should.be.greaterThan(10) + }); + + it('client.currentUser.auth.token should be set to the token returned from Usergrid', function () { + client.currentUser.auth.should.have.property('token').equal(token) + }); + + it('client.currentUser.auth.isValid should be true', function () { + client.currentUser.auth.should.have.property('isValid').which.is.true() + }); + + it('client.currentUser.auth.expiry should be set to a future date', function () { + client.currentUser.auth.should.have.property('expiry').greaterThan(Date.now()) + }); + + it('client.currentUser should have a username and email', function () { + client.currentUser.should.have.property('username'); + client.currentUser.should.have.property('email').equal(email) + }); + + it('client.currentUser and client.currentUser.auth should not store password', function () { + client.currentUser.should.not.have.property('password'); + client.currentUser.auth.should.not.have.property('password') + }); + + it('should support an optional bool to not set as current user', function (done) { + var noCurrentUserClient = new UsergridClient({ + orgId: config.orgId, + appId: config.appId, + baseUrl: config.baseUrl + }); + noCurrentUserClient.authenticateUser({ + username: config.test.username, + password: config.test.password, + email: config.test.email + }, false, function (error,response) { + should(noCurrentUserClient.currentUser).be.undefined(); + done() + }) + }); + + it('should support passing a UsergridUserAuth instance with a custom ttl', function (done) { + var newClient = new UsergridClient({orgId: config.orgId, appId: config.appId, baseUrl: config.baseUrl}); + var ttlInMilliseconds = 500000; + var userAuth = new UsergridUserAuth(config.test.username, config.test.password, ttlInMilliseconds); + newClient.authenticateUser(userAuth, function (error, usergridResponse, authToken) { + usergridResponse.ok.should.be.true(); + newClient.currentUser.auth.token.should.equal(authToken); + usergridResponse.responseJSON.expires_in.should.equal(ttlInMilliseconds / 1000); + done() + }) + }) + }); + + describe('appAuth, setAppAuth()', function () { + var client = getClient(); + it('should initialize by passing a list of arguments', function () { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl); + client.appAuth.should.be.instanceof(UsergridAppAuth) + }); + + it('should be a subclass of UsergridAuth', function () { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl); + client.appAuth.should.be.instanceof(UsergridAuth) + }); + + it('should initialize by passing an object', function () { + client.setAppAuth({ + clientId: config.clientId, + clientSecret: config.clientSecret, + tokenTtl: config.tokenTtl + }); + client.appAuth.should.be.instanceof(UsergridAppAuth) + }); + + it('should initialize by passing an instance of UsergridAppAuth', function () { + client.setAppAuth(new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl)); + client.appAuth.should.be.instanceof(UsergridAppAuth) + }); + + it('should initialize by setting to an instance of UsergridAppAuth', function () { + client.appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl); + client.appAuth.should.be.instanceof(UsergridAppAuth) + }) + }); + + describe('usingAuth()', function () { + + var client = getClient(), + authFromToken; + + before(function (done) { + client.authenticateUser({ + username: config.test.username, + password: config.test.password + }, function (error, response, token) { + authFromToken = new UsergridAuth(token); + done() + }) + }); + + it('should authenticate using an ad-hoc token', function (done) { + authFromToken.isValid.should.be.true(); + authFromToken.should.have.property('token'); + client.usingAuth(authFromToken).GET('/users/me', function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + usergridResponse.should.have.property('user').which.is.an.instanceof(UsergridUser); + usergridResponse.user.should.have.property('uuid'); + done() + }) + }); + + it('client.tempAuth should be destroyed after making a request with ad-hoc authentication', function (done) { + should(client.tempAuth).be.undefined(); + done() + }); + + it('should send an unauthenticated request when UsergridAuth.NO_AUTH is passed to .usingAuth()', function (done) { + client.authMode = UsergridAuthMode.NONE; + client.GET('/users/me', function (error,usergridResponse) { + usergridResponse.ok.should.be.false(); + usergridResponse.request.headers.should.not.have.property('authentication'); + usergridResponse.should.not.have.property('user'); + done() + }) + }); + + it('should send an unauthenticated request when no arguments are passed to .usingAuth()', function (done) { + client.usingAuth().GET('/users/me', function (error,usergridResponse) { + usergridResponse.ok.should.be.false(); + usergridResponse.request.headers.should.not.have.property('authentication'); + usergridResponse.should.not.have.property('user'); + done() + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_client_connections.js b/tests/mocha/test_client_connections.js new file mode 100644 index 0000000..caa775a --- /dev/null +++ b/tests/mocha/test_client_connections.js @@ -0,0 +1,269 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('Client Connections ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + var response, + entity1, + entity2; + + before(function (done) { + // Create the entities we're going to use for connections + client.POST({ + type: config.test.collection, + body: [{"name": "testClientConnectOne"}, {"name": "testClientConnectTwo"}] + }, function (error,postResponse) { + response = postResponse; + entity1 = response.first; + entity2 = response.last; + done() + }) + }); + + after(function (done) { + // Delete the entities we used for connections + _.forEach(response.entities, function (entity) { + entity.remove(client) + }); + done() + }); + + describe('connect()', function () { + + it('should connect entities by passing UsergridEntity objects as parameters', function (done) { + var relationship = "foos"; + + client.connect(entity1, relationship, entity2, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should connect entities by passing a source UsergridEntity object and a target uuid', function (done) { + var relationship = "bars"; + + client.connect(entity1, relationship, entity2.uuid, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should connect entities by passing source type, source uuid, and target uuid as parameters', function (done) { + var relationship = "bazzes"; + + client.connect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should connect entities by passing source type, source name, target type, and target name as parameters', function (done) { + var relationship = "quxes"; + + client.connect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should connect entities by passing a preconfigured options object', function (done) { + var options = { + entity: entity1, + relationship: "quuxes", + to: entity2 + }; + + client.connect(options, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[options.relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + options.relationship, + entity2.uuid, + "connecting", + options.relationship + )); + done() + }) + }) + }); + + it('should fail to connect entities when specifying target name without type', function () { + should(function () { + client.connect(entity1.type, entity1.name, "fails", 'badName', function () { + }) + }).throw() + }) + }); + + describe('getConnections()', function () { + + it('should get an entity\'s outbound connections', function (done) { + + var relationship = "foos"; + + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }); + + it('should get an entity\'s inbound connections', function (done) { + + var relationship = "foos"; + + client.getConnections(UsergridDirection.IN, entity2, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( + "/", + config.test.collection, + entity2.uuid, + "connecting", + entity1.uuid, + relationship + )); + done() + }) + }) + }); + + describe('disconnect()', function () { + + it('should disconnect entities by passing UsergridEntity objects as parameters', function (done) { + + var relationship = "foos"; + + client.disconnect(entity1, relationship, entity2, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should disconnect entities by passing source type, source uuid, and target uuid as parameters', function (done) { + + var relationship = "bars"; + + client.disconnect(entity1.type, entity1.uuid, relationship, entity2.uuid, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should disconnect entities by passing source type, source name, target type, and target name as parameters', function (done) { + + var relationship = "bazzes"; + + client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should disconnect entities by passing a preconfigured options object', function (done) { + + var options = { + entity: entity1, + relationship: "quxes", + to: entity2 + }; + + client.disconnect(options, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, options.relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should fail to disconnect entities when specifying target name without type', function () { + + should(function () { + client.disconnect(entity1.type, entity1.name, "fails", entity2.name, function () { + }) + }).throw() + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_client_init.js b/tests/mocha/test_client_init.js new file mode 100644 index 0000000..a909231 --- /dev/null +++ b/tests/mocha/test_client_init.js @@ -0,0 +1,47 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +describe('Client Initialization', function() { + it('should fail to initialize without an orgId and appId', function() { + should(function() { + var client = new UsergridClient(null, null); + client.GET() + }).throw() + }); + + // it('should initialize using properties defined in config.json', function() { + // var client = new UsergridClient() + // client.should.be.an.instanceof(UsergridClient).with.property('orgId').equal(config.orgId) + // client.should.have.property('appId').equal(config.appId) + // }) + + it('should initialize when passing orgId and appId as arguments, taking precedence over config', function() { + var client = new UsergridClient('foo', 'bar'); + client.should.be.an.instanceof(UsergridClient).with.property('orgId').equal('foo'); + client.should.have.property('appId').equal('bar') + }); + + it('should initialize when passing an object containing orgId and appId, taking precedence over config', function() { + var client = new UsergridClient({ + orgId: 'foo', + appId: 'bar', + baseUrl: 'https://sdk-example-test.apigee.net/appservices' + }); + client.should.be.an.instanceof(UsergridClient).with.property('orgId').equal('foo'); + client.should.have.property('appId').equal('bar'); + client.should.have.property('baseUrl').equal('https://sdk-example-test.apigee.net/appservices') + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_client_rest.js b/tests/mocha/test_client_rest.js new file mode 100644 index 0000000..684037c --- /dev/null +++ b/tests/mocha/test_client_rest.js @@ -0,0 +1,489 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('Client REST Tests ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + var _uuid; + + describe('POST()', function () { + + var response; + before(function (done) { + client.POST({ + type: config.test.collection, body: { + author: 'Sir Arthur Conan Doyle' + } + }, function (error,usergridResponse) { + response = usergridResponse; + _uuid = usergridResponse.entity.uuid; + done() + }) + }); + + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.POST(config.test.collection, {}) + }); + + it('response.ok should be true', function () { + response.ok.should.be.true() + }); + + it('response.entities should be an array', function () { + response.entities.should.be.an.Array().with.a.lengthOf(1) + }); + + it('response.entity should exist and have a valid uuid', function () { + response.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + });; + + it('response.entity.author should equal "Sir Arthur Conan Doyle"', function () { + response.entity.should.have.property('author').equal('Sir Arthur Conan Doyle') + }); + + it('should support creating an entity by passing a UsergridEntity object', function (done) { + + var entity = new UsergridEntity({ + type: config.test.collection, + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + }); + + client.POST(entity, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant); + sleepFor(config.defaultSleepTime); + client.DELETE(usergridResponse.entity, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); + done() + }) + }) + }); + + it('should support creating an entity by passing a UsergridEntity object with a unique name', function (done) { + var entity = new UsergridEntity({ + type: config.test.collection, + name: randomWord() + }); + client.POST(entity, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('name').equal(entity.name); + sleepFor(config.defaultSleepTime); + client.DELETE(usergridResponse.entity, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); + done() + }) + }) + }); + + it('should support creating an entity by passing type and a body object', function (done) { + var options = { + type: config.test.collection, + body: { + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + } + }; + client.POST(options, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish"); + sleepFor(config.defaultSleepTime); + client.DELETE(usergridResponse.entity, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); + done() + }) + }) + }); + + it('should support creating an entity by passing a body object that includes type', function (done) { + var options = { + body: { + type: config.test.collection, + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + } + }; + client.POST(options, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal("Dino's Deep Dish"); + sleepFor(config.defaultSleepTime); + client.DELETE(usergridResponse.entity, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); + done() + }) + }) + }); + + it('should support creating an entity by passing an array of UsergridEntity objects', function (done) { + var entities = [ + new UsergridEntity({ + type: config.test.collection, + restaurant: "Dino's Deep Dish", + cuisine: "pizza" + }), new UsergridEntity({ + type: config.test.collection, + restaurant: "Giordanos", + cuisine: "pizza" + }) + ]; + + client.POST({ + body: entities, callback: function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(2); + _.forEach(usergridResponse.entities, function (entity) { + entity.should.be.an.Object().with.property('restaurant').equal(entity.restaurant) + }); + done() + } + }) + }); + + it('should support creating an entity by passing a preformatted POST builder object', function (done) { + var options = { + type: config.test.collection, + body: { + restaurant: "Chipotle", + cuisine: "mexican" + } + }; + + client.POST(options, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('restaurant').equal(usergridResponse.entity.restaurant); + usergridResponse.entity.remove(client, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); + done() + }) + }) + }) + }); + + describe('GET()', function () { + + var response; + before(function (done) { + client.GET({type: config.test.collection}, function (error,usergridResponse) { + response = usergridResponse; + done() + }) + }); + + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.GET(config.test.collection) + }); + + it('response.ok should be true', function () { + response.ok.should.be.true() + }); + + it('response.entities should be an array', function () { + response.entities.should.be.an.Array() + }); + + it('response.first should exist and have a valid uuid', function () { + response.first.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + });; + + it('response.entity should exist and have a valid uuid', function () { + response.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + });; + + it('response.last should exist and have a valid uuid', function () { + response.last.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + });; + + it('each entity should match the search criteria when passing a UsergridQuery object', function (done) { + var query = new UsergridQuery(config.test.collection).eq('author', 'Sir Arthur Conan Doyle'); + client.GET(query, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(1); + usergridResponse.entities.forEach(function (entity) { + entity.should.be.an.Object().with.property('author').equal('Sir Arthur Conan Doyle') + }); + done() + }) + }); + + it('a single entity should be retrieved when specifying a uuid', function (done) { + client.GET(config.test.collection, response.entity.uuid, function (error,usergridResponse) { + usergridResponse.should.have.property('entity').which.is.an.instanceof(UsergridEntity); + usergridResponse.entities.should.be.an.Array().with.a.lengthOf(1); + done() + }) + }) + }); + + describe('PUT()', function () { + + var response; + + before(function (done) { + client.PUT(config.test.collection, _uuid, {narrator: 'Peter Doyle'}, function (error,usergridResponse) { + response = usergridResponse; + done() + }) + }); + after(function (done) { + client.DELETE(response.entity, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(response.entity.uuid); + done() + }) + }); + + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.PUT(config.test.collection, _uuid, {}) + }); + + it('response.ok should be true', function () { + response.ok.should.be.true() + }); + + it('response.entities should be an array with a single entity', function () { + response.entities.should.be.an.Array().with.a.lengthOf(1) + }); + + it('response.entity should exist and its uuid should the uuid from the previous POST request', function () { + response.entity.should.be.an.Object().with.property('uuid').equal(_uuid) + }); + + it('response.entity.narrator should be updated to "Peter Doyle"', function () { + response.entity.should.have.property('narrator').equal('Peter Doyle') + }); + + it('should create a new entity when no uuid or name is passed', function (done) { + var newEntity = new UsergridEntity({ + type: config.test.collection, + author: 'Frank Mills' + }); + + client.PUT(newEntity, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object(); + usergridResponse.entity.should.be.an.instanceof(UsergridEntity).with.property('uuid')//.which.is.a.uuid() + usergridResponse.entity.should.have.property('author').equal('Frank Mills'); + usergridResponse.entity.created.should.equal(usergridResponse.entity.modified); + sleepFor(config.defaultSleepTime); + client.DELETE(usergridResponse.entity, function (error,delResponse) { + delResponse.entity.should.be.an.Object(); + delResponse.entity.should.have.property('uuid').equal(usergridResponse.entity.uuid); + done() + }) + }); + }); + + it('should support updating the entity by passing a UsergridEntity object', function (done) { + + var updateEntity = _.assign(response.entity, { + publisher: { + name: "George Newns", + date: "14 October 1892", + country: "United Kingdom" + } + }); + + client.PUT(updateEntity, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('publisher').deepEqual(updateEntity.publisher); + done() + }) + }); + + it('should support updating an entity by passing type and a body object', function (done) { + + var options = { + type: config.test.collection, + body: { + uuid: response.entity.uuid, + updateByPassingTypeAndBody: true + } + }; + client.PUT(options, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('updateByPassingTypeAndBody').equal(true); + done() + }) + }); + + it('should support updating an entity by passing a body object that includes type', function (done) { + + var options = { + type: config.test.collection, + body: { + type: config.test.collection, + uuid: response.entity.uuid, + updateByPassingBodyIncludingType: true + } + }; + client.PUT(options, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('updateByPassingBodyIncludingType').equal(true); + done() + }) + }); + + it('should support updating a set of entities by passing an UsergridQuery object', function (done) { + var query = new UsergridQuery(config.test.collection).eq('cuisine', 'pizza').limit(2); + var body = { + testUuid: uuid() + }; + + sleepFor(config.defaultSleepTime); + client.PUT(query, body, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(2); + usergridResponse.entities.forEach(function (entity) { + entity.should.be.an.Object().with.property('testUuid').equal(body.testUuid) + }); + sleepFor(config.defaultLongSleepTime + config.defaultSleepTime); + client.DELETE(query, function (error,delResponse) { + delResponse.entities.should.be.an.Array().with.lengthOf(usergridResponse.entities.length); + done() + }) + }) + }); + + it('should support updating an entity by passing a preformatted PUT builder object', function (done) { + + var options = { + uuid: response.entity.uuid, + type: config.test.collection, + body: { + relatedUuid: uuid() + } + }; + + client.PUT(options, function (error,usergridResponse) { + usergridResponse.entity.should.be.an.Object().with.property('relatedUuid').equal(options.body.relatedUuid); + done() + }) + }) + }); + + describe('DELETE()', function () { + + var response; + before(function (done) { + client.DELETE(config.test.collection, _uuid, function () { + client.GET(config.test.collection, _uuid, function (error,usergridResponse) { + response = usergridResponse; + done() + }) + }) + }); + + it('should not fail when a callback function is not passed', function () { + // note: this test will NOT fail gracefully inside the Mocha event chain + client.DELETE(config.test.collection, _uuid) + }); + + it('should return a 404 not found', function () { + response.statusCode.should.equal(404) + }); + + it('response.error.name should equal "entity_not_found"', function () { + response.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found') + }); + + it('should support deleting an entity by passing a UsergridEntity object', function (done) { + var entity = new UsergridEntity({ + type: config.test.collection, + command: "CTRL+ALT+DEL" + }); + + client.POST(entity, function (error,postResponse) { + postResponse.entity.should.have.property('uuid'); + postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL'); + sleepFor(config.defaultSleepTime); + client.DELETE(postResponse.entity, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid); + sleepFor(config.defaultSleepTime); + client.GET(config.test.collection, postResponse.entity.uuid, function (error,getResponse) { + getResponse.ok.should.be.false(); + getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found'); + done() + }) + }) + }) + }); + + it('should support deleting an entity by passing type and uuid', function (done) { + var body = { + command: "CTRL+ALT+DEL" + }; + + client.POST(config.test.collection, body, function (error,postResponse) { + postResponse.entity.should.have.property('uuid'); + postResponse.entity.should.have.property('command').equal('CTRL+ALT+DEL'); + sleepFor(config.defaultSleepTime); + client.DELETE(config.test.collection, postResponse.entity.uuid, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid); + sleepFor(config.defaultSleepTime); + client.GET(config.test.collection, postResponse.entity.uuid, function (error,getResponse) { + getResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found'); + done() + }) + }) + }) + }); + + it('should support deleting multiple entities by passing a UsergridQuery object', function (done) { + var entity = new UsergridEntity({ + type: config.test.collection, + command: "CMD" + }); + + var query = new UsergridQuery(config.test.collection).eq('command', 'CMD'); + + client.POST({ + body: [entity, entity, entity, entity], callback: function (error,postResponse) { + postResponse.entities.should.be.an.Array().with.lengthOf(4); + sleepFor(config.defaultLongSleepTime); + client.DELETE(query, function (error,delResponse) { + delResponse.entities.should.be.an.Array().with.lengthOf(4); + sleepFor(config.defaultLongSleepTime); + client.GET(query, function (error,getResponse) { + getResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + } + }) + }); + + it('should support deleting an entity by passing a preformatted DELETE builder object', function (done) { + var options = { + type: config.test.collection, + body: { + restaurant: "IHOP", + cuisine: "breakfast" + } + }; + + client.POST(options, function (error,postResponse) { + postResponse.entity.should.have.property('uuid'); + postResponse.entity.should.have.property('restaurant').equal('IHOP'); + postResponse.entity.should.have.property('cuisine').equal('breakfast'); + sleepFor(config.defaultSleepTime); + client.DELETE(config.test.collection, postResponse.entity.uuid, function (error,delResponse) { + delResponse.entity.should.have.property('uuid').equal(postResponse.entity.uuid); + sleepFor(config.defaultSleepTime); + client.GET(config.test.collection, postResponse.entity.uuid, function (error,delResponse) { + delResponse.error.name.should.equal((config.target === '1.0') ? 'service_resource_not_found' : 'entity_not_found'); + done() + }) + }) + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_entity.js b/tests/mocha/test_entity.js new file mode 100644 index 0000000..95bd1ab --- /dev/null +++ b/tests/mocha/test_entity.js @@ -0,0 +1,609 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('UsergridEntity ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + describe('putProperty()', function () { + it('should set the value for a given key if the key does not exist', function () { + var entity = new UsergridEntity('cat', 'Cosmo'); + entity.putProperty('foo', ['bar']); + entity.should.have.property('foo').deepEqual(['bar']) + }); + + it('should overwrite the value for a given key if the key exists', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }); + entity.putProperty('foo', 'bar'); + entity.should.have.property('foo').deepEqual('bar') + }); + + it('should not be able to set the name key (name is immutable)', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }); + should(function() { + entity.putProperty('name', 'Bazinga'); + }).throw(); + entity.should.have.property('name').deepEqual('Cosmo'); + }) + }); + + describe('putProperties()', function () { + it('should set properties for a given object, overwriting properties that exist and creating those that don\'t', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }); + entity.putProperties({ + foo: 'baz', + qux: 'quux', + barray: [1, 2, 3, 4] + }); + entity.should.containEql({ + type: 'cat', + name: 'Cosmo', + foo: 'baz', + qux: 'quux', + barray: [1, 2, 3, 4] + }) + }); + + it('should not be able to set properties for immutable keys', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }); + should(function() { + entity.putProperties({ + name: 'Bazinga', + uuid: 'BadUuid', + bar: 'qux' + }); + }).throw(); + entity.should.containEql({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }) + }) + }); + + describe('removeProperty()', function () { + it('should remove a given property if it exists', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'baz' + }); + entity.removeProperty('foo'); + entity.should.not.have.property('foo') + }); + + it('should fail gracefully when removing an undefined property', function () { + var entity = new UsergridEntity('cat', 'Cosmo'); + entity.removeProperty('foo'); + entity.should.not.have.property('foo') + }) + }); + + describe('removeProperties()', function () { + it('should remove an array of properties for a given object, failing gracefully for undefined properties', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar', + baz: 'qux' + }); + entity.removeProperties(['foo', 'baz']); + entity.should.containEql({ + type: 'cat', + name: 'Cosmo' + }) + }) + }); + + describe('insert()', function () { + it('should insert a single value into an existing array at the specified index', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3, 5, 6] + }); + entity.insert('foo', 4, 3); + entity.should.have.property('foo').deepEqual([1, 2, 3, 4, 5, 6]) + }); + + it('should merge an array of values into an existing array at the specified index', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3, 7, 8] + }); + entity.insert('foo', [4, 5, 6], 3); + entity.should.have.property('foo').deepEqual([1, 2, 3, 4, 5, 6, 7, 8]) + }); + + it('should convert an existing value into an array when inserting a second value', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }); + entity.insert('foo', 'baz', 1); + entity.should.have.property('foo').deepEqual(['bar', 'baz']) + }); + + it('should create a new array when a property does not exist', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo' + }); + entity.insert('foo', 'bar', 1000); + entity.should.have.property('foo').deepEqual(['bar']) + }); + + it('should gracefully handle indexes out of range', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: ['bar'] + }); + entity.insert('foo', 'baz', 1000); + entity.should.have.property('foo').deepEqual(['bar', 'baz']); + entity.insert('foo', 'qux', -1000); + entity.should.have.property('foo').deepEqual(['qux', 'bar', 'baz']) + }) + }); + + describe('append()', function () { + it('should append a value to the end of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }); + entity.append('foo', 4); + entity.should.have.property('foo').deepEqual([1, 2, 3, 4]) + }); + + it('should create a new array if a property does not exist', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo' + }); + entity.append('foo', 'bar'); + entity.should.have.property('foo').deepEqual(['bar']) + }) + }); + + describe('prepend()', function () { + it('should prepend a value to the beginning of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }); + entity.prepend('foo', 0); + entity.should.have.property('foo').deepEqual([0, 1, 2, 3]) + }); + + it('should create a new array if a property does not exist', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo' + }); + entity.prepend('foo', 'bar'); + entity.should.have.property('foo').deepEqual(['bar']) + }) + }); + + describe('pop()', function () { + it('should remove the last value of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }); + entity.pop('foo'); + entity.should.have.property('foo').deepEqual([1, 2]) + }); + + it('value should remain unchanged if it is not an array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }); + entity.pop('foo'); + entity.should.have.property('foo').deepEqual('bar') + }); + + it('should gracefully handle empty arrays', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [] + }); + entity.pop('foo'); + entity.should.have.property('foo').deepEqual([]) + }) + }); + + describe('shift()', function () { + it('should remove the first value of an existing array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [1, 2, 3] + }); + entity.shift('foo'); + entity.should.have.property('foo').deepEqual([2, 3]) + }); + + it('value should remain unchanged if it is not an array', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: 'bar' + }); + entity.shift('foo'); + entity.should.have.property('foo').deepEqual('bar') + }); + + it('should gracefully handle empty arrays', function () { + var entity = new UsergridEntity({ + type: 'cat', + name: 'Cosmo', + foo: [] + }); + entity.shift('foo'); + entity.should.have.property('foo').deepEqual([]) + }) + }); + + var now = Date.now(); + var entity = new UsergridEntity({type: config.test.collection, name: 'Cosmo'}); + + describe('save()', function () { + + it('should POST an entity without a uuid', function (done) { + entity.save(client, function (error,response) { + response.entity.should.have.property('uuid'); + done() + }) + }); + it('should PUT an entity without a uuid', function (done) { + entity.putProperty('saveTest', now); + entity.save(client, function (error,response) { + response.entity.should.have.property('saveTest').equal(now); + done() + }) + }) + }); + + describe('reload()', function () { + + it('should refresh an entity with the latest server copy of itself', function (done) { + var modified = entity.modified; + entity.putProperty('reloadTest', now); + client.PUT(entity, function (error,putResponse) { + entity.modified.should.equal(modified); + entity.reload(client, function (error,reloadResponse) { + entity.reloadTest.should.equal(now); + entity.modified.should.not.equal(modified); + done() + }) + }) + }) + }); + + describe('remove()', function () { + + it('should remove an entity from the server', function (done) { + entity.remove(client, function (error,deleteResponse) { + deleteResponse.ok.should.be.true(); + // best practice is to destroy the 'entity' instance here, because it no longer exists on the server + entity = null; + done() + }) + }) + }); + + describe('connect()', function () { + + var response, + entity1, + entity2; + + before(function (done) { + // Create the entities we're going to use for connections + client.POST({ + type: config.test.collection, body: [{ + "name": "testEntityConnectOne" + }, { + "name": "testEntityConnectTwo" + }], callback: function (error,postResponse) { + response = postResponse; + entity1 = response.first; + entity2 = response.last; + done() + } + }) + }); + + it('should connect entities by passing a target UsergridEntity object as a parameter', function (done) { + var relationship = "foos"; + entity1.connect(client, relationship, entity2, function (error,usergridResponse) { + sleepFor(config.defaultSleepTime); + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should connect entities by passing target uuid as a parameter', function (done) { + var relationship = "bars"; + + entity1.connect(client, relationship, entity2.uuid, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + sleepFor(config.defaultSleepTime); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should connect entities by passing target type and name as parameters', function (done) { + var relationship = "bazzes"; + + entity1.connect(client, relationship, entity2.type, entity2.name, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + sleepFor(config.defaultSleepTime); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }) + }); + + it('should fail to connect entities when specifying target name without type', function () { + should(function () { + entity1.connect("fails", 'badName', function () { + }) + }).throw() + }) + }); + + describe('getConnections()', function () { + + var response, + query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name'); + + before(function (done) { + sleepFor(config.defaultLongSleepTime); + client.GET(query, function (error,usergridResponse) { + response = usergridResponse; + done() + }) + }); + + it('should get an entity\'s outbound connections', function (done) { + var entity1 = response.first; + var entity2 = response.last; + + var relationship = "foos"; + + entity1.getConnections(client, UsergridDirection.OUT, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connecting[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity1.uuid, + relationship, + entity2.uuid, + "connecting", + relationship + )); + done() + }) + }); + + it('should get an entity\'s inbound connections', function (done) { + var entity1 = response.first; + var entity2 = response.last; + + var relationship = "foos"; + + entity2.getConnections(client, UsergridDirection.IN, relationship, function (error,usergridResponse) { + usergridResponse.first.metadata.connections[relationship].should.equal(UsergridHelpers.urljoin( + "", + config.test.collection, + entity2.uuid, + "connecting", + entity1.uuid, + relationship + )); + done() + }) + }) + }); + + describe('disconnect()', function () { + + var response, + entity1, + entity2, + query = new UsergridQuery(config.test.collection).eq('name', 'testEntityConnectOne').or.eq('name', 'testEntityConnectTwo').asc('name'); + + before(function (done) { + client.GET(query, function (error,usergridResponse) { + response = usergridResponse; + entity1 = response.first; + entity2 = response.last; + done() + }) + }); + after(function (done) { + var deleteQuery = new UsergridQuery(config.test.collection).eq('uuid', entity1.uuid).or.eq('uuid', entity2.uuid); + client.DELETE(deleteQuery, function (error,delResponse) { + delResponse.entities.should.be.an.Array().with.lengthOf(2); + done() + }) + }); + + it('should disconnect entities by passing a target UsergridEntity object as a parameter', function (done) { + var relationship = "foos"; + entity1.disconnect(client, relationship, entity2, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should disconnect entities by passing target uuid as a parameter', function (done) { + var relationship = "bars"; + entity1.disconnect(client, relationship, entity2.uuid, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should disconnect entities by passing target type and name as parameters', function (done) { + var relationship = "bazzes"; + entity1.disconnect(client, relationship, entity2.type, entity2.name, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + client.getConnections(UsergridDirection.OUT, entity1, relationship, function (error,usergridResponse) { + usergridResponse.entities.should.be.an.Array().with.lengthOf(0); + done() + }) + }) + }); + + it('should fail to disconnect entities when specifying target name without type', function () { + should(function () { + entity1.disconnect("fails", entity2.name, function () { + }) + }).throw() + }) + }); + + var assetEntity = new UsergridEntity({type: config.test.collection, name: "attachAssetTest"}); + + describe('attachAsset() and uploadAsset()', function (done) { + + var asset; + + before(function (done) { + assetEntity.save(client, function (error,response) { + response.ok.should.be.true(); + assetEntity.should.have.property('uuid'); + done() + }) + }); + + before(function (done) { + var req = new XMLHttpRequest(); + req.open('GET', testFile.uri, true); + req.responseType = 'blob'; + req.onload = function () { + asset = new UsergridAsset(req.response); + done(); + }; + req.onerror = function (err) { + console.error(err); + done(); + }; + req.send(null); + }); + + it('should attach a UsergridAsset to the entity', function (done) { + assetEntity.attachAsset(asset); + assetEntity.should.have.property('asset').equal(asset); + done() + }); + + it('should upload an image asset to the remote entity', function (done) { + assetEntity.uploadAsset(client, function (error, usergridResponse, entity) { + entity.should.have.property('file-metadata'); + entity['file-metadata'].should.have.property('content-type').equal(testFile.contentType); + entity['file-metadata'].should.have.property('content-length').equal(testFile.contentLength); + done() + }) + }) + }); + + describe('downloadAsset()', function (done) { + + after(function (done) { + assetEntity.remove(client); + done() + }); + + it('should download a an image from the remote entity', function (done) { + assetEntity.downloadAsset(client, function (error, usergridResponse, entityWithAsset) { + entityWithAsset.should.have.property('asset').which.is.an.instanceof(UsergridAsset); + entityWithAsset.asset.should.have.property('contentType').equal(assetEntity['file-metadata']['content-type']); + entityWithAsset.asset.should.have.property('contentLength').equal(assetEntity['file-metadata']['content-length']); + done() + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_helpers.js b/tests/mocha/test_helpers.js new file mode 100644 index 0000000..fe5bf88 --- /dev/null +++ b/tests/mocha/test_helpers.js @@ -0,0 +1,90 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +var targetedConfigs = { + "1.0": { + "orgId": "rwalsh", + "appId": "jssdktestapp", + "baseUrl": UsergridClientDefaultOptions.baseUrl, + "clientId": "YXA6KPq8cIsPEea0i-W5Jx8cgw", + "clientSecret": "YXA6WaT7qsxh_eRS3ryBresi-HwoQAQ", + "target": "1.0", + "defaultSleepTime":0, + "defaultLongSleepTime":0, + "test": { + "collection": "nodejs", + "email": "authtest@test.com", + "password": "P@ssw0rd", + "username": "authtest" + } + }, + "2.1": { + "orgId": "api-connectors", + "appId": "sdksandbox", + "baseUrl": "https://api-connectors-prod.apigee.net/appservices", + "clientId": "YXA6WMhAuFJTEeWoggrRE9kXrQ", + "clientSecret": "YXA6zZbat7PKgOlN73rpByc36LWaUhw", + "target": "2.1", + "defaultSleepTime":200, + "defaultLongSleepTime":600, + "test": { + "collection": "nodejs", + "email": "authtest@test.com", + "password": "P@ssw0rd", + "username": "authtest" + } + } + +}; + +var configs = []; +configs.push(_.get(targetedConfigs,'1.0')); +configs.push(_.get(targetedConfigs,'2.1')); + +var testFile = { + uri:'https://raw.githubusercontent.com/apache/usergrid-javascript/master/tests/resources/images/apigee.png', + contentLength: 6010, + contentType: 'image/png' +}; + +// Test slow and timeout times. Timeout is set to 0 meaning tests will not timeout, though this might not be ideal. +var _slow = 400, + _timeout = 0; + +function sleepFor( sleepDuration ){ + if( sleepDuration > 0 ) { + var now = new Date().getTime(); + while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } + } +} + +function randomWord() { + var text = ""; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for( var i=0; i < 5; i++ ) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} + +function uuid() { + var d = _.now(); + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (d + _.random(16)) % 16 | 0; + d = Math.floor(d / 16); + return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); + }); +} diff --git a/tests/mocha/test_query.js b/tests/mocha/test_query.js new file mode 100644 index 0000000..d4f9092 --- /dev/null +++ b/tests/mocha/test_query.js @@ -0,0 +1,121 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +describe('UsergridQuery', function() { + + describe('_type', function() { + it('_type should equal "cats" when passing "type" as a parameter to UsergridQuery', function() { + var query = new UsergridQuery('cats'); + query.should.have.property('_type').equal('cats') + }); + + it('_type should equal "cats" when calling .type() builder method', function() { + var query = new UsergridQuery().type('cats'); + query.should.have.property('_type').equal('cats') + }); + + it('_type should equal "cats" when calling .collection() builder method', function() { + var query = new UsergridQuery().collection('cats'); + query.should.have.property('_type').equal('cats') + }) + }); + + describe('_limit', function() { + it('_limit should equal 2 when setting .limit(2)', function() { + var query = new UsergridQuery('cats').limit(2); + query.should.have.property('_limit').equal(2) + }); + + it('_limit should equal 10 when setting .limit(10)', function() { + var query = new UsergridQuery('cats').limit(10); + query.should.have.property('_limit').equal(10) + }) + }); + + describe('_ql', function() { + it('should be an select all if query or sort are empty or underfined', function() { + var query = new UsergridQuery('cats'); + query.should.have.property('_ql').equal("select * ") + }); + + it('should support complex builder pattern syntax (chained constructor methods)', function() { + var query = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*') + .not + .eq('color', 'blue') + .or + .eq('color', 'orange'); + query.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*' and not color = 'blue' or color = 'orange'") + }); + + it('and operator should be implied when joining multiple conditions', function() { + var query1 = new UsergridQuery('cats') + .gt('weight', 2.4) + .contains('color', 'bl*'); + query1.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*'"); + var query2 = new UsergridQuery('cats') + .gt('weight', 2.4) + .and + .contains('color', 'bl*'); + query2.should.have.property('_ql').equal("select * where weight > 2.4 and color contains 'bl*'") + }); + + it('not operator should precede conditional statement', function() { + var query = new UsergridQuery('cats') + .not + .eq('color', 'white'); + query.should.have.property('_ql').equal("select * where not color = 'white'") + }); + + it('fromString should set _ql directly, bypassing builder pattern methods', function() { + var q = "where color = 'black' or color = 'orange'"; + var query = new UsergridQuery('cats') + .fromString(q); + query.should.have.property('_ql').equal(q) + }); + + it('string values should be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('color', 'black'); + query.should.have.property('_ql').equal("select * where color = 'black'") + }); + + it('boolean values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('longHair', true); + query.should.have.property('_ql').equal("select * where longHair = true") + }); + + it('float values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .lt('weight', 18); + query.should.have.property('_ql').equal("select * where weight < 18") + }); + + it('integer values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .gte('weight', 2); + query.should.have.property('_ql').equal("select * where weight >= 2") + }); + + it('uuid values should not be contained in single quotes', function() { + var query = new UsergridQuery('cats') + .eq('uuid', 'a61e29ba-944f-11e5-8690-fbb14f62c803'); + query.should.have.property('_ql').equal("select * where uuid = a61e29ba-944f-11e5-8690-fbb14f62c803") + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_response.js b/tests/mocha/test_response.js new file mode 100644 index 0000000..1dce049 --- /dev/null +++ b/tests/mocha/test_response.js @@ -0,0 +1,193 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('UsergridResponse ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + var _response, entitiesArray = []; + + before(function (done) { + var entity = new UsergridEntity({ + type: config.test.collection, + info: 'responseTestEntity' + }); + for (var i = 0; i < 20; i++) { + entitiesArray.push(entity) + } + client.POST({ + body: entitiesArray, callback: function (error,postResponse) { + postResponse.entities.should.be.an.Array().with.lengthOf(entitiesArray.length); + entitiesArray = postResponse.entities; + done() + } + }) + }); + + before(function (done) { + client.GET(config.test.collection, function (error,usergridResponse) { + _response = usergridResponse; + done() + }) + }); + + after(function (done) { + client.DELETE(new UsergridQuery(config.test.collection).eq('info', 'responseTestEntity').limit(entitiesArray.length)); + done() + }); + + describe('headers', function () { + it('should be an object', function () { + _response.headers.should.be.an.Object().with.property('content-type') + }) + }); + + describe('statusCode', function () { + it('should be a number', function () { + _response.statusCode.should.be.a.Number() + }) + }); + + describe('ok', function () { + it('should be a bool', function () { + _response.ok.should.be.a.Boolean() + }) + }); + + describe('responseJSON', function () { + it('should be a read-only object', function () { + _response.responseJSON.should.be.an.Object().with.any.properties(['action', 'application', 'path', 'uri', 'timestamp', 'duration']); + Object.isFrozen(_response.responseJSON).should.be.true(); + should(function () { + _response.responseJSON.uri = 'TEST' + }).throw() + }) + }); + + describe('error', function () { + it('should be a UsergridResponseError object', function (done) { + client.GET(config.test.collection, 'BADNAMEORUUID', function (error,usergridResponse) { + usergridResponse.error.should.be.an.instanceof(UsergridResponseError); + done() + }) + }) + }); + + describe('users', function () { + it('response.users should be an array of UsergridUser objects', function (done) { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl); + client.authenticateApp(function (error,response) { + should(response.error).be.undefined(); + client.GET('users', function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + usergridResponse.users.should.be.an.Array(); + usergridResponse.users.forEach(function (user) { + user.should.be.an.instanceof(UsergridUser) + }); + done() + }) + }) + }) + }); + + describe('user', function () { + var user; + + it('response.user should be a UsergridUser object and have a valid uuid matching the first object in response.users', function (done) { + client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl); + client.authenticateApp(function (error,response) { + should(response.error).be.undefined(); + client.GET('users', function (error,usergridResponse) { + user = usergridResponse.user; + user.should.be.an.instanceof(UsergridUser).with.property('uuid').equal(_.first(usergridResponse.entities).uuid); + done() + }) + }) + }); + + it('response.user should be a subclass of UsergridEntity', function (done) { + user.isUser.should.be.true(); + user.should.be.an.instanceof(UsergridEntity); + done() + }) + }); + + describe('entities', function () { + it('should be an array of UsergridEntity objects', function () { + _response.entities.should.be.an.Array(); + _response.entities.forEach(function (entity) { + entity.should.be.an.instanceof(UsergridEntity) + }) + }) + }); + + describe('first, entity', function () { + it('response.first should be a UsergridEntity object and have a valid uuid matching the first object in response.entities', function () { + _response.first.should.be.an.instanceof(UsergridEntity).with.property('uuid').equal(_.first(_response.entities).uuid) + }); + + it('response.entity should be a reference to response.first', function () { + _response.should.have.property('entity').deepEqual(_response.first) + }) + }); + + describe('last', function () { + it('last should be a UsergridEntity object and have a valid uuid matching the last object in response.entities', function () { + _response.last.should.be.an.instanceof(UsergridEntity).with.property('uuid').equal(_.last(_response.entities).uuid) + }) + }); + + describe('hasNextPage', function () { + it('should be true when more entities exist', function (done) { + client.GET({type: config.test.collection}, function (error,usergridResponse) { + usergridResponse.hasNextPage.should.be.true(); + done() + }) + }); + + it('should be false when no more entities exist', function (done) { + client.GET({type: 'users'}, function (error,usergridResponse) { + usergridResponse.responseJSON.count.should.be.lessThan(10); + usergridResponse.hasNextPage.should.not.be.true(); + done() + }) + }) + }); + + describe('loadNextPage()', function () { + var firstResponse; + + before(function (done) { + client.GET({type: config.test.collection}, function (error,usergridResponse) { + firstResponse = usergridResponse; + done() + }) + }); + + it('should load a new page of entities by passing an instance of UsergridClient', function (done) { + firstResponse.loadNextPage(client, function (error,usergridResponse) { + usergridResponse.first.uuid.should.not.equal(firstResponse.first.uuid); + usergridResponse.entities.length.should.equal(10); + done() + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_response_error.js b/tests/mocha/test_response_error.js new file mode 100644 index 0000000..ee3a491 --- /dev/null +++ b/tests/mocha/test_response_error.js @@ -0,0 +1,56 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('UsergridResponseError ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + var _response; + + describe('name, description, exception', function () { + + before(function (done) { + client.GET(config.test.collection, 'BADNAMEORUUID', function (error,usergridResponse) { + _response = usergridResponse; + done() + }) + }); + + it('response.statusCode should be greater than or equal to 400', function () { + _response.ok.should.be.false() + }); + + it('response.error should be a UsergridResponseError object with name, description, and exception keys', function () { + _response.ok.should.be.false(); + _response.error.should.be.an.instanceof(UsergridResponseError).with.properties(['name', 'description', 'exception']) + }) + }); + + describe('undefined check', function () { + it('response.error should be undefined on a successful response', function (done) { + client.GET(config.test.collection, function (error,usergridResponse) { + usergridResponse.ok.should.be.true(); + should(usergridResponse.error).be.undefined(); + done() + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_user.js b/tests/mocha/test_user.js new file mode 100644 index 0000000..93d0f8a --- /dev/null +++ b/tests/mocha/test_user.js @@ -0,0 +1,268 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + var client = new UsergridClient(config); + + describe('UsergridUser ' + config.target, function () { + this.timeout(_timeout); + this.slow(_slow); + + var _username1 = randomWord(), + _user1 = new UsergridUser({ + username: _username1, + password: config.test.password + }); + + + before(function (done) { + var query = new UsergridQuery('users').not.eq('username', config.test.username).limit(20); + // clean up old user entities as the UsergridResponse tests rely on this collection containing less than 10 entities + client.DELETE(query, function () { + _user1.create(client, function (err, usergridResponse, user) { + done() + }) + }) + }); + + describe('create()', function () { + + it("should create a new user with the username " + _username1, function () { + _user1.username.should.equal(_username1) + }); + + it('should have a valid uuid', function () { + _user1.should.have.property('uuid')//.which.is.a.uuid() + });; + + it('should have a created date', function () { + _user1.should.have.property('created') + }); + + it('should be activated (i.e. has a valid password)', function () { + _user1.should.have.property('activated').true() + }); + + it('should not have a password property', function () { + _user1.should.not.have.property('password') + }); + + it('should fail gracefully when a username already exists', function (done) { + var user = new UsergridUser({ + username: _username1, + password: config.test.password + }); + user.create(client, function (error,usergridResponse) { + usergridResponse.error.should.not.be.null(); + usergridResponse.error.should.containDeep({ + name: 'duplicate_unique_property_exists' + }); + usergridResponse.ok.should.be.false(); + done() + }) + }); + + it('should create a new user on the server', function (done) { + var username = randomWord(); + var user = new UsergridUser({ + username: username, + password: config.test.password + }); + user.create(client, function (error,usergridResponse) { + user.username.should.equal(username); + user.should.have.property('uuid')//.which.is.a.uuid() + user.should.have.property('created'); + user.should.have.property('activated').true(); + user.should.not.have.property('password'); + // cleanup + user.remove(client, function (error,response) { + done() + }) + }); + }) + }); + + describe('login()', function () { + it("it should log in the user '" + _username1 + "' and receive a token", function (done) { + _user1.password = config.test.password; + _user1.login(client, function (error, response, token) { + _user1.auth.should.have.property('token').equal(token); + _user1.should.not.have.property('password'); + _user1.auth.should.not.have.property('password'); + done() + }) + }) + }); + + describe('logout()', function () { + + it("it should log out " + _username1 + " and destroy the saved UsergridUserAuth instance", function (done) { + _user1.logout(client, function (error,response) { + response.ok.should.be.true(); + response.responseJSON.action.should.equal("revoked user token"); + _user1.auth.isValid.should.be.false(); + done() + }) + }); + + it("it should return an error when attempting to log out a user that does not have a valid token", function (done) { + _user1.logout(client, function (error,response) { + response.error.name.should.equal('no_valid_token'); + done() + }) + }) + }); + + describe('logoutAllSessions()', function () { + it("it should log out all tokens for the user " + _username1 + " destroy the saved UsergridUserAuth instance", function (done) { + _user1.password = config.test.password; + _user1.login(client, function (error, response, token) { + _user1.logoutAllSessions(client, function (error,response) { + response.ok.should.be.true(); + response.responseJSON.action.should.equal("revoked user tokens"); + _user1.auth.isValid.should.be.false(); + done() + }) + }) + }) + }); + + describe('resetPassword()', function () { + + it("it should reset the password for " + _username1 + " by passing parameters", function (done) { + _user1.resetPassword(client, config.test.password, '2cool4u', function (error,response) { + response.ok.should.be.true(); + response.responseJSON.action.should.equal("set user password"); + done() + }) + }); + + it("it should reset the password for " + _username1 + " by passing an object", function (done) { + _user1.resetPassword(client, { + oldPassword: '2cool4u', + newPassword: config.test.password + }, function (error,response) { + response.ok.should.be.true(); + response.responseJSON.action.should.equal("set user password"); + done() + }) + }); + + it("it should not reset the password for " + _username1 + " when passing a bad old password", function (done) { + _user1.resetPassword(client, { + oldPassword: 'BADOLDPASSWORD', + newPassword: config.test.password + }, function (error,response) { + response.ok.should.be.false(); + response.error.name.should.equal('auth_invalid_username_or_password'); + _user1.remove(client, function () { + done() + }) + }) + }); + + it("it should return an error when attempting to reset a password with missing arguments", function () { + should(function () { + _user1.resetPassword(client, 'NEWPASSWORD', function () { + }) + }).throw() + }) + }); + + describe('CheckAvailable()', function () { + + var nonExistentEmail = randomWord() + '@' + randomWord() + '.com'; + var nonExistentUsername = randomWord(); + + it("it should return true for username " + config.test.username, function (done) { + UsergridUser.CheckAvailable(client, { + username: config.test.username + }, function (error,response, exists) { + exists.should.be.true(); + done() + }) + }); + + it("it should return true for email " + config.test.email, function (done) { + UsergridUser.CheckAvailable(client, { + email: config.test.email + }, function (error,response, exists) { + exists.should.be.true(); + done() + }) + }); + + it("it should return true for email " + config.test.email + " and non-existent username " + nonExistentUsername, function (done) { + UsergridUser.CheckAvailable(client, { + email: config.test.email, + username: nonExistentUsername + }, function (error,response, exists) { + exists.should.be.true(); + done() + }) + }); + + it("it should return true for non-existent email " + nonExistentEmail + " and username " + config.test.username, function (done) { + UsergridUser.CheckAvailable(client, { + email: nonExistentEmail, + username: config.test.username + }, function (error,response, exists) { + exists.should.be.true(); + done() + }) + }); + + it("it should return true for email " + config.test.email + " and username " + config.test.username, function (done) { + UsergridUser.CheckAvailable(client, { + email: config.test.email, + username: config.test.useranme + }, function (error,response, exists) { + exists.should.be.true(); + done() + }) + }); + + it("it should return false for non-existent email " + nonExistentEmail, function (done) { + UsergridUser.CheckAvailable(client, { + email: nonExistentEmail + }, function (error,response, exists) { + exists.should.be.false(); + done() + }) + }); + + it("it should return false for non-existent username " + nonExistentUsername, function (done) { + UsergridUser.CheckAvailable(client, { + username: nonExistentUsername + }, function (error,response, exists) { + exists.should.be.false(); + done() + }) + }); + + it("it should return false for non-existent email " + nonExistentEmail + " and non-existent username " + nonExistentUsername, function (done) { + UsergridUser.CheckAvailable(client, { + email: nonExistentEmail, + username: nonExistentUsername + }, function (error,response, exists) { + exists.should.be.false(); + done() + }) + }) + }) + }) +}); \ No newline at end of file diff --git a/tests/mocha/test_usergrid_init.js b/tests/mocha/test_usergrid_init.js new file mode 100644 index 0000000..3ed6159 --- /dev/null +++ b/tests/mocha/test_usergrid_init.js @@ -0,0 +1,32 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +'use strict'; + +configs.forEach(function(config) { + + describe('Usergrid init() / initSharedInstance() ' + config.target, function () { + it('should be an instance of UsergridClient', function (done) { + Usergrid.init(config); + Usergrid.initSharedInstance(config); + Usergrid.should.be.an.instanceof(UsergridClient); + done() + }); + it('should be initialized when defined in another module', function (done) { + Usergrid.should.have.property('isInitialized').which.is.true(); + Usergrid.should.have.property('isSharedInstance').which.is.true(); + done() + }) + }) +}); \ No newline at end of file diff --git a/tests/qunit/apigee_test.html b/tests/qunit/apigee_test.html deleted file mode 100644 index 2dae960..0000000 --- a/tests/qunit/apigee_test.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - QUnit Example - - - -
    -
    - - - - diff --git a/tests/qunit/tests.js b/tests/qunit/tests.js deleted file mode 100644 index 1d58b00..0000000 --- a/tests/qunit/tests.js +++ /dev/null @@ -1,20 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -test( "hello test", function() { - ok( 1 == "1", "Passed!" ); -}); diff --git a/tests/resources/css/mocha.css b/tests/resources/css/mocha.css index 42b9798..f5dc118 100644 --- a/tests/resources/css/mocha.css +++ b/tests/resources/css/mocha.css @@ -1,3 +1,17 @@ +/** + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + @charset "utf-8"; body { diff --git a/tests/resources/css/styles.css b/tests/resources/css/styles.css index 7492f93..7daf953 100755 --- a/tests/resources/css/styles.css +++ b/tests/resources/css/styles.css @@ -1,12 +1,4 @@ /** -* All Calls is a Node.js sample app that is powered by Usergrid -* This app shows how to make the 4 REST calls (GET, POST, -* PUT, DELETE) against the usergrid API. -* -* Learn more at http://Usergrid.com/docs -* -* Copyright 2012 Apigee Corporation -* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,12 +12,6 @@ * limitations under the License. */ -/** -* @file styles.css -* @author Rod Simpson (rod@apigee.com) -* -*/ - body { background-color: #fff; min-height: 800px; diff --git a/tests/resources/images/apigee.png b/tests/resources/images/apigee.png deleted file mode 100755 index c0d0f84..0000000 Binary files a/tests/resources/images/apigee.png and /dev/null differ diff --git a/tests/resources/js/blanket_mocha.min.js b/tests/resources/js/blanket_mocha.min.js deleted file mode 100644 index db01cab..0000000 --- a/tests/resources/js/blanket_mocha.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(e){(function(t,n){"use strict";typeof e=="function"&&e.amd?e(["exports"],n):typeof exports!="undefined"?n(exports):n(t.esprima={})})(this,function(e){"use strict";function m(e,t){if(!e)throw new Error("ASSERT: "+t)}function g(e,t){return u.slice(e,t)}function y(e){return"0123456789".indexOf(e)>=0}function b(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function w(e){return"01234567".indexOf(e)>=0}function E(e){return e===" "||e===" "||e==="\f"||e==="\u00a0"||e.charCodeAt(0)>=5760&&"\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\ufeff".indexOf(e)>=0}function S(e){return e==="\n"||e==="\r"||e==="\u2028"||e==="\u2029"}function x(e){return e==="$"||e==="_"||e==="\\"||e>="a"&&e<="z"||e>="A"&&e<="Z"||e.charCodeAt(0)>=128&&o.NonAsciiIdentifierStart.test(e)}function T(e){return e==="$"||e==="_"||e==="\\"||e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||e.charCodeAt(0)>=128&&o.NonAsciiIdentifierPart.test(e)}function N(e){switch(e){case"class":case"enum":case"export":case"extends":case"import":case"super":return!0}return!1}function C(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0}return!1}function k(e){return e==="eval"||e==="arguments"}function L(e){var t=!1;switch(e.length){case 2:t=e==="if"||e==="in"||e==="do";break;case 3:t=e==="var"||e==="for"||e==="new"||e==="try";break;case 4:t=e==="this"||e==="else"||e==="case"||e==="void"||e==="with";break;case 5:t=e==="while"||e==="break"||e==="catch"||e==="throw";break;case 6:t=e==="return"||e==="typeof"||e==="delete"||e==="switch";break;case 7:t=e==="default"||e==="finally";break;case 8:t=e==="function"||e==="continue"||e==="debugger";break;case 10:t=e==="instanceof"}if(t)return!0;switch(e){case"const":return!0;case"yield":case"let":return!0}return a&&C(e)?!0:N(e)}function A(){var e,t,n;t=!1,n=!1;while(f=h&&R({},s.UnexpectedToken,"ILLEGAL")):(e=u[f++],f>=h&&R({},s.UnexpectedToken,"ILLEGAL"),e==="*"&&(e=u[f],e==="/"&&(++f,t=!1)));else if(e==="/"){e=u[f+1];if(e==="/")f+=2,n=!0;else{if(e!=="*")break;f+=2,t=!0,f>=h&&R({},s.UnexpectedToken,"ILLEGAL")}}else if(E(e))++f;else{if(!S(e))break;++f,e==="\r"&&u[f]==="\n"&&++f,++l,c=f}}}function O(e){var t,n,r,i=0;n=e==="u"?4:2;for(t=0;t"&&r===">"&&i===">"&&s==="=")return f+=4,{type:t.Punctuator,value:">>>=",lineNumber:l,lineStart:c,range:[e,f]};if(n==="="&&r==="="&&i==="=")return f+=3,{type:t.Punctuator,value:"===",lineNumber:l,lineStart:c,range:[e,f]};if(n==="!"&&r==="="&&i==="=")return f+=3,{type:t.Punctuator,value:"!==",lineNumber:l,lineStart:c,range:[e,f]};if(n===">"&&r===">"&&i===">")return f+=3,{type:t.Punctuator,value:">>>",lineNumber:l,lineStart:c,range:[e,f]};if(n==="<"&&r==="<"&&i==="=")return f+=3,{type:t.Punctuator,value:"<<=",lineNumber:l,lineStart:c,range:[e,f]};if(n===">"&&r===">"&&i==="=")return f+=3,{type:t.Punctuator,value:">>=",lineNumber:l,lineStart:c,range:[e,f]};if(r==="="&&"<>=!+-*%&|^/".indexOf(n)>=0)return f+=2,{type:t.Punctuator,value:n+r,lineNumber:l,lineStart:c,range:[e,f]};if(n===r&&"+-<>&|".indexOf(n)>=0&&"+-<>&|".indexOf(r)>=0)return f+=2,{type:t.Punctuator,value:n+r,lineNumber:l,lineStart:c,range:[e,f]};if("[]<>+-*%&|^!~?:=/".indexOf(n)>=0)return{type:t.Punctuator,value:u[f++],lineNumber:l,lineStart:c,range:[e,f]}}function D(){var e,n,r;r=u[f],m(y(r)||r===".","Numeric literal must start with a decimal digit or a decimal point"),n=f,e="";if(r!=="."){e=u[f++],r=u[f];if(e==="0"){if(r==="x"||r==="X"){e+=u[f++];while(f=h&&(r=""),R({},s.UnexpectedToken,"ILLEGAL")}return f=0&&f=h)return{type:t.EOF,lineNumber:l,lineStart:c,range:[f,f]};n=_();if(typeof n!="undefined")return n;e=u[f];if(e==="'"||e==='"')return P();if(e==="."||y(e))return D();n=M();if(typeof n!="undefined")return n;R({},s.UnexpectedToken,"ILLEGAL")}function F(){var e;return p?(f=p.range[1],l=p.lineNumber,c=p.lineStart,e=p,p=null,e):(p=null,j())}function I(){var e,t,n;return p!==null?p:(e=f,t=l,n=c,p=j(),f=e,l=t,c=n,p)}function q(){var e,t,n,r;return e=f,t=l,n=c,A(),r=l!==t,f=e,l=t,c=n,r}function R(e,t){var n,r=Array.prototype.slice.call(arguments,2),i=t.replace(/%(\d)/g,function(e,t){return r[t]||""});throw typeof e.lineNumber=="number"?(n=new Error("Line "+e.lineNumber+": "+i),n.index=e.range[0],n.lineNumber=e.lineNumber,n.column=e.range[0]-c+1):(n=new Error("Line "+l+": "+i),n.index=f,n.lineNumber=l,n.column=f-c+1),n}function U(){try{R.apply(null,arguments)}catch(e){if(!v.errors)throw e;v.errors.push(e)}}function z(e){e.type===t.EOF&&R(e,s.UnexpectedEOS),e.type===t.NumericLiteral&&R(e,s.UnexpectedNumber),e.type===t.StringLiteral&&R(e,s.UnexpectedString),e.type===t.Identifier&&R(e,s.UnexpectedIdentifier);if(e.type===t.Keyword){if(N(e.value))R(e,s.UnexpectedReserved);else if(a&&C(e.value)){U(e,s.StrictReservedWord);return}R(e,s.UnexpectedToken,e.value)}R(e,s.UnexpectedToken,e.value)}function W(e){var n=F();(n.type!==t.Punctuator||n.value!==e)&&z(n)}function X(e){var n=F();(n.type!==t.Keyword||n.value!==e)&&z(n)}function V(e){var n=I();return n.type===t.Punctuator&&n.value===e}function $(e){var n=I();return n.type===t.Keyword&&n.value===e}function J(){var e=I(),n=e.value;return e.type!==t.Punctuator?!1:n==="="||n==="*="||n==="/="||n==="%="||n==="+="||n==="-="||n==="<<="||n===">>="||n===">>>="||n==="&="||n==="^="||n==="|="}function K(){var e,n;if(u[f]===";"){F();return}n=l,A();if(l!==n)return;if(V(";")){F();return}e=I(),e.type!==t.EOF&&!V("}")&&z(e)}function Q(e){return e.type===r.Identifier||e.type===r.MemberExpression}function G(){var e=[];W("[");while(!V("]"))V(",")?(F(),e.push(null)):(e.push(Tt()),V("]")||W(","));return W("]"),{type:r.ArrayExpression,elements:e}}function Y(e,t){var n,i;return n=a,i=Gt(),t&&a&&k(e[0].name)&&U(t,s.StrictParamName),a=n,{type:r.FunctionExpression,id:null,params:e,defaults:[],body:i,rest:null,generator:!1,expression:!1}}function Z(){var e=F();return e.type===t.StringLiteral||e.type===t.NumericLiteral?(a&&e.octal&&U(e,s.StrictOctalLiteral),ln(e)):{type:r.Identifier,name:e.value}}function et(){var e,n,i,o;e=I();if(e.type===t.Identifier)return i=Z(),e.value==="get"&&!V(":")?(n=Z(),W("("),W(")"),{type:r.Property,key:n,value:Y([]),kind:"get"}):e.value==="set"&&!V(":")?(n=Z(),W("("),e=I(),e.type!==t.Identifier?(W(")"),U(e,s.UnexpectedToken,e.value),{type:r.Property,key:n,value:Y([]),kind:"set"}):(o=[Lt()],W(")"),{type:r.Property,key:n,value:Y(o,e),kind:"set"})):(W(":"),{type:r.Property,key:i,value:Tt(),kind:"init"});if(e.type!==t.EOF&&e.type!==t.Punctuator)return n=Z(),W(":"),{type:r.Property,key:n,value:Tt(),kind:"init"};z(e)}function tt(){var e=[],t,n,o,u={},f=String;W("{");while(!V("}"))t=et(),t.key.type===r.Identifier?n=t.key.name:n=f(t.key.value),o=t.kind==="init"?i.Data:t.kind==="get"?i.Get:i.Set,Object.prototype.hasOwnProperty.call(u,n)?(u[n]===i.Data?a&&o===i.Data?U({},s.StrictDuplicateProperty):o!==i.Data&&U({},s.AccessorDataProperty):o===i.Data?U({},s.AccessorDataProperty):u[n]&o&&U({},s.AccessorGetSet),u[n]|=o):u[n]=o,e.push(t),V("}")||W(",");return W("}"),{type:r.ObjectExpression,properties:e}}function nt(){var e;return W("("),e=Nt(),W(")"),e}function rt(){var e=I(),n=e.type;if(n===t.Identifier)return{type:r.Identifier,name:F().value};if(n===t.StringLiteral||n===t.NumericLiteral)return a&&e.octal&&U(e,s.StrictOctalLiteral),ln(F());if(n===t.Keyword){if($("this"))return F(),{type:r.ThisExpression};if($("function"))return Zt()}return n===t.BooleanLiteral?(F(),e.value=e.value==="true",ln(e)):n===t.NullLiteral?(F(),e.value=null,ln(e)):V("[")?G():V("{")?tt():V("(")?nt():V("/")||V("/=")?ln(H()):z(F())}function it(){var e=[];W("(");if(!V(")"))while(f>")||V(">>>"))e={type:r.BinaryExpression,operator:F().value,left:e,right:dt()};return e}function mt(){var e,t;t=d.allowIn,d.allowIn=!0,e=vt();while(V("<")||V(">")||V("<=")||V(">=")||t&&$("in")||$("instanceof"))e={type:r.BinaryExpression,operator:F().value,left:e,right:vt()};return d.allowIn=t,e}function gt(){var e=mt();while(V("==")||V("!=")||V("===")||V("!=="))e={type:r.BinaryExpression,operator:F().value,left:e,right:mt()};return e}function yt(){var e=gt();while(V("&"))F(),e={type:r.BinaryExpression,operator:"&",left:e,right:gt()};return e}function bt(){var e=yt();while(V("^"))F(),e={type:r.BinaryExpression,operator:"^",left:e,right:yt()};return e}function wt(){var e=bt();while(V("|"))F(),e={type:r.BinaryExpression,operator:"|",left:e,right:bt()};return e}function Et(){var e=wt();while(V("&&"))F(),e={type:r.LogicalExpression,operator:"&&",left:e,right:wt()};return e}function St(){var e=Et();while(V("||"))F(),e={type:r.LogicalExpression,operator:"||",left:e,right:Et()};return e}function xt(){var e,t,n;return e=St(),V("?")&&(F(),t=d.allowIn,d.allowIn=!0,n=Tt(),d.allowIn=t,W(":"),e={type:r.ConditionalExpression,test:e,consequent:n,alternate:Tt()}),e}function Tt(){var e,t;return e=I(),t=xt(),J()&&(Q(t)||U({},s.InvalidLHSInAssignment),a&&t.type===r.Identifier&&k(t.name)&&U(e,s.StrictLHSAssignment),t={type:r.AssignmentExpression,operator:F().value,left:t,right:Tt()}),t}function Nt(){var e=Tt();if(V(",")){e={type:r.SequenceExpression,expressions:[e]};while(f0&&v.comments[v.comments.length-1].range[1]>n)return;v.comments.push({type:e,value:t,range:[n,r],loc:i})}function sn(){var e,t,n,r,i,o;e="",i=!1,o=!1;while(f=h?(o=!1,e+=t,n.end={line:l,column:h-c},rn("Line",e,r,h,n)):e+=t;else if(i)S(t)?(t==="\r"&&u[f+1]==="\n"?(++f,e+="\r\n"):e+=t,++l,++f,c=f,f>=h&&R({},s.UnexpectedToken,"ILLEGAL")):(t=u[f++],f>=h&&R({},s.UnexpectedToken,"ILLEGAL"),e+=t,t==="*"&&(t=u[f],t==="/"&&(e=e.substr(0,e.length-1),i=!1,++f,n.end={line:l,column:f-c},rn("Block",e,r,f,n),e="")));else if(t==="/"){t=u[f+1];if(t==="/")n={start:{line:l,column:f-c}},r=f,f+=2,o=!0,f>=h&&(n.end={line:l,column:f-c},o=!1,rn("Line",e,r,f,n));else{if(t!=="*")break;r=f,f+=2,i=!0,n={start:{line:l,column:f-c-2}},f>=h&&R({},s.UnexpectedToken,"ILLEGAL")}}else if(E(t))++f;else{if(!S(t))break;++f,t==="\r"&&u[f]==="\n"&&++f,++l,c=f}}}function on(){var e,t,n,r=[];for(e=0;e0&&(r=v.tokens[v.tokens.length-1],r.range[0]===e&&r.type==="Punctuator"&&(r.value==="/"||r.value==="/=")&&v.tokens.pop()),v.tokens.push({type:"RegularExpression",value:n.literal,range:[e,f],loc:t}),n}function fn(){var e,t,n,r=[];for(e=0;e0?1:0,c=0,h=u.length,p=null,d={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1},v={},typeof t!="undefined"&&(v.range=typeof t.range=="boolean"&&t.range,v.loc=typeof t.loc=="boolean"&&t.loc,v.raw=typeof t.raw=="boolean"&&t.raw,typeof t.tokens=="boolean"&&t.tokens&&(v.tokens=[]),typeof t.comment=="boolean"&&t.comment&&(v.comments=[]),typeof t.tolerant=="boolean"&&t.tolerant&&(v.errors=[])),h>0&&typeof u[0]=="undefined"&&(e instanceof String&&(u=e.valueOf()),typeof u[0]=="undefined"&&(u=wn(e))),yn();try{n=nn(),typeof v.comments!="undefined"&&(on(),n.comments=v.comments),typeof v.tokens!="undefined"&&(fn(),n.tokens=v.tokens),typeof v.errors!="undefined"&&(n.errors=v.errors);if(v.range||v.loc)n.body=mn(n.body)}catch(i){throw i}finally{bn(),v={}}return n}var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v;t={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8},n={},n[t.BooleanLiteral]="Boolean",n[t.EOF]="",n[t.Identifier]="Identifier",n[t.Keyword]="Keyword",n[t.NullLiteral]="Null",n[t.NumericLiteral]="Numeric",n[t.Punctuator]="Punctuator",n[t.StringLiteral]="String",r={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},i={Data:1,Get:2,Set:4},s={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},o={NonAsciiIdentifierStart:new RegExp("[\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]"),NonAsciiIdentifierPart:new RegExp("[\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]")},typeof "esprima"[0]=="undefined"&&(g=function(t,n){return u.slice(t,n).join("")}),e.version="1.0.4",e.parse=En,e.Syntax=function(){var e,t={};typeof Object.create=="function"&&(t=Object.create(null));for(e in r)r.hasOwnProperty(e)&&(t[e]=r[e]);return typeof Object.freeze=="function"&&Object.freeze(t),t}()})})(null),function(e,t){function o(e,t,n){function o(t){n[e.range[0]]=t;for(var r=e.range[0]+1;rparseInt(t,10)}).forEach(function(t){i+=s+"['"+e+"']["+t+"]=0;\n"}),n&&_blanket._branchingArraySetup.sort(function(e,t){return e.line>t.line}).sort(function(e,t){return e.column>t.column}).forEach(function(t){t.file===e&&(i+="if (typeof "+s+"['"+e+"'].branchData["+t.line+"] === 'undefined'){\n",i+=s+"['"+e+"'].branchData["+t.line+"]=[];\n",i+="}",i+=s+"['"+e+"'].branchData["+t.line+"]["+t.column+"] = [];\n",i+=s+"['"+e+"'].branchData["+t.line+"]["+t.column+"].consequent = "+JSON.stringify(t.consequent)+";\n",i+=s+"['"+e+"'].branchData["+t.line+"]["+t.column+"].alternate = "+JSON.stringify(t.alternate)+";\n")}),i+="}",i},_blockifyIf:function(e){if(t.indexOf(e.type)>-1){var n=e.consequent||e.body,r=e.alternate;r&&r.type!=="BlockStatement"&&r.update("{\n"+r.source()+"}\n"),n&&n.type!=="BlockStatement"&&n.update("{\n"+n.source()+"}\n")}},_trackBranch:function(e,t){var n=e.loc.start.line,r=e.loc.start.column;_blanket._branchingArraySetup.push({line:n,column:r,file:t,consequent:e.consequent.loc,alternate:e.alternate.loc});var i="_$branchFcn('"+t+"',"+n+","+r+","+e.test.source()+")?"+e.consequent.source()+":"+e.alternate.source();e.update(i)},_addTracking:function(t){var n=_blanket.getCovVar();return function(r){_blanket._blockifyIf(r);if(e.indexOf(r.type)>-1&&r.parent.type!=="LabeledStatement"){_blanket._checkDefs(r,t);if(r.type==="VariableDeclaration"&&(r.parent.type==="ForStatement"||r.parent.type==="ForInStatement"))return;if(!r.loc||!r.loc.start)throw new Error("The instrumenter encountered a node with no location: "+Object.keys(r));r.update(n+"['"+t+"']["+r.loc.start.line+"]++;\n"+r.source()),_blanket._trackingArraySetup.push(r.loc.start.line)}else _blanket.options("branchTracking")&&r.type==="ConditionalExpression"&&_blanket._trackBranch(r,t)}},_checkDefs:function(e,t){if(inBrowser){e.type==="VariableDeclaration"&&e.declarations&&e.declarations.forEach(function(n){if(n.id.name==="window")throw new Error("Instrumentation error, you cannot redefine the 'window' variable in "+t+":"+e.loc.start.line)}),e.type==="FunctionDeclaration"&&e.params&&e.params.forEach(function(n){if(n.name==="window")throw new Error("Instrumentation error, you cannot redefine the 'window' variable in "+t+":"+e.loc.start.line)});if(e.type==="ExpressionStatement"&&e.expression&&e.expression.left&&e.expression.left.object&&e.expression.left.property&&e.expression.left.object.name+"."+e.expression.left.property.name===_blanket.getCovVar())throw new Error("Instrumentation error, you cannot redefine the coverage variable in "+t+":"+e.loc.start.line)}else if(e.type==="ExpressionStatement"&&e.expression&&e.expression.left&&!e.expression.left.object&&!e.expression.left.property&&e.expression.left.name===_blanket.getCovVar())throw new Error("Instrumentation error, you cannot redefine the coverage variable in "+t+":"+e.loc.start.line)},setupCoverage:function(){i.instrumentation="blanket",i.stats={suites:0,tests:0,passes:0,pending:0,failures:0,start:new Date}},_checkIfSetup:function(){if(!i.stats)throw new Error("You must call blanket.setupCoverage() first.")},onTestStart:function(){_blanket.options("debug")&&console.log("BLANKET-Test event started"),this._checkIfSetup(),i.stats.tests++,i.stats.pending++},onTestDone:function(e,t){this._checkIfSetup(),t===e?i.stats.passes++:i.stats.failures++,i.stats.pending--},onModuleStart:function(){this._checkIfSetup(),i.stats.suites++},onTestsDone:function(){_blanket.options("debug")&&console.log("BLANKET-Test event done"),this._checkIfSetup(),i.stats.end=new Date,inBrowser?this.report(i):(_blanket.options("branchTracking")||delete (inBrowser?window:global)[_blanket.getCovVar()].branchFcn,this.options("reporter").call(this,i))}},_blanket}(),function(e){var t=e.options;e.extend({outstandingRequireFiles:[],options:function(n,r){var i={};if(typeof n!="string")t(n),i=n;else{if(typeof r=="undefined")return t(n);t(n,r),i[n]=r}i.adapter&&e._loadFile(i.adapter),i.loader&&e._loadFile(i.loader)},requiringFile:function(t,n){typeof t=="undefined"?e.outstandingRequireFiles=[]:typeof n=="undefined"?e.outstandingRequireFiles.push(t):e.outstandingRequireFiles.splice(e.outstandingRequireFiles.indexOf(t),1)},requireFilesLoaded:function(){return e.outstandingRequireFiles.length===0},showManualLoader:function(){if(document.getElementById("blanketLoaderDialog"))return;var e="
    ";e+=" 
    ",e+="
    ",e+="
    ",e+="Error: Blanket.js encountered a cross origin request error while instrumenting the source files. ",e+="

    This is likely caused by the source files being referenced locally (using the file:// protocol). ",e+="

    Some solutions include starting Chrome with special flags, running a server locally, or using a browser without these CORS restrictions (Safari).",e+="
    ",typeof FileReader!="undefined"&&(e+="
    Or, try the experimental loader. When prompted, simply click on the directory containing all the source files you want covered.",e+="Start Loader",e+=""),e+="
    Close",e+="
    ",e+="
    ";var t=".blanketDialogWrapper {";t+="display:block;",t+="position:fixed;",t+="z-index:40001; }",t+=".blanketDialogOverlay {",t+="position:fixed;",t+="width:100%;",t+="height:100%;",t+="background-color:black;",t+="opacity:.5; ",t+="-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)'; ",t+="filter:alpha(opacity=50); ",t+="z-index:40001; }",t+=".blanketDialogVerticalOffset { ",t+="position:fixed;",t+="top:30%;",t+="width:100%;",t+="z-index:40002; }",t+=".blanketDialogBox { ",t+="width:405px; ",t+="position:relative;",t+="margin:0 auto;",t+="background-color:white;",t+="padding:10px;",t+="border:1px solid black; }";var n=document.createElement("style");n.innerHTML=t,document.head.appendChild(n);var r=document.createElement("div");r.id="blanketLoaderDialog",r.className="blanketDialogWrapper",r.innerHTML=e,document.body.insertBefore(r,document.body.firstChild)},manualFileLoader:function(e){function o(e){var t=new FileReader;t.onload=s,t.readAsText(e)}var t=Array.prototype.slice;e=t.call(e).filter(function(e){return e.type!==""});var n=e.length-1,r=0,i={};sessionStorage.blanketSessionLoader&&(i=JSON.parse(sessionStorage.blanketSessionLoader));var s=function(t){var s=t.currentTarget.result,u=e[r],a=u.webkitRelativePath&&u.webkitRelativePath!==""?u.webkitRelativePath:u.name;i[a]=s,r++,r===n?(sessionStorage.setItem("blanketSessionLoader",JSON.stringify(i)),document.location.reload()):o(e[r])};o(e[r])},_loadFile:function(t){if(typeof t!="undefined"){var n=new XMLHttpRequest;n.open("GET",t,!1),n.send(),e._addScript(n.responseText)}},_addScript:function(e){var t=document.createElement("script");t.type="text/javascript",t.text=e,(document.body||document.getElementsByTagName("head")[0]).appendChild(t)},hasAdapter:function(t){return e.options("adapter")!==null},report:function(t){document.getElementById("blanketLoaderDialog")||(e.blanketSession=null),t.files=window._$blanket;var n=blanket.options("commonJS")?blanket._commonjs.require:window.require;if(!t.files||!Object.keys(t.files).length){e.options("debug")&&console.log("BLANKET-Reporting No files were instrumented.");return}typeof t.files.branchFcn!="undefined"&&delete t.files.branchFcn;if(typeof e.options("reporter")=="string")e._loadFile(e.options("reporter")),e.customReporter(t,e.options("reporter_options"));else if(typeof e.options("reporter")=="function")e.options("reporter")(t,e.options("reporter_options"));else{if(typeof e.defaultReporter!="function")throw new Error("no reporter defined.");e.defaultReporter(t,e.options("reporter_options"))}},_bindStartTestRunner:function(e,t){e?e(t):window.addEventListener("load",t,!1)},_loadSourceFiles:function(t){function r(e){var t=Object.create(Object.getPrototypeOf(e)),n=Object.getOwnPropertyNames(e);return n.forEach(function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r)}),t}var n=blanket.options("commonJS")?blanket._commonjs.require:window.require;e.options("debug")&&console.log("BLANKET-Collecting page scripts");var i=e.utils.collectPageScripts();if(i.length===0)t();else{sessionStorage.blanketSessionLoader&&(e.blanketSession=JSON.parse(sessionStorage.blanketSessionLoader)),i.forEach(function(t,n){e.utils.cache[t]={loaded:!1}});var s=-1;e.utils.loadAll(function(e){return e?typeof i[s+1]!="undefined":(s++,s>=i.length?null:i[s])},t)}},beforeStartTestRunner:function(t){t=t||{},t.checkRequirejs=typeof t.checkRequirejs=="undefined"?!0:t.checkRequirejs,t.callback=t.callback||function(){},t.coverage=typeof t.coverage=="undefined"?!0:t.coverage,t.coverage?e._bindStartTestRunner(t.bindEvent,function(){e._loadSourceFiles(function(){var n=function(){return t.condition?t.condition():e.requireFilesLoaded()},r=function(){if(n()){e.options("debug")&&console.log("BLANKET-All files loaded, init start test runner callback.");var i=e.options("testReadyCallback");i?typeof i=="function"?i(t.callback):typeof i=="string"&&(e._addScript(i),t.callback()):t.callback()}else setTimeout(r,13)};r()})}):t.callback()},utils:{qualifyURL:function(e){var t=document.createElement("a");return t.href=e,t.href}}})}(blanket),blanket.defaultReporter=function(e){function l(e){var t=document.getElementById(e);t.style.display==="block"?t.style.display="none":t.style.display="block"}function d(e){return e.replace(/\&/g,"&").replace(//g,">").replace(/\"/g,""").replace(/\'/g,"'")}function v(e,t){var n=t?0:1;return typeof e=="undefined"||typeof e===null||typeof e[n]=="undefined"?!1:e[n].length>0}function g(e,t,n,r,i){var s="",o="";if(m.length>0){s+="";if(m[0][0].end.line===i){s+=d(t.slice(0,m[0][0].end.column))+"",t=t.slice(m[0][0].end.column),m.shift();if(m.length>0){s+="";if(m[0][0].end.line===i){s+=d(t.slice(0,m[0][0].end.column))+"",t=t.slice(m[0][0].end.column),m.shift();if(!n)return{src:s+d(t),cols:n}}else{if(!n)return{src:s+d(t)+"",cols:n};o=""}}else if(!n)return{src:s+d(t),cols:n}}else{if(!n)return{src:s+d(t)+"",cols:n};o=""}}var u=n[e],a=u.consequent;if(a.start.line>i)m.unshift([u.alternate,u]),m.unshift([a,u]),t=d(t);else{var f="";s+=d(t.slice(0,a.start.column-r))+f;if(n.length>e+1&&n[e+1].consequent.start.line===i&&n[e+1].consequent.start.column-r";var c=u.alternate;if(c.start.line>i)s+=d(t.slice(a.end.column-r)),m.unshift([c,u]);else{s+=d(t.slice(a.end.column-r,c.start.column-r)),f="",s+=f;if(n.length>e+1&&n[e+1].consequent.start.line===i&&n[e+1].consequent.start.column-r",s+=d(t.slice(c.end.column-r)),t=s}}return{src:t+o,cols:n}}var t="#blanket-main {margin:2px;background:#EEE;color:#333;clear:both;font-family:'Helvetica Neue Light', 'HelveticaNeue-Light', 'Helvetica Neue', Calibri, Helvetica, Arial, sans-serif; font-size:17px;} #blanket-main a {color:#333;text-decoration:none;} #blanket-main a:hover {text-decoration:underline;} .blanket {margin:0;padding:5px;clear:both;border-bottom: 1px solid #FFFFFF;} .bl-error {color:red;}.bl-success {color:#5E7D00;} .bl-file{width:auto;} .bl-cl{float:left;} .blanket div.rs {margin-left:50px; width:150px; float:right} .bl-nb {padding-right:10px;} #blanket-main a.bl-logo {color: #EB1764;cursor: pointer;font-weight: bold;text-decoration: none} .bl-source{ overflow-x:scroll; background-color: #FFFFFF; border: 1px solid #CBCBCB; color: #363636; margin: 25px 20px; width: 80%;} .bl-source div{white-space: pre;font-family: monospace;} .bl-source > div > span:first-child{background-color: #EAEAEA;color: #949494;display: inline-block;padding: 0 10px;text-align: center;width: 30px;} .bl-source .miss{background-color:#e6c3c7} .bl-source span.branchWarning{color:#000;background-color:yellow;} .bl-source span.branchOkay{color:#000;background-color:transparent;}",n=60,r=document.head,i=0,s=document.body,o,u=Object.keys(e.files).some(function(t){return typeof e.files[t].branchData!="undefined"}),a="
    results
    Coverage (%)
    Covered/Total Smts.
    "+(u?"
    Covered/Total Branches
    ":"")+"
    ",f="
    {{fileNumber}}.{{file}}
    {{percentage}} %
    {{numberCovered}}/{{totalSmts}}
    "+(u?"
    {{passedBranches}}/{{totalBranches}}
    ":"")+"
    ";grandTotalTemplate="
    {{rowTitle}}
    {{percentage}} %
    {{numberCovered}}/{{totalSmts}}
    "+(u?"
    {{passedBranches}}/{{totalBranches}}
    ":"")+"
    ";var c=document.createElement("script");c.type="text/javascript",c.text=l.toString().replace("function "+l.name,"function blanket_toggleSource"),s.appendChild(c);var h=function(e,t){return Math.round(e/t*100*100)/100},p=function(e,t,n){var r=document.createElement(e);r.innerHTML=n,t.appendChild(r)},m=[],y=function(e){return typeof e!="undefined"},b=e.files,w={totalSmts:0,numberOfFilesCovered:0,passedBranches:0,totalBranches:0,moduleTotalStatements:{},moduleTotalCoveredStatements:{},moduleTotalBranches:{},moduleTotalCoveredBranches:{}},E=_blanket.options("modulePattern"),S=E?new RegExp(E):null;for(var x in b){i++;var T=b[x],N=0,C=0,k=[],L,A=[];for(L=0;L0||typeof T.branchData!="undefined")if(typeof T.branchData[L+1]!="undefined"){var M=T.branchData[L+1].filter(y),_=0;O=g(_,O,M,0,L+1).src}else m.length?O=g(0,O,null,0,L+1).src:O=d(O);else O=d(O);var D="";T[L+1]?(C+=1,N+=1,D="hit"):T[L+1]===0&&(N++,D="miss"),k[L+1]="
    "+(L+1)+""+O+"
    "}w.totalSmts+=N,w.numberOfFilesCovered+=C;var P=0,H=0;if(typeof T.branchData!="undefined")for(var B=0;B0&&typeof T.branchData[B][j][1]!="undefined"&&T.branchData[B][j][1].length>0&&H++);w.passedBranches+=H,w.totalBranches+=P;if(S){var F=x.match(S)[1];w.moduleTotalStatements.hasOwnProperty(F)||(w.moduleTotalStatements[F]=0,w.moduleTotalCoveredStatements[F]=0),w.moduleTotalStatements[F]+=N,w.moduleTotalCoveredStatements[F]+=C,w.moduleTotalBranches.hasOwnProperty(F)||(w.moduleTotalBranches[F]=0,w.moduleTotalCoveredBranches[F]=0),w.moduleTotalBranches[F]+=P,w.moduleTotalCoveredBranches[F]+=H}var I=h(C,N),q=f.replace("{{file}}",x).replace("{{percentage}}",I).replace("{{numberCovered}}",C).replace(/\{\{fileNumber\}\}/g,i).replace("{{totalSmts}}",N).replace("{{totalBranches}}",P).replace("{{passedBranches}}",H).replace("{{source}}",k.join(" "));I",p("style",r,t),document.getElementById("blanket-main")?document.getElementById("blanket-main").innerHTML=a.slice(23,-6):p("div",s,a)},function(){var e={},t=Array.prototype.slice,n=t.call(document.scripts);t.call(n[n.length-1].attributes).forEach(function(t){t.nodeName==="data-cover-only"&&(e.filter=t.nodeValue),t.nodeName==="data-cover-never"&&(e.antifilter=t.nodeValue),t.nodeName==="data-cover-reporter"&&(e.reporter=t.nodeValue),t.nodeName==="data-cover-adapter"&&(e.adapter=t.nodeValue),t.nodeName==="data-cover-loader"&&(e.loader=t.nodeValue),t.nodeName==="data-cover-timeout"&&(e.timeout=t.nodeValue),t.nodeName==="data-cover-modulepattern"&&(e.modulePattern=t.nodeValue);if(t.nodeName==="data-cover-reporter-options")try{e.reporter_options=JSON.parse(t.nodeValue)}catch(n){if(blanket.options("debug"))throw new Error("Invalid reporter options. Must be a valid stringified JSON object.")}t.nodeName==="data-cover-testReadyCallback"&&(e.testReadyCallback=t.nodeValue),t.nodeName==="data-cover-customVariable"&&(e.customVariable=t.nodeValue);if(t.nodeName==="data-cover-flags"){var r=" "+t.nodeValue+" ";r.indexOf(" ignoreError ")>-1&&(e.ignoreScriptError=!0),r.indexOf(" autoStart ")>-1&&(e.autoStart=!0),r.indexOf(" ignoreCors ")>-1&&(e.ignoreCors=!0),r.indexOf(" branchTracking ")>-1&&(e.branchTracking=!0),r.indexOf(" sourceURL ")>-1&&(e.sourceURL=!0),r.indexOf(" debug ")>-1&&(e.debug=!0),r.indexOf(" engineOnly ")>-1&&(e.engineOnly=!0),r.indexOf(" commonJS ")>-1&&(e.commonJS=!0),r.indexOf(" instrumentCache ")>-1&&(e.instrumentCache=!0)}}),blanket.options(e),typeof requirejs!="undefined"&&blanket.options("existingRequireJS",!0),blanket.options("commonJS")&&(blanket._commonjs={})}(),function(e){e.extend({utils:{normalizeBackslashes:function(e){return e.replace(/\\/g,"/")},matchPatternAttribute:function(t,n){if(typeof n=="string"){if(n.indexOf("[")===0){var r=n.slice(1,n.length-1).split(",");return r.some(function(n){return e.utils.matchPatternAttribute(t,e.utils.normalizeBackslashes(n.slice(1,-1)))})}if(n.indexOf("//")===0){var i=n.slice(2,n.lastIndexOf("/")),s=n.slice(n.lastIndexOf("/")+1),o=new RegExp(i,s);return o.test(t)}return n.indexOf("#")===0?window[n.slice(1)].call(window,t):t.indexOf(e.utils.normalizeBackslashes(n))>-1}if(n instanceof Array)return n.some(function(n){return e.utils.matchPatternAttribute(t,n)});if(n instanceof RegExp)return n.test(t);if(typeof n=="function")return n.call(window,t)},blanketEval:function(t){e._addScript(t)},collectPageScripts:function(){var t=Array.prototype.slice,n=t.call(document.scripts),r=[],i=[],s=e.options("filter");if(s!=null){var o=e.options("antifilter");r=t.call(document.scripts).filter(function(n){return t.call(n.attributes).filter(function(t){return t.nodeName==="src"&&e.utils.matchPatternAttribute(t.nodeValue,s)&&(typeof o=="undefined"||!e.utils.matchPatternAttribute(t.nodeValue,o))}).length===1})}else r=t.call(document.querySelectorAll("script[data-cover]"));return i=r.map(function(n){return e.utils.qualifyURL(t.call(n.attributes).filter(function(e){return e.nodeName==="src"})[0].nodeValue)}),s||e.options("filter","['"+i.join("','")+"']"),i},loadAll:function(t,n,r){var i=t(),s=e.utils.scriptIsLoaded(i,e.utils.ifOrdered,t,n);if(!e.utils.cache[i]||!e.utils.cache[i].loaded){var o=function(){e.options("debug")&&console.log("BLANKET-Mark script:"+i+", as loaded and move to next script."),s()},u=function(t){e.options("debug")&&console.log("BLANKET-File loading finished"),typeof t!="undefined"&&(e.options("debug")&&console.log("BLANKET-Add file to DOM."),e._addScript(t)),o()};e.utils.attachScript({url:i},function(t){e.utils.processFile(t,i,u,u)})}else s()},attachScript:function(t,n){var r=e.options("timeout")||3e3;setTimeout(function(){if(!e.utils.cache[t.url].loaded)throw new Error("error loading source script")},r),e.utils.getFile(t.url,n,function(){throw new Error("error loading source script")})},ifOrdered:function(t,n){var r=t(!0);r?e.utils.loadAll(t,n):n(new Error("Error in loading chain."))},scriptIsLoaded:function(t,n,r,i){return e.options("debug")&&console.log("BLANKET-Returning function"),function(){e.options("debug")&&console.log("BLANKET-Marking file as loaded: "+t),e.utils.cache[t].loaded=!0,e.utils.allLoaded()?(e.options("debug")&&console.log("BLANKET-All files loaded"),i()):n&&(e.options("debug")&&console.log("BLANKET-Load next file."),n(r,i))}},cache:{},allLoaded:function(){var t=Object.keys(e.utils.cache);for(var n=0;n-1){n(e.blanketSession[a]),s=!0;return}}}if(!s){var f=e.utils.createXhr();f.open("GET",t,!0),i&&i(f,t),f.onreadystatechange=function(e){var i,s;f.readyState===4&&(i=f.status,i>399&&i<600?(s=new Error(t+" HTTP status: "+i),s.xhr=f,r(s)):n(f.responseText))};try{f.send(null)}catch(l){if(!l.code||l.code!==101&&l.code!==1012||e.options("ignoreCors")!==!1)throw l;e.showManualLoader()}}}}}),function(){var t=blanket.options("commonJS")?blanket._commonjs.require:window.require,n=blanket.options("commonJS")?blanket._commonjs.requirejs:window.requirejs;!e.options("engineOnly")&&e.options("existingRequireJS")&&(e.utils.oldloader=n.load,n.load=function(t,n,r){e.requiringFile(r),e.utils.getFile(r,function(i){e.utils.processFile(i,r,function(){t.completeLoad(n)},function(){e.utils.oldloader(t,n,r)})},function(t){throw e.requiringFile(),t})}),e.utils.cacheXhrConstructor()}()}(blanket),function(){if(!mocha)throw new Exception("mocha library does not exist in global namespace!");var e=mocha._reporter,t=function(t){t.on("start",function(){blanket.setupCoverage()}),t.on("end",function(){blanket.onTestsDone()}),t.on("suite",function(){blanket.onModuleStart()}),t.on("test",function(){blanket.onTestStart()}),t.on("test end",function(e){blanket.onTestDone(e.parent.tests.length,e.state==="passed")}),e.apply(this,arguments)};mocha.reporter(t);var n=mocha.run,r=null;mocha.run=function(e){r=e,console.log("waiting for blanket...")},blanket.beforeStartTestRunner({callback:function(){blanket.options("existingRequireJS")||n(r),mocha.run=n}})}(); diff --git a/tests/resources/js/json2.js b/tests/resources/js/json2.js deleted file mode 100755 index c7745df..0000000 --- a/tests/resources/js/json2.js +++ /dev/null @@ -1,486 +0,0 @@ -/* - json2.js - 2012-10-08 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, regexp: true */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (typeof JSON !== 'object') { - JSON = {}; -} - -(function () { - 'use strict'; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function (key) { - - return isFinite(this.valueOf()) - ? this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' - : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } - - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' - ? c - : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 - ? '[]' - : gap - ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' - : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 - ? '{}' - : gap - ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' - : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof JSON.stringify !== 'function') { - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof JSON.parse !== 'function') { - JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' - ? walk({'': j}, '') - : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); diff --git a/tests/resources/js/mocha.js b/tests/resources/js/mocha.js deleted file mode 100644 index 00dcda1..0000000 --- a/tests/resources/js/mocha.js +++ /dev/null @@ -1,5341 +0,0 @@ -;(function(){ - - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ - -module.exports = function(type){ - return function(){ - - } -}; -}); // module: browser/debug.js - -require.register("browser/diff.js", function(module, exports, require){ -/* See license.txt for terms of usage */ - -/* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -var JsDiff = (function() { - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, "&"); - n = n.replace(//g, ">"); - n = n.replace(/"/g, """); - - return n; - } - - - var fbDiff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - fbDiff.prototype = { - diff: function(oldString, newString) { - // Handle the identity case (this is due to unrolling editLength == 0 - if (newString == oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } - - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); - - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; - - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } - - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } - - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } - - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } - - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); - - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; - } - } - } - }, - - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left == right; - } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; - } - }; - - var CharDiff = new fbDiff(); - - var WordDiff = new fbDiff(true); - WordDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; - - var CssDiff = new fbDiff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; - - var LineDiff = new fbDiff(); - LineDiff.tokenize = function(value) { - return value.split(/^/m); - }; - - return { - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, - - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, - - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; - - ret.push("Index: " + fileName); - ret.push("==================================================================="); - ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader)); - ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader)); - - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } - - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, "").split("\n"); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; })); - eofNL(curRange, i, current); - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize) - + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize) - + " @@"); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); - } - - oldRangeStart = 0; newRangeStart = 0; curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - - return ret.join('\n') + '\n'; - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(""); - } else if (change.removed) { - ret.push(""); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(""); - } else if (change.removed) { - ret.push(""); - } - } - return ret.join(""); - } - }; -})(); - -if (typeof module !== "undefined") { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/events.js", function(module, exports, require){ - -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; -}); // module: browser/events.js - -require.register("browser/fs.js", function(module, exports, require){ - -}); // module: browser/fs.js - -require.register("browser/path.js", function(module, exports, require){ - -}); // module: browser/path.js - -require.register("browser/progress.js", function(module, exports, require){ - -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - return [window.innerHeight, window.innerWidth]; -}; -}); // module: browser/tty.js - -require.register("context.js", function(module, exports, require){ - -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; - - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) var fn = null; - var test = new Test(title, fn); - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - mocha.grep(test.fullTitle()); - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - suites[0].addTest(new Test(key, fn)); - } - } else { - var suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); - -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context){ - - /** - * Execute before running tests. - */ - - context.before = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before each test case. - */ - - context.setup = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.teardown = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Execute before the suite. - */ - - context.suiteSetup = function(fn){ - suites[0].beforeAll(fn); - }; - - /** - * Execute after the suite. - */ - - context.suiteTeardown = function(fn){ - suites[0].afterAll(fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - mocha.grep(test.fullTitle()); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('browser/path') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter); - if (options.timeout) this.timeout(options.timeout); - if (options.slow) this.slow(options.slow); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "dot". - * - * @param {String|Function} reporter name or constructor - * @api public - */ - -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'dot'; - try { - this._reporter = require('./reporters/' + reporter); - } catch (err) { - this._reporter = require(reporter); - } - if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); - } - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(utils.escapeRegexp(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(){ - this.options.ignoreLeaks = true; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ - -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner); - runner.ignoreLeaks = options.ignoreLeaks; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - return runner.run(fn); -}; - -}); // module: blanket_mocha.js - -require.register("ms.js", function(module, exports, require){ - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; - -/** - * Parse or format the given `val`. - * - * @param {String|Number} val - * @return {String|Number} - * @api public - */ - -module.exports = function(val){ - if ('string' == typeof val) return parse(val); - return format(val); -} - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!m) return; - var n = parseFloat(m[1]); - var type = (m[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * 31557600000; - case 'days': - case 'day': - case 'd': - return n * 86400000; - case 'hours': - case 'hour': - case 'h': - return n * 3600000; - case 'minutes': - case 'minute': - case 'm': - return n * 60000; - case 'seconds': - case 'second': - case 's': - return n * 1000; - case 'ms': - return n; - } -} - -/** - * Format the given `ms`. - * - * @param {Number} ms - * @return {String} - * @api public - */ - -function format(ms) { - if (ms == d) return Math.round(ms / d) + ' day'; - if (ms > d) return Math.round(ms / d) + ' days'; - if (ms == h) return Math.round(ms / h) + ' hour'; - if (ms > h) return Math.round(ms / h) + ' hours'; - if (ms == m) return Math.round(ms / m) + ' minute'; - if (ms > m) return Math.round(ms / m) + ' minutes'; - if (ms == s) return Math.round(ms / s) + ' second'; - if (ms > s) return Math.round(ms / s) + ' seconds'; - return ms + ' ms'; -} -}); // module: ms.js - -require.register("reporters/base.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; - - // explicitly show diff - if (err.showDiff) { - escape = false; - err.actual = actual = JSON.stringify(actual, null, 2); - err.expected = expected = JSON.stringify(expected, null, 2); - } - - // actual / expected diff - if ('string' == typeof actual && 'string' == typeof expected) { - var len = Math.max(actual.length, expected.length); - - if (len < 20) msg = errorDiff(err, 'Chars', escape); - else msg = errorDiff(err, 'Words', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - - fmt = color('error title', ' %s) %s:\n%s') - + color('error stack', '\n%s\n'); - } - - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); - - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt - , tests; - - console.log(); - - function pluralize(n) { - return 1 == n ? 'test' : 'tests'; - } - - // failure - if (stats.failures) { - fmt = color('bright fail', ' ' + exports.symbols.err) - + color('fail', ' %d of %d %s failed') - + color('light', ':') - - console.error(fmt, - stats.failures, - this.runner.total, - pluralize(this.runner.total)); - - Base.list(this.failures); - console.error(); - return; - } - - // pass - fmt = color('bright pass', ' ') - + color('green', ' %d %s complete') - + color('light', ' (%s)'); - - console.log(fmt, - stats.tests || 0, - pluralize(stats.tests), - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d %s pending'); - - console.log(fmt, stats.pending, pluralize(stats.pending)); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - return diff['diff' + type](err.actual, err.expected).map(function(str){ - if (escape) { - str.value = str.value - .replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); - } - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
    ', indent()); - ++indents; - console.log('%s

    %s

    ', indent(), utils.escape(suite.title)); - console.log('%s
    ', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
    ', indent()); - --indents; - console.log('%s
    ', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
    %s
    ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
    %s
    ', indent(), code); - }); -} - -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = 0; - - runner.on('start', function(){ - process.stdout.write('\n '); - }); - - runner.on('pending', function(test){ - process.stdout.write(color('pending', Base.symbols.dot)); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Dot.prototype = new F; -Dot.prototype.constructor = Dot; - -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); - -/** - * Expose `HTMLCov`. - */ - -exports = module.exports = HTMLCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; - - JSONCov.call(this, runner, false); - - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} - -/** - * Return coverage class for `n`. - * - * @return {String} - * @api private - */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} -}); // module: reporters/html-cov.js - -require.register("reporters/html.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `Doc`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = ''; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner, root) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
      ') - , stack = [report] - , progress - , ctx - - root = root || document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } - - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = '?grep=' + encodeURIComponent(suite.fullTitle()); - var el = fragment('
    • %s

    • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - window.scrollTo(0, document.body.scrollHeight); - - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle())); - } else if (test.pending) { - var el = fragment('
    • %e

    • ', test.title); - } else { - var el = fragment('
    • %e

    • ', test.title, encodeURIComponent(test.fullTitle())); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
      %e
      ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
      %e
      ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
      %s
      ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); -exports.Teamcity = require('./teamcity'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -}; - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) - }; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; - - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; - buf += stringifyTOC(obj[key], level); - } - --level; - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw('start'); - }); - - runner.on('pending', function(test){ - self.draw('pending'); - }); - - runner.on('pass', function(test){ - self.draw('pass'); - }); - - runner.on('fail', function(test, err){ - self.draw('fail'); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat with runner `status`. - * - * @param {String} status - * @api private - */ - -NyanCat.prototype.draw = function(status){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(status); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - var colors = Base.colors; - - function draw(color, n) { - write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); - write('\n'); - } - - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat with `status`. - * - * @param {String} status - * @api private - */ - -NyanCat.prototype.drawNyanCat = function(status) { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - - [0, 1, 2, 3].forEach(function(index) { - write('\u001b[' + startWidth + 'C'); - - switch (index) { - case 0: - write('_,------,'); - write('\n'); - break; - case 1: - var padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - break; - case 2: - var padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - switch (status) { - case 'pass': - face = '( ^ .^)'; - break; - case 'fail': - face = '( o .o)'; - break; - default: - face = '( - .-)'; - } - write(tail + '|' + padding + face + ' '); - write('\n'); - break; - case 3: - var padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - break; - } - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s '); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/teamcity.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Teamcity`. - */ - -exports = module.exports = Teamcity; - -/** - * Initialize a new `Teamcity` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Teamcity(runner) { - Base.call(this, runner); - var stats = this.stats; - - runner.on('start', function() { - console.log("##teamcity[testSuiteStarted name='mocha.suite']"); - }); - - runner.on('test', function(test) { - console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); - }); - - runner.on('fail', function(test, err) { - console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); - }); - - runner.on('pending', function(test) { - console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); - }); - - runner.on('test end', function(test) { - console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); - }); - - runner.on('end', function() { - console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); - }); -} - -/** - * Escape the given `str`. - */ - -function escape(str) { - return str - .replace(/\|/g, "||") - .replace(/\n/g, "|n") - .replace(/\r/g, "|r") - .replace(/\[/g, "|[") - .replace(/\]/g, "|]") - .replace(/\u0085/g, "|x") - .replace(/\u2028/g, "|l") - .replace(/\u2029/g, "|p") - .replace(/'/g, "|'"); -} - -}); // module: reporters/teamcity.js - -require.register("reporters/xunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - console.log(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skip: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: stats.duration / 1000 - }, false)); - - tests.forEach(test); - console.log(''); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; - - -/** - * Output tag for the given `test.` - */ - -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: test.duration / 1000 - }; - - if ('failed' == test.state) { - var err = test.err; - attrs.message = escape(err.message); - console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this.timedOut = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this - , ms = this.timeout(); - - this.clearTimeout(); - if (ms) { - this.timer = setTimeout(function(){ - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , ms = this.timeout() - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - if (ctx) ctx.runnable(this); - - // timeout - if (this.async) { - if (ms) { - this.timer = setTimeout(function(){ - done(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } - } - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times')); - } - - // finished - function done(err) { - if (self.timedOut) return; - if (finished) return multiple(err); - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // async - if (this.async) { - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); - done(); - }); - } catch (err) { - done(err); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync - try { - if (!this.pending) this.fn.call(ctx); - this.duration = new Date - start; - fn(); - } catch (err) { - fn(err); - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys - , noop = function(){} - , immediately = global.setImmediate || process.nextTick; - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - * @api public - */ - -function Runner(suite) { - var self = this; - this._globals = []; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(['errno'])); -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - utils.forEach(arr, function(arr){ - this._globals.push(arr); - }, this); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - var globals = this.globalProps(); - var isNode = process.kill; - var leaks; - - // check length - 2 ('errno' and 'location' globals) - if (isNode && 1 == ok.length - globals.length) return - else if (2 == ok.length - globals.length) return; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - ++this.failures; - test.state = 'failed'; - - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); - } - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures (currently) hard-end due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - this.emit('end'); -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - self.currentRunnable = hook; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) return self.failHook(hook, err); - self.emit('hook end', hook); - next(++i); - }); - } - - immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - self.suite = orig; - return fn(err); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - function next(err) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - self.fail(test, err); - self.emit('test end', test); - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next() { - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done() { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(); - }); - } - - this.hook('beforeAll', function(){ - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - debug('uncaught exception %s', err.message); - var runnable = this.currentRunnable; - if (!runnable || 'failed' == runnable.state) return; - runnable.clearTimeout(); - err.uncaught = true; - this.fail(runnable, err); - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - return this; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return true; - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, ctx) { - this.title = title; - this.ctx = ctx; - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._slow = 75; - this._bail = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; - - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @parma {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before all" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after all" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before each" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after each" hook', fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var fs = require('browser/fs') - , path = require('browser/path') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ret){ - ret = ret || []; - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ret); - } else if (path.match(/\.(js|coffee)$/)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/^function *\(.*\) *{/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Escape regular expression characters in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.escapeRegexp = function(str){ - return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew *(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - -}); // module: utils.js -/** - * Node shims. - * - * These are meant only to allow - * blanket_mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -process = {}; -process.exit = function(status){}; -process.stdout = {}; -global = window; - -/** - * next tick implementation. - */ - -process.nextTick = (function(){ - // postMessage behaves badly on IE8 - if (window.ActiveXObject || !window.postMessage) { - return function(fn){ fn() }; - } - - // based on setZeroTimeout by David Baron - // - http://dbaron.org/log/20100309-faster-timeouts - var timeouts = [] - , name = 'mocha-zero-timeout' - - window.addEventListener('message', function(e){ - if (e.source == window && e.data == name) { - if (e.stopPropagation) e.stopPropagation(); - if (timeouts.length) timeouts.shift()(); - } - }, true); - - return function(fn){ - timeouts.push(fn); - window.postMessage(name, '*'); - } -})(); - -/** - * Remove uncaughtException listener. - */ - -process.removeListener = function(e){ - if ('uncaughtException' == e) { - window.onerror = null; - } -}; - -/** - * Implements uncaughtException listener. - */ - -process.on = function(e, fn){ - if ('uncaughtException' == e) { - window.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - }; - } -}; - -// boot -;(function(){ - - /** - * Expose mocha. - */ - - var Mocha = window.Mocha = require('mocha'), - mocha = window.mocha = new Mocha({ reporter: 'html' }); - - /** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - - mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', window, null, this); - return this; - }; - - /** - * Setup mocha with the given setting options. - */ - - mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; - }; - - /** - * Run mocha, returning the Runner. - */ - - mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); - - var query = Mocha.utils.parseQuery(window.location.search || ''); - if (query.grep) mocha.grep(query.grep); - if (query.invert) mocha.invert(); - - return Mocha.prototype.run.call(mocha, function(){ - Mocha.utils.highlightTags('code'); - if (fn) fn(); - }); - }; -})(); -})(); \ No newline at end of file diff --git a/tests/test.html b/tests/test.html deleted file mode 100755 index 66391d2..0000000 --- a/tests/test.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - Readme File Tests - - - - - - - - - -
      - App Services (Usergrid) Javascript SDK -
      -
      - This sample application runs tests on the sample code examples in the readme file. Tests are run against App Services (Usergrid) using the Usergrid Javascript SDK. -
      -
      -
      README sample code tests
      -
      -
      -
      - -   -
      -
      -
      -
      Test Output
      -
      -
      // Press Start button to begin
      -
      - - diff --git a/tests/test.js b/tests/test.js deleted file mode 100755 index f726680..0000000 --- a/tests/test.js +++ /dev/null @@ -1,927 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** -* Test suite for all the examples in the readme -* -* NOTE: No, this test suite doesn't use the traditional format for -* a test suite. This is because the goal is to require as little -* alteration as possible during the copy / paste operation from this test -* suite to the readme file. -* -* @author rod simpson (rod@apigee.com) -*/ - -$(document).ready(function () { - -//call the runner function to start the process -$('#start-button').bind('click', function() { - $('#start-button').attr("disabled", "disabled"); - $('#test-output').html(''); - runner(0); -}); - -var logSuccess = true; -var successCount = 0; -var logError = true; -var errorCount = 0; -var logNotice = true; -var _username = 'marty2'; -var _email = 'marty2@timetravel.com'; -var _password = 'password2'; -var _newpassword = 'password3'; - -var client = new Usergrid.Client({ - orgName:'yourorgname', - appName:'sandbox', - logging: true, //optional - turn on logging, off by default - buildCurl: true //optional - turn on curl commands, off by default -}); - -client.logout(); - -function runner(step, arg, arg2){ - step++; - switch(step) - { - case 1: - notice('-----running step '+step+': DELETE user from DB to prep test'); - clearUser(step); - break; - case 2: - notice('-----running step '+step+': GET test'); - testGET(step); - break; - case 3: - notice('-----running step '+step+': POST test'); - testPOST(step); - break; - case 4: - notice('-----running step '+step+': PUT test'); - testPUT(step); - break; - case 5: - notice('-----running step '+step+': DELETE test'); - testDELETE(step); - break; - case 6: - notice('-----running step '+step+': prepare database - remove all dogs (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 7: - notice('-----running step '+step+': make a new dog'); - makeNewDog(step); - break; - case 8: - notice('-----running step '+step+': update our dog'); - updateDog(step, arg); - break; - case 9: - notice('-----running step '+step+': refresh our dog'); - refreshDog(step, arg); - break; - case 10: - notice('-----running step '+step+': remove our dog from database (no real dogs harmed here!!)'); - removeDogFromDatabase(step, arg); - break; - case 11: - notice('-----running step '+step+': make lots of dogs!'); - makeSampleData(step, arg); - break; - case 12: - notice('-----running step '+step+': make a dogs collection and show each dog'); - testDogsCollection(step); - break; - case 13: - notice('-----running step '+step+': get the next page of the dogs collection and show each dog'); - getNextDogsPage(step, arg); - break; - case 14: - notice('-----running step '+step+': get the previous page of the dogs collection and show each dog'); - getPreviousDogsPage(step, arg); - break; - case 15: - notice('-----running step '+step+': remove all dogs from the database (no real dogs harmed here!!)'); - cleanupAllDogs(step); - break; - case 16: - notice('-----running step '+step+': prepare database (remove existing user if present)'); - prepareDatabaseForNewUser(step); - break; - case 17: - notice('-----running step '+step+': create a new user'); - createUser(step); - break; - case 18: - notice('-----running step '+step+': update the user'); - updateUser(step, arg); - break; - case 19: - notice('-----running step '+step+': get the existing user'); - getExistingUser(step, arg); - break; - case 20: - notice('-----running step '+step+': refresh the user from the database'); - refreshUser(step, arg); - break; - case 21: - notice('-----running step '+step+': log user in'); - loginUser(step, arg); - break; - case 22: - notice('-----running step '+step+': change users password'); - changeUsersPassword(step, arg); - break; - case 23: - notice('-----running step '+step+': log user out'); - logoutUser(step, arg); - break; - case 24: - notice('-----running step '+step+': relogin user'); - reloginUser(step, arg); - break; - case 25: - notice('-----running step '+step+': logged in user creates dog'); - createDog(step, arg); - break; - case 26: - notice('-----running step '+step+': logged in user likes dog'); - userLikesDog(step, arg, arg2); - break; - case 27: - notice('-----running step '+step+': logged in user removes likes connection to dog'); - removeUserLikesDog(step, arg, arg2); - break; - case 28: - notice('-----running step '+step+': user removes dog'); - removeDog(step, arg, arg2); - break; - case 29: - notice('-----running step '+step+': log the user out'); - logoutUser(step, arg); - break; - case 30: - notice('-----running step '+step+': remove the user from the database'); - destroyUser(step, arg); - break; - case 31: - notice('-----running step '+step+': try to create existing entity'); - createExistingEntity(step, arg); - break; - case 32: - notice('-----running step '+step+': try to create new entity with no name'); - createNewEntityNoName(step, arg); - break; - default: - notice('-----test complete!-----'); - notice('Success count= ' + successCount); - notice('Error count= ' + errorCount); - notice('-----thank you for playing!-----'); - $('#start-button').removeAttr("disabled"); - } -} - -//logging functions -function success(message){ - successCount++; - if (logSuccess) { - console.log('SUCCESS: ' + message); - var html = $('#test-output').html(); - html += ('SUCCESS: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function error(message){ - errorCount++ - if (logError) { - console.log('ERROR: ' + message); - var html = $('#test-output').html(); - html += ('ERROR: ' + message + '\r\n'); - $('#test-output').html(html); - } -} - -function notice(message){ - if (logNotice) { - console.log('NOTICE: ' + message); - var html = $('#test-output').html(); - html += (message + '\r\n'); - $('#test-output').html(html); - } -} - -//tests -function clearUser(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - //data will contain raw results from API call - success('User cleared from DB'); - runner(step); - }); -} - -function testGET(step) { - var options = { - method:'GET', - endpoint:'users' - }; - client.request(options, function (err, data) { - if (err) { - error('GET failed'); - } else { - //data will contain raw results from API call - success('GET worked'); - runner(step); - } - }); -} - -function testPOST(step) { - var options = { - method:'POST', - endpoint:'users', - body:{ username:'fred', password:'secret' } - }; - client.request(options, function (err, data) { - if (err) { - error('POST failed'); - } else { - //data will contain raw results from API call - success('POST worked'); - runner(step); - } - }); -} - -function testPUT(step) { - var options = { - method:'PUT', - endpoint:'users/fred', - body:{ newkey:'newvalue' } - }; - client.request(options, function (err, data) { - if (err) { - error('PUT failed'); - } else { - //data will contain raw results from API call - success('PUT worked'); - runner(step); - } - }); -} - -function testDELETE(step) { - var options = { - method:'DELETE', - endpoint:'users/fred' - }; - client.request(options, function (err, data) { - if (err) { - error('DELETE failed'); - } else { - //data will contain raw results from API call - success('DELETE worked'); - runner(step); - } - }); -} - -function makeNewDog(step) { - - var options = { - type:'dogs', - name:'Rocky' - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('dog not created'); - } else { - success('dog is created'); - - //once the dog is created, you can set single properties: - dog.set('breed','Dinosaur'); - - //the set function can also take a JSON object: - var data = { - master:'Fred', - state:'hungry' - } - //set is additive, so previously set properties are not overwritten - dog.set(data); - - //finally, call save on the object to save it back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('new dog is saved'); - runner(step, dog); - } - }); - } - }); - -} - -function updateDog(step, dog) { - - //change a property in the object - dog.set("state", "fed"); - //and save back to the database - dog.save(function(err){ - if (err){ - error('dog not saved'); - } else { - success('dog is saved'); - runner(step, dog); - } - }); - -} - -function refreshDog(step, dog){ - - //call fetch to refresh the data from the server - dog.fetch(function(err){ - if (err){ - error('dog not refreshed from database'); - } else { - //dog has been refreshed from the database - //will only work if the UUID for the entity is in the dog object - success('dog entity refreshed from database'); - runner(step, dog); - } - }); - -} - -function removeDogFromDatabase(step, dog){ - - //the destroy method will delete the entity from the database - dog.destroy(function(err){ - if (err){ - error('dog not removed from database'); - } else { - success('dog removed from database'); // no real dogs were harmed! - dog = null; //no real dogs were harmed! - runner(step, 1); - } - }); - -} - -function makeSampleData(step, i) { - notice('making dog '+i); - - var options = { - type:'dogs', - name:'dog'+i, - index:i - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('dog ' + i + ' not created'); - } else { - if (i >= 30) { - //data made, ready to go - success('all dogs made'); - runner(step); - } else { - success('dog ' + i + ' made'); - //keep making dogs - makeSampleData(step, ++i); - } - } - }); -} - -function testDogsCollection(step) { - - var options = { - type:'dogs', - qs:{ql:'order by index'} - } - - client.createCollection(options, function (err, dogs) { - if (err) { - error('could not make collection'); - } else { - - success('new Collection created'); - - //we got the dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - - success('looped through dogs'); - - //create a new dog and add it to the collection - var options = { - name:'extra-dog', - fur:'shedding' - } - //just pass the options to the addEntity method - //to the collection and it is saved automatically - dogs.addEntity(options, function(err, dog, data) { - if (err) { - error('extra dog not saved or added to collection'); - } else { - success('extra dog saved and added to collection'); - runner(step, dogs); - } - }); - } - }); - -} - -function getNextDogsPage(step, dogs) { - - if (dogs.hasNextPage()) { - //there is a next page, so get it from the server - dogs.getNextPage(function(err){ - if (err) { - error('could not get next page of dogs'); - } else { - success('got next page of dogs'); - //we got the next page of data, so do something with it: - var i = 11; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs') - runner(step, dogs); - } - }); - } else { - getPreviousDogsPage(dogs); - } - -} - -function getPreviousDogsPage(step, dogs) { - - if (dogs.hasPreviousPage()) { - //there is a previous page, so get it from the server - dogs.getPreviousPage(function(err){ - if(err) { - error('could not get previous page of dogs'); - } else { - success('got next page of dogs'); - //we got the previous page of data, so do something with it: - var i = 1; - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var index = dog.get('index'); - if(i !== index) { - error('wrong dog loaded: wanted' + i + ', got ' + index); - } - notice('got dog ' + i); - i++ - } - success('looped through dogs'); - runner(step); - } - }); - } else { - getAllDogs(); - } -} - -function cleanupAllDogs(step){ - - var options = { - type:'dogs', - qs:{limit:50} //limit statement set to 50 - } - - client.createCollection(options, function (err, dogs) { - if (err) { - error('could not get all dogs'); - } else { - success('got at most 50 dogs'); - //we got 50 dogs, now display the Entities: - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var name = dog.get('name'); - notice('dog is called ' + name); - } - dogs.resetEntityPointer(); - //do doggy cleanup - while(dogs.hasNextEntity()) { - //get a reference to the dog - var dog = dogs.getNextEntity(); - var dogname = dog.get('name'); - notice('removing dog ' + dogname + ' from database'); - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - } - - //no need to wait around for dogs to be removed, so go on to next test - runner(step); - } - }); -} - - -function prepareDatabaseForNewUser(step) { - var options = { - method:'DELETE', - endpoint:'users/'+_username - }; - client.request(options, function (err, data) { - if (err) { - notice('database ready - no user to delete'); - runner(step); - } else { - //data will contain raw results from API call - success('database ready - user deleted worked'); - runner(step); - } - }); -} - - -function createUser(step) { - client.signup(_username, _password, _email, 'Marty McFly', - function (err, marty) { - if (err){ - error('user not created'); - runner(step, marty); - } else { - success('user created'); - runner(step, marty); - } - } - ); -} - -function updateUser(step, marty) { - - //add properties cumulatively - marty.set('state', 'California'); - marty.set("girlfriend","Jennifer"); - marty.save(function(err){ - if (err){ - error('user not updated'); - } else { - success('user updated'); - runner(step, marty); - } - }); - -} - -function getExistingUser(step, marty) { - - var options = { - type:'users', - username:_username - } - client.getEntity(options, function(err, existingUser){ - if (err){ - error('existing user not retrieved'); - } else { - success('existing user was retrieved'); - - var username = existingUser.get('username'); - if (username === _username){ - success('got existing user username'); - } else { - error('could not get existing user username'); - } - runner(step, marty); - } - }); - -} - - -function refreshUser(step, marty) { - - marty.fetch(function(err){ - if (err){ - error('not refreshed'); - } else { - success('user refreshed'); - runner(step, marty); - } - }); - -} - -function loginUser(step, marty) { - username = _username; - password = _password; - client.login(username, password, - function (err) { - if (err) { - error('could not log user in'); - } else { - success('user has been logged in'); - - //the login call will return an OAuth token, which is saved - //in the client. Any calls made now will use the token. - //once a user has logged in, their user object is stored - //in the client and you can access it this way: - var token = client.token; - - //Then make calls against the API. For example, you can - //get the user entity this way: - client.getLoggedInUser(function(err, data, user) { - if(err) { - error('could not get logged in user'); - } else { - success('got logged in user'); - - //you can then get info from the user entity object: - var username = user.get('username'); - notice('logged in user was: ' + username); - - runner(step, user); - } - }); - - } - } - ); -} - -function changeUsersPassword(step, marty) { - - marty.set('oldpassword', _password); - marty.set('newpassword', _newpassword); - marty.save(function(err){ - if (err){ - error('user password not updated'); - } else { - success('user password updated'); - runner(step, marty); - } - }); - -} - -function logoutUser(step, marty) { - - //to log the user out, call the logout() method - client.logout(); - - //verify the logout worked - if (client.isLoggedIn()) { - error('logout failed'); - } else { - success('user has been logged out'); - } - - runner(step, marty); -} - -function reloginUser(step, marty) { - - username = _username - password = _newpassword; - client.login(username, password, - function (err) { - if (err) { - error('could not relog user in'); - } else { - success('user has been re-logged in'); - runner(step, marty); - } - } - ); -} - - - -//TODO: currently, this code assumes permissions have been set to support user actions. need to add code to show how to add new role and permission programatically -// -//first create a new permission on the default role: -//POST "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions" -d '{"permission":"get,post,put,delete:/dogs/**"}' -//then after user actions, delete the permission on the default role: -//DELETE "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions?permission=get%2Cpost%2Cput%2Cdelete%3A%2Fdogs%2F**" - - -function createDog(step, marty) { - - var options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('POST new dog by logged in user failed'); - } else { - success('POST new dog by logged in user succeeded'); - runner(step, marty, dog); - } - }); - -} - -function userLikesDog(step, marty, dog) { - - marty.connect('likes', dog, function (err, data) { - if (err) { - error('connection not created'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, data) { - if (err) { - error('could not get connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - success('connection exists'); - } else { - error('connection does not exist'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeUserLikesDog(step, marty, dog) { - - marty.disconnect('likes', dog, function (err, data) { - if (err) { - error('connection not deleted'); - runner(step, marty); - } else { - - //call succeeded, so pull the connections back down - marty.getConnections('likes', function (err, data) { - if (err) { - error('error getting connections'); - } else { - //verify that connection exists - if (marty.likes.einstein) { - error('connection still exists'); - } else { - success('connection deleted'); - } - - runner(step, marty, dog); - } - }); - } - }); - -} - -function removeDog(step, marty, dog) { - - //now delete the dog from the database - dog.destroy(function(err, data) { - if (err) { - error('dog not removed'); - } else { - success('dog removed'); - } - }); - runner(step, marty); -} - -function destroyUser(step, marty) { - - marty.destroy(function(err){ - if (err){ - error('user not deleted from database'); - } else { - success('user deleted from database'); - marty = null; //blow away the local object - runner(step); - } - }); - -} - -function createExistingEntity(step, marty) { - - var options = { - type:'dogs', - name:'einstein' - } - - client.createEntity(options, function (err, dog) { - if (err) { - error('Create new entity to use for existing entity failed'); - } else { - success('Create new entity to use for existing entity succeeded'); - - var uuid = dog.get('uuid'); - //now create new entity, but use same entity name of einstein. This means that - //the original einstein entity now exists. Thus, the new einstein entity should - //be the same as the original + any data differences from the options var: - - options = { - type:'dogs', - name:'einstein', - breed:'mutt' - } - client.createEntity(options, function (err, newdog) { - if (err) { - error('Create new entity to use for existing entity failed'); - } else { - success('Create new entity to use for existing entity succeeded'); - - var newuuid = newdog.get('uuid'); - if (newuuid === uuid) { - success('UUIDs of new and old entities match'); - } else { - error('UUIDs of new and old entities do not match'); - } - - var breed = newdog.get('breed'); - if (breed === 'mutt') { - success('attribute sucesfully set on new entity'); - } else { - error('attribute not sucesfully set on new entity'); - } - - newdog.destroy(function(err){ - if (err){ - error('existing entity not deleted from database'); - } else { - success('existing entity deleted from database'); - dog = null; //blow away the local object - newdog = null; //blow away the local object - runner(step); - } - }); - - } - }); - } - }); - -} - -function createNewEntityNoName(step, marty) { - - var options = { - type:"something", - othervalue:"something else" - } - - client.createEntity(options, function (err, entity) { - if (err) { - error('Create new entity with no name failed'); - } else { - success('Create new entity with no name succeeded'); - - entity.destroy(); - runner(step); - } - }); - -} - -}); \ No newline at end of file diff --git a/usergrid.js b/usergrid.js index 5989d8a..132f0f1 100644 --- a/usergrid.js +++ b/usergrid.js @@ -1,127 +1,30 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at +/*! + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * + * usergrid@2.0.0 2016-10-14 */ -var UsergridEventable = function() { - throw Error("'UsergridEventable' is not intended to be invoked directly"); -}; - -UsergridEventable.prototype = { - bind: function(event, fn) { - this._events = this._events || {}; - this._events[event] = this._events[event] || []; - this._events[event].push(fn); - }, - unbind: function(event, fn) { - this._events = this._events || {}; - if (event in this._events === false) return; - this._events[event].splice(this._events[event].indexOf(fn), 1); - }, - trigger: function(event) { - this._events = this._events || {}; - if (event in this._events === false) return; - for (var i = 0; i < this._events[event].length; i++) { - this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); - } - } -}; - -UsergridEventable.mixin = function(destObject) { - var props = [ "bind", "unbind", "trigger" ]; - for (var i = 0; i < props.length; i++) { - if (props[i] in destObject.prototype) { - console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'."); - console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'."); - destObject.prototype["_" + props[i]] = destObject.prototype[props[i]]; - } - destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]]; - } -}; - -(function() { - var name = "Logger", global = this, overwrittenName = global[name], exports; - /* logging */ - function Logger(name) { - this.logEnabled = true; - this.init(name, true); - } - Logger.METHODS = [ "log", "error", "warn", "info", "debug", "assert", "clear", "count", "dir", "dirxml", "exception", "group", "groupCollapsed", "groupEnd", "profile", "profileEnd", "table", "time", "timeEnd", "trace" ]; - Logger.prototype.init = function(name, logEnabled) { - this.name = name || "UNKNOWN"; - this.logEnabled = logEnabled || true; - var addMethod = function(method) { - this[method] = this.createLogMethod(method); - }.bind(this); - Logger.METHODS.forEach(addMethod); - }; - Logger.prototype.createLogMethod = function(method) { - return Logger.prototype.log.bind(this, method); - }; - Logger.prototype.prefix = function(method, args) { - var prepend = "[" + method.toUpperCase() + "][" + name + "]: "; - if ([ "log", "error", "warn", "info" ].indexOf(method) !== -1) { - if ("string" === typeof args[0]) { - args[0] = prepend + args[0]; - } else { - args.unshift(prepend); - } - } - return args; - }; - Logger.prototype.log = function() { - var args = [].slice.call(arguments); - method = args.shift(); - if (Logger.METHODS.indexOf(method) === -1) { - method = "log"; - } - if (!(this.logEnabled && console && console[method])) return; - args = this.prefix(method, args); - console[method].apply(console, args); - }; - Logger.prototype.setLogEnabled = function(logEnabled) { - this.logEnabled = logEnabled || true; - }; - Logger.mixin = function(destObject) { - destObject.__logger = new Logger(destObject.name || "UNKNOWN"); - var addMethod = function(method) { - if (method in destObject.prototype) { - console.warn("overwriting '" + method + "' on '" + destObject.name + "'."); - console.warn("the previous version can be found at '_" + method + "' on '" + destObject.name + "'."); - destObject.prototype["_" + method] = destObject.prototype[method]; - } - destObject.prototype[method] = destObject.__logger.createLogMethod(method); - }; - Logger.METHODS.forEach(addMethod); - }; - global[name] = Logger; - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; - } - return Logger; - }; - return global[name]; -})(); +"use strict"; (function(global) { - var name = "Promise", overwrittenName = global[name], exports; + var name = "Promise", overwrittenName = global[name]; function Promise() { this.complete = false; - this.error = null; this.result = null; this.callbacks = []; } @@ -130,29 +33,29 @@ UsergridEventable.mixin = function(destObject) { return callback.apply(context, arguments); }; if (this.complete) { - f(this.error, this.result); + f(this.result); } else { this.callbacks.push(f); } }; - Promise.prototype.done = function(error, result) { + Promise.prototype.done = function(result) { this.complete = true; - this.error = error; this.result = result; if (this.callbacks) { - for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](error, result); + _.forEach(this.callbacks, function(callback) { + callback(result); + }); this.callbacks.length = 0; } }; Promise.join = function(promises) { - var p = new Promise(), total = promises.length, completed = 0, errors = [], results = []; + var p = new Promise(), total = promises.length, completed = 0, results = []; function notifier(i) { - return function(error, result) { + return function(result) { completed += 1; - errors[i] = error; results[i] = result; if (completed === total) { - p.done(errors, results); + p.done(results); } }; } @@ -161,19 +64,19 @@ UsergridEventable.mixin = function(destObject) { } return p; }; - Promise.chain = function(promises, error, result) { + Promise.chain = function(promises, result) { var p = new Promise(); if (promises === null || promises.length === 0) { - p.done(error, result); + p.done(result); } else { - promises[0](error, result).then(function(res, err) { + promises[0](result).then(function(res) { promises.splice(0, 1); if (promises) { - Promise.chain(promises, res, err).then(function(r, e) { - p.done(r, e); + Promise.chain(promises, res).then(function(r) { + p.done(r); }); } else { - p.done(res, err); + p.done(res); } }); } @@ -190,3097 +93,6605 @@ UsergridEventable.mixin = function(destObject) { })(this); (function() { - var name = "Ajax", global = this, overwrittenName = global[name], exports; - function partial() { - var args = Array.prototype.slice.call(arguments); - var fn = args.shift(); - return fn.bind(this, args); - } - function Ajax() { - this.logger = new global.Logger(name); - var self = this; - function encode(data) { - var result = ""; - if (typeof data === "string") { - result = data; - } else { - var e = encodeURIComponent; - for (var i in data) { - if (data.hasOwnProperty(i)) { - result += "&" + e(i) + "=" + e(data[i]); - } - } - } - return result; - } - function request(m, u, d) { - var p = new Promise(), timeout; - self.logger.time(m + " " + u); - (function(xhr) { - xhr.onreadystatechange = function() { - if (this.readyState === 4) { - self.logger.timeEnd(m + " " + u); - clearTimeout(timeout); - p.done(null, this); - } - }; - xhr.onerror = function(response) { - clearTimeout(timeout); - p.done(response, null); - }; - xhr.oncomplete = function(response) { - clearTimeout(timeout); - self.logger.timeEnd(m + " " + u); - self.info("%s request to %s returned %s", m, u, this.status); - }; - xhr.open(m, u); - if (d) { - if ("object" === typeof d) { - d = JSON.stringify(d); - } - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Accept", "application/json"); - } - timeout = setTimeout(function() { - xhr.abort(); - p.done("API Call timed out.", null); - }, 3e4); - xhr.send(encode(d)); - })(new XMLHttpRequest()); - return p; - } - this.request = request; - this.get = partial(request, "GET"); - this.post = partial(request, "POST"); - this.put = partial(request, "PUT"); - this.delete = partial(request, "DELETE"); - } - global[name] = new Ajax(); - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; - } - return exports; + "use strict"; + var undefined; + var VERSION = "4.16.4"; + var LARGE_ARRAY_SIZE = 200; + var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://github.com/es-shims.", FUNC_ERROR_TEXT = "Expected a function"; + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var MAX_MEMOIZE_SIZE = 500; + var PLACEHOLDER = "__lodash_placeholder__"; + var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256, FLIP_FLAG = 512; + var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; + var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; + var HOT_COUNT = 500, HOT_SPAN = 16; + var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; + var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e308, NAN = 0 / 0; + var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + var wrapFlags = [ [ "ary", ARY_FLAG ], [ "bind", BIND_FLAG ], [ "bindKey", BIND_KEY_FLAG ], [ "curry", CURRY_FLAG ], [ "curryRight", CURRY_RIGHT_FLAG ], [ "flip", FLIP_FLAG ], [ "partial", PARTIAL_FLAG ], [ "partialRight", PARTIAL_RIGHT_FLAG ], [ "rearg", REARG_FLAG ] ]; + var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; + var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; + var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); + var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + var reEscapeChar = /\\(\\)?/g; + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + var reFlags = /\w*$/; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var reIsOctal = /^0o[0-7]+$/i; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var reNoMatch = /($^)/; + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23", rsComboSymbolsRange = "\\u20d0-\\u20f0", rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; + var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")", rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [ rsNonAstral, rsRegional, rsSurrPair ].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [ rsDingbat, rsRegional, rsSurrPair ].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [ rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral ].join("|") + ")"; + var reApos = RegExp(rsApos, "g"); + var reComboMark = RegExp(rsCombo, "g"); + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reUnicodeWord = RegExp([ rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [ rsBreak, rsUpper, "$" ].join("|") + ")", rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [ rsBreak, rsUpper + rsLowerMisc, "$" ].join("|") + ")", rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr, rsUpper + "+" + rsOptUpperContr, rsDigits, rsEmoji ].join("|"), "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + var contextProps = [ "Array", "Buffer", "DataView", "Date", "Error", "Float32Array", "Float64Array", "Function", "Int8Array", "Int16Array", "Int32Array", "Map", "Math", "Object", "Promise", "RegExp", "Set", "String", "Symbol", "TypeError", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "WeakMap", "_", "clearTimeout", "isFinite", "parseInt", "setTimeout" ]; + var templateCounter = -1; + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; + var deburredLetters = { + "À": "A", + "Á": "A", + "Â": "A", + "Ã": "A", + "Ä": "A", + "Å": "A", + "à": "a", + "á": "a", + "â": "a", + "ã": "a", + "ä": "a", + "å": "a", + "Ç": "C", + "ç": "c", + "Ð": "D", + "ð": "d", + "È": "E", + "É": "E", + "Ê": "E", + "Ë": "E", + "è": "e", + "é": "e", + "ê": "e", + "ë": "e", + "Ì": "I", + "Í": "I", + "Î": "I", + "Ï": "I", + "ì": "i", + "í": "i", + "î": "i", + "ï": "i", + "Ñ": "N", + "ñ": "n", + "Ò": "O", + "Ó": "O", + "Ô": "O", + "Õ": "O", + "Ö": "O", + "Ø": "O", + "ò": "o", + "ó": "o", + "ô": "o", + "õ": "o", + "ö": "o", + "ø": "o", + "Ù": "U", + "Ú": "U", + "Û": "U", + "Ü": "U", + "ù": "u", + "ú": "u", + "û": "u", + "ü": "u", + "Ý": "Y", + "ý": "y", + "ÿ": "y", + "Æ": "Ae", + "æ": "ae", + "Þ": "Th", + "þ": "th", + "ß": "ss", + "Ā": "A", + "Ă": "A", + "Ą": "A", + "ā": "a", + "ă": "a", + "ą": "a", + "Ć": "C", + "Ĉ": "C", + "Ċ": "C", + "Č": "C", + "ć": "c", + "ĉ": "c", + "ċ": "c", + "č": "c", + "Ď": "D", + "Đ": "D", + "ď": "d", + "đ": "d", + "Ē": "E", + "Ĕ": "E", + "Ė": "E", + "Ę": "E", + "Ě": "E", + "ē": "e", + "ĕ": "e", + "ė": "e", + "ę": "e", + "ě": "e", + "Ĝ": "G", + "Ğ": "G", + "Ġ": "G", + "Ģ": "G", + "ĝ": "g", + "ğ": "g", + "ġ": "g", + "ģ": "g", + "Ĥ": "H", + "Ħ": "H", + "ĥ": "h", + "ħ": "h", + "Ĩ": "I", + "Ī": "I", + "Ĭ": "I", + "Į": "I", + "İ": "I", + "ĩ": "i", + "ī": "i", + "ĭ": "i", + "į": "i", + "ı": "i", + "Ĵ": "J", + "ĵ": "j", + "Ķ": "K", + "ķ": "k", + "ĸ": "k", + "Ĺ": "L", + "Ļ": "L", + "Ľ": "L", + "Ŀ": "L", + "Ł": "L", + "ĺ": "l", + "ļ": "l", + "ľ": "l", + "ŀ": "l", + "ł": "l", + "Ń": "N", + "Ņ": "N", + "Ň": "N", + "Ŋ": "N", + "ń": "n", + "ņ": "n", + "ň": "n", + "ŋ": "n", + "Ō": "O", + "Ŏ": "O", + "Ő": "O", + "ō": "o", + "ŏ": "o", + "ő": "o", + "Ŕ": "R", + "Ŗ": "R", + "Ř": "R", + "ŕ": "r", + "ŗ": "r", + "ř": "r", + "Ś": "S", + "Ŝ": "S", + "Ş": "S", + "Š": "S", + "ś": "s", + "ŝ": "s", + "ş": "s", + "š": "s", + "Ţ": "T", + "Ť": "T", + "Ŧ": "T", + "ţ": "t", + "ť": "t", + "ŧ": "t", + "Ũ": "U", + "Ū": "U", + "Ŭ": "U", + "Ů": "U", + "Ű": "U", + "Ų": "U", + "ũ": "u", + "ū": "u", + "ŭ": "u", + "ů": "u", + "ű": "u", + "ų": "u", + "Ŵ": "W", + "ŵ": "w", + "Ŷ": "Y", + "ŷ": "y", + "Ÿ": "Y", + "Ź": "Z", + "Ż": "Z", + "Ž": "Z", + "ź": "z", + "ż": "z", + "ž": "z", + "IJ": "IJ", + "ij": "ij", + "Œ": "Oe", + "œ": "oe", + "ʼn": "'n", + "ſ": "s" }; - return global[name]; -})(); - -/* - * This module is a collection of classes designed to make working with - * the Appigee App Services API as easy as possible. - * Learn more at http://Usergrid.com/docs/usergrid - * - * Copyright 2012 Usergrid Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author rod simpson (rod@Usergrid.com) - * @author matt dobson (matt@Usergrid.com) - * @author ryan bridges (rbridges@Usergrid.com) - */ -window.console = window.console || {}; - -window.console.log = window.console.log || function() {}; - -function extend(subClass, superClass) { - var F = function() {}; - F.prototype = superClass.prototype; - subClass.prototype = new F(); - subClass.prototype.constructor = subClass; - subClass.superclass = superClass.prototype; - if (superClass.prototype.constructor == Object.prototype.constructor) { - superClass.prototype.constructor = superClass; - } - return subClass; -} - -function propCopy(from, to) { - for (var prop in from) { - if (from.hasOwnProperty(prop)) { - if ("object" === typeof from[prop] && "object" === typeof to[prop]) { - to[prop] = propCopy(from[prop], to[prop]); - } else { - to[prop] = from[prop]; - } - } - } - return to; -} - -function NOOP() {} - -function isValidUrl(url) { - if (!url) return false; - var doc, base, anchor, isValid = false; - try { - doc = document.implementation.createHTMLDocument(""); - base = doc.createElement("base"); - base.href = base || window.lo; - doc.head.appendChild(base); - anchor = doc.createElement("a"); - anchor.href = url; - doc.body.appendChild(anchor); - isValid = !(anchor.href === ""); - } catch (e) { - console.error(e); - } finally { - doc.head.removeChild(base); - doc.body.removeChild(anchor); - base = null; - anchor = null; - doc = null; - return isValid; - } -} - -/* - * Tests if the string is a uuid - * - * @public - * @method isUUID - * @param {string} uuid The string to test - * @returns {Boolean} true if string is uuid - */ -var uuidValueRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; + var htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }; + var htmlUnescapes = { + "&": "&", + "<": "<", + ">": ">", + """: '"', + "'": "'" + }; + var stringEscapes = { + "\\": "\\", + "'": "'", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029" + }; + var freeParseFloat = parseFloat, freeParseInt = parseInt; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; + var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = function() { + try { + return freeProcess && freeProcess.binding("util"); + } catch (e) {} + }(); + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + function addMapEntry(map, pair) { + map.set(pair[0], pair[1]); + return map; + } + function addSetEntry(set, value) { + set.add(value); + return set; + } + function apply(func, thisArg, args) { + switch (args.length) { + case 0: + return func.call(thisArg); -function isUUID(uuid) { - return !uuid ? false : uuidValueRegex.test(uuid); -} + case 1: + return func.call(thisArg, args[0]); -/* - * method to encode the query string parameters - * - * @method encodeParams - * @public - * @params {object} params - an object of name value pairs that will be urlencoded - * @return {string} Returns the encoded string - */ -function encodeParams(params) { - var queryString; - if (params && Object.keys(params)) { - queryString = [].slice.call(arguments).reduce(function(a, b) { - return a.concat(b instanceof Array ? b : [ b ]); - }, []).filter(function(c) { - return "object" === typeof c; - }).reduce(function(p, c) { - !(c instanceof Array) ? p = p.concat(Object.keys(c).map(function(key) { - return [ key, c[key] ]; - })) : p.push(c); - return p; - }, []).reduce(function(p, c) { - c.length === 2 ? p.push(c) : p = p.concat(c); - return p; - }, []).reduce(function(p, c) { - c[1] instanceof Array ? c[1].forEach(function(v) { - p.push([ c[0], v ]); - }) : p.push(c); - return p; - }, []).map(function(c) { - c[1] = encodeURIComponent(c[1]); - return c.join("="); - }).join("&"); - } - return queryString; -} - -/* - * method to determine whether or not the passed variable is a function - * - * @method isFunction - * @public - * @params {any} f - any variable - * @return {boolean} Returns true or false - */ -function isFunction(f) { - return f && f !== null && typeof f === "function"; -} + case 2: + return func.call(thisArg, args[0], args[1]); -/* - * a safe wrapper for executing a callback - * - * @method doCallback - * @public - * @params {Function} callback - the passed-in callback method - * @params {Array} params - an array of arguments to pass to the callback - * @params {Object} context - an optional calling context for the callback - * @return Returns whatever would be returned by the callback. or false. - */ -function doCallback(callback, params, context) { - var returnValue; - if (isFunction(callback)) { - if (!params) params = []; - if (!context) context = this; - params.push(context); - returnValue = callback.apply(context, params); + case 3: + return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); } - return returnValue; -} - -(function(global) { - var name = "Usergrid", overwrittenName = global[name]; - var VALID_REQUEST_METHODS = [ "GET", "POST", "PUT", "DELETE" ]; - function Usergrid() { - this.logger = new Logger(name); + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, length = array ? array.length : 0; + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + function arrayEach(array, iteratee) { + var index = -1, length = array ? array.length : 0; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + function arrayEachRight(array, iteratee) { + var length = array ? array.length : 0; + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; } - Usergrid.isValidEndpoint = function(endpoint) { + function arrayEvery(array, predicate) { + var index = -1, length = array ? array.length : 0; + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } return true; - }; - Usergrid.Request = function(method, endpoint, query_params, data, callback) { - var p = new Promise(); - /* - Create a logger - */ - this.logger = new global.Logger("Usergrid.Request"); - this.logger.time("process request " + method + " " + endpoint); - /* - Validate our input - */ - this.endpoint = endpoint + "?" + encodeParams(query_params); - this.method = method.toUpperCase(); - this.data = "object" === typeof data ? JSON.stringify(data) : data; - if (VALID_REQUEST_METHODS.indexOf(this.method) === -1) { - throw new UsergridInvalidHTTPMethodError("invalid request method '" + this.method + "'"); - } - /* - Prepare our request - */ - if (!isValidUrl(this.endpoint)) { - this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint)); - throw new UsergridInvalidURIError("The provided endpoint is not valid: " + this.endpoint); - } - /* a callback to make the request */ - var request = function() { - return Ajax.request(this.method, this.endpoint, this.data); - }.bind(this); - /* a callback to process the response */ - var response = function(err, request) { - return new Usergrid.Response(err, request); - }.bind(this); - /* a callback to clean up and return data to the client */ - var oncomplete = function(err, response) { - p.done(err, response); - this.logger.info("REQUEST", err, response); - doCallback(callback, [ err, response ]); - this.logger.timeEnd("process request " + method + " " + endpoint); - }.bind(this); - /* and a promise to chain them all together */ - Promise.chain([ request, response ]).then(oncomplete); - return p; - }; - Usergrid.Response = function(err, response) { - var p = new Promise(); - var data = null; - try { - data = JSON.parse(response.responseText); - } catch (e) { - data = {}; - } - Object.keys(data).forEach(function(key) { - Object.defineProperty(this, key, { - value: data[key], - enumerable: true - }); - }.bind(this)); - Object.defineProperty(this, "logger", { - enumerable: false, - configurable: false, - writable: false, - value: new global.Logger(name) - }); - Object.defineProperty(this, "success", { - enumerable: false, - configurable: false, - writable: true, - value: true - }); - Object.defineProperty(this, "err", { - enumerable: false, - configurable: false, - writable: true, - value: err - }); - Object.defineProperty(this, "status", { - enumerable: false, - configurable: false, - writable: true, - value: parseInt(response.status) - }); - Object.defineProperty(this, "statusGroup", { - enumerable: false, - configurable: false, - writable: true, - value: this.status - this.status % 100 - }); - switch (this.statusGroup) { - case 200: - this.success = true; - break; - - case 400: - case 500: - case 300: - case 100: - default: - this.success = false; - break; - } - if (this.success) { - p.done(null, this); - } else { - p.done(UsergridError.fromResponse(data), this); + } + function arrayFilter(array, predicate) { + var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } } - return p; - }; - Usergrid.Response.prototype.getEntities = function() { - var entities; - if (this.success) { - entities = this.data ? this.data.entities : this.entities; + return result; + } + function arrayIncludes(array, value) { + var length = array ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; + } + function arrayIncludesWith(array, value, comparator) { + var index = -1, length = array ? array.length : 0; + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } } - return entities || []; - }; - Usergrid.Response.prototype.getEntity = function() { - var entities = this.getEntities(); - return entities[0]; - }; - Usergrid.VERSION = Usergrid.USERGRID_SDK_VERSION = "0.11.0"; - global[name] = Usergrid; - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; + return false; + } + function arrayMap(array, iteratee) { + var index = -1, length = array ? array.length : 0, result = Array(length); + while (++index < length) { + result[index] = iteratee(array[index], index, array); } - return Usergrid; - }; - return global[name]; -})(this); - -(function() { - var name = "Client", global = this, overwrittenName = global[name], exports; - var AUTH_ERRORS = [ "auth_expired_session_token", "auth_missing_credentials", "auth_unverified_oath", "expired_token", "unauthorized", "auth_invalid" ]; - Usergrid.Client = function(options) { - this.URI = options.URI || "https://api.usergrid.com"; - if (options.orgName) { - this.set("orgName", options.orgName); + return result; + } + function arrayPush(array, values) { + var index = -1, length = values.length, offset = array.length; + while (++index < length) { + array[offset + index] = values[index]; } - if (options.appName) { - this.set("appName", options.appName); + return array; + } + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, length = array ? array.length : 0; + if (initAccum && length) { + accumulator = array[++index]; } - if (options.qs) { - this.setObject("default_qs", options.qs); + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); } - this.buildCurl = options.buildCurl || false; - this.logging = options.logging || false; - }; - /* - * Main function for making requests to the API. Can be called directly. - * - * options object: - * `method` - http method (GET, POST, PUT, or DELETE), defaults to GET - * `qs` - object containing querystring values to be appended to the uri - * `body` - object containing entity body for POST and PUT requests - * `endpoint` - API endpoint, for example 'users/fred' - * `mQuery` - boolean, set to true if running management query, defaults to false - * - * @method request - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.request = function(options, callback) { - var method = options.method || "GET"; - var endpoint = options.endpoint; - var body = options.body || {}; - var qs = options.qs || {}; - var mQuery = options.mQuery || false; - var orgName = this.get("orgName"); - var appName = this.get("appName"); - var default_qs = this.getObject("default_qs"); - var uri; - /*var logoutCallback=function(){ - if (typeof(this.logoutCallback) === 'function') { - return this.logoutCallback(true, 'no_org_or_app_name_specified'); - } - }.bind(this);*/ - if (!mQuery && !orgName && !appName) { - return logoutCallback(); - } - if (mQuery) { - uri = this.URI + "/" + endpoint; - } else { - uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint; + return accumulator; + } + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array ? array.length : 0; + if (initAccum && length) { + accumulator = array[--length]; } - if (this.getToken()) { - qs.access_token = this.getToken(); + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); } - if (default_qs) { - qs = propCopy(qs, default_qs); + return accumulator; + } + function arraySome(array, predicate) { + var index = -1, length = array ? array.length : 0; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } } - var self = this; - var req = new Usergrid.Request(method, uri, qs, body, function(err, response) { - /*if (AUTH_ERRORS.indexOf(response.error) !== -1) { - return logoutCallback(); - }*/ - if (err) { - doCallback(callback, [ err, response, self ], self); - } else { - doCallback(callback, [ null, response, self ], self); + return false; + } + var asciiSize = baseProperty("length"); + function asciiToArray(string) { + return string.split(""); + } + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; } }); - }; - /* - * function for building asset urls - * - * @method buildAssetURL - * @public - * @params {string} uuid - * @return {string} assetURL - */ - Usergrid.Client.prototype.buildAssetURL = function(uuid) { - var self = this; - var qs = {}; - var assetURL = this.URI + "/" + this.orgName + "/" + this.appName + "/assets/" + uuid + "/data"; - if (self.getToken()) { - qs.access_token = self.getToken(); + return result; + } + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } } - var encoded_params = encodeParams(qs); - if (encoded_params) { - assetURL += "?" + encoded_params; + return -1; + } + function baseIndexOf(array, value, fromIndex) { + return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); + } + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } } - return assetURL; - }; - /* - * Main function for creating new groups. Call this directly. - * - * @method createGroup - * @public - * @params {string} path - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createGroup = function(options, callback) { - var group = new Usergrid.Group({ - path: options.path, - client: this, - data: options - }); - group.save(function(err, response) { - doCallback(callback, [ err, response, group ], group); - }); - }; - /* - * Main function for creating new entities - should be called directly. - * - * options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}} - * - * @method createEntity - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createEntity = function(options, callback) { - var entity = new Usergrid.Entity({ - client: this, - data: options - }); - entity.save(function(err, response) { - doCallback(callback, [ err, response, entity ], entity); + return -1; + } + function baseIsNaN(value) { + return value !== value; + } + function baseMean(array, iteratee) { + var length = array ? array.length : 0; + return length ? baseSum(array, iteratee) / length : NAN; + } + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); - }; - /* - * Main function for getting existing entities - should be called directly. - * - * You must supply a uuid or (username or name). Username only applies to users. - * Name applies to all custom entities - * - * options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}} - * - * @method createEntity - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.getEntity = function(options, callback) { - var entity = new Usergrid.Entity({ - client: this, - data: options - }); - entity.fetch(function(err, response) { - doCallback(callback, [ err, response, entity ], entity); + return accumulator; + } + function baseSortBy(array, comparer) { + var length = array.length; + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + function baseSum(array, iteratee) { + var result, index = -1, length = array.length; + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : result + current; + } + } + return result; + } + function baseTimes(n, iteratee) { + var index = -1, result = Array(n); + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [ key, object[key] ]; }); - }; - /* - * Main function for restoring an entity from serialized data. - * - * serializedObject should have come from entityObject.serialize(); - * - * @method restoreEntity - * @public - * @param {string} serializedObject - * @return {object} Entity Object - */ - Usergrid.Client.prototype.restoreEntity = function(serializedObject) { - var data = JSON.parse(serializedObject); - var options = { - client: this, - data: data + } + function baseUnary(func) { + return function(value) { + return func(value); }; - var entity = new Usergrid.Entity(options); - return entity; - }; - /* - * Main function for creating new counters - should be called directly. - * - * options object: options {timestamp:0, category:'value', counters:{name : value}} - * - * @method createCounter - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, response, counter) - */ - Usergrid.Client.prototype.createCounter = function(options, callback) { - var counter = new Usergrid.Counter({ - client: this, - data: options - }); - counter.save(callback); - }; - /* - * Main function for creating new assets - should be called directly. - * - * options object: options {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000", file: FileOrBlobObject } - * - * @method createCounter - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, response, counter) - */ - Usergrid.Client.prototype.createAsset = function(options, callback) { - var file = options.file; - if (file) { - options.name = options.name || file.name; - options["content-type"] = options["content-type"] || file.type; - options.path = options.path || "/"; - delete options.file; - } - var asset = new Usergrid.Asset({ - client: this, - data: options - }); - asset.save(function(err, response, asset) { - if (file && !err) { - asset.upload(file, callback); - } else { - doCallback(callback, [ err, response, asset ], asset); - } + } + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; }); - }; - /* - * Main function for creating new collections - should be called directly. - * - * options object: options {client:client, type: type, qs:qs} - * - * @method createCollection - * @public - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createCollection = function(options, callback) { - options.client = this; - return new Usergrid.Collection(options, function(err, data, collection) { - console.log("createCollection", arguments); - doCallback(callback, [ err, collection, data ]); + } + function cacheHas(cache, key) { + return cache.has(key); + } + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, length = strSymbols.length; + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + function countHolders(array, placeholder) { + var length = array.length, result = 0; + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + var deburrLetter = basePropertyOf(deburredLetters); + var escapeHtmlChar = basePropertyOf(htmlEscapes); + function escapeStringChar(chr) { + return "\\" + stringEscapes[chr]; + } + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + function hasUnicode(string) { + return reHasUnicode.test(string); + } + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + function iteratorToArray(iterator) { + var data, result = []; + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + function mapToArray(map) { + var index = -1, result = Array(map.size); + map.forEach(function(value, key) { + result[++index] = [ key, value ]; }); - }; - /* - * Main function for restoring a collection from serialized data. - * - * serializedObject should have come from collectionObject.serialize(); - * - * @method restoreCollection - * @public - * @param {string} serializedObject - * @return {object} Collection Object - */ - Usergrid.Client.prototype.restoreCollection = function(serializedObject) { - var data = JSON.parse(serializedObject); - data.client = this; - var collection = new Usergrid.Collection(data); - return collection; - }; - /* - * Main function for retrieving a user's activity feed. - * - * @method getFeedForUser - * @public - * @params {string} username - * @param {function} callback - * @return {callback} callback(err, data, activities) - */ - Usergrid.Client.prototype.getFeedForUser = function(username, callback) { - var options = { - method: "GET", - endpoint: "users/" + username + "/feed" + return result; + } + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); }; - this.request(options, function(err, data) { - if (err) { - doCallback(callback, [ err ]); - } else { - doCallback(callback, [ err, data, data.getEntities() ]); + } + function replaceHolders(array, placeholder) { + var index = -1, length = array.length, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; } + } + return result; + } + function setToArray(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = value; }); - }; - /* - * Function for creating new activities for the current user - should be called directly. - * - * //user can be any of the following: "me", a uuid, a username - * Note: the "me" alias will reference the currently logged in user (e.g. 'users/me/activties') - * - * //build a json object that looks like this: - * var options = - * { - * "actor" : { - * "displayName" :"myusername", - * "uuid" : "myuserid", - * "username" : "myusername", - * "email" : "myemail", - * "picture": "http://path/to/picture", - * "image" : { - * "duration" : 0, - * "height" : 80, - * "url" : "http://www.gravatar.com/avatar/", - * "width" : 80 - * }, - * }, - * "verb" : "post", - * "content" : "My cool message", - * "lat" : 48.856614, - * "lon" : 2.352222 - * } - * - * @method createEntity - * @public - * @params {string} user // "me", a uuid, or a username - * @params {object} options - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createUserActivity = function(user, options, callback) { - options.type = "users/" + user + "/activities"; - options = { - client: this, - data: options - }; - var entity = new Usergrid.Entity(options); - entity.save(function(err, data) { - doCallback(callback, [ err, data, entity ]); + return result; + } + function setToPairs(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = [ value, value ]; }); - }; - /* - * Function for creating user activities with an associated user entity. - * - * user object: - * The user object passed into this function is an instance of Usergrid.Entity. - * - * @method createUserActivityWithEntity - * @public - * @params {object} user - * @params {string} content - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.createUserActivityWithEntity = function(user, content, callback) { - var username = user.get("username"); - var options = { - actor: { - displayName: username, - uuid: user.get("uuid"), - username: username, - email: user.get("email"), - picture: user.get("picture"), - image: { - duration: 0, - height: 80, - url: user.get("picture"), - width: 80 - } - }, - verb: "post", - content: content - }; - this.createUserActivity(username, options, callback); - }; - /* - * A private method to get call timing of last call - */ - Usergrid.Client.prototype.calcTimeDiff = function() { - var seconds = 0; - var time = this._end - this._start; - try { - seconds = (time / 10 / 60).toFixed(2); - } catch (e) { - return 0; + return result; + } + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value) { + return index; + } } - return seconds; - }; - /* - * A public method to store the OAuth token for later use - uses localstorage if available - * - * @method setToken - * @public - * @params {string} token - * @return none - */ - Usergrid.Client.prototype.setToken = function(token) { - this.set("token", token); - }; - /* - * A public method to get the OAuth token - * - * @method getToken - * @public - * @return {string} token - */ - Usergrid.Client.prototype.getToken = function() { - return this.get("token"); - }; - Usergrid.Client.prototype.setObject = function(key, value) { - if (value) { - value = JSON.stringify(value); + return -1; + } + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } } - this.set(key, value); - }; - Usergrid.Client.prototype.set = function(key, value) { - var keyStore = "apigee_" + key; - this[key] = value; - if (typeof Storage !== "undefined") { - if (value) { - localStorage.setItem(keyStore, value); - } else { - localStorage.removeItem(keyStore); + return index; + } + function stringSize(string) { + return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); + } + function stringToArray(string) { + return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); + } + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + var runInContext = function runInContext(context) { + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; + var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; + var coreJsData = context["__core-js_shared__"]; + var maskSrcKey = function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); + return uid ? "Symbol(src)_1." + uid : ""; + }(); + var funcToString = funcProto.toString; + var hasOwnProperty = objectProto.hasOwnProperty; + var idCounter = 0; + var objectCtorString = funcToString.call(Object); + var objectToString = objectProto.toString; + var oldDash = root._; + var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); + var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), iteratorSymbol = Symbol ? Symbol.iterator : undefined, objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + var defineProperty = function() { + try { + var func = getNative(Object, "defineProperty"); + func({}, "", {}); + return func; + } catch (e) {} + }(); + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; + var DataView = getNative(context, "DataView"), Map = getNative(context, "Map"), Promise = getNative(context, "Promise"), Set = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object, "create"); + var metaMap = WeakMap && new WeakMap(); + var realNames = {}; + var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); + var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, "__wrapped__")) { + return wrapperClone(value); + } } + return new LodashWrapper(value); } - }; - Usergrid.Client.prototype.getObject = function(key) { - return JSON.parse(this.get(key)); - }; - Usergrid.Client.prototype.get = function(key) { - var keyStore = "apigee_" + key; - var value = null; - if (this[key]) { - value = this[key]; - } else if (typeof Storage !== "undefined") { - value = localStorage.getItem(keyStore); - } - return value; - }; - /* - * A public facing helper method for signing up users - * - * @method signup - * @public - * @params {string} username - * @params {string} password - * @params {string} email - * @params {string} name - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.signup = function(username, password, email, name, callback) { - var self = this; - var options = { - type: "users", - username: username, - password: password, - email: email, - name: name - }; - this.createEntity(options, callback); - }; - /* - * - * A public method to log in an app user - stores the token for later use - * - * @method login - * @public - * @params {string} username - * @params {string} password - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.login = function(username, password, callback) { - var self = this; - var options = { - method: "POST", - endpoint: "token", - body: { - username: username, - password: password, - grant_type: "password" + var baseCreate = function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object(); + object.prototype = undefined; + return result; + }; + }(); + function baseLodash() {} + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + lodash.templateSettings = { + escape: reEscape, + evaluate: reEvaluate, + interpolate: reInterpolate, + variable: "", + imports: { + _: lodash } }; - self.request(options, function(err, response) { - var user = {}; - if (err) { - if (self.logging) console.log("error trying to log user in"); + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; } else { - var options = { - client: self, - data: response.user - }; - user = new Usergrid.Entity(options); - self.setToken(response.access_token); + result = this.clone(); + result.__dir__ *= -1; } - doCallback(callback, [ err, response, user ]); - }); - }; - Usergrid.Client.prototype.reAuthenticateLite = function(callback) { - var self = this; - var options = { - method: "GET", - endpoint: "management/me", - mQuery: true - }; - this.request(options, function(err, response) { - if (err && self.logging) { - console.log("error trying to re-authenticate user"); - } else { - self.setToken(response.data.access_token); + return result; + } + function lazyValue() { + var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); + if (!isArr || arrLength < LARGE_ARRAY_SIZE || arrLength == length && takeCount == length) { + return baseWrapperValue(array, this.__actions__); } - doCallback(callback, [ err ]); - }); - }; - Usergrid.Client.prototype.reAuthenticate = function(email, callback) { - var self = this; - var options = { - method: "GET", - endpoint: "management/users/" + email, - mQuery: true - }; - this.request(options, function(err, response) { - var organizations = {}; - var applications = {}; - var user = {}; - var data; - if (err && self.logging) { - console.log("error trying to full authenticate user"); - } else { - data = response.data; - self.setToken(data.token); - self.set("email", data.email); - localStorage.setItem("accessToken", data.token); - localStorage.setItem("userUUID", data.uuid); - localStorage.setItem("userEmail", data.email); - var userData = { - username: data.username, - email: data.email, - name: data.name, - uuid: data.uuid - }; - var options = { - client: self, - data: userData - }; - user = new Usergrid.Entity(options); - organizations = data.organizations; - var org = ""; - try { - var existingOrg = self.get("orgName"); - org = organizations[existingOrg] ? organizations[existingOrg] : organizations[Object.keys(organizations)[0]]; - self.set("orgName", org.name); - } catch (e) { - err = true; - if (self.logging) { - console.log("error selecting org"); + var result = []; + outer: while (length-- && resIndex < takeCount) { + index += dir; + var iterIndex = -1, value = array[index]; + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } } } - applications = self.parseApplicationsArray(org); - self.selectFirstApp(applications); - self.setObject("organizations", organizations); - self.setObject("applications", applications); - } - doCallback(callback, [ err, data, user, organizations, applications ], self); - }); - }; - /* - * A public method to log in an app user with facebook - stores the token for later use - * - * @method loginFacebook - * @public - * @params {string} username - * @params {string} password - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.loginFacebook = function(facebookToken, callback) { - var self = this; - var options = { - method: "GET", - endpoint: "auth/facebook", - qs: { - fb_access_token: facebookToken + result[resIndex++] = value; } - }; - this.request(options, function(err, data) { - var user = {}; - if (err && self.logging) { - console.log("error trying to log user in"); - } else { - var options = { - client: self, - data: data.user - }; - user = new Usergrid.Entity(options); - self.setToken(data.access_token); + return result; + } + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + function Hash(entries) { + var index = -1, length = entries ? entries.length : 0; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - doCallback(callback, [ err, data, user ], self); - }); - }; - /* - * A public method to get the currently logged in user entity - * - * @method getLoggedInUser - * @public - * @param {function} callback - * @return {callback} callback(err, data) - */ - Usergrid.Client.prototype.getLoggedInUser = function(callback) { - var self = this; - if (!this.getToken()) { - doCallback(callback, [ new UsergridError("Access Token not set"), null, self ], self); - } else { - var options = { - method: "GET", - endpoint: "users/me" + } + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); + } + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value; + return this; + } + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + function ListCache(entries) { + var index = -1, length = entries ? entries.length : 0; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? undefined : data[index][1]; + } + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + function listCacheSet(key, value) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([ key, value ]); + } else { + data[index][1] = value; + } + return this; + } + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + function MapCache(entries) { + var index = -1, length = entries ? entries.length : 0; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function mapCacheClear() { + this.size = 0; + this.__data__ = { + hash: new Hash(), + map: new (Map || ListCache)(), + string: new Hash() + }; + } + function mapCacheDelete(key) { + var result = getMapData(this, key)["delete"](key); + this.size -= result ? 1 : 0; + return result; + } + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + function mapCacheSet(key, value) { + var data = getMapData(this, key), size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + function SetCache(values) { + var index = -1, length = values ? values.length : 0; + this.__data__ = new MapCache(); + while (++index < length) { + this.add(values[index]); + } + } + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + function setCacheHas(value) { + return this.__data__.has(value); + } + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + function stackClear() { + this.__data__ = new ListCache(); + this.size = 0; + } + function stackDelete(key) { + var data = this.__data__, result = data["delete"](key); + this.size = data.size; + return result; + } + function stackGet(key) { + return this.__data__.get(key); + } + function stackHas(key) { + return this.__data__.has(key); + } + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([ key, value ]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + Stack.prototype.clear = stackClear; + Stack.prototype["delete"] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { + result.push(key); + } + } + return result; + } + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) { + return srcValue; + } + return objValue; + } + function assignMergeValue(object, key, value) { + if (value !== undefined && !eq(object[key], value) || value === undefined && !(key in object)) { + baseAssignValue(object, key, value); + } + } + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) { + baseAssignValue(object, key, value); + } + } + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + function baseAssignValue(object, key, value) { + if (key == "__proto__" && defineProperty) { + defineProperty(object, key, { + configurable: true, + enumerable: true, + value: value, + writable: true + }); + } else { + object[key] = value; + } + } + function baseAt(object, paths) { + var index = -1, isNil = object == null, length = paths.length, result = Array(length); + while (++index < length) { + result[index] = isNil ? undefined : get(object, paths[index]); + } + return result; + } + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + function baseClone(value, isDeep, isFull, customizer, key, object, stack) { + var result; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || isFunc && !object) { + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + stack || (stack = new Stack()); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + var props = isArr ? undefined : (isFull ? getAllKeys : keys)(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); + }); + return result; + } + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], predicate = source[key], value = object[key]; + if (value === undefined && !(key in object) || !predicate(value)) { + return false; + } + } + return true; + } + function baseDelay(func, wait, args) { + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { + func.apply(undefined, args); + }, wait); + } + function baseDifference(array, values, iteratee, comparator) { + var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: while (++index < length) { + var value = array[index], computed = iteratee ? iteratee(value) : value; + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + var baseEach = createBaseEach(baseForOwn); + var baseEachRight = createBaseEach(baseForOwnRight, true); + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + function baseExtremum(array, iteratee, comparator) { + var index = -1, length = array.length; + while (++index < length) { + var value = array[index], current = iteratee(value); + if (current != null && (computed === undefined ? current === current && !isSymbol(current) : comparator(current, computed))) { + var computed = current, result = value; + } + } + return result; + } + function baseFill(array, value, start, end) { + var length = array.length; + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end === undefined || end > length ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, length = array.length; + predicate || (predicate = isFlattenable); + result || (result = []); + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + var baseFor = createBaseFor(); + var baseForRight = createBaseFor(true); + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + function baseGet(object, path) { + path = isKey(path, object) ? [ path ] : castPath(path); + var index = 0, length = path.length; + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return index && index == length ? object : undefined; + } + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + function baseGetTag(value) { + return objectToString.call(value); + } + function baseGt(value, other) { + return value > other; + } + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined; + } + array = arrays[0]; + var index = -1, seen = caches[0]; + outer: while (++index < length && result.length < maxLength) { + var value = array[index], computed = iteratee ? iteratee(value) : value; + value = comparator || value !== 0 ? value : 0; + if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator))) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator))) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + function baseInvoke(object, path, args) { + if (!isKey(path, object)) { + path = castPath(path); + object = parent(object, path); + path = last(path); + } + var func = object == null ? object : object[toKey(path)]; + return func == null ? undefined : apply(func, object, args); + } + function baseIsArguments(value) { + return isObjectLike(value) && objectToString.call(value) == argsTag; + } + function baseIsArrayBuffer(value) { + return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; + } + function baseIsDate(value) { + return isObjectLike(value) && objectToString.call(value) == dateTag; + } + function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || !isObject(value) && !isObjectLike(other)) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); + } + function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; + if (!objIsArr) { + objTag = getTag(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = getTag(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack()); + return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new Stack()); + return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack()); + return equalObjects(object, other, equalFunc, customizer, bitmask, stack); + } + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, length = index, noCustomizer = !customizer; + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], objValue = object[key], srcValue = data[1]; + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack(); + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result)) { + return false; + } + } + } + return true; + } + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + function baseIsRegExp(value) { + return isObject(value) && objectToString.call(value) == regexpTag; + } + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + function baseIsTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; + } + function baseIteratee(value) { + if (typeof value == "function") { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == "object") { + return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); + } + return property(value); + } + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != "constructor") { + result.push(key); + } + } + return result; + } + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), result = []; + for (var key in object) { + if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + function baseLt(value, other) { + return value < other; + } + function baseMap(collection, iteratee) { + var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); + }; + } + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack()); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } else { + var newValue = customizer ? customizer(object[key], srcValue, key + "", object, source, stack) : undefined; + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined; + var isCommon = newValue === undefined; + if (isCommon) { + var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } else { + newValue = []; + } + } else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } else if (!isObject(objValue) || srcIndex && isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } else { + isCommon = false; + } + } + if (isCommon) { + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack["delete"](srcValue); + } + assignMergeValue(object, key, newValue); + } + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [ identity ], baseUnary(getIteratee())); + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { + criteria: criteria, + index: ++index, + value: value + }; + }); + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + function basePick(object, props) { + object = Object(object); + return basePickBy(object, props, function(value, key) { + return key in object; + }); + } + function basePickBy(object, props, predicate) { + var index = -1, length = props.length, result = {}; + while (++index < length) { + var key = props[index], value = object[key]; + if (predicate(value, key)) { + baseAssignValue(result, key, value); + } + } + return result; + } + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, lastIndex = length - 1; + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else if (!isKey(index, array)) { + var path = castPath(index), object = parent(array, path); + if (object != null) { + delete object[toKey(last(path))]; + } + } else { + delete array[toKey(index)]; + } + } + } + return array; + } + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + function baseRange(start, end, step, fromRight) { + var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + function baseRepeat(string, n) { + var result = ""; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + return result; + } + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ""); + } + function baseSample(collection) { + return arraySample(values(collection)); + } + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = isKey(path, object) ? [ path ] : castPath(path); + var index = -1, length = path.length, lastIndex = length - 1, nested = object; + while (nested != null && ++index < length) { + var key = toKey(path[index]), newValue = value; + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, "toString", { + configurable: true, + enumerable: false, + value: constant(string), + writable: true + }); + }; + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + function baseSlice(array, start, end) { + var index = -1, length = array.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + function baseSome(collection, predicate) { + var result; + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + function baseSortedIndex(array, value, retHighest) { + var low = 0, high = array ? array.length : low; + if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = low + high >>> 1, computed = array[mid]; + if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; + while (low < high) { + var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? computed <= value : computed < value; + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + function baseSortedUniq(array, iteratee) { + var index = -1, length = array.length, resIndex = 0, result = []; + while (++index < length) { + var value = array[index], computed = iteratee ? iteratee(value) : value; + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + function baseToNumber(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + function baseToString(value) { + if (typeof value == "string") { + return value; + } + if (isArray(value)) { + return arrayMap(value, baseToString) + ""; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ""; + } + var result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; + } + function baseUniq(array, iteratee, comparator) { + var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache(); + } else { + seen = iteratee ? [] : result; + } + outer: while (++index < length) { + var value = array[index], computed = iteratee ? iteratee(value) : value; + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + function baseUnset(object, path) { + path = isKey(path, object) ? [ path ] : castPath(path); + object = parent(object, path); + var key = toKey(last(path)); + return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; + } + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, index = fromRight ? length : -1; + while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} + return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); + } + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([ result ], action.args)); + }, result); + } + function baseXor(arrays, iteratee, comparator) { + var index = -1, length = arrays.length; + while (++index < length) { + var result = result ? arrayPush(baseDifference(result, arrays[index], iteratee, comparator), baseDifference(arrays[index], result, iteratee, comparator)) : arrays[index]; + } + return result && result.length ? baseUniq(result, iteratee, comparator) : []; + } + function baseZipObject(props, values, assignFunc) { + var index = -1, length = props.length, valsLength = values.length, result = {}; + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + function castFunction(value) { + return typeof value == "function" ? value : identity; + } + function castPath(value) { + return isArray(value) ? value : stringToPath(value); + } + var castRest = baseRest; + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return !start && end >= length ? array : baseSlice(array, start, end); + } + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + buffer.copy(result); + return result; + } + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor()); + } + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor()); + } + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); + var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); + if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { + return 1; + } + if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { + return -1; + } + } + return 0; + } + function compareMultiple(object, other, orders) { + var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == "desc" ? -1 : 1); + } + } + return object.index - other.index; + } + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + function copyArray(source, array) { + var index = -1, length = source.length; + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + var index = -1, length = props.length; + while (++index < length) { + var key = props[index]; + var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; + customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, + customizer) : undefined; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); + while (fromRight ? index-- : ++index < length) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var fn = this && this !== root && this instanceof wrapper ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; + var chr = strSymbols ? strSymbols[0] : string.charAt(0); + var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); + return chr[methodName]() + trailing; + }; + } + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); + }; + } + function createCtor(Ctor) { + return function() { + var args = arguments; + switch (args.length) { + case 0: + return new Ctor(); + + case 1: + return new Ctor(args[0]); + + case 2: + return new Ctor(args[0], args[1]); + + case 3: + return new Ctor(args[0], args[1], args[2]); + + case 4: + return new Ctor(args[0], args[1], args[2], args[3]); + + case 5: + return new Ctor(args[0], args[1], args[2], args[3], args[4]); + + case 6: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + + case 7: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + }; + } + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + function wrapper() { + var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); + while (index--) { + args[index] = arguments[index]; + } + var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); + length -= holders.length; + if (length < arity) { + return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); + } + var fn = this && this !== root && this instanceof wrapper ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { + return iteratee(iterable[key], key, iterable); + }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == "wrapper") { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined; + if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); + } + } + return function() { + var args = arguments, value = args[0]; + if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { + return wrapper.plant(value).value(); + } + var index = 0, result = length ? funcs[index].apply(this, args) : value; + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), isFlip = bitmask & FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); + function wrapper() { + var length = arguments.length, args = Array(length), index = length; + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length); + } + var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == "string" || typeof other == "string") { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + function createPadding(length, chars) { + chars = chars === undefined ? " " : baseToString(chars); + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join("") : result.slice(0, length); + } + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != "number" && isIterateeCall(start, end, step)) { + end = step = undefined; + } + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? start < end ? 1 : -1 : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == "string" && typeof other == "string")) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; + bitmask |= isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG; + bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); + if (!(bitmask & CURRY_BOUND_FLAG)) { + bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); + } + var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = nativeMin(toInteger(precision), 292); + if (precision) { + var pair = (toString(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); + pair = (toString(value) + "e").split("e"); + return +(pair[0] + "e" + (+pair[1] - precision)); + } + return func(number); + }; + } + var createSet = !(Set && 1 / setToArray(new Set([ , -0 ]))[1] == INFINITY) ? noop : function(values) { + return new Set(values); + }; + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & BIND_KEY_FLAG; + if (!isBindKey && typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + if (bitmask & PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, holdersRight = holders; + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] == null ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); + if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) { + bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, result = true, seen = bitmask & UNORDERED_COMPARE_FLAG ? new SetCache() : undefined; + stack.set(array, other); + stack.set(other, array); + while (++index < arrLength) { + var arrValue = array[index], othValue = other[index]; + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + result = false; + break; + } + } + stack["delete"](array); + stack["delete"](other); + return result; + } + function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + return object == other + ""; + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & PARTIAL_COMPARE_FLAG; + convert || (convert = setToArray); + if (object.size != other.size && !isPartial) { + return false; + } + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= UNORDERED_COMPARE_FLAG; + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); + stack["delete"](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], othValue = other[key]; + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } + if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) { + result = false; + break; + } + skipCtor || (skipCtor = key == "constructor"); + } + if (result && !skipCtor) { + var objCtor = object.constructor, othCtor = other.constructor; + if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { + result = false; + } + } + stack["delete"](object); + stack["delete"](other); + return result; + } + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ""); + } + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + function getFuncName(func) { + var result = func.name + "", array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; + while (length--) { + var data = array[length], otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + function getHolder(func) { + var object = hasOwnProperty.call(lodash, "placeholder") ? lodash : func; + return object.placeholder; + } + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + function getMatchData(object) { + var result = keys(object), length = result.length; + while (length--) { + var key = result[length], value = object[key]; + result[length] = [ key, value, isStrictComparable(value) ]; + } + return result; + } + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + var getTag = baseGetTag; + if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { + getTag = function(value) { + var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag; + + case mapCtorString: + return mapTag; + + case promiseCtorString: + return promiseTag; + + case setCtorString: + return setTag; + + case weakMapCtorString: + return weakMapTag; + } + } + return result; + }; + } + function getView(start, end, transforms) { + var index = -1, length = transforms.length; + while (++index < length) { + var data = transforms[index], size = data.size; + switch (data.type) { + case "drop": + start += size; + break; + + case "dropRight": + end -= size; + break; + + case "take": + end = nativeMin(end, start + size); + break; + + case "takeRight": + start = nativeMax(start, end - size); + break; + } + } + return { + start: start, + end: end + }; + } + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + function hasPath(object, path, hasFunc) { + path = isKey(path, object) ? [ path ] : castPath(path); + var index = -1, length = path.length, result = false; + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object ? object.length : 0; + return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); + } + function initCloneArray(array) { + var length = array.length, result = array.constructor(length); + if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) { + result.index = array.index; + result.input = array.input; + } + return result; + } + function initCloneObject(object) { + return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {}; + } + function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: + case float64Tag: + case int8Tag: + case int16Tag: + case int32Tag: + case uint8Tag: + case uint8ClampedTag: + case uint16Tag: + case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); + } + } + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; + details = details.join(length > 2 ? ", " : " "); + return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); + } + function isFlattenable(value) { + return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); + } + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); + } + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { + return eq(object[index], value); + } + return false; + } + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); + } + function isKeyable(value) { + var type = typeof value; + return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; + } + function isLaziable(func) { + var funcName = getFuncName(func), other = lodash[funcName]; + if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; + } + var isMaskable = coreJsData ? isFunction : stubFalse; + function isPrototype(value) { + var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value === proto; + } + function isStrictComparable(value) { + return value === value && !isObject(value); + } + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && (srcValue !== undefined || key in Object(object)); + }; + } + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + var cache = result.cache; + return result; + } + function mergeData(data, source) { + var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG); + var isCombo = srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG || srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8] || srcBitmask == (ARY_FLAG | REARG_FLAG) && source[7].length <= source[8] && bitmask == CURRY_FLAG; + if (!(isCommon || isCombo)) { + return data; + } + if (srcBitmask & BIND_FLAG) { + data[2] = source[2]; + newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG; + } + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + value = source[7]; + if (value) { + data[7] = value; + } + if (srcBitmask & ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + if (data[9] == null) { + data[9] = source[9]; + } + data[0] = source[0]; + data[1] = newBitmask; + return data; + } + function mergeDefaults(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, mergeDefaults, stack); + stack["delete"](srcValue); + } + return objValue; + } + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? func.length - 1 : start, 0); + return function() { + var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + function parent(object, path) { + return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + function reorder(array, indexes) { + var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + var setData = shortOut(baseSetData); + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + var setToString = shortOut(baseSetToString); + function setWrapToString(wrapper, reference, bitmask) { + var source = reference + ""; + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + function shortOut(func) { + var count = 0, lastCalled = 0; + return function() { + var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + function shuffleSelf(array, size) { + var index = -1, length = array.length, lastIndex = length - 1; + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), value = array[rand]; + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + var stringToPath = memoizeCapped(function(string) { + string = toString(string); + var result = []; + if (reLeadingDot.test(string)) { + result.push(""); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, "$1") : number || match); + }); + return result; + }); + function toKey(value) { + if (typeof value == "string" || isSymbol(value)) { + return value; + } + var result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; + } + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return func + ""; + } catch (e) {} + } + return ""; + } + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = "_." + pair[0]; + if (bitmask & pair[1] && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + function chunk(array, size, guard) { + if (guard ? isIterateeCall(array, size, guard) : size === undefined) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array ? array.length : 0; + if (!length || size < 1) { + return []; + } + var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); + while (index < length) { + result[resIndex++] = baseSlice(array, index, index += size); + } + return result; + } + function compact(array) { + var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), array = arguments[0], index = length; + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [ array ], baseFlatten(args, 1)); + } + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; + }); + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; + }); + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; + }); + function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = guard || n === undefined ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = guard || n === undefined ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + function dropRightWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; + } + function dropWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; + } + function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != "number" && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + function findIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + function findLastIndex(array, predicate, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; + } + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, INFINITY) : []; + } + function flattenDepth(array, depth) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + function fromPairs(pairs) { + var index = -1, length = pairs ? pairs.length : 0, result = {}; + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + function head(array) { + return array && array.length ? array[0] : undefined; + } + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + function initial(array) { + var length = array ? array.length : 0; + return length ? baseSlice(array, 0, -1) : []; + } + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; + }); + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; + }); + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); + if (comparator === last(mapped)) { + comparator = undefined; + } else { + mapped.pop(); + } + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined, comparator) : []; + }); + function join(array, separator) { + return array ? nativeJoin.call(array, separator) : ""; + } + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); + } + function nth(array, n) { + return array && array.length ? baseNth(array, toInteger(n)) : undefined; + } + var pull = baseRest(pullAll); + function pullAll(array, values) { + return array && array.length && values && values.length ? basePullAll(array, values) : array; + } + function pullAllBy(array, values, iteratee) { + return array && array.length && values && values.length ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; + } + function pullAllWith(array, values, comparator) { + return array && array.length && values && values.length ? basePullAll(array, values, undefined, comparator) : array; + } + var pullAt = flatRest(function(array, indexes) { + var length = array ? array.length : 0, result = baseAt(array, indexes); + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + return result; + }); + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, indexes = [], length = array.length; + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + function reverse(array) { + return array ? nativeReverse.call(array) : array; + } + function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != "number" && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + function sortedIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + function sortedLastIndexOf(array, value) { + var length = array ? array.length : 0; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + function sortedUniq(array) { + return array && array.length ? baseSortedUniq(array) : []; + } + function sortedUniqBy(array, iteratee) { + return array && array.length ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; + } + function tail(array) { + var length = array ? array.length : 0; + return length ? baseSlice(array, 1, length) : []; + } + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = guard || n === undefined ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + n = guard || n === undefined ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + function takeRightWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; + } + function takeWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; + } + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + function uniq(array) { + return array && array.length ? baseUniq(array) : []; + } + function uniqBy(array, iteratee) { + return array && array.length ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + function uniqWith(array, comparator) { + return array && array.length ? baseUniq(array, undefined, comparator) : []; + } + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) ? baseDifference(array, values) : []; + }); + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + var zip = baseRest(unzip); + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + var zipWith = baseRest(function(arrays) { + var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; + iteratee = typeof iteratee == "function" ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + function tap(value, interceptor) { + interceptor(value); + return value; + } + function thru(value, interceptor) { + return interceptor(value); + } + var wrapperAt = flatRest(function(paths) { + var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { + return baseAt(object, paths); + }; + if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + func: thru, + args: [ interceptor ], + thisArg: undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + function wrapperChain() { + return chain(this); + } + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; + return { + done: done, + value: value + }; + } + function wrapperToIterator() { + return this; + } + function wrapperPlant(value) { + var result, parent = this; + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + func: thru, + args: [ reverse ], + thisArg: undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + var find = createFind(findIndex); + var findLast = createFind(findLastIndex); + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [ value ]); + } + }); + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; + } + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, isFunc = typeof path == "function", isProp = isKey(path), result = isArrayLike(collection) ? Array(collection.length) : []; + baseEach(collection, function(value) { + var func = isFunc ? path : isProp && value != null ? value[path] : undefined; + result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [ iteratees ]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [ orders ]; + } + return baseOrderBy(collection, iteratees, orders); + } + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { + return [ [], [] ]; + }); + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + function sampleSize(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n === undefined) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [ iteratees[0] ]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + var now = ctxNow || function() { + return root.Date.now(); + }; + function after(n, func) { + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + function ary(func, n, guard) { + n = guard ? undefined : n; + n = func && n == null ? func.length : n; + return createWrap(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + function before(n, func) { + var result; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + var bindKey = baseRest(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + function debounce(func, wait, options) { + var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = "maxWait" in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + function invokeFunc(time) { + var args = lastArgs, thisArg = lastThis; + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + function leadingEdge(time) { + lastInvokeTime = time; + timerId = setTimeout(timerExpired, wait); + return leading ? invokeFunc(time) : result; + } + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; + return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; + } + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + timerId = setTimeout(timerExpired, remainingWait(time)); + } + function trailingEdge(time) { + timerId = undefined; + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + function debounced() { + var time = now(), isInvoking = shouldInvoke(time); + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + function flip(func) { + return createWrap(func, FLIP_FLAG); + } + function memoize(func, resolver) { + if (typeof func != "function" || resolver && typeof resolver != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache)(); + return memoized; + } + memoize.Cache = MapCache; + function negate(predicate) { + if (typeof predicate != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: + return !predicate.call(this); + + case 1: + return !predicate.call(this, args[0]); + + case 2: + return !predicate.call(this, args[0], args[1]); + + case 3: + return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); }; - this.request(options, function(err, response) { - if (err) { - if (self.logging) { - console.log("error trying to log user in"); + } + function once(func) { + return before(2, func); + } + var overArgs = castRest(function(func, transforms) { + transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, length = nativeMin(args.length, funcsLength); + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, PARTIAL_FLAG, undefined, partials, holders); + }); + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + var rearg = flatRest(function(func, indexes) { + return createWrap(func, REARG_FLAG, undefined, undefined, undefined, indexes); + }); + function rest(func, start) { + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + function spread(func, start) { + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], otherArgs = castSlice(args, 0, start); + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + function throttle(func, wait, options) { + var leading = true, trailing = true; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = "leading" in options ? !!options.leading : leading; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + leading: leading, + maxWait: wait, + trailing: trailing + }); + } + function unary(func) { + return ary(func, 1); + } + function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return partial(wrapper, value); + } + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [ value ]; + } + function clone(value) { + return baseClone(value, false, true); + } + function cloneWith(value, customizer) { + return baseClone(value, false, true, customizer); + } + function cloneDeep(value) { + return baseClone(value, true, true); + } + function cloneDeepWith(value, customizer) { + return baseClone(value, true, true, customizer); + } + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + function eq(value, other) { + return value === other || value !== value && other !== other; + } + var gt = createRelationalOperation(baseGt); + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + var isArguments = baseIsArguments(function() { + return arguments; + }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + }; + var isArray = Array.isArray; + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + function isBoolean(value) { + return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag; + } + var isBuffer = nativeIsBuffer || stubFalse; + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + function isElement(value) { + return value != null && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); + } + function isEmpty(value) { + if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + function isEqual(value, other) { + return baseIsEqual(value, other); + } + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; + } + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + return objectToString.call(value) == errorTag || typeof value.message == "string" && typeof value.name == "string"; + } + function isFinite(value) { + return typeof value == "number" && nativeIsFinite(value); + } + function isFunction(value) { + var tag = isObject(value) ? objectToString.call(value) : ""; + return tag == funcTag || tag == genTag || tag == proxyTag; + } + function isInteger(value) { + return typeof value == "number" && value == toInteger(value); + } + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + function isObject(value) { + var type = typeof value; + return value != null && (type == "object" || type == "function"); + } + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + function isNaN(value) { + return isNumber(value) && value != +value; + } + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + function isNull(value) { + return value === null; + } + function isNil(value) { + return value == null; + } + function isNumber(value) { + return typeof value == "number" || isObjectLike(value) && objectToString.call(value) == numberTag; + } + function isPlainObject(value) { + if (!isObjectLike(value) || objectToString.call(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; + } + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + function isString(value) { + return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + } + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + } + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function isUndefined(value) { + return value === undefined; + } + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + function isWeakSet(value) { + return isObjectLike(value) && objectToString.call(value) == weakSetTag; + } + var lt = createRelationalOperation(baseLt); + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (iteratorSymbol && value[iteratorSymbol]) { + return iteratorToArray(value[iteratorSymbol]()); + } + var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; + return func(value); + } + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + function toInteger(value) { + var result = toFinite(value), remainder = result % 1; + return result === result ? remainder ? result - remainder : result : 0; + } + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + function toNumber(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == "function" ? value.valueOf() : value; + value = isObject(other) ? other + "" : other; + } + if (typeof value != "string") { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ""); + var isBinary = reIsBinary.test(value); + return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; + } + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + function toSafeInteger(value) { + return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + } + function toString(value) { + return value == null ? "" : baseToString(value); + } + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + var at = flatRest(baseAt); + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? baseAssign(result, properties) : result; + } + var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return apply(assignInWith, undefined, args); + }); + var defaultsDeep = baseRest(function(args) { + args.push(undefined, mergeDefaults); + return apply(mergeWith, undefined, args); + }); + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + function forIn(object, iteratee) { + return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + function forInRight(object, iteratee) { + return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + var invert = createInverter(function(result, value, key) { + result[value] = key; + }, constant(identity)); + var invertBy = createInverter(function(result, value, key) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [ key ]; + } + }, getIteratee); + var invoke = baseRest(baseInvoke); + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + var omit = flatRest(function(object, props) { + if (object == null) { + return {}; + } + props = arrayMap(props, toKey); + return basePick(object, baseDifference(getAllKeysIn(object), props)); + }); + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + var pick = flatRest(function(object, props) { + return object == null ? {} : basePick(object, arrayMap(props, toKey)); + }); + function pickBy(object, predicate) { + return object == null ? {} : basePickBy(object, getAllKeysIn(object), getIteratee(predicate)); + } + function result(object, path, defaultValue) { + path = isKey(path, object) ? [ path ] : castPath(path); + var index = -1, length = path.length; + if (!length) { + object = undefined; + length = 1; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + function setWith(object, path, value, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + var toPairs = createToPairs(keys); + var toPairsIn = createToPairs(keysIn); + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor() : []; + } else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + function values(object) { + return object ? baseValues(object, keys(object)) : []; + } + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + function random(lower, upper, floating) { + if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == "boolean") { + floating = upper; + upper = undefined; + } else if (typeof lower == "boolean") { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper); + } + return baseRandom(lower, upper); + } + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); + } + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + var length = string.length; + position = position === undefined ? length : baseClamp(toInteger(position), 0, length); + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + function escape(string) { + string = toString(string); + return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; + } + function escapeRegExp(string) { + string = toString(string); + return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; + } + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? "-" : "") + word.toLowerCase(); + }); + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? " " : "") + word.toLowerCase(); + }); + var lowerFirst = createCaseFirst("toLowerCase"); + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); + } + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + var strLength = length ? stringSize(string) : 0; + return length && strLength < length ? string + createPadding(length - strLength, chars) : string; + } + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + var strLength = length ? stringSize(string) : 0; + return length && strLength < length ? createPadding(length - strLength, chars) + string : string; + } + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0); + } + function repeat(string, n, guard) { + if (guard ? isIterateeCall(string, n, guard) : n === undefined) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + function replace() { + var args = arguments, string = toString(args[0]); + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? "_" : "") + word.toLowerCase(); + }); + function split(string, separator, limit) { + if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + var startCase = createCompounder(function(result, word, index) { + return result + (index ? " " : "") + upperFirst(word); + }); + function startsWith(string, target, position) { + string = toString(string); + position = baseClamp(toInteger(position), 0, string.length); + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + function template(string, options, guard) { + var settings = lodash.templateSettings; + if (guard && isIterateeCall(string, options, guard)) { + options = undefined; + } + string = toString(string); + options = assignInWith({}, options, settings, assignInDefaults); + var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); + var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; + var reDelimiters = RegExp((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); + var sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; + string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { + interpolateValue || (interpolateValue = esTemplateValue); + source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); + if (escapeValue) { + isEscaping = true; + source += "' +\n__e(" + escapeValue + ") +\n'"; + } + if (evaluateValue) { + isEvaluating = true; + source += "';\n" + evaluateValue + ";\n__p += '"; + } + if (interpolateValue) { + source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + var variable = options.variable; + if (!variable) { + source = "with (obj) {\n" + source + "\n}\n"; + } + source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); + source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}"; + var result = attempt(function() { + return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues); + }); + result.source = source; + if (isError(result)) { + throw result; + } + return result; + } + function toLower(value) { + return toString(value).toLowerCase(); + } + function toUpper(value) { + return toString(value).toUpperCase(); + } + function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ""); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; + return castSlice(strSymbols, start, end).join(""); + } + function trimEnd(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrimEnd, ""); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; + return castSlice(strSymbols, 0, end).join(""); + } + function trimStart(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrimStart, ""); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); + return castSlice(strSymbols, start).join(""); + } + function truncate(string, options) { + var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; + if (isObject(options)) { + var separator = "separator" in options ? options.separator : separator; + length = "length" in options ? toInteger(options.length) : length; + omission = "omission" in options ? baseToString(options.omission) : omission; + } + string = toString(string); + var strLength = string.length; + if (hasUnicode(string)) { + var strSymbols = stringToArray(string); + strLength = strSymbols.length; + } + if (length >= strLength) { + return string; + } + var end = length - stringSize(omission); + if (end < 1) { + return omission; + } + var result = strSymbols ? castSlice(strSymbols, 0, end).join("") : string.slice(0, end); + if (separator === undefined) { + return result + omission; + } + if (strSymbols) { + end += result.length - end; + } + if (isRegExp(separator)) { + if (string.slice(end).search(separator)) { + var match, substring = result; + if (!separator.global) { + separator = RegExp(separator.source, toString(reFlags.exec(separator)) + "g"); } - console.error(err, response); - doCallback(callback, [ err, response, self ], self); - } else { - var options = { - client: self, - data: response.getEntity() + separator.lastIndex = 0; + while (match = separator.exec(substring)) { + var newEnd = match.index; + } + result = result.slice(0, newEnd === undefined ? end : newEnd); + } + } else if (string.indexOf(baseToString(separator), end) != end) { + var index = result.lastIndexOf(separator); + if (index > -1) { + result = result.slice(0, index); + } + } + return result + omission; + } + function unescape(string) { + string = toString(string); + return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; + } + var upperCase = createCompounder(function(result, word, index) { + return result + (index ? " " : "") + word.toUpperCase(); + }); + var upperFirst = createCaseFirst("toUpperCase"); + function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined : pattern; + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; + } + var attempt = baseRest(function(func, args) { + try { + return apply(func, undefined, args); + } catch (e) { + return isError(e) ? e : new Error(e); + } + }); + var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind(object[key], object)); + }); + return object; + }); + function cond(pairs) { + var length = pairs ? pairs.length : 0, toIteratee = getIteratee(); + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + return [ toIteratee(pair[0]), pair[1] ]; + }); + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply(pair[0], this, args)) { + return apply(pair[1], this, args); + } + } + }); + } + function conforms(source) { + return baseConforms(baseClone(source, true)); + } + function constant(value) { + return function() { + return value; + }; + } + function defaultTo(value, defaultValue) { + return value == null || value !== value ? defaultValue : value; + } + var flow = createFlow(); + var flowRight = createFlow(true); + function identity(value) { + return value; + } + function iteratee(func) { + return baseIteratee(typeof func == "function" ? func : baseClone(func, true)); + } + function matches(source) { + return baseMatches(baseClone(source, true)); + } + function matchesProperty(path, srcValue) { + return baseMatchesProperty(path, baseClone(srcValue, true)); + } + var method = baseRest(function(path, args) { + return function(object) { + return baseInvoke(object, path, args); + }; + }); + var methodOf = baseRest(function(object, args) { + return function(path) { + return baseInvoke(object, path, args); + }; + }); + function mixin(object, source, options) { + var props = keys(source), methodNames = baseFunctions(source, props); + if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); + } + var chain = !(isObject(options) && "chain" in options) || !!options.chain, isFunc = isFunction(object); + arrayEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); + actions.push({ + func: func, + args: arguments, + thisArg: object + }); + result.__chain__ = chainAll; + return result; + } + return func.apply(object, arrayPush([ this.value() ], arguments)); }; - var user = new Usergrid.Entity(options); - doCallback(callback, [ null, response, user ], self); } }); + return object; } - }; - /* - * A public method to test if a user is logged in - does not guarantee that the token is still valid, - * but rather that one exists - * - * @method isLoggedIn - * @public - * @return {boolean} Returns true the user is logged in (has token and uuid), false if not - */ - Usergrid.Client.prototype.isLoggedIn = function() { - var token = this.getToken(); - return "undefined" !== typeof token && token !== null; - }; - /* - * A public method to log out an app user - clears all user fields from client - * - * @method logout - * @public - * @return none - */ - Usergrid.Client.prototype.logout = function() { - this.setToken(); - }; - /* - * A public method to destroy access tokens on the server - * - * @method logout - * @public - * @param {string} username the user associated with the token to revoke - * @param {string} token set to 'null' to revoke the token of the currently logged in user - * or set to token value to revoke a specific token - * @param {string} revokeAll set to 'true' to revoke all tokens for the user - * @return none - */ - Usergrid.Client.prototype.destroyToken = function(username, token, revokeAll, callback) { - var options = { - client: self, - method: "PUT" - }; - if (revokeAll === true) { - options.endpoint = "users/" + username + "/revoketokens"; - } else if (token === null) { - options.endpoint = "users/" + username + "/revoketoken?token=" + this.getToken(); - } else { - options.endpoint = "users/" + username + "/revoketoken?token=" + token; + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + function noop() {} + function nthArg(n) { + n = toInteger(n); + return baseRest(function(args) { + return baseNth(args, n); + }); + } + var over = createOver(arrayMap); + var overEvery = createOver(arrayEvery); + var overSome = createOver(arraySome); + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } - this.request(options, function(err, data) { - if (err) { - if (self.logging) { - console.log("error destroying access token"); + function propertyOf(object) { + return function(path) { + return object == null ? undefined : baseGet(object, path); + }; + } + var range = createRange(); + var rangeRight = createRange(true); + function stubArray() { + return []; + } + function stubFalse() { + return false; + } + function stubObject() { + return {}; + } + function stubString() { + return ""; + } + function stubTrue() { + return true; + } + function times(n, iteratee) { + n = toInteger(n); + if (n < 1 || n > MAX_SAFE_INTEGER) { + return []; + } + var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); + iteratee = getIteratee(iteratee); + n -= MAX_ARRAY_LENGTH; + var result = baseTimes(length, iteratee); + while (++index < n) { + iteratee(index); + } + return result; + } + function toPath(value) { + if (isArray(value)) { + return arrayMap(value, toKey); + } + return isSymbol(value) ? [ value ] : copyArray(stringToPath(value)); + } + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + var add = createMathOperation(function(augend, addend) { + return augend + addend; + }, 0); + var ceil = createRound("ceil"); + var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; + }, 1); + var floor = createRound("floor"); + function max(array) { + return array && array.length ? baseExtremum(array, identity, baseGt) : undefined; + } + function maxBy(array, iteratee) { + return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; + } + function mean(array) { + return baseMean(array, identity); + } + function meanBy(array, iteratee) { + return baseMean(array, getIteratee(iteratee, 2)); + } + function min(array) { + return array && array.length ? baseExtremum(array, identity, baseLt) : undefined; + } + function minBy(array, iteratee) { + return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; + } + var multiply = createMathOperation(function(multiplier, multiplicand) { + return multiplier * multiplicand; + }, 1); + var round = createRound("round"); + var subtract = createMathOperation(function(minuend, subtrahend) { + return minuend - subtrahend; + }, 0); + function sum(array) { + return array && array.length ? baseSum(array, identity) : 0; + } + function sumBy(array, iteratee) { + return array && array.length ? baseSum(array, getIteratee(iteratee, 2)) : 0; + } + lodash.after = after; + lodash.ary = ary; + lodash.assign = assign; + lodash.assignIn = assignIn; + lodash.assignInWith = assignInWith; + lodash.assignWith = assignWith; + lodash.at = at; + lodash.before = before; + lodash.bind = bind; + lodash.bindAll = bindAll; + lodash.bindKey = bindKey; + lodash.castArray = castArray; + lodash.chain = chain; + lodash.chunk = chunk; + lodash.compact = compact; + lodash.concat = concat; + lodash.cond = cond; + lodash.conforms = conforms; + lodash.constant = constant; + lodash.countBy = countBy; + lodash.create = create; + lodash.curry = curry; + lodash.curryRight = curryRight; + lodash.debounce = debounce; + lodash.defaults = defaults; + lodash.defaultsDeep = defaultsDeep; + lodash.defer = defer; + lodash.delay = delay; + lodash.difference = difference; + lodash.differenceBy = differenceBy; + lodash.differenceWith = differenceWith; + lodash.drop = drop; + lodash.dropRight = dropRight; + lodash.dropRightWhile = dropRightWhile; + lodash.dropWhile = dropWhile; + lodash.fill = fill; + lodash.filter = filter; + lodash.flatMap = flatMap; + lodash.flatMapDeep = flatMapDeep; + lodash.flatMapDepth = flatMapDepth; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.flattenDepth = flattenDepth; + lodash.flip = flip; + lodash.flow = flow; + lodash.flowRight = flowRight; + lodash.fromPairs = fromPairs; + lodash.functions = functions; + lodash.functionsIn = functionsIn; + lodash.groupBy = groupBy; + lodash.initial = initial; + lodash.intersection = intersection; + lodash.intersectionBy = intersectionBy; + lodash.intersectionWith = intersectionWith; + lodash.invert = invert; + lodash.invertBy = invertBy; + lodash.invokeMap = invokeMap; + lodash.iteratee = iteratee; + lodash.keyBy = keyBy; + lodash.keys = keys; + lodash.keysIn = keysIn; + lodash.map = map; + lodash.mapKeys = mapKeys; + lodash.mapValues = mapValues; + lodash.matches = matches; + lodash.matchesProperty = matchesProperty; + lodash.memoize = memoize; + lodash.merge = merge; + lodash.mergeWith = mergeWith; + lodash.method = method; + lodash.methodOf = methodOf; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.nthArg = nthArg; + lodash.omit = omit; + lodash.omitBy = omitBy; + lodash.once = once; + lodash.orderBy = orderBy; + lodash.over = over; + lodash.overArgs = overArgs; + lodash.overEvery = overEvery; + lodash.overSome = overSome; + lodash.partial = partial; + lodash.partialRight = partialRight; + lodash.partition = partition; + lodash.pick = pick; + lodash.pickBy = pickBy; + lodash.property = property; + lodash.propertyOf = propertyOf; + lodash.pull = pull; + lodash.pullAll = pullAll; + lodash.pullAllBy = pullAllBy; + lodash.pullAllWith = pullAllWith; + lodash.pullAt = pullAt; + lodash.range = range; + lodash.rangeRight = rangeRight; + lodash.rearg = rearg; + lodash.reject = reject; + lodash.remove = remove; + lodash.rest = rest; + lodash.reverse = reverse; + lodash.sampleSize = sampleSize; + lodash.set = set; + lodash.setWith = setWith; + lodash.shuffle = shuffle; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.sortedUniq = sortedUniq; + lodash.sortedUniqBy = sortedUniqBy; + lodash.split = split; + lodash.spread = spread; + lodash.tail = tail; + lodash.take = take; + lodash.takeRight = takeRight; + lodash.takeRightWhile = takeRightWhile; + lodash.takeWhile = takeWhile; + lodash.tap = tap; + lodash.throttle = throttle; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.toPairs = toPairs; + lodash.toPairsIn = toPairsIn; + lodash.toPath = toPath; + lodash.toPlainObject = toPlainObject; + lodash.transform = transform; + lodash.unary = unary; + lodash.union = union; + lodash.unionBy = unionBy; + lodash.unionWith = unionWith; + lodash.uniq = uniq; + lodash.uniqBy = uniqBy; + lodash.uniqWith = uniqWith; + lodash.unset = unset; + lodash.unzip = unzip; + lodash.unzipWith = unzipWith; + lodash.update = update; + lodash.updateWith = updateWith; + lodash.values = values; + lodash.valuesIn = valuesIn; + lodash.without = without; + lodash.words = words; + lodash.wrap = wrap; + lodash.xor = xor; + lodash.xorBy = xorBy; + lodash.xorWith = xorWith; + lodash.zip = zip; + lodash.zipObject = zipObject; + lodash.zipObjectDeep = zipObjectDeep; + lodash.zipWith = zipWith; + lodash.entries = toPairs; + lodash.entriesIn = toPairsIn; + lodash.extend = assignIn; + lodash.extendWith = assignInWith; + mixin(lodash, lodash); + lodash.add = add; + lodash.attempt = attempt; + lodash.camelCase = camelCase; + lodash.capitalize = capitalize; + lodash.ceil = ceil; + lodash.clamp = clamp; + lodash.clone = clone; + lodash.cloneDeep = cloneDeep; + lodash.cloneDeepWith = cloneDeepWith; + lodash.cloneWith = cloneWith; + lodash.conformsTo = conformsTo; + lodash.deburr = deburr; + lodash.defaultTo = defaultTo; + lodash.divide = divide; + lodash.endsWith = endsWith; + lodash.eq = eq; + lodash.escape = escape; + lodash.escapeRegExp = escapeRegExp; + lodash.every = every; + lodash.find = find; + lodash.findIndex = findIndex; + lodash.findKey = findKey; + lodash.findLast = findLast; + lodash.findLastIndex = findLastIndex; + lodash.findLastKey = findLastKey; + lodash.floor = floor; + lodash.forEach = forEach; + lodash.forEachRight = forEachRight; + lodash.forIn = forIn; + lodash.forInRight = forInRight; + lodash.forOwn = forOwn; + lodash.forOwnRight = forOwnRight; + lodash.get = get; + lodash.gt = gt; + lodash.gte = gte; + lodash.has = has; + lodash.hasIn = hasIn; + lodash.head = head; + lodash.identity = identity; + lodash.includes = includes; + lodash.indexOf = indexOf; + lodash.inRange = inRange; + lodash.invoke = invoke; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isArrayBuffer = isArrayBuffer; + lodash.isArrayLike = isArrayLike; + lodash.isArrayLikeObject = isArrayLikeObject; + lodash.isBoolean = isBoolean; + lodash.isBuffer = isBuffer; + lodash.isDate = isDate; + lodash.isElement = isElement; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isEqualWith = isEqualWith; + lodash.isError = isError; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isInteger = isInteger; + lodash.isLength = isLength; + lodash.isMap = isMap; + lodash.isMatch = isMatch; + lodash.isMatchWith = isMatchWith; + lodash.isNaN = isNaN; + lodash.isNative = isNative; + lodash.isNil = isNil; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isObjectLike = isObjectLike; + lodash.isPlainObject = isPlainObject; + lodash.isRegExp = isRegExp; + lodash.isSafeInteger = isSafeInteger; + lodash.isSet = isSet; + lodash.isString = isString; + lodash.isSymbol = isSymbol; + lodash.isTypedArray = isTypedArray; + lodash.isUndefined = isUndefined; + lodash.isWeakMap = isWeakMap; + lodash.isWeakSet = isWeakSet; + lodash.join = join; + lodash.kebabCase = kebabCase; + lodash.last = last; + lodash.lastIndexOf = lastIndexOf; + lodash.lowerCase = lowerCase; + lodash.lowerFirst = lowerFirst; + lodash.lt = lt; + lodash.lte = lte; + lodash.max = max; + lodash.maxBy = maxBy; + lodash.mean = mean; + lodash.meanBy = meanBy; + lodash.min = min; + lodash.minBy = minBy; + lodash.stubArray = stubArray; + lodash.stubFalse = stubFalse; + lodash.stubObject = stubObject; + lodash.stubString = stubString; + lodash.stubTrue = stubTrue; + lodash.multiply = multiply; + lodash.nth = nth; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.now = now; + lodash.pad = pad; + lodash.padEnd = padEnd; + lodash.padStart = padStart; + lodash.parseInt = parseInt; + lodash.random = random; + lodash.reduce = reduce; + lodash.reduceRight = reduceRight; + lodash.repeat = repeat; + lodash.replace = replace; + lodash.result = result; + lodash.round = round; + lodash.runInContext = runInContext; + lodash.sample = sample; + lodash.size = size; + lodash.snakeCase = snakeCase; + lodash.some = some; + lodash.sortedIndex = sortedIndex; + lodash.sortedIndexBy = sortedIndexBy; + lodash.sortedIndexOf = sortedIndexOf; + lodash.sortedLastIndex = sortedLastIndex; + lodash.sortedLastIndexBy = sortedLastIndexBy; + lodash.sortedLastIndexOf = sortedLastIndexOf; + lodash.startCase = startCase; + lodash.startsWith = startsWith; + lodash.subtract = subtract; + lodash.sum = sum; + lodash.sumBy = sumBy; + lodash.template = template; + lodash.times = times; + lodash.toFinite = toFinite; + lodash.toInteger = toInteger; + lodash.toLength = toLength; + lodash.toLower = toLower; + lodash.toNumber = toNumber; + lodash.toSafeInteger = toSafeInteger; + lodash.toString = toString; + lodash.toUpper = toUpper; + lodash.trim = trim; + lodash.trimEnd = trimEnd; + lodash.trimStart = trimStart; + lodash.truncate = truncate; + lodash.unescape = unescape; + lodash.uniqueId = uniqueId; + lodash.upperCase = upperCase; + lodash.upperFirst = upperFirst; + lodash.each = forEach; + lodash.eachRight = forEachRight; + lodash.first = head; + mixin(lodash, function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; } - doCallback(callback, [ err, data, null ], self); - } else { - if (revokeAll === true) { - console.log("all user tokens invalidated"); + }); + return source; + }(), { + chain: false + }); + lodash.VERSION = VERSION; + arrayEach([ "bind", "bindKey", "curry", "curryRight", "partial", "partialRight" ], function(methodName) { + lodash[methodName].placeholder = lodash; + }); + arrayEach([ "drop", "take" ], function(methodName, index) { + LazyWrapper.prototype[methodName] = function(n) { + var filtered = this.__filtered__; + if (filtered && !index) { + return new LazyWrapper(this); + } + n = n === undefined ? 1 : nativeMax(toInteger(n), 0); + var result = this.clone(); + if (filtered) { + result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { - console.log("token invalidated"); + result.__views__.push({ + size: nativeMin(n, MAX_ARRAY_LENGTH), + type: methodName + (result.__dir__ < 0 ? "Right" : "") + }); } - doCallback(callback, [ err, data, null ], self); + return result; + }; + LazyWrapper.prototype[methodName + "Right"] = function(n) { + return this.reverse()[methodName](n).reverse(); + }; + }); + arrayEach([ "filter", "map", "takeWhile" ], function(methodName, index) { + var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; + LazyWrapper.prototype[methodName] = function(iteratee) { + var result = this.clone(); + result.__iteratees__.push({ + iteratee: getIteratee(iteratee, 3), + type: type + }); + result.__filtered__ = result.__filtered__ || isFilter; + return result; + }; + }); + arrayEach([ "head", "last" ], function(methodName, index) { + var takeName = "take" + (index ? "Right" : ""); + LazyWrapper.prototype[methodName] = function() { + return this[takeName](1).value()[0]; + }; + }); + arrayEach([ "initial", "tail" ], function(methodName, index) { + var dropName = "drop" + (index ? "" : "Right"); + LazyWrapper.prototype[methodName] = function() { + return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); + }; + }); + LazyWrapper.prototype.compact = function() { + return this.filter(identity); + }; + LazyWrapper.prototype.find = function(predicate) { + return this.filter(predicate).head(); + }; + LazyWrapper.prototype.findLast = function(predicate) { + return this.reverse().find(predicate); + }; + LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { + if (typeof path == "function") { + return new LazyWrapper(this); } + return this.map(function(value) { + return baseInvoke(value, path, args); + }); }); - }; - /* - * A public method to log out an app user - clears all user fields from client - * and destroys the access token on the server. - * - * @method logout - * @public - * @param {string} username the user associated with the token to revoke - * @param {string} token set to 'null' to revoke the token of the currently logged in user - * or set to token value to revoke a specific token - * @param {string} revokeAll set to 'true' to revoke all tokens for the user - * @return none - */ - Usergrid.Client.prototype.logoutAndDestroyToken = function(username, token, revokeAll, callback) { - if (username === null) { - console.log("username required to revoke tokens"); - } else { - this.destroyToken(username, token, revokeAll, callback); - if (revokeAll === true || token === this.getToken() || token === null) { - this.setToken(null); + LazyWrapper.prototype.reject = function(predicate) { + return this.filter(negate(getIteratee(predicate))); + }; + LazyWrapper.prototype.slice = function(start, end) { + start = toInteger(start); + var result = this; + if (result.__filtered__ && (start > 0 || end < 0)) { + return new LazyWrapper(result); } - } - }; - /* - * A private method to build the curl call to display on the command line - * - * @method buildCurlCall - * @private - * @param {object} options - * @return {string} curl - */ - Usergrid.Client.prototype.buildCurlCall = function(options) { - var curl = [ "curl" ]; - var method = (options.method || "GET").toUpperCase(); - var body = options.body; - var uri = options.uri; - curl.push("-X"); - curl.push([ "POST", "PUT", "DELETE" ].indexOf(method) >= 0 ? method : "GET"); - curl.push(uri); - if ("object" === typeof body && Object.keys(body).length > 0 && [ "POST", "PUT" ].indexOf(method) !== -1) { - curl.push("-d"); - curl.push("'" + JSON.stringify(body) + "'"); - } - curl = curl.join(" "); - console.log(curl); - return curl; - }; - Usergrid.Client.prototype.getDisplayImage = function(email, picture, size) { - size = size || 50; - var image = "https://apigee.com/usergrid/images/user_profile.png"; - try { - if (picture) { - image = picture; - } else if (email.length) { - image = "https://secure.gravatar.com/avatar/" + MD5(email) + "?s=" + size + encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"); + if (start < 0) { + result = result.takeRight(-start); + } else if (start) { + result = result.drop(start); } - } catch (e) {} finally { - return image; - } - }; - global[name] = Usergrid.Client; - global[name].noConflict = function() { - if (overwrittenName) { - global[name] = overwrittenName; + if (end !== undefined) { + end = toInteger(end); + result = end < 0 ? result.dropRight(-end) : result.take(end - start); + } + return result; + }; + LazyWrapper.prototype.takeRightWhile = function(predicate) { + return this.reverse().takeWhile(predicate).reverse(); + }; + LazyWrapper.prototype.toArray = function() { + return this.take(MAX_ARRAY_LENGTH); + }; + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); + if (!lodashFunc) { + return; + } + lodash.prototype[methodName] = function() { + var value = this.__wrapped__, args = isTaker ? [ 1 ] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); + var interceptor = function(value) { + var result = lodashFunc.apply(lodash, arrayPush([ value ], args)); + return isTaker && chainAll ? result[0] : result; + }; + if (useLazy && checkIteratee && typeof iteratee == "function" && iteratee.length != 1) { + isLazy = useLazy = false; + } + var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; + if (!retUnwrapped && useLazy) { + value = onlyLazy ? value : new LazyWrapper(this); + var result = func.apply(value, args); + result.__actions__.push({ + func: thru, + args: [ interceptor ], + thisArg: undefined + }); + return new LodashWrapper(result, chainAll); + } + if (isUnwrapped && onlyLazy) { + return func.apply(this, args); + } + result = this.thru(interceptor); + return isUnwrapped ? isTaker ? result.value()[0] : result.value() : result; + }; + }); + arrayEach([ "pop", "push", "shift", "sort", "splice", "unshift" ], function(methodName) { + var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var lodashFunc = lodash[methodName]; + if (lodashFunc) { + var key = lodashFunc.name + "", names = realNames[key] || (realNames[key] = []); + names.push({ + name: methodName, + func: lodashFunc + }); + } + }); + realNames[createHybrid(undefined, BIND_KEY_FLAG).name] = [ { + name: "wrapper", + func: undefined + } ]; + LazyWrapper.prototype.clone = lazyClone; + LazyWrapper.prototype.reverse = lazyReverse; + LazyWrapper.prototype.value = lazyValue; + lodash.prototype.at = wrapperAt; + lodash.prototype.chain = wrapperChain; + lodash.prototype.commit = wrapperCommit; + lodash.prototype.next = wrapperNext; + lodash.prototype.plant = wrapperPlant; + lodash.prototype.reverse = wrapperReverse; + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + lodash.prototype.first = lodash.prototype.head; + if (iteratorSymbol) { + lodash.prototype[iteratorSymbol] = wrapperToIterator; } - return exports; + return lodash; }; - return global[name]; -})(); - -var ENTITY_SYSTEM_PROPERTIES = [ "metadata", "created", "modified", "oldpassword", "newpassword", "type", "activated", "uuid" ]; - -/* - * A class to Model a Usergrid Entity. - * Set the type and uuid of entity in the 'data' json object - * - * @constructor - * @param {object} options {client:client, data:{'type':'collection_type', uuid:'uuid', 'key':'value'}} - */ -Usergrid.Entity = function(options) { - this._data = {}; - this._client = undefined; - if (options) { - this.set(options.data || {}); - this._client = options.client || {}; + var _ = runInContext(); + if (typeof define == "function" && typeof define.amd == "object" && define.amd) { + root._ = _; + define(function() { + return _; + }); + } else if (freeModule) { + (freeModule.exports = _)._ = _; + freeExports._ = _; + } else { + root._ = _; } -}; +}).call(this); -/* - * method to determine whether or not the passed variable is a Usergrid Entity - * - * @method isEntity - * @public - * @params {any} obj - any variable - * @return {boolean} Returns true or false - */ -Usergrid.Entity.isEntity = function(obj) { - return obj && obj instanceof Usergrid.Entity; -}; +"use strict"; -/* - * method to determine whether or not the passed variable is a Usergrid Entity - * That has been saved. - * - * @method isPersistedEntity - * @public - * @params {any} obj - any variable - * @return {boolean} Returns true or false - */ -Usergrid.Entity.isPersistedEntity = function(obj) { - return isEntity(obj) && isUUID(obj.get("uuid")); -}; +var UsergridAuthMode = Object.freeze({ + NONE: "none", + USER: "user", + APP: "app" +}); -/* - * returns a serialized version of the entity object - * - * Note: use the client.restoreEntity() function to restore - * - * @method serialize - * @return {string} data - */ -Usergrid.Entity.prototype.serialize = function() { - return JSON.stringify(this._data); -}; +var UsergridDirection = Object.freeze({ + IN: "connecting", + OUT: "connections" +}); -/* - * gets a specific field or the entire data object. If null or no argument - * passed, will return all data, else, will return a specific field - * - * @method get - * @param {string} field - * @return {string} || {object} data - */ -Usergrid.Entity.prototype.get = function(key) { - var value; - if (arguments.length === 0) { - value = this._data; - } else if (arguments.length > 1) { - key = [].slice.call(arguments).reduce(function(p, c, i, a) { - if (c instanceof Array) { - p = p.concat(c); - } else { - p.push(c); - } - return p; - }, []); - } - if (key instanceof Array) { - var self = this; - value = key.map(function(k) { - return self.get(k); - }); - } else if ("undefined" !== typeof key) { - value = this._data[key]; - } - return value; -}; +var UsergridHttpMethod = Object.freeze({ + GET: "GET", + PUT: "PUT", + POST: "POST", + DELETE: "DELETE" +}); -/* - * adds a specific key value pair or object to the Entity's data - * is additive - will not overwrite existing values unless they - * are explicitly specified - * - * @method set - * @param {string} key || {object} - * @param {string} value - * @return none - */ -Usergrid.Entity.prototype.set = function(key, value) { - if (typeof key === "object") { - for (var field in key) { - this._data[field] = key[field]; - } - } else if (typeof key === "string") { - if (value === null) { - delete this._data[key]; - } else { - this._data[key] = value; - } - } else { - this._data = {}; - } -}; +var UsergridQueryOperator = Object.freeze({ + EQUAL: "=", + GREATER_THAN: ">", + GREATER_THAN_EQUAL_TO: ">=", + LESS_THAN: "<", + LESS_THAN_EQUAL_TO: "<=" +}); -Usergrid.Entity.prototype.getEndpoint = function() { - var type = this.get("type"), nameProperties = [ "uuid", "name" ], name; - if (type === undefined) { - throw new UsergridError("cannot fetch entity, no entity type specified", "no_type_specified"); - } else if (/^users?$/.test(type)) { - nameProperties.unshift("username"); - } - name = this.get(nameProperties).filter(function(x) { - return x !== null && "undefined" !== typeof x; - }).shift(); - return name ? [ type, name ].join("/") : type; -}; +var UsergridQuerySortOrder = Object.freeze({ + ASC: "asc", + DESC: "desc" +}); -/* - * Saves the entity back to the database - * - * @method save - * @public - * @param {function} callback - * @return {callback} callback(err, response, self) - */ -Usergrid.Entity.prototype.save = function(callback) { - var self = this, type = this.get("type"), method = "POST", entityId = this.get("uuid"), changePassword, entityData = this.get(), options = { - method: method, - endpoint: type - }; - if (entityId) { - options.method = "PUT"; - options.endpoint += "/" + entityId; - } - options.body = Object.keys(entityData).filter(function(key) { - return ENTITY_SYSTEM_PROPERTIES.indexOf(key) === -1; - }).reduce(function(data, key) { - data[key] = entityData[key]; - return data; - }, {}); - self._client.request(options, function(err, response) { - var entity = response.getEntity(); - if (entity) { - self.set(entity); - self.set("type", /^\//.test(response.path) ? response.path.substring(1) : response.path); - } - if (err && self._client.logging) { - console.log("could not save entity"); - } - doCallback(callback, [ err, response, self ], self); - }); -}; +"use strict"; -/* - * - * Updates the user's password - */ -Usergrid.Entity.prototype.changePassword = function(oldpassword, newpassword, callback) { - var self = this; - if ("function" === typeof oldpassword && callback === undefined) { - callback = oldpassword; - oldpassword = self.get("oldpassword"); - newpassword = self.get("newpassword"); - } - self.set({ - password: null, - oldpassword: null, - newpassword: null +var UsergridApplicationJSONHeaderValue = "application/json"; + +(function(global) { + var name = "UsergridHelpers", overwrittenName = global[name]; + function UsergridHelpers() {} + UsergridHelpers.DefaultHeaders = Object.freeze({ + "Content-Type": UsergridApplicationJSONHeaderValue, + Accept: UsergridApplicationJSONHeaderValue }); - if (/^users?$/.test(self.get("type")) && oldpassword && newpassword) { - var options = { - method: "PUT", - endpoint: "users/" + self.get("uuid") + "/password", - body: { - uuid: self.get("uuid"), - username: self.get("username"), - oldpassword: oldpassword, - newpassword: newpassword - } - }; - self._client.request(options, function(err, response) { - if (err && self._client.logging) { - console.log("could not update user"); + UsergridHelpers.validateAndRetrieveClient = function(args) { + var client = _.first([ args, args[0], _.get(args, "client"), Usergrid.isInitialized ? Usergrid : undefined ].filter(function(client) { + return client instanceof UsergridClient; + })); + if (!client) { + throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument"); + } + return client; + }; + UsergridHelpers.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true } - doCallback(callback, [ err, response, self ], self); }); - } else { - throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'"); - } -}; - -/* - * refreshes the entity by making a GET call back to the database - * - * @method fetch - * @public - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Entity.prototype.fetch = function(callback) { - var endpoint, self = this; - endpoint = this.getEndpoint(); - var options = { - method: "GET", - endpoint: endpoint }; - this._client.request(options, function(err, response) { - var entity = response.getEntity(); - if (entity) { - self.set(entity); - } - doCallback(callback, [ err, response, self ], self); - }); -}; - -/* - * deletes the entity from the database - will only delete - * if the object has a valid uuid - * - * @method destroy - * @public - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.destroy = function(callback) { - var self = this; - var endpoint = this.getEndpoint(); - var options = { - method: "DELETE", - endpoint: endpoint + UsergridHelpers.flattenArgs = function(args) { + return _.flattenDeep(Array.prototype.slice.call(args)); }; - this._client.request(options, function(err, response) { - if (!err) { - self.set(null); + UsergridHelpers.callback = function() { + var args = UsergridHelpers.flattenArgs(arguments).reverse(); + var emptyFunc = function() {}; + return _.first(_.flattenDeep([ args, _.get(args, "0.callback"), emptyFunc ]).filter(_.isFunction)); + }; + UsergridHelpers.authForRequests = function(client) { + var authForRequests = undefined; + if (_.get(client, "tempAuth.isValid")) { + authForRequests = client.tempAuth; + client.tempAuth = undefined; + } else if (_.get(client, "currentUser.auth.isValid") && client.authMode === UsergridAuthMode.USER) { + authForRequests = client.currentUser.auth; + } else if (_.get(client, "appAuth.isValid") && client.authMode === UsergridAuthMode.APP) { + authForRequests = client.appAuth; } - doCallback(callback, [ err, response, self ], self); - }); -}; - -/* - * connects one entity to another - * - * @method connect - * @public - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.connect = function(connection, entity, callback) { - this.addOrRemoveConnection("POST", connection, entity, callback); -}; - -/* - * disconnects one entity from another - * - * @method disconnect - * @public - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.disconnect = function(connection, entity, callback) { - this.addOrRemoveConnection("DELETE", connection, entity, callback); -}; - -/* - * adds or removes a connection between two entities - * - * @method addOrRemoveConnection - * @public - * @param {string} method - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.addOrRemoveConnection = function(method, connection, entity, callback) { - var self = this; - if ([ "POST", "DELETE" ].indexOf(method.toUpperCase()) == -1) { - throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'"); - } - var connecteeType = entity.get("type"); - var connectee = this.getEntityId(entity); - if (!connectee) { - throw new UsergridInvalidArgumentError("connectee could not be identified"); - } - var connectorType = this.get("type"); - var connector = this.getEntityId(this); - if (!connector) { - throw new UsergridInvalidArgumentError("connector could not be identified"); - } - var endpoint = [ connectorType, connector, connection, connecteeType, connectee ].join("/"); - var options = { - method: method, - endpoint: endpoint + return authForRequests; }; - this._client.request(options, function(err, response) { - if (err && self._client.logging) { - console.log("There was an error with the connection call"); + UsergridHelpers.userLoginBody = function(options) { + var body = { + grant_type: "password", + password: options.password + }; + if (options.tokenTtl) { + body.ttl = options.tokenTtl; } - doCallback(callback, [ err, response, self ], self); - }); -}; - -/* - * returns a unique identifier for an entity - * - * @method connect - * @public - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - * - */ -Usergrid.Entity.prototype.getEntityId = function(entity) { - var id; - if (isUUID(entity.get("uuid"))) { - id = entity.get("uuid"); - } else if (this.get("type") === "users" || this.get("type") === "user") { - id = entity.get("username"); - } else { - id = entity.get("name"); - } - return id; -}; - -/* - * gets an entities connections - * - * @method getConnections - * @public - * @param {string} connection - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data, connections) - * - */ -Usergrid.Entity.prototype.getConnections = function(connection, callback) { - var self = this; - var connectorType = this.get("type"); - var connector = this.getEntityId(this); - if (!connector) { - if (typeof callback === "function") { - var error = "Error in getConnections - no uuid specified."; - if (self._client.logging) { - console.log(error); - } - doCallback(callback, [ true, error ], self); - } - return; - } - var endpoint = connectorType + "/" + connector + "/" + connection + "/"; - var options = { - method: "GET", - endpoint: endpoint + body[options.username ? "username" : "email"] = options.username ? options.username : options.email; + return body; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("entity could not be connected"); - } - self[connection] = {}; - var length = data && data.entities ? data.entities.length : 0; - for (var i = 0; i < length; i++) { - if (data.entities[i].type === "user") { - self[connection][data.entities[i].username] = data.entities[i]; - } else { - self[connection][data.entities[i].name] = data.entities[i]; - } + UsergridHelpers.appLoginBody = function(options) { + var body = { + grant_type: "client_credentials", + client_id: options.clientId, + client_secret: options.clientSecret + }; + if (options.tokenTtl) { + body.ttl = options.tokenTtl; } - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Entity.prototype.getGroups = function(callback) { - var self = this; - var endpoint = "users" + "/" + this.get("uuid") + "/groups"; - var options = { - method: "GET", - endpoint: endpoint + return body; + }; + UsergridHelpers.userResetPasswordBody = function(args) { + return { + oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined, + newpassword: _.isPlainObject(args[0]) ? args[0].newPassword : _.isString(args[1]) ? args[1] : undefined + }; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("entity could not be connected"); + UsergridHelpers.calculateExpiry = function(expires_in) { + return Date.now() + (expires_in ? expires_in - 5 : 0) * 1e3; + }; + var uuidValueRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/; + UsergridHelpers.isUUID = function(uuid) { + return !uuid ? false : uuidValueRegex.test(uuid); + }; + UsergridHelpers.useQuotesIfRequired = function(value) { + return _.isFinite(value) || UsergridHelpers.isUUID(value) || _.isBoolean(value) || _.isObject(value) && !_.isFunction(value) || _.isArray(value) ? value : "'" + value + "'"; + }; + UsergridHelpers.setReadOnly = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setReadOnly(obj, k); + }); + } else if (_.isPlainObject(obj[key])) { + return Object.freeze(obj[key]); + } else if (_.isPlainObject(obj) && key === undefined) { + return Object.freeze(obj); + } else if (_.has(obj, key)) { + return Object.defineProperty(obj, key, { + writable: false + }); + } else { + return obj; } - self.groups = data.entities; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Entity.prototype.getActivities = function(callback) { - var self = this; - var endpoint = this.get("type") + "/" + this.get("uuid") + "/activities"; - var options = { - method: "GET", - endpoint: endpoint }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("entity could not be connected"); + UsergridHelpers.setWritable = function(obj, key) { + if (_.isArray(key)) { + return key.forEach(function(k) { + UsergridHelpers.setWritable(obj, k); + }); + } else if (_.isPlainObject(obj[key])) { + return _.clone(obj[key]); + } else if (_.isPlainObject(obj) && key === undefined) { + return _.clone(obj); + } else if (_.has(obj, key)) { + return Object.defineProperty(obj, key, { + writable: true + }); + } else { + return obj; } - for (var entity in data.entities) { - data.entities[entity].createdDate = new Date(data.entities[entity].created).toUTCString(); + }; + UsergridHelpers.assignPrefabOptions = function(args) { + if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.has(args, "method")) { + _.assign(this, args[0]); } - self.activities = data.entities; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Entity.prototype.getFollowing = function(callback) { - var self = this; - var endpoint = "users" + "/" + this.get("uuid") + "/following"; - var options = { - method: "GET", - endpoint: endpoint + return this; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not get user following"); + UsergridHelpers.normalize = function(str) { + str = str.replace(/\/+/g, "/"); + str = str.replace(/:\//g, "://"); + str = str.replace(/\/(\?|&|#[^!])/g, "$1"); + str = str.replace(/(\?.+)\?/g, "$1&"); + return str; + }; + UsergridHelpers.urljoin = function() { + var input = arguments; + var options = {}; + if (typeof arguments[0] === "object") { + input = arguments[0]; + options = arguments[1] || {}; } - for (var entity in data.entities) { - data.entities[entity].createdDate = new Date(data.entities[entity].created).toUTCString(); - var image = self._client.getDisplayImage(data.entities[entity].email, data.entities[entity].picture); - data.entities[entity]._portal_image_icon = image; + var joined = [].slice.call(input, 0).join("/"); + return UsergridHelpers.normalize(joined, options); + }; + UsergridHelpers.parseResponseHeaders = function(headerStr) { + var headers = {}; + if (headerStr) { + var headerPairs = headerStr.split("\r\n"); + for (var i = 0; i < headerPairs.length; i++) { + var headerPair = headerPairs[i]; + var index = headerPair.indexOf(": "); + if (index > 0) { + var key = headerPair.substring(0, index).toLowerCase(); + headers[key] = headerPair.substring(index + 2); + } + } } - self.following = data.entities; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Entity.prototype.getFollowers = function(callback) { - var self = this; - var endpoint = "users" + "/" + this.get("uuid") + "/followers"; - var options = { - method: "GET", - endpoint: endpoint + return headers; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not get user followers"); + UsergridHelpers.uri = function(client, options) { + var path = ""; + if (options instanceof UsergridEntity) { + path = options.type; + } else if (options instanceof UsergridQuery) { + path = options._type; + } else if (_.isString(options)) { + path = options; + } else if (_.isArray(options)) { + path = _.get(options, "0.type") || _.get(options, "0.path"); + } else { + path = options.path || options.type || _.get(options, "entity.type") || _.get(options, "query._type") || _.get(options, "body.type") || _.get(options, "body.path"); } - for (var entity in data.entities) { - data.entities[entity].createdDate = new Date(data.entities[entity].created).toUTCString(); - var image = self._client.getDisplayImage(data.entities[entity].email, data.entities[entity].picture); - data.entities[entity]._portal_image_icon = image; + var uuidOrName = ""; + if (options.method !== UsergridHttpMethod.POST) { + uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, _.get(options, "entity.uuid"), _.get(options, "entity.name"), _.get(options, "body.uuid"), _.get(options, "body.name"), "" ].filter(_.isString)); } - self.followers = data.entities; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Client.prototype.createRole = function(roleName, permissions, callback) { - var options = { - type: "role", - name: roleName + return UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, path, uuidOrName); }; - this.createEntity(options, function(err, response, entity) { - if (err) { - doCallback(callback, [ err, response, self ]); - } else { - entity.assignPermissions(permissions, function(err, data) { - if (err) { - doCallback(callback, [ err, response, self ]); - } else { - doCallback(callback, [ err, data, data.data ], self); - } + UsergridHelpers.updateEntityFromRemote = function(entity, usergridResponse) { + UsergridHelpers.setWritable(entity, [ "uuid", "name", "type", "created" ]); + _.assign(entity, usergridResponse.entity); + UsergridHelpers.setReadOnly(entity, [ "uuid", "name", "type", "created" ]); + }; + UsergridHelpers.headers = function(client, options, defaultHeaders) { + var returnHeaders = {}; + _.defaults(returnHeaders, options.headers, defaultHeaders); + _.assign(returnHeaders, { + "User-Agent": "usergrid-js/v" + UsergridSDKVersion + }); + var authForRequests = UsergridHelpers.authForRequests(client); + if (authForRequests) { + _.assign(returnHeaders, { + authorization: "Bearer " + authForRequests.token }); } - }); -}; - -Usergrid.Entity.prototype.getRoles = function(callback) { - var self = this; - var endpoint = this.get("type") + "/" + this.get("uuid") + "/roles"; - var options = { - method: "GET", - endpoint: endpoint + return returnHeaders; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not get user roles"); + UsergridHelpers.setEntity = function(options, args) { + options.entity = _.first([ options.entity, args[0] ].filter(function(property) { + return property instanceof UsergridEntity; + })); + if (options.entity !== undefined) { + options.type = options.entity.type; } - self.roles = data.entities; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -Usergrid.Entity.prototype.assignRole = function(roleName, callback) { - var self = this; - var type = self.get("type"); - var collection = type + "s"; - var entityID; - if (type == "user" && this.get("username") != null) { - entityID = self.get("username"); - } else if (type == "group" && this.get("name") != null) { - entityID = self.get("name"); - } else if (this.get("uuid") != null) { - entityID = self.get("uuid"); - } - if (type != "users" && type != "groups") { - doCallback(callback, [ new UsergridError("entity must be a group or user", "invalid_entity_type"), null, this ], this); - } - var endpoint = "roles/" + roleName + "/" + collection + "/" + entityID; - var options = { - method: "POST", - endpoint: endpoint + return options; }; - this._client.request(options, function(err, response) { - if (err) { - console.log("Could not assign role."); - } - doCallback(callback, [ err, response, self ]); - }); -}; - -Usergrid.Entity.prototype.removeRole = function(roleName, callback) { - var self = this; - var type = self.get("type"); - var collection = type + "s"; - var entityID; - if (type == "user" && this.get("username") != null) { - entityID = this.get("username"); - } else if (type == "group" && this.get("name") != null) { - entityID = this.get("name"); - } else if (this.get("uuid") != null) { - entityID = this.get("uuid"); - } - if (type != "users" && type != "groups") { - doCallback(callback, [ new UsergridError("entity must be a group or user", "invalid_entity_type"), null, this ], this); - } - var endpoint = "roles/" + roleName + "/" + collection + "/" + entityID; - var options = { - method: "DELETE", - endpoint: endpoint + UsergridHelpers.setAsset = function(options, args) { + options.asset = _.first([ options.asset, _.get(options, "entity.asset"), args[1], args[0] ].filter(function(property) { + return property instanceof UsergridAsset; + })); + return options; }; - this._client.request(options, function(err, response) { - if (err) { - console.log("Could not assign role."); - } - doCallback(callback, [ err, response, self ]); - }); -}; - -Usergrid.Entity.prototype.assignPermissions = function(permissions, callback) { - var self = this; - var entityID; - var type = this.get("type"); - if (type != "user" && type != "users" && type != "group" && type != "groups" && type != "role" && type != "roles") { - doCallback(callback, [ new UsergridError("entity must be a group, user, or role", "invalid_entity_type"), null, this ], this); - } - if (type == "user" && this.get("username") != null) { - entityID = this.get("username"); - } else if (type == "group" && this.get("name") != null) { - entityID = this.get("name"); - } else if (this.get("uuid") != null) { - entityID = this.get("uuid"); - } - var endpoint = type + "/" + entityID + "/permissions"; - var options = { - method: "POST", - endpoint: endpoint, - body: { - permission: permissions - } + UsergridHelpers.setUuidOrName = function(options, args) { + options.uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, _.get(options, "entity.uuid"), _.get(options, "body.uuid"), _.get(options, "entity.name"), _.get(options, "body.name"), _.get(args, "0.uuid"), _.get(args, "0.name"), _.get(args, "2"), _.get(args, "1") ].filter(_.isString)); + return options; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not assign permissions"); - } - doCallback(callback, [ err, data, data.data ], self); - }); -}; - -Usergrid.Entity.prototype.removePermissions = function(permissions, callback) { - var self = this; - var entityID; - var type = this.get("type"); - if (type != "user" && type != "users" && type != "group" && type != "groups" && type != "role" && type != "roles") { - doCallback(callback, [ new UsergridError("entity must be a group, user, or role", "invalid_entity_type"), null, this ], this); - } - if (type == "user" && this.get("username") != null) { - entityID = this.get("username"); - } else if (type == "group" && this.get("name") != null) { - entityID = this.get("name"); - } else if (this.get("uuid") != null) { - entityID = this.get("uuid"); - } - var endpoint = type + "/" + entityID + "/permissions"; - var options = { - method: "DELETE", - endpoint: endpoint, - qs: { - permission: permissions - } + UsergridHelpers.setPathOrType = function(options, args) { + var pathOrType = _.first([ args.type, _.get(args, "0.type"), _.get(options, "entity.type"), _.get(args, "body.type"), _.get(options, "body.0.type"), _.isArray(args) ? args[0] : undefined ].filter(_.isString)); + options[/\//.test(pathOrType) ? "path" : "type"] = pathOrType; + return options; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not remove permissions"); + UsergridHelpers.setQs = function(options, args) { + if (options.path) { + options.qs = _.first([ options.qs, args[2], args[1], args[0] ].filter(_.isPlainObject)); } - doCallback(callback, [ err, data, data.params.permission ], self); - }); -}; - -Usergrid.Entity.prototype.getPermissions = function(callback) { - var self = this; - var endpoint = this.get("type") + "/" + this.get("uuid") + "/permissions"; - var options = { - method: "GET", - endpoint: endpoint + return options; }; - this._client.request(options, function(err, data) { - if (err && self._client.logging) { - console.log("could not get user permissions"); - } - var permissions = []; - if (data.data) { - var perms = data.data; - var count = 0; - for (var i in perms) { - count++; - var perm = perms[i]; - var parts = perm.split(":"); - var ops_part = ""; - var path_part = parts[0]; - if (parts.length > 1) { - ops_part = parts[0]; - path_part = parts[1]; - } - ops_part = ops_part.replace("*", "get,post,put,delete"); - var ops = ops_part.split(","); - var ops_object = {}; - ops_object.get = "no"; - ops_object.post = "no"; - ops_object.put = "no"; - ops_object.delete = "no"; - for (var j in ops) { - ops_object[ops[j]] = "yes"; - } - permissions.push({ - operations: ops_object, - path: path_part, - perm: perm + UsergridHelpers.setQuery = function(options, args) { + options.query = _.first([ options, options.query, args[0] ].filter(function(property) { + return property instanceof UsergridQuery; + })); + return options; + }; + UsergridHelpers.setAsset = function(options, args) { + options.asset = _.first([ options.asset, _.get(options, "entity.asset"), args[1], args[0] ].filter(function(property) { + return property instanceof UsergridAsset; + })); + return options; + }; + UsergridHelpers.setBody = function(options, args) { + var body = _.first([ args.entity, args.body, args[0].entity, args[0].body, args[2], args[1], args[0] ].filter(function(property) { + return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery) && !(property instanceof UsergridAsset); + })); + if (body instanceof UsergridEntity) { + body = body.jsonValue(); + } else if (_.isArray(body)) { + if (body[0] instanceof UsergridEntity) { + body = _.map(body, function(entity) { + return entity.jsonValue(); }); } } - self.permissions = permissions; - doCallback(callback, [ err, data, data.entities ], self); - }); -}; - -/* - * The Collection class models Usergrid Collections. It essentially - * acts as a container for holding Entity objects, while providing - * additional funcitonality such as paging, and saving - * - * @constructor - * @param {string} options - configuration object - * @return {Collection} collection - */ -Usergrid.Collection = function(options) { - if (options) { - this._client = options.client; - this._type = options.type; - this.qs = options.qs || {}; - this._list = options.list || []; - this._iterator = options.iterator || -1; - this._previous = options.previous || []; - this._next = options.next || null; - this._cursor = options.cursor || null; - if (options.list) { - var count = options.list.length; - for (var i = 0; i < count; i++) { - var entity = this._client.restoreEntity(options.list[i]); - this._list[i] = entity; + options.body = body; + return options; + }; + UsergridHelpers.buildRequest = function(client, method, args) { + var options = { + client: client, + method: method, + queryParams: args.queryParams || _.get(args, "0.queryParams"), + callback: UsergridHelpers.callback(args) + }; + UsergridHelpers.assignPrefabOptions(options, args); + UsergridHelpers.setEntity(options, args); + if (method === UsergridHttpMethod.POST || method === UsergridHttpMethod.PUT) { + UsergridHelpers.setAsset(options, args); + if (!options.asset) { + UsergridHelpers.setBody(options, args); + if (!options.body) { + throw new Error("'body' is required when making a " + options.method + " request"); + } } } - } -}; - -/* - * method to determine whether or not the passed variable is a Usergrid Collection - * - * @method isCollection - * @public - * @params {any} obj - any variable - * @return {boolean} Returns true or false - */ -Usergrid.isCollection = function(obj) { - return obj && obj instanceof Usergrid.Collection; -}; - -/* - * gets the data from the collection object for serialization - * - * @method serialize - * @return {object} data - */ -Usergrid.Collection.prototype.serialize = function() { - var data = {}; - data.type = this._type; - data.qs = this.qs; - data.iterator = this._iterator; - data.previous = this._previous; - data.next = this._next; - data.cursor = this._cursor; - this.resetEntityPointer(); - var i = 0; - data.list = []; - while (this.hasNextEntity()) { - var entity = this.getNextEntity(); - data.list[i] = entity.serialize(); - i++; - } - data = JSON.stringify(data); - return data; -}; - -/*Usergrid.Collection.prototype.addCollection = function (collectionName, options, callback) { - self = this; - options.client = this._client; - var collection = new Usergrid.Collection(options, function(err, data) { - if (typeof(callback) === 'function') { - - collection.resetEntityPointer(); - while(collection.hasNextEntity()) { - var user = collection.getNextEntity(); - var email = user.get('email'); - var image = self._client.getDisplayImage(user.get('email'), user.get('picture')); - user._portal_image_icon = image; - } - - self[collectionName] = collection; - doCallback(callback, [err, collection], self); - } - }); -};*/ -/* - * Populates the collection from the server - * - * @method fetch - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.fetch = function(callback) { - var self = this; - var qs = this.qs; - if (this._cursor) { - qs.cursor = this._cursor; - } else { - delete qs.cursor; - } - var options = { - method: "GET", - endpoint: this._type, - qs: this.qs + UsergridHelpers.setUuidOrName(options, args); + UsergridHelpers.setPathOrType(options, args); + UsergridHelpers.setQs(options, args); + UsergridHelpers.setQuery(options, args); + options.uri = UsergridHelpers.uri(client, options); + return new UsergridRequest(options); }; - this._client.request(options, function(err, response) { - if (err && self._client.logging) { - console.log("error getting collection"); - } else { - self.saveCursor(response.cursor || null); - self.resetEntityPointer(); - self._list = response.getEntities().filter(function(entity) { - return isUUID(entity.uuid); - }).map(function(entity) { - var ent = new Usergrid.Entity({ - client: self._client - }); - ent.set(entity); - ent.type = self._type; - return ent; - }); + UsergridHelpers.buildAppAuthRequest = function(client, auth, callback) { + var requestOptions = { + client: client, + method: UsergridHttpMethod.POST, + uri: UsergridHelpers.uri(client, { + path: "token" + }), + body: UsergridHelpers.appLoginBody(auth), + callback: callback + }; + return new UsergridRequest(requestOptions); + }; + UsergridHelpers.buildConnectionRequest = function(client, method, args) { + var options = { + client: client, + method: method, + entity: {}, + to: {}, + callback: UsergridHelpers.callback(args) + }; + UsergridHelpers.assignPrefabOptions.call(options, args); + if (_.isObject(options.from)) { + options.to = options.from; } - doCallback(callback, [ err, response, self ], self); - }); -}; - -/* - * Adds a new Entity to the collection (saves, then adds to the local object) - * - * @method addNewEntity - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data, entity) - */ -Usergrid.Collection.prototype.addEntity = function(entityObject, callback) { - var self = this; - entityObject.type = this._type; - this._client.createEntity(entityObject, function(err, response, entity) { - if (!err) { - self.addExistingEntity(entity); + if (_.isObject(args[0]) && _.has(args[0], "entity") && _.has(args[0], "to")) { + _.assign(options.entity, args[0].entity); + options.relationship = _.get(args, "0.relationship"); + _.assign(options.to, args[0].to); } - doCallback(callback, [ err, response, self ], self); - }); -}; - -Usergrid.Collection.prototype.addExistingEntity = function(entity) { - var count = this._list.length; - this._list[count] = entity; -}; - -/* - * Removes the Entity from the collection, then destroys the object on the server - * - * @method destroyEntity - * @param {object} entity - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.destroyEntity = function(entity, callback) { - var self = this; - entity.destroy(function(err, response) { - if (err) { - if (self._client.logging) { - console.log("could not destroy entity"); - } - doCallback(callback, [ err, response, self ], self); - } else { - self.fetch(callback); + if (_.isObject(args[0]) && !_.isFunction(args[0]) && _.isString(args[1])) { + _.assign(options.entity, args[0]); + options.relationship = _.first([ options.relationship, args[1] ].filter(_.isString)); } - self.removeEntity(entity); - }); -}; - -/* - * Filters the list of entities based on the supplied criteria function - * works like Array.prototype.filter - * - * @method getEntitiesByCriteria - * @param {function} criteria A function that takes each entity as an argument and returns true or false - * @return {Entity[]} returns a list of entities that caused the criteria function to return true - */ -Usergrid.Collection.prototype.getEntitiesByCriteria = function(criteria) { - return this._list.filter(criteria); -}; - -/* - * Returns the first entity from the list of entities based on the supplied criteria function - * works like Array.prototype.filter - * - * @method getEntitiesByCriteria - * @param {function} criteria A function that takes each entity as an argument and returns true or false - * @return {Entity[]} returns a list of entities that caused the criteria function to return true - */ -Usergrid.Collection.prototype.getEntityByCriteria = function(criteria) { - return this.getEntitiesByCriteria(criteria).shift(); -}; - -/* - * Removed an entity from the collection without destroying it on the server - * - * @method removeEntity - * @param {object} entity - * @return {Entity} returns the removed entity or undefined if it was not found - */ -Usergrid.Collection.prototype.removeEntity = function(entity) { - var removedEntity = this.getEntityByCriteria(function(item) { - return entity.uuid === item.get("uuid"); - }); - delete this._list[this._list.indexOf(removedEntity)]; - return removedEntity; -}; - -/* - * Looks up an Entity by UUID - * - * @method getEntityByUUID - * @param {string} UUID - * @param {function} callback - * @return {callback} callback(err, data, entity) - */ -Usergrid.Collection.prototype.getEntityByUUID = function(uuid, callback) { - var entity = this.getEntityByCriteria(function(item) { - return item.get("uuid") === uuid; - }); - if (entity) { - doCallback(callback, [ null, entity, entity ], this); - } else { + if (_.isObject(args[2]) && !_.isFunction(args[2])) { + _.assign(options.to, args[2]); + } + options.entity.uuidOrName = _.first([ options.entity.uuidOrName, options.entity.uuid, options.entity.name, args[1] ].filter(_.isString)); + if (!options.entity.type) { + options.entity.type = _.first([ options.entity.type, args[0] ].filter(_.isString)); + } + options.relationship = _.first([ options.relationship, args[2] ].filter(_.isString)); + if (_.isString(args[3]) && !UsergridHelpers.isUUID(args[3]) && _.isString(args[4])) { + options.to.type = args[3]; + } else if (_.isString(args[2]) && !UsergridHelpers.isUUID(args[2]) && _.isString(args[3]) && _.isObject(args[0]) && !_.isFunction(args[0])) { + options.to.type = args[2]; + } + options.to.uuidOrName = _.first([ options.to.uuidOrName, options.to.uuid, options.to.name, args[4], args[3], args[2] ].filter(function(property) { + return _.isString(options.to.type) && _.isString(property) || UsergridHelpers.isUUID(property); + })); + if (!_.isString(options.entity.uuidOrName)) { + throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities"); + } + if (!_.isString(options.to.uuidOrName)) { + throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities"); + } + if (!_.isString(options.to.type) && !UsergridHelpers.isUUID(options.to.uuidOrName)) { + throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name"); + } + options.uri = UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, _.isString(options.entity.type) ? options.entity.type : "", _.isString(options.entity.uuidOrName) ? options.entity.uuidOrName : "", options.relationship, _.isString(options.to.type) ? options.to.type : "", _.isString(options.to.uuidOrName) ? options.to.uuidOrName : ""); + return new UsergridRequest(options); + }; + UsergridHelpers.buildGetConnectionRequest = function(client, args) { var options = { - data: { - type: this._type, - uuid: uuid - }, - client: this._client + client: client, + method: "GET", + callback: UsergridHelpers.callback(args) }; - entity = new Usergrid.Entity(options); - entity.fetch(callback); - } -}; + UsergridHelpers.assignPrefabOptions.call(options, args); + if (_.isObject(args[1]) && !_.isFunction(args[1])) { + _.assign(options, args[1]); + } + options.direction = _.first([ options.direction, args[0] ].filter(function(property) { + return property === UsergridDirection.IN || property === UsergridDirection.OUT; + })); + options.relationship = _.first([ options.relationship, args[3], args[2] ].filter(_.isString)); + options.uuidOrName = _.first([ options.uuidOrName, options.uuid, options.name, args[2] ].filter(_.isString)); + options.type = _.first([ options.type, args[1] ].filter(_.isString)); + if (!_.isString(options.type)) { + throw new Error("'type' (collection name) parameter is required when retrieving connections"); + } + if (!_.isString(options.uuidOrName)) { + throw new Error("target entity 'uuidOrName' is required when retrieving connections"); + } + options.uri = UsergridHelpers.urljoin(client.baseUrl, client.orgId, client.appId, _.isString(options.type) ? options.type : "", _.isString(options.uuidOrName) ? options.uuidOrName : "", options.direction, options.relationship); + return new UsergridRequest(options); + }; + global[name] = UsergridHelpers; + global[name].noConflict = function() { + if (overwrittenName) { + global[name] = overwrittenName; + } + return UsergridHelpers; + }; + return global[name]; +})(this); -/* - * Returns the first Entity of the Entity list - does not affect the iterator - * - * @method getFirstEntity - * @return {object} returns an entity object - */ -Usergrid.Collection.prototype.getFirstEntity = function() { - var count = this._list.length; - if (count > 0) { - return this._list[0]; - } - return null; -}; +"use strict"; -/* - * Returns the last Entity of the Entity list - does not affect the iterator - * - * @method getLastEntity - * @return {object} returns an entity object - */ -Usergrid.Collection.prototype.getLastEntity = function() { - var count = this._list.length; - if (count > 0) { - return this._list[count - 1]; - } - return null; +var UsergridClientDefaultOptions = { + baseUrl: "https://api.usergrid.com", + authMode: UsergridAuthMode.USER }; -/* - * Entity iteration -Checks to see if there is a "next" entity - * in the list. The first time this method is called on an entity - * list, or after the resetEntityPointer method is called, it will - * return true referencing the first entity in the list - * - * @method hasNextEntity - * @return {boolean} true if there is a next entity, false if not - */ -Usergrid.Collection.prototype.hasNextEntity = function() { - var next = this._iterator + 1; - var hasNextElement = next >= 0 && next < this._list.length; - if (hasNextElement) { - return true; +var UsergridClient = function(options) { + var self = this; + var __appAuth; + self.tempAuth = undefined; + self.isSharedInstance = false; + if (arguments.length === 2) { + self.orgId = arguments[0]; + self.appId = arguments[1]; } - return false; -}; - -/* - * Entity iteration - Gets the "next" entity in the list. The first - * time this method is called on an entity list, or after the method - * resetEntityPointer is called, it will return the, - * first entity in the list - * - * @method hasNextEntity - * @return {object} entity - */ -Usergrid.Collection.prototype.getNextEntity = function() { - this._iterator++; - var hasNextElement = this._iterator >= 0 && this._iterator <= this._list.length; - if (hasNextElement) { - return this._list[this._iterator]; + _.defaults(self, options, UsergridClientDefaultOptions); + if (!self.orgId || !self.appId) { + throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient"); } - return false; -}; - -/* - * Entity iteration - Checks to see if there is a "previous" - * entity in the list. - * - * @method hasPrevEntity - * @return {boolean} true if there is a previous entity, false if not - */ -Usergrid.Collection.prototype.hasPrevEntity = function() { - var previous = this._iterator - 1; - var hasPreviousElement = previous >= 0 && previous < this._list.length; - if (hasPreviousElement) { - return true; + Object.defineProperty(self, "clientId", { + enumerable: false + }); + Object.defineProperty(self, "clientSecret", { + enumerable: false + }); + Object.defineProperty(self, "appAuth", { + get: function() { + return __appAuth; + }, + set: function(options) { + if (options instanceof UsergridAppAuth) { + __appAuth = options; + } else if (typeof options !== "undefined") { + __appAuth = new UsergridAppAuth(options); + } + } + }); + if (self.clientId && self.clientSecret) { + self.setAppAuth(self.clientId, self.clientSecret); } - return false; + return self; }; -/* - * Entity iteration - Gets the "previous" entity in the list. - * - * @method getPrevEntity - * @return {object} entity - */ -Usergrid.Collection.prototype.getPrevEntity = function() { - this._iterator--; - var hasPreviousElement = this._iterator >= 0 && this._iterator <= this._list.length; - if (hasPreviousElement) { - return this._list[this._iterator]; +UsergridClient.prototype = { + sendRequest: function(usergridRequest) { + return usergridRequest.sendRequest(); + }, + GET: function() { + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + PUT: function() { + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + POST: function() { + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + DELETE: function() { + var usergridRequest = UsergridHelpers.buildRequest(this, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + connect: function() { + var usergridRequest = UsergridHelpers.buildConnectionRequest(this, UsergridHttpMethod.POST, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + disconnect: function() { + var usergridRequest = UsergridHelpers.buildConnectionRequest(this, UsergridHttpMethod.DELETE, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + getConnections: function() { + var usergridRequest = UsergridHelpers.buildGetConnectionRequest(this, UsergridHelpers.flattenArgs(arguments)); + return this.sendRequest(usergridRequest); + }, + usingAuth: function(auth) { + var self = this; + if (_.isString(auth)) { + self.tempAuth = new UsergridAuth(auth); + } else if (auth instanceof UsergridAuth) { + self.tempAuth = auth; + } else { + self.tempAuth = undefined; + } + return self; + }, + setAppAuth: function() { + this.appAuth = new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments)); + }, + authenticateApp: function(options) { + var self = this; + var authenticateAppCallback = UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)); + var auth = _.first([ options, self.appAuth, new UsergridAppAuth(options), new UsergridAppAuth(self.clientId, self.clientSecret) ].filter(function(p) { + return p instanceof UsergridAppAuth; + })); + if (!(auth instanceof UsergridAppAuth)) { + throw new Error("App auth context was not defined when attempting to call .authenticateApp()"); + } else if (!auth.clientId || !auth.clientSecret) { + throw new Error("authenticateApp() failed because clientId or clientSecret are missing"); + } + var callback = function(error, usergridResponse) { + var token = _.get(usergridResponse.responseJSON, "access_token"); + var expiresIn = _.get(usergridResponse.responseJSON, "expires_in"); + if (usergridResponse.ok) { + if (!self.appAuth) { + self.appAuth = auth; + } + self.appAuth.token = token; + self.appAuth.expiry = UsergridHelpers.calculateExpiry(expiresIn); + self.appAuth.tokenTtl = expiresIn; + } + authenticateAppCallback(error, usergridResponse, token); + }; + var usergridRequest = UsergridHelpers.buildAppAuthRequest(self, auth, callback); + return self.sendRequest(usergridRequest); + }, + authenticateUser: function(options) { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var setAsCurrentUser = _.last(args.filter(_.isBoolean)) !== undefined ? _.last(args.filter(_.isBoolean)) : true; + var userToAuthenticate = new UsergridUser(options); + userToAuthenticate.login(self, function(error, usergridResponse, token) { + if (usergridResponse.ok && setAsCurrentUser) { + self.currentUser = userToAuthenticate; + } + callback(usergridResponse.error, usergridResponse, token); + }); + }, + downloadAsset: function() { + var self = this; + var usergridRequest = UsergridHelpers.buildRequest(self, UsergridHttpMethod.GET, UsergridHelpers.flattenArgs(arguments)); + var assetContentType = _.get(usergridRequest, "entity.file-metadata.content-type"); + if (assetContentType !== undefined) { + _.assign(usergridRequest.headers, { + Accept: assetContentType + }); + } + var realDownloadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function(error, usergridResponse) { + var entity = usergridRequest.entity; + entity.asset = usergridResponse.asset; + realDownloadAssetCallback(error, usergridResponse, entity); + }; + return self.sendRequest(usergridRequest); + }, + uploadAsset: function() { + var self = this; + var usergridRequest = UsergridHelpers.buildRequest(self, UsergridHttpMethod.PUT, UsergridHelpers.flattenArgs(arguments)); + if (usergridRequest.asset === undefined) { + throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()"); + } + var realUploadAssetCallback = usergridRequest.callback; + usergridRequest.callback = function(error, usergridResponse) { + var requestEntity = usergridRequest.entity; + var responseEntity = usergridResponse.entity; + var requestAsset = usergridRequest.asset; + if (usergridResponse.ok && responseEntity !== undefined) { + UsergridHelpers.updateEntityFromRemote(requestEntity, usergridResponse); + requestEntity.asset = requestAsset; + if (responseEntity) { + responseEntity.asset = requestAsset; + } + } + realUploadAssetCallback(error, usergridResponse, requestEntity); + }; + return self.sendRequest(usergridRequest); } - return false; -}; - -/* - * Entity iteration - Resets the iterator back to the beginning - * of the list - * - * @method resetEntityPointer - * @return none - */ -Usergrid.Collection.prototype.resetEntityPointer = function() { - this._iterator = -1; }; -/* - * Method to save off the cursor just returned by the last API call - * - * @public - * @method saveCursor - * @return none - */ -Usergrid.Collection.prototype.saveCursor = function(cursor) { - if (this._next !== cursor) { - this._next = cursor; - } -}; +"use strict"; -/* - * Resets the paging pointer (back to original page) - * - * @public - * @method resetPaging - * @return none - */ -Usergrid.Collection.prototype.resetPaging = function() { - this._previous = []; - this._next = null; - this._cursor = null; -}; +var UsergridSDKVersion = "2.0.0"; -/* - * Paging - checks to see if there is a next page od data - * - * @method hasNextPage - * @return {boolean} returns true if there is a next page of data, false otherwise - */ -Usergrid.Collection.prototype.hasNextPage = function() { - return this._next; +var UsergridClientSharedInstance = function() { + var self = this; + self.isInitialized = false; + self.isSharedInstance = true; + return self; }; -/* - * Paging - advances the cursor and gets the next - * page of data from the API. Stores returned entities - * in the Entity list. - * - * @method getNextPage - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.getNextPage = function(callback) { - if (this.hasNextPage()) { - this._previous.push(this._cursor); - this._cursor = this._next; - this._list = []; - this.fetch(callback); - } -}; +UsergridHelpers.inherits(UsergridClientSharedInstance, UsergridClient); -/* - * Paging - checks to see if there is a previous page od data - * - * @method hasPreviousPage - * @return {boolean} returns true if there is a previous page of data, false otherwise - */ -Usergrid.Collection.prototype.hasPreviousPage = function() { - return this._previous.length > 0; -}; +var Usergrid = new UsergridClientSharedInstance(); -/* - * Paging - reverts the cursor and gets the previous - * page of data from the API. Stores returned entities - * in the Entity list. - * - * @method getPreviousPage - * @param {function} callback - * @return {callback} callback(err, data) - */ -Usergrid.Collection.prototype.getPreviousPage = function(callback) { - if (this.hasPreviousPage()) { - this._next = null; - this._cursor = this._previous.pop(); - this._list = []; - this.fetch(callback); +Usergrid.initSharedInstance = function(options) { + if (Usergrid.isInitialized) { + console.log("Usergrid shared instance is already initialized"); + } else { + _.assign(Usergrid, new UsergridClient(options)); + Usergrid.isInitialized = true; + Usergrid.isSharedInstance = true; } + return Usergrid; }; -/* - * A class to model a Usergrid group. - * Set the path in the options object. - * - * @constructor - * @param {object} options {client:client, data: {'key': 'value'}, path:'path'} - */ -Usergrid.Group = function(options, callback) { - this._path = options.path; - this._list = []; - this._client = options.client; - this._data = options.data || {}; - this._data.type = "groups"; -}; +Usergrid.init = Usergrid.initSharedInstance; -/* - * Inherit from Usergrid.Entity. - * Note: This only accounts for data on the group object itself. - * You need to use add and remove to manipulate group membership. - */ -Usergrid.Group.prototype = new Usergrid.Entity(); +"use strict"; -/* - * Fetches current group data, and members. - * - * @method fetch - * @public - * @param {function} callback - * @returns {function} callback(err, data) - */ -Usergrid.Group.prototype.fetch = function(callback) { +var UsergridQuery = function(type) { var self = this; - var groupEndpoint = "groups/" + this._path; - var memberEndpoint = "groups/" + this._path + "/users"; - var groupOptions = { - method: "GET", - endpoint: groupEndpoint - }; - var memberOptions = { - method: "GET", - endpoint: memberEndpoint - }; - this._client.request(groupOptions, function(err, response) { - if (err) { - if (self._client.logging) { - console.log("error getting group"); + var query = "", queryString, sort, urlTerms = {}, __nextIsNot = false; + self._type = type; + _.assign(self, { + type: function(value) { + self._type = value; + return self; + }, + collection: function(value) { + self._type = value; + return self; + }, + limit: function(value) { + self._limit = value; + return self; + }, + cursor: function(value) { + self._cursor = value; + return self; + }, + eq: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.EQUAL + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + equal: this.eq, + gt: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.GREATER_THAN + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + greaterThan: this.gt, + gte: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.GREATER_THAN_EQUAL_TO + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + greaterThanOrEqual: this.gte, + lt: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.LESS_THAN + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + lessThan: this.lt, + lte: function(key, value) { + query = self.andJoin(key + " " + UsergridQueryOperator.LESS_THAN_EQUAL_TO + " " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + lessThanOrEqual: this.lte, + contains: function(key, value) { + query = self.andJoin(key + " contains " + UsergridHelpers.useQuotesIfRequired(value)); + return self; + }, + locationWithin: function(distanceInMeters, lat, lng) { + query = self.andJoin("location within " + distanceInMeters + " of " + lat + ", " + lng); + return self; + }, + asc: function(key) { + self.sort(key, UsergridQuerySortOrder.ASC); + return self; + }, + desc: function(key) { + self.sort(key, UsergridQuerySortOrder.DESC); + return self; + }, + sort: function(key, order) { + sort = key && order ? " order by " + key + " " + order : ""; + return self; + }, + fromString: function(string) { + queryString = string; + return self; + }, + urlTerm: function(key, value) { + if (key === "ql") { + self.fromString(); + } else { + urlTerms[key] = value; } - doCallback(callback, [ err, response ], self); - } else { - var entities = response.getEntities(); - if (entities && entities.length) { - var groupresponse = entities.shift(); - self._client.request(memberOptions, function(err, response) { - if (err && self._client.logging) { - console.log("error getting group users"); - } else { - self._list = response.getEntities().filter(function(entity) { - return isUUID(entity.uuid); - }).map(function(entity) { - return new Usergrid.Entity({ - type: entity.type, - client: self._client, - uuid: entity.uuid, - response: entity - }); - }); - } - doCallback(callback, [ err, response, self ], self); - }); + return self; + }, + andJoin: function(append) { + if (__nextIsNot) { + append = "not " + append; + __nextIsNot = false; + } + if (!append) { + return query; + } else if (query.length === 0) { + return append; + } else { + return _.endsWith(query, "and") || _.endsWith(query, "or") ? query + " " + append : query + " and " + append; + } + }, + orJoin: function() { + return query.length > 0 && !_.endsWith(query, "or") ? query + " or" : query; + } + }); + Object.defineProperty(self, "_ql", { + get: function() { + var ql = "select * "; + if (queryString !== undefined) { + ql = queryString; + } else { + ql += query.length > 0 ? "where " + (query || "") : ""; + ql += sort !== undefined ? sort : ""; + } + return ql; + } + }); + Object.defineProperty(self, "encodedStringValue", { + get: function() { + var self = this; + var limit = self._limit; + var cursor = self._cursor; + var requirementsString = self._ql; + var returnString = undefined; + if (limit !== undefined) { + returnString = "limit" + UsergridQueryOperator.EQUAL + limit; + } + if (!_.isEmpty(cursor)) { + var cursorString = "cursor" + UsergridQueryOperator.EQUAL + cursor; + if (_.isEmpty(returnString)) { + returnString = cursorString; + } else { + returnString += "&" + cursorString; + } + } + _.forEach(urlTerms, function(value, key) { + var encodedURLTermString = encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); + if (_.isEmpty(returnString)) { + returnString = encodedURLTermString; + } else { + returnString += "&" + encodedURLTermString; + } + }); + if (!_.isEmpty(requirementsString)) { + var qLString = "ql=" + encodeURIComponent(requirementsString); + if (_.isEmpty(returnString)) { + returnString = qLString; + } else { + returnString += "&" + qLString; + } + } + if (!_.isEmpty(returnString)) { + returnString = "?" + returnString; } + return !_.isEmpty(returnString) ? returnString : undefined; + } + }); + Object.defineProperty(self, "and", { + get: function() { + query = self.andJoin(""); + return self; + } + }); + Object.defineProperty(self, "or", { + get: function() { + query = self.orJoin(); + return self; } }); + Object.defineProperty(self, "not", { + get: function() { + __nextIsNot = true; + return self; + } + }); + return self; }; -/* - * Retrieves the members of a group. - * - * @method members - * @public - * @param {function} callback - * @return {function} callback(err, data); - */ -Usergrid.Group.prototype.members = function(callback) { - return this._list; -}; +"use strict"; -/* - * Adds an existing user to the group, and refreshes the group object. - * - * Options object: {user: user_entity} - * - * @method add - * @public - * @params {object} options - * @param {function} callback - * @return {function} callback(err, data) - */ -Usergrid.Group.prototype.add = function(options, callback) { +var UsergridRequest = function(options) { var self = this; - if (options.user) { - options = { - method: "POST", - endpoint: "groups/" + this._path + "/users/" + options.user.get("username") - }; - this._client.request(options, function(error, response) { - if (error) { - doCallback(callback, [ error, response, self ], self); - } else { - self.fetch(callback); - } + var client = UsergridHelpers.validateAndRetrieveClient(options); + if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) { + throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest"); + } + if (!_.includes([ "GET", "PUT", "POST", "DELETE" ], options.method)) { + throw new Error("'method' parameter is required when initializing a UsergridRequest"); + } + self.method = options.method; + self.callback = options.callback; + self.uri = options.uri || UsergridHelpers.uri(client, options); + self.entity = options.entity; + self.body = options.body; + self.asset = options.asset; + self.query = options.query; + self.queryParams = options.queryParams || options.qs; + var defaultHeadersToUse = !self.asset ? UsergridHelpers.DefaultHeaders : {}; + self.headers = UsergridHelpers.headers(client, options, defaultHeadersToUse); + if (self.query !== undefined) { + self.uri += UsergridHelpers.normalize(self.query.encodedStringValue, {}); + } + if (self.queryParams) { + _.forOwn(self.queryParams, function(value, key) { + self.uri += "?" + encodeURIComponent(key) + UsergridQueryOperator.EQUAL + encodeURIComponent(value); }); + self.uri = UsergridHelpers.normalize(self.uri, {}); + } + if (self.asset) { + self.body = new FormData(); + self.body.append(self.asset.filename, self.asset.data); } else { - doCallback(callback, [ new UsergridError("no user specified", "no_user_specified"), null, this ], this); + try { + if (_.isPlainObject(self.body)) { + self.body = JSON.stringify(self.body); + } else if (_.isArray(self.body)) { + self.body = JSON.stringify(self.body); + } + } catch (exception) { + console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: " + exception); + } } + return self; }; -/* - * Removes a user from a group, and refreshes the group object. - * - * Options object: {user: user_entity} - * - * @method remove - * @public - * @params {object} options - * @param {function} callback - * @return {function} callback(err, data) - */ -Usergrid.Group.prototype.remove = function(options, callback) { +UsergridRequest.prototype.sendRequest = function() { var self = this; - if (options.user) { - options = { - method: "DELETE", - endpoint: "groups/" + this._path + "/users/" + options.user.username + var requestPromise = function() { + var promise = new Promise(); + var xmlHttpRequest = new XMLHttpRequest(); + xmlHttpRequest.open(self.method, self.uri, true); + xmlHttpRequest.onload = function() { + promise.done(xmlHttpRequest); }; - this._client.request(options, function(error, response) { - if (error) { - doCallback(callback, [ error, response, self ], self); - } else { - self.fetch(callback); - } + _.forOwn(self.headers, function(value, key) { + xmlHttpRequest.setRequestHeader(key, value); }); - } else { - doCallback(callback, [ new UsergridError("no user specified", "no_user_specified"), null, this ], this); - } -}; - -/* - * Gets feed for a group. - * - * @public - * @method feed - * @param {function} callback - * @returns {callback} callback(err, data, activities) - */ -Usergrid.Group.prototype.feed = function(callback) { - var self = this; - var options = { - method: "GET", - endpoint: "groups/" + this._path + "/feed" + if (self.method === UsergridHttpMethod.GET && _.get(self.headers, "Accept") !== UsergridApplicationJSONHeaderValue) { + xmlHttpRequest.responseType = "blob"; + } + xmlHttpRequest.send(self.body); + return promise; }; - this._client.request(options, function(err, response) { - doCallback(callback, [ err, response, self ], self); - }); + var responsePromise = function(xmlRequest) { + var promise = new Promise(); + var usergridResponse = new UsergridResponse(xmlRequest, self); + promise.done(usergridResponse); + return promise; + }; + var onCompletePromise = function(usergridResponse) { + self.callback(usergridResponse.error, usergridResponse); + }; + Promise.chain([ requestPromise, responsePromise ]).then(onCompletePromise); + return self; }; -/* - * Creates activity and posts to group feed. - * - * options object: {user: user_entity, content: "activity content"} - * - * @public - * @method createGroupActivity - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, entity) - */ -Usergrid.Group.prototype.createGroupActivity = function(options, callback) { +"use strict"; + +var UsergridAuth = function(token, expiry) { var self = this; - var user = options.user; - var entity = new Usergrid.Entity({ - client: this._client, - data: { - actor: { - displayName: user.get("username"), - uuid: user.get("uuid"), - username: user.get("username"), - email: user.get("email"), - picture: user.get("picture"), - image: { - duration: 0, - height: 80, - url: user.get("picture"), - width: 80 - } - }, - verb: "post", - content: options.content, - type: "groups/" + this._path + "/activities" - } + self.token = token; + self.expiry = expiry || 0; + var usingToken = token ? true : false; + Object.defineProperty(self, "hasToken", { + get: function() { + return self.token !== undefined; + }, + configurable: true }); - entity.save(function(err, response, entity) { - doCallback(callback, [ err, response, self ]); + Object.defineProperty(self, "isExpired", { + get: function() { + return usingToken ? false : Date.now() >= self.expiry; + }, + configurable: true }); + Object.defineProperty(self, "isValid", { + get: function() { + return !self.isExpired && self.hasToken; + }, + configurable: true + }); + Object.defineProperty(self, "tokenTtl", { + configurable: true, + writable: true + }); + _.assign(self, { + destroy: function() { + self.token = undefined; + self.expiry = 0; + self.tokenTtl = undefined; + } + }); + return self; }; -/* - * A class to model a Usergrid event. - * - * @constructor - * @param {object} options {timestamp:0, category:'value', counters:{name : value}} - * @returns {callback} callback(err, event) - */ -Usergrid.Counter = function(options) { - this._client = options.client; - this._data = options.data || {}; - this._data.category = options.category || "UNKNOWN"; - this._data.timestamp = options.timestamp || 0; - this._data.type = "events"; - this._data.counters = options.counters || {}; -}; - -var COUNTER_RESOLUTIONS = [ "all", "minute", "five_minutes", "half_hour", "hour", "six_day", "day", "week", "month" ]; - -/* - * Inherit from Usergrid.Entity. - * Note: This only accounts for data on the group object itself. - * You need to use add and remove to manipulate group membership. - */ -Usergrid.Counter.prototype = new Usergrid.Entity(); - -/* - * overrides Entity.prototype.fetch. Returns all data for counters - * associated with the object as specified in the constructor - * - * @public - * @method increment - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.fetch = function(callback) { - this.getData({}, callback); -}; - -/* - * increments the counter for a specific event - * - * options object: {name: counter_name} - * - * @public - * @method increment - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.increment = function(options, callback) { - var self = this, name = options.name, value = options.value; - if (!name) { - return doCallback(callback, [ new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"), null, self ], self); - } else if (isNaN(value)) { - return doCallback(callback, [ new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"), null, self ], self); +var UsergridAppAuth = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + if (_.isPlainObject(args[0])) { + self.clientId = args[0].clientId; + self.clientSecret = args[0].clientSecret; + self.tokenTtl = args[0].tokenTtl; } else { - self._data.counters[name] = parseInt(value) || 1; - return self.save(callback); + self.clientId = args[0]; + self.clientSecret = args[1]; + self.tokenTtl = args[2]; } + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; }; -/* - * decrements the counter for a specific event - * - * options object: {name: counter_name} - * - * @public - * @method decrement - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.decrement = function(options, callback) { - var self = this, name = options.name, value = options.value; - self.increment({ - name: name, - value: -(parseInt(value) || 1) - }, callback); -}; - -/* - * resets the counter for a specific event - * - * options object: {name: counter_name} - * - * @public - * @method reset - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.reset = function(options, callback) { - var self = this, name = options.name; - self.increment({ - name: name, - value: 0 - }, callback); -}; +UsergridHelpers.inherits(UsergridAppAuth, UsergridAuth); -/* - * gets data for one or more counters over a given - * time period at a specified resolution - * - * options object: { - * counters: ['counter1', 'counter2', ...], - * start: epoch timestamp or ISO date string, - * end: epoch timestamp or ISO date string, - * resolution: one of ('all', 'minute', 'five_minutes', 'half_hour', 'hour', 'six_day', 'day', 'week', or 'month') - * } - * - * @public - * @method getData - * @params {object} options - * @param {function} callback - * @returns {callback} callback(err, event) - */ -Usergrid.Counter.prototype.getData = function(options, callback) { - var start_time, end_time, start = options.start || 0, end = options.end || Date.now(), resolution = (options.resolution || "all").toLowerCase(), counters = options.counters || Object.keys(this._data.counters), res = (resolution || "all").toLowerCase(); - if (COUNTER_RESOLUTIONS.indexOf(res) === -1) { - res = "all"; - } - start_time = getSafeTime(start); - end_time = getSafeTime(end); +var UsergridUserAuth = function(options) { var self = this; - var params = Object.keys(counters).map(function(counter) { - return [ "counter", encodeURIComponent(counters[counter]) ].join("="); - }); - params.push("resolution=" + res); - params.push("start_time=" + String(start_time)); - params.push("end_time=" + String(end_time)); - var endpoint = "counters?" + params.join("&"); - this._client.request({ - endpoint: endpoint - }, function(err, data) { - if (data.counters && data.counters.length) { - data.counters.forEach(function(counter) { - self._data.counters[counter.name] = counter.value || counter.values; - }); - } - return doCallback(callback, [ err, data, self ], self); - }); + var args = _.flattenDeep(UsergridHelpers.flattenArgs(arguments)); + if (_.isPlainObject(args[0])) { + options = args[0]; + } + self.username = options.username || args[0]; + self.email = options.email; + if (options.password || args[1]) { + self.password = options.password || args[1]; + } + self.tokenTtl = options.tokenTtl || args[2]; + UsergridAuth.call(self); + _.assign(self, UsergridAuth); + return self; }; -function getSafeTime(prop) { - var time; - switch (typeof prop) { - case "undefined": - time = Date.now(); - break; - - case "number": - time = prop; - break; +UsergridHelpers.inherits(UsergridUserAuth, UsergridAuth); - case "string": - time = isNaN(prop) ? Date.parse(prop) : parseInt(prop); - break; +"use strict"; - default: - time = Date.parse(prop.toString()); +var UsergridEntity = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + if (args.length === 0) { + throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments"); } - return time; -} - -/* - * A class to model a Usergrid folder. - * - * @constructor - * @param {object} options {name:"MyPhotos", path:"/user/uploads", owner:"00000000-0000-0000-0000-000000000000" } - * @returns {callback} callback(err, folder) - */ -Usergrid.Folder = function(options, callback) { - var self = this, messages = []; - console.log("FOLDER OPTIONS", options); - self._client = options.client; - self._data = options.data || {}; - self._data.type = "folders"; - var missingData = [ "name", "owner", "path" ].some(function(required) { - return !(required in self._data); - }); - if (missingData) { - return doCallback(callback, [ new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."), null, self ], self); + self.asset = undefined; + if (_.isPlainObject(args[0])) { + _.assign(self, args[0]); + } else { + if (!self.type) { + self.type = _.isString(args[0]) ? args[0] : undefined; + } + if (!self.name) { + self.name = _.isString(args[1]) ? args[1] : undefined; + } } - self.save(function(err, response) { - if (err) { - doCallback(callback, [ new UsergridError(response), response, self ], self); - } else { - if (response && response.entities && response.entities.length) { - self.set(response.entities[0]); - } - doCallback(callback, [ null, response, self ], self); + if (!_.isString(self.type)) { + throw new Error("'type' (or 'collection') parameter is required when initializing a UsergridEntity object"); + } + Object.defineProperty(self, "isUser", { + get: function() { + return self.type.toLowerCase() === "user"; } }); -}; - -/* - * Inherit from Usergrid.Entity. - */ -Usergrid.Folder.prototype = new Usergrid.Entity(); - -/* - * fetch the folder and associated assets - * - * @method fetch - * @public - * @param {function} callback(err, self) - * @returns {callback} callback(err, self) - */ -Usergrid.Folder.prototype.fetch = function(callback) { - var self = this; - Usergrid.Entity.prototype.fetch.call(self, function(err, data) { - console.log("self", self.get()); - console.log("data", data); - if (!err) { - self.getAssets(function(err, response) { - if (err) { - doCallback(callback, [ new UsergridError(response), resonse, self ], self); - } else { - doCallback(callback, [ null, self ], self); - } - }); - } else { - doCallback(callback, [ null, data, self ], self); + Object.defineProperty(self, "hasAsset", { + get: function() { + return _.has(self, "file-metadata"); } }); + UsergridHelpers.setReadOnly(self, [ "uuid", "name", "type", "created" ]); + return self; }; -/* - * Add an asset to the folder. - * - * @method addAsset - * @public - * @param {object} options {asset:(uuid || Usergrid.Asset || {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" }) } - * @returns {callback} callback(err, folder) - */ -Usergrid.Folder.prototype.addAsset = function(options, callback) { - var self = this; - if ("asset" in options) { - var asset = null; - switch (typeof options.asset) { - case "object": - asset = options.asset; - if (!(asset instanceof Usergrid.Entity)) { - asset = new Usergrid.Asset(asset); - } - break; - - case "string": - if (isUUID(options.asset)) { - asset = new Usergrid.Asset({ - client: self._client, - data: { - uuid: options.asset, - type: "assets" - } - }); +UsergridEntity.prototype = { + jsonValue: function() { + var jsonValue = {}; + _.forOwn(this, function(value, key) { + jsonValue[key] = value; + }); + return jsonValue; + }, + putProperty: function(key, value) { + this[key] = value; + }, + putProperties: function(obj) { + _.assign(this, obj); + }, + removeProperty: function(key) { + this.removeProperties([ key ]); + }, + removeProperties: function(keys) { + var self = this; + keys.forEach(function(key) { + delete self[key]; + }); + }, + insert: function(key, value, idx) { + if (!_.isArray(this[key])) { + this[key] = this[key] ? [ this[key] ] : []; + } + this[key].splice.apply(this[key], [ idx, 0 ].concat(value)); + }, + append: function(key, value) { + this.insert(key, value, Number.MAX_VALUE); + }, + prepend: function(key, value) { + this.insert(key, value, 0); + }, + pop: function(key) { + if (_.isArray(this[key])) { + this[key].pop(); + } + }, + shift: function(key) { + if (_.isArray(this[key])) { + this[key].shift(); + } + }, + reload: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.GET(self, function(error, usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + callback(error, usergridResponse, self); + }.bind(self)); + }, + save: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + var currentAsset = self.asset; + client.PUT(self, function(error, usergridResponse) { + UsergridHelpers.updateEntityFromRemote(self, usergridResponse); + if (self.hasAsset) { + self.asset = currentAsset; } - break; + callback(error, usergridResponse, self); + }.bind(self)); + }, + remove: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.DELETE(self, function(error, usergridResponse) { + callback(error, usergridResponse, self); + }.bind(self)); + }, + attachAsset: function(asset) { + this.asset = asset; + }, + uploadAsset: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + if (_.has(self, "asset.contentType")) { + client.uploadAsset(self, callback); + } else { + var response = UsergridResponse.responseWithError({ + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" + }); + callback(response.error, response, self); } - if (asset && asset instanceof Usergrid.Entity) { - asset.fetch(function(err, data) { - if (err) { - doCallback(callback, [ new UsergridError(data), data, self ], self); - } else { - var endpoint = [ "folders", self.get("uuid"), "assets", asset.get("uuid") ].join("/"); - var options = { - method: "POST", - endpoint: endpoint - }; - self._client.request(options, callback); - } + }, + downloadAsset: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + if (_.has(self, "asset.contentType")) { + client.downloadAsset(self, callback); + } else { + var response = UsergridResponse.responseWithError({ + name: "asset_not_found", + description: "The specified entity does not have a valid asset attached" }); + callback(response.error, response, self); } - } else { - doCallback(callback, [ new UsergridInvalidArgumentError("No asset specified"), null, self ], self); + }, + connect: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args[0] = this; + return client.connect.apply(client, args); + }, + disconnect: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args[0] = this; + return client.disconnect.apply(client, args); + }, + getConnections: function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + args.shift(); + args.splice(1, 0, this); + return client.getConnections.apply(client, args); } }; -/* - * Remove an asset from the folder. - * - * @method removeAsset - * @public - * @param {object} options {asset:(uuid || Usergrid.Asset || {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" }) } - * @returns {callback} callback(err, folder) - */ -Usergrid.Folder.prototype.removeAsset = function(options, callback) { +"use strict"; + +var UsergridUser = function(obj) { + if (!_.has(obj, "email") && !_.has(obj, "username")) { + throw new Error("'email' or 'username' property is required when initializing a UsergridUser object"); + } var self = this; - if ("asset" in options) { - var asset = null; - switch (typeof options.asset) { - case "object": - asset = options.asset; - break; - - case "string": - if (isUUID(options.asset)) { - asset = new Usergrid.Asset({ - client: self._client, - data: { - uuid: options.asset, - type: "assets" - } - }); - } - break; + _.assign(self, obj, UsergridEntity); + UsergridEntity.call(self, "user"); + UsergridHelpers.setWritable(self, "name"); + return self; +}; + +UsergridUser.CheckAvailable = function() { + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + var username = args[0].username || args[1].username; + var email = args[0].email || args[1].email; + if (!username && !email) { + throw new Error("'username' or 'email' property is required when checking for available users"); + } else { + var checkQuery = new UsergridQuery("users"); + if (username) { + checkQuery.eq("username", username); } - if (asset && asset !== null) { - var endpoint = [ "folders", self.get("uuid"), "assets", asset.get("uuid") ].join("/"); - self._client.request({ - method: "DELETE", - endpoint: endpoint - }, function(err, response) { - if (err) { - doCallback(callback, [ new UsergridError(response), response, self ], self); - } else { - doCallback(callback, [ null, response, self ], self); - } - }); + if (email) { + checkQuery.or.eq("email", email); } - } else { - doCallback(callback, [ new UsergridInvalidArgumentError("No asset specified"), null, self ], self); + client.GET(checkQuery, function(error, usergridResponse) { + callback(error, usergridResponse, usergridResponse.entities.length > 0); + }); } }; -/* - * List the assets in the folder. - * - * @method getAssets - * @public - * @returns {callback} callback(err, assets) - */ -Usergrid.Folder.prototype.getAssets = function(callback) { - return this.getConnections("assets", callback); +UsergridHelpers.inherits(UsergridUser, UsergridEntity); + +UsergridUser.prototype.uniqueId = function() { + var self = this; + return _.first([ self.uuid, self.username, self.email ].filter(_.isString)); }; -/* - * XMLHttpRequest.prototype.sendAsBinary polyfill - * from: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary() - * - * @method sendAsBinary - * @param {string} sData - */ -if (!XMLHttpRequest.prototype.sendAsBinary) { - XMLHttpRequest.prototype.sendAsBinary = function(sData) { - var nBytes = sData.length, ui8Data = new Uint8Array(nBytes); - for (var nIdx = 0; nIdx < nBytes; nIdx++) { - ui8Data[nIdx] = sData.charCodeAt(nIdx) & 255; - } - this.send(ui8Data); - }; -} +UsergridUser.prototype.create = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.POST(self, function(error, usergridResponse) { + delete self.password; + _.assign(self, usergridResponse.user); + callback(error, usergridResponse, self); + }.bind(self)); +}; -/* - * A class to model a Usergrid asset. - * - * @constructor - * @param {object} options {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" } - * @returns {callback} callback(err, asset) - */ -Usergrid.Asset = function(options, callback) { - var self = this, messages = []; - self._client = options.client; - self._data = options.data || {}; - self._data.type = "assets"; - var missingData = [ "name", "owner", "path" ].some(function(required) { - return !(required in self._data); +UsergridUser.prototype.login = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + client.POST("token", UsergridHelpers.userLoginBody(self), function(error, usergridResponse) { + delete self.password; + var responseJSON = usergridResponse.responseJSON; + var token = _.get(responseJSON, "access_token"); + var expiresIn = _.get(responseJSON, "expires_in"); + if (usergridResponse.ok) { + self.auth = new UsergridUserAuth(self); + self.auth.token = token; + self.auth.expiry = UsergridHelpers.calculateExpiry(expiresIn); + self.auth.tokenTtl = expiresIn; + } + callback(error, usergridResponse, token); }); - if (missingData) { - doCallback(callback, [ new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."), null, self ], self); - } else { - self.save(function(err, data) { - if (err) { - doCallback(callback, [ new UsergridError(data), data, self ], self); - } else { - if (data && data.entities && data.entities.length) { - self.set(data.entities[0]); - } - doCallback(callback, [ null, data, self ], self); - } - }); - } }; -/* - * Inherit from Usergrid.Entity. - */ -Usergrid.Asset.prototype = new Usergrid.Entity(); - -/* - * Add an asset to a folder. - * - * @method connect - * @public - * @param {object} options {folder:"F01DE600-0000-0000-0000-000000000000"} - * @returns {callback} callback(err, asset) - */ -Usergrid.Asset.prototype.addToFolder = function(options, callback) { - var self = this, error = null; - if ("folder" in options && isUUID(options.folder)) { - var folder = Usergrid.Folder({ - uuid: options.folder - }, function(err, folder) { - if (err) { - doCallback(callback, [ UsergridError.fromResponse(folder), folder, self ], self); - } else { - var endpoint = [ "folders", folder.get("uuid"), "assets", self.get("uuid") ].join("/"); - var options = { - method: "POST", - endpoint: endpoint - }; - this._client.request(options, function(err, response) { - if (err) { - doCallback(callback, [ UsergridError.fromResponse(folder), response, self ], self); - } else { - doCallback(callback, [ null, folder, self ], self); - } - }); - } +UsergridUser.prototype.logout = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + if (!self.auth || !self.auth.isValid) { + var response = UsergridResponse.responseWithError({ + name: "no_valid_token", + description: "this user does not have a valid token" }); + callback(response.error, response); } else { - doCallback(callback, [ new UsergridError("folder not specified"), null, self ], self); + var revokeAll = _.first(args.filter(_.isBoolean)) || false; + var requestOptions = { + client: client, + path: [ "users", self.uniqueId(), "revoketoken" + (revokeAll ? "s" : "") ].join("/"), + method: UsergridHttpMethod.PUT, + callback: function(error, usergridResponse) { + self.auth.destroy(); + callback(error, usergridResponse, usergridResponse.ok); + }.bind(self) + }; + if (!revokeAll) { + requestOptions.queryParams = { + token: self.auth.token + }; + } + var request = new UsergridRequest(requestOptions); + client.sendRequest(request); } }; -Usergrid.Entity.prototype.attachAsset = function(file, callback) { - if (!(window.File && window.FileReader && window.FileList && window.Blob)) { - doCallback(callback, [ new UsergridError("The File APIs are not fully supported by your browser."), null, this ], this); - return; +UsergridUser.prototype.logoutAllSessions = function() { + var args = UsergridHelpers.flattenArgs(arguments); + args = _.concat([ UsergridHelpers.validateAndRetrieveClient(args), true ], args); + return this.logout.apply(this, args); +}; + +UsergridUser.prototype.resetPassword = function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var client = UsergridHelpers.validateAndRetrieveClient(args); + var callback = UsergridHelpers.callback(args); + if (args[0] instanceof UsergridClient) { + args.shift(); } + var body = UsergridHelpers.userResetPasswordBody(args); + if (!body.oldpassword || !body.newpassword) { + throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password"); + } + client.PUT([ "users", self.uniqueId(), "password" ].join("/"), body, callback); +}; + +"use strict"; + +var UsergridResponseError = function(options) { var self = this; - var args = arguments; - var type = this._data.type; - var attempts = self.get("attempts"); - if (isNaN(attempts)) { - attempts = 3; - } - if (type != "assets" && type != "asset") { - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); - } else { - self.set("content-type", file.type); - self.set("size", file.size); - var endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); - } - var xhr = new XMLHttpRequest(); - xhr.open("POST", endpoint, true); - xhr.onerror = function(err) { - doCallback(callback, [ new UsergridError("The File APIs are not fully supported by your browser.") ], xhr, self); - }; - xhr.onload = function(ev) { - if (xhr.status >= 500 && attempts > 0) { - self.set("attempts", --attempts); - setTimeout(function() { - self.attachAsset.apply(self, args); - }, 100); - } else if (xhr.status >= 300) { - self.set("attempts"); - doCallback(callback, [ new UsergridError(JSON.parse(xhr.responseText)), xhr, self ], self); - } else { - self.set("attempts"); - self.fetch(); - doCallback(callback, [ null, xhr, self ], self); - } - }; - var fr = new FileReader(); - fr.onload = function() { - var binary = fr.result; - if (type === "assets" || type === "asset") { - xhr.overrideMimeType("application/octet-stream"); - xhr.setRequestHeader("Content-Type", "application/octet-stream"); - } - xhr.sendAsBinary(binary); - }; - fr.readAsBinaryString(file); + _.assign(self, options); + return self; }; -/* - * Upload Asset data - * - * @method upload - * @public - * @param {object} data Can be a javascript Blob or File object - * @returns {callback} callback(err, asset) - */ -Usergrid.Asset.prototype.upload = function(data, callback) { - this.attachAsset(data, function(err, response) { - if (!err) { - doCallback(callback, [ null, response, self ], self); - } else { - doCallback(callback, [ new UsergridError(err), response, self ], self); - } - }); +UsergridResponseError.fromJSON = function(responseErrorObject) { + var usergridResponseError; + var error = { + name: _.get(responseErrorObject, "error") + }; + if (error.name) { + _.assign(error, { + exception: _.get(responseErrorObject, "exception"), + description: _.get(responseErrorObject, "error_description") || _.get(responseErrorObject, "description") + }); + usergridResponseError = new UsergridResponseError(error); + } + return usergridResponseError; }; -/* - * Download Asset data - * - * @method download - * @public - * @returns {callback} callback(err, blob) blob is a javascript Blob object. - */ -Usergrid.Entity.prototype.downloadAsset = function(callback) { +var UsergridResponse = function(xmlRequest, usergridRequest) { var self = this; - var endpoint; - var type = this._data.type; - var xhr = new XMLHttpRequest(); - if (type != "assets" && type != "asset") { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, type, self.get("uuid") ].join("/"); - } else { - endpoint = [ this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), "data" ].join("/"); - } - xhr.open("GET", endpoint, true); - xhr.responseType = "blob"; - xhr.onload = function(ev) { - var blob = xhr.response; - if (type != "assets" && type != "asset") { - doCallback(callback, [ null, blob, xhr ], self); + self.ok = false; + self.request = usergridRequest; + if (xmlRequest) { + self.statusCode = parseInt(xmlRequest.status); + self.ok = self.statusCode < 400; + self.headers = UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders()); + var responseContentType = _.get(self.headers, "content-type"); + if (responseContentType === UsergridApplicationJSONHeaderValue) { + try { + var responseJSON = JSON.parse(xmlRequest.responseText); + if (responseJSON) { + self.parseResponseJSON(responseJSON); + } + } catch (e) {} } else { - doCallback(callback, [ null, xhr, self ], self); + self.asset = new UsergridAsset(xmlRequest.response); } - }; - xhr.onerror = function(err) { - callback(true, err); - doCallback(callback, [ new UsergridError(err), xhr, self ], self); - }; - if (type != "assets" && type != "asset") { - xhr.setRequestHeader("Accept", self._data["file-metadata"]["content-type"]); - } else { - xhr.overrideMimeType(self.get("content-type")); } - xhr.send(); + return self; }; -/* - * Download Asset data - * - * @method download - * @public - * @returns {callback} callback(err, blob) blob is a javascript Blob object. - */ -Usergrid.Asset.prototype.download = function(callback) { - this.downloadAsset(function(err, response) { - if (!err) { - doCallback(callback, [ null, response, self ], self); - } else { - doCallback(callback, [ new UsergridError(err), response, self ], self); - } - }); +UsergridResponse.responseWithError = function(options) { + var usergridResponse = new UsergridResponse(); + usergridResponse.error = new UsergridResponseError(options); + return usergridResponse; }; -/** - * Created by ryan bridges on 2014-02-05. - */ -(function(global) { - var name = "UsergridError", short, _name = global[name], _short = short && short !== undefined ? global[short] : undefined; - /* - * Instantiates a new UsergridError - * - * @method UsergridError - * @public - * @params {} message - * @params {} id - the error code, id, or name - * @params {} timestamp - * @params {} duration - * @params {} exception - the Java exception from Usergrid - * @return Returns - a new UsergridError object - * - * Example: - * - * UsergridError(message); - */ - function UsergridError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridError.prototype = new Error(); - UsergridError.prototype.constructor = UsergridError; - /* - * Creates a UsergridError from the JSON response returned from the backend - * - * @method fromResponse - * @public - * @params {object} response - the deserialized HTTP response from the Usergrid API - * @return Returns a new UsergridError object. - * - * Example: - * { - * "error":"organization_application_not_found", - * "timestamp":1391618508079, - * "duration":0, - * "exception":"org.usergrid.rest.exceptions.OrganizationApplicationNotFoundException", - * "error_description":"Could not find application for yourorgname/sandboxxxxx from URI: yourorgname/sandboxxxxx" - * } - */ - UsergridError.fromResponse = function(response) { - if (response && "undefined" !== typeof response) { - return new UsergridError(response.error_description, response.error, response.timestamp, response.duration, response.exception); +UsergridResponse.prototype = { + parseResponseJSON: function(responseJSON) { + var self = this; + self.responseJSON = _.cloneDeep(responseJSON); + if (self.ok) { + self.cursor = _.get(self, "responseJSON.cursor"); + self.hasNextPage = !_.isNil(self.cursor); + var entitiesJSON = _.get(responseJSON, "entities"); + if (entitiesJSON) { + self.parseResponseEntities(entitiesJSON); + delete self.responseJSON.entities; + } } else { - return new UsergridError(); + self.error = UsergridResponseError.fromJSON(responseJSON); } - }; - UsergridError.createSubClass = function(name) { - if (name in global && global[name]) return global[name]; - global[name] = function() {}; - global[name].name = name; - global[name].prototype = new UsergridError(); - return global[name]; - }; - function UsergridHTTPResponseError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridHTTPResponseError.prototype = new UsergridError(); - function UsergridInvalidHTTPMethodError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name || "invalid_http_method"; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridInvalidHTTPMethodError.prototype = new UsergridError(); - function UsergridInvalidURIError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name || "invalid_uri"; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridInvalidURIError.prototype = new UsergridError(); - function UsergridInvalidArgumentError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name || "invalid_argument"; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridInvalidArgumentError.prototype = new UsergridError(); - function UsergridKeystoreDatabaseUpgradeNeededError(message, name, timestamp, duration, exception) { - this.message = message; - this.name = name; - this.timestamp = timestamp || Date.now(); - this.duration = duration || 0; - this.exception = exception; - } - UsergridKeystoreDatabaseUpgradeNeededError.prototype = new UsergridError(); - global.UsergridHTTPResponseError = UsergridHTTPResponseError; - global.UsergridInvalidHTTPMethodError = UsergridInvalidHTTPMethodError; - global.UsergridInvalidURIError = UsergridInvalidURIError; - global.UsergridInvalidArgumentError = UsergridInvalidArgumentError; - global.UsergridKeystoreDatabaseUpgradeNeededError = UsergridKeystoreDatabaseUpgradeNeededError; - global[name] = UsergridError; - if (short !== undefined) { - global[short] = UsergridError; - } - global[name].noConflict = function() { - if (_name) { - global[name] = _name; + UsergridHelpers.setReadOnly(self.responseJSON); + }, + parseResponseEntities: function(entitiesJSON) { + var self = this; + self.entities = _.map(entitiesJSON, function(entityJSON) { + var entity = new UsergridEntity(entityJSON); + if (entity.isUser) { + entity = new UsergridUser(entity); + } + return entity; + }); + self.first = _.first(self.entities); + self.entity = self.first; + self.last = _.last(self.entities); + if (_.get(self, "responseJSON.path") === "/users") { + self.user = self.first; + self.users = self.entities; } - if (short !== undefined) { - global[short] = _short; + }, + loadNextPage: function() { + var self = this; + var args = UsergridHelpers.flattenArgs(arguments); + var callback = UsergridHelpers.callback(args); + var cursor = self.cursor; + if (!cursor) { + callback(UsergridResponse.responseWithError({ + name: "cursor_not_found", + description: "Cursor must be present in order perform loadNextPage()." + })); + } else { + var client = UsergridHelpers.validateAndRetrieveClient(args); + var type = _.last(_.get(self, "responseJSON.path").split("/")); + var limit = _.first(_.get(self, "responseJSON.params.limit")); + var ql = _.first(_.get(self, "responseJSON.params.ql")); + var query = new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit); + client.GET(query, callback); } - return UsergridError; - }; - return global[name]; -})(this); \ No newline at end of file + } +}; + +"use strict"; + +var UsergridAssetDefaultFileName = "file"; + +var UsergridAsset = function(fileOrBlob) { + if (!fileOrBlob instanceof File || !fileOrBlob instanceof Blob) { + throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'"); + } + var self = this; + self.data = fileOrBlob; + self.filename = fileOrBlob.name || UsergridAssetDefaultFileName; + self.contentLength = fileOrBlob.size; + self.contentType = fileOrBlob.type; + return self; +}; \ No newline at end of file diff --git a/usergrid.min.js b/usergrid.min.js index 0f50f94..b6659c6 100644 --- a/usergrid.min.js +++ b/usergrid.min.js @@ -1,20 +1,27 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at +/*! + *Licensed to the Apache Software Foundation (ASF) under one + *or more contributor license agreements. See the NOTICE file + *distributed with this work for additional information + *regarding copyright ownership. The ASF licenses this file + *to you under the Apache License, Version 2.0 (the + *"License"); you may not use this file except in compliance + *with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + *Unless required by applicable law or agreed to in writing, + *software distributed under the License is distributed on an + *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + *KIND, either express or implied. See the License for the + *specific language governing permissions and limitations + *under the License. + * + * + * usergrid@2.0.0 2016-10-14 */ -function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function propCopy(from,to){for(var prop in from)from.hasOwnProperty(prop)&&(to[prop]="object"==typeof from[prop]&&"object"==typeof to[prop]?propCopy(from[prop],to[prop]):from[prop]);return to}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;try{doc=document.implementation.createHTMLDocument(""),base=doc.createElement("base"),base.href=base||window.lo,doc.head.appendChild(base),anchor=doc.createElement("a"),anchor.href=url,doc.body.appendChild(anchor),isValid=!(""===anchor.href)}catch(e){console.error(e)}finally{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}function getSafeTime(prop){var time;switch(typeof prop){case"undefined":time=Date.now();break;case"number":time=prop;break;case"string":time=isNaN(prop)?Date.parse(prop):parseInt(prop);break;default:time=Date.parse(prop.toString())}return time}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;ii;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4===this.readyState&&(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name],VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.isValidEndpoint=function(){return!0},Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities;return this.success&&(entities=this.data?this.data.entities:this.entities),entities||[]},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.VERSION=Usergrid.USERGRID_SDK_VERSION="0.11.0",global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),options.qs&&this.setObject("default_qs",options.qs),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),default_qs=this.getObject("default_qs");if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken()),default_qs&&(qs=propCopy(qs,default_qs));{var self=this;new Usergrid.Request(method,uri,qs,body,function(err,response){err?doCallback(callback,[err,response,self],self):doCallback(callback,[null,response,self],self)})}},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var group=new Usergrid.Group({path:options.path,client:this,data:options});group.save(function(err,response){doCallback(callback,[err,response,group],group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.save(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.fetch(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCounter=function(options,callback){var counter=new Usergrid.Counter({client:this,data:options});counter.save(callback)},Usergrid.Client.prototype.createAsset=function(options,callback){var file=options.file;file&&(options.name=options.name||file.name,options["content-type"]=options["content-type"]||file.type,options.path=options.path||"/",delete options.file);var asset=new Usergrid.Asset({client:this,data:options});asset.save(function(err,response,asset){file&&!err?asset.upload(file,callback):doCallback(callback,[err,response,asset],asset)})},Usergrid.Client.prototype.createCollection=function(options,callback){return options.client=this,new Usergrid.Collection(options,function(err,data,collection){console.log("createCollection",arguments),doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities",options={client:this,data:options};var entity=new Usergrid.Entity(options);entity.save(function(err,data){doCallback(callback,[err,data,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),options={actor:{displayName:username,uuid:user.get("uuid"),username:username,email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:content};this.createUserActivity(username,options,callback)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localStorage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log user in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full authenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}doCallback(callback,[err,data,user,organizations,applications],self)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,options={method:"GET",endpoint:"auth/facebook",qs:{fb_access_token:facebookToken}};this.request(options,function(err,data){var user={};if(err&&self.logging)console.log("error trying to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}doCallback(callback,[err,data,user],self)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){var self=this;if(this.getToken()){var options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){if(err)self.logging&&console.log("error trying to log user in"),console.error(err,response),doCallback(callback,[err,response,self],self);else{var options={client:self,data:response.getEntity()},user=new Usergrid.Entity(options);doCallback(callback,[null,response,user],self)}})}else doCallback(callback,[new UsergridError("Access Token not set"),null,self],self)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.destroyToken=function(username,token,revokeAll,callback){var options={client:self,method:"PUT"};options.endpoint=revokeAll===!0?"users/"+username+"/revoketokens":null===token?"users/"+username+"/revoketoken?token="+this.getToken():"users/"+username+"/revoketoken?token="+token,this.request(options,function(err,data){err?(self.logging&&console.log("error destroying access token"),doCallback(callback,[err,data,null],self)):(console.log(revokeAll===!0?"all user tokens invalidated":"token invalidated"),doCallback(callback,[err,data,null],self))})},Usergrid.Client.prototype.logoutAndDestroyToken=function(username,token,revokeAll,callback){null===username?console.log("username required to revoke tokens"):(this.destroyToken(username,token,revokeAll,callback),(revokeAll===!0||token===this.getToken()||null===token)&&this.setToken(null))},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){this._data={},this._client=void 0,options&&(this.set(options.data||{}),this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");return/^users?$/.test(type)&&nameProperties.unshift("username"),name=this.get(nameProperties).filter(function(x){return null!==x&&"undefined"!=typeof x}).shift(),name?[type,name].join("/"):type},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),entityData=this.get(),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),options.body=Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).reduce(function(data,key){return data[key]=entityData[key],data},{}),self._client.request(options,function(err,response){var entity=response.getEntity();entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),err&&self._client.logging&&console.log("could not save entity"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.changePassword=function(oldpassword,newpassword,callback){var self=this;if("function"==typeof oldpassword&&void 0===callback&&(callback=oldpassword,oldpassword=self.get("oldpassword"),newpassword=self.get("newpassword")),self.set({password:null,oldpassword:null,newpassword:null}),!(/^users?$/.test(self.get("type"))&&oldpassword&&newpassword))throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'");var options={method:"PUT",endpoint:"users/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,response){err&&self._client.logging&&console.log("could not update user"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err||self.set(null),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){this.addOrRemoveConnection("POST",connection,entity,callback)},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){this.addOrRemoveConnection("DELETE",connection,entity,callback)},Usergrid.Entity.prototype.addOrRemoveConnection=function(method,connection,entity,callback){var self=this;if(-1==["POST","DELETE"].indexOf(method.toUpperCase()))throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'");var connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)throw new UsergridInvalidArgumentError("connectee could not be identified");var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)throw new UsergridInvalidArgumentError("connector could not be identified");var endpoint=[connectorType,connector,connection,connecteeType,connectee].join("/"),options={method:method,endpoint:endpoint};this._client.request(options,function(err,response){err&&self._client.logging&&console.log("There was an error with the connection call"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id;return id=entity.get(isUUID(entity.get("uuid"))?"uuid":"users"===this.get("type")||"user"===this.get("type")?"username":"name")},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];doCallback(callback,[err,data,data.entities],self)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),doCallback(callback,[!0,error],self)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Client.prototype.createRole=function(roleName,permissions,callback){var options={type:"role",name:roleName};this.createEntity(options,function(err,response,entity){err?doCallback(callback,[err,response,self]):entity.assignPermissions(permissions,function(err,data){err?doCallback(callback,[err,response,self]):doCallback(callback,[err,data,data.data],self)})})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.assignRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=self.get("username"):"group"==type&&null!=this.get("name")?entityID=self.get("name"):null!=this.get("uuid")&&(entityID=self.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.removeRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.assignPermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"POST",endpoint:endpoint,body:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not assign permissions"),doCallback(callback,[err,data,data.data],self)})},Usergrid.Entity.prototype.removePermissions=function(permissions,callback){var entityID,self=this,type=this.get("type"); -"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"DELETE",endpoint:endpoint,qs:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not remove permissions"),doCallback(callback,[err,data,data.params.permission],self)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part=ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Collection=function(options){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){var data={};data.type=this._type,data.qs=this.qs,data.iterator=this._iterator,data.previous=this._previous,data.next=this._next,data.cursor=this._cursor,this.resetEntityPointer();var i=0;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor:delete qs.cursor;var options={method:"GET",endpoint:this._type,qs:this.qs};this._client.request(options,function(err,response){err&&self._client.logging?console.log("error getting collection"):(self.saveCursor(response.cursor||null),self.resetEntityPointer(),self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){var ent=new Usergrid.Entity({client:self._client});return ent.set(entity),ent.type=self._type,ent})),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addEntity=function(entityObject,callback){var self=this;entityObject.type=this._type,this._client.createEntity(entityObject,function(err,response,entity){err||self.addExistingEntity(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,response){err?(self._client.logging&&console.log("could not destroy entity"),doCallback(callback,[err,response,self],self)):self.fetch(callback),self.removeEntity(entity)})},Usergrid.Collection.prototype.getEntitiesByCriteria=function(criteria){return this._list.filter(criteria)},Usergrid.Collection.prototype.getEntityByCriteria=function(criteria){return this.getEntitiesByCriteria(criteria).shift()},Usergrid.Collection.prototype.removeEntity=function(entity){var removedEntity=this.getEntityByCriteria(function(item){return entity.uuid===item.get("uuid")});return delete this._list[this._list.indexOf(removedEntity)],removedEntity},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){var entity=this.getEntityByCriteria(function(item){return item.get("uuid")===uuid});if(entity)doCallback(callback,[null,entity,entity],this);else{var options={data:{type:this._type,uuid:uuid},client:this._client};entity=new Usergrid.Entity(options),entity.fetch(callback)}},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,response){if(err)self._client.logging&&console.log("error getting group"),doCallback(callback,[err,response],self);else{var entities=response.getEntities();if(entities&&entities.length){{entities.shift()}self._client.request(memberOptions,function(err,response){err&&self._client.logging?console.log("error getting group users"):self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){return new Usergrid.Entity({type:entity.type,client:self._client,uuid:entity.uuid,response:entity})}),doCallback(callback,[err,response,self],self)})}}})},Usergrid.Group.prototype.members=function(){return this._list},Usergrid.Group.prototype.add=function(options,callback){var self=this;options.user?(options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.remove=function(options,callback){var self=this;options.user?(options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.username},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.feed=function(callback){var self=this,options={method:"GET",endpoint:"groups/"+this._path+"/feed"};this._client.request(options,function(err,response){doCallback(callback,[err,response,self],self)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var self=this,user=options.user,entity=new Usergrid.Entity({client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}});entity.save(function(err,response){doCallback(callback,[err,response,self])})},Usergrid.Counter=function(options){this._client=options.client,this._data=options.data||{},this._data.category=options.category||"UNKNOWN",this._data.timestamp=options.timestamp||0,this._data.type="events",this._data.counters=options.counters||{}};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;return name?isNaN(value)?doCallback(callback,[new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"),null,self],self):(self._data.counters[name]=parseInt(value)||1,self.save(callback)):doCallback(callback,[new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"),null,self],self)},Usergrid.Counter.prototype.decrement=function(options,callback){var self=this,name=options.name,value=options.value;self.increment({name:name,value:-(parseInt(value)||1)},callback)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},Usergrid.Counter.prototype.getData=function(options,callback){var start_time,end_time,start=options.start||0,end=options.end||Date.now(),resolution=(options.resolution||"all").toLowerCase(),counters=options.counters||Object.keys(this._data.counters),res=(resolution||"all").toLowerCase();-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start_time=getSafeTime(start),end_time=getSafeTime(end);var self=this,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});params.push("resolution="+res),params.push("start_time="+String(start_time)),params.push("end_time="+String(end_time));var endpoint="counters?"+params.join("&");this._client.request({endpoint:endpoint},function(err,data){return data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),doCallback(callback,[err,data,self],self)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):void self.save(function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):(response&&response.entities&&response.entities.length&&self.set(response.entities[0]),doCallback(callback,[null,response,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[null,data,self],self):self.getAssets(function(err,response){err?doCallback(callback,[new UsergridError(response),resonse,self],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[new UsergridError(data),data,self],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):doCallback(callback,[null,response,self],self)})}}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;self._client=options.client,self._data=options.data||{},self._data.type="assets";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});missingData?doCallback(callback,[new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):self.save(function(err,data){err?doCallback(callback,[new UsergridError(data),data,self],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[null,data,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)doCallback(callback,[UsergridError.fromResponse(folder),folder,self],self);else{var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err?doCallback(callback,[UsergridError.fromResponse(folder),response,self],self):doCallback(callback,[null,folder,self],self)})}})}else doCallback(callback,[new UsergridError("folder not specified"),null,self],self)},Usergrid.Entity.prototype.attachAsset=function(file,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser."),null,this],this);var self=this,args=arguments,type=this._data.type,attempts=self.get("attempts");if(isNaN(attempts)&&(attempts=3),"assets"!=type&&"asset"!=type)var endpoint=[this._client.URI,this._client.orgName,this._client.appName,type,self.get("uuid")].join("/");else{self.set("content-type",file.type),self.set("size",file.size);var endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/")}var xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser.")],xhr,self)},xhr.onload=function(){xhr.status>=500&&attempts>0?(self.set("attempts",--attempts),setTimeout(function(){self.attachAsset.apply(self,args)},100)):xhr.status>=300?(self.set("attempts"),doCallback(callback,[new UsergridError(JSON.parse(xhr.responseText)),xhr,self],self)):(self.set("attempts"),self.fetch(),doCallback(callback,[null,xhr,self],self))};var fr=new FileReader;fr.onload=function(){var binary=fr.result;("assets"===type||"asset"===type)&&(xhr.overrideMimeType("application/octet-stream"),xhr.setRequestHeader("Content-Type","application/octet-stream")),xhr.sendAsBinary(binary)},fr.readAsBinaryString(file)},Usergrid.Asset.prototype.upload=function(data,callback){this.attachAsset(data,function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Entity.prototype.downloadAsset=function(callback){var endpoint,self=this,type=this._data.type,xhr=new XMLHttpRequest;endpoint="assets"!=type&&"asset"!=type?[this._client.URI,this._client.orgName,this._client.appName,type,self.get("uuid")].join("/"):[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;"assets"!=type&&"asset"!=type?doCallback(callback,[null,blob,xhr],self):doCallback(callback,[null,xhr,self],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[new UsergridError(err),xhr,self],self)},"assets"!=type&&"asset"!=type?xhr.setRequestHeader("Accept",self._data["file-metadata"]["content-type"]):xhr.overrideMimeType(self.get("content-type")),xhr.send()},Usergrid.Asset.prototype.download=function(callback){this.downloadAsset(function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_http_method",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_uri",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidArgumentError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_argument",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridInvalidArgumentError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridInvalidArgumentError=UsergridInvalidArgumentError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this); \ No newline at end of file +"use strict";!function(global){function Promise(){this.complete=!1,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.result):this.callbacks.push(f)},Promise.prototype.done=function(result){this.complete=!0,this.result=result,this.callbacks&&(_.forEach(this.callbacks,function(callback){callback(result)}),this.callbacks.length=0)},Promise.join=function(promises){function notifier(i){return function(result){completed+=1,results[i]=result,completed===total&&p.done(results)}}for(var p=new Promise,total=promises.length,completed=0,results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,result){var p=new Promise;return null===promises||0===promises.length?p.done(result):promises[0](result).then(function(res){promises.splice(0,1),promises?Promise.chain(promises,res).then(function(r){p.done(r)}):p.done(res)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function addMapEntry(map,pair){return map.set(pair[0],pair[1]),map}function addSetEntry(set,value){return set.add(value),set}function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayAggregator(array,setter,iteratee,accumulator){for(var index=-1,length=array?array.length:0;++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++index>>1,wrapFlags=[["ary",ARY_FLAG],["bind",BIND_FLAG],["bindKey",BIND_KEY_FLAG],["curry",CURRY_FLAG],["curryRight",CURRY_RIGHT_FLAG],["flip",FLIP_FLAG],["partial",PARTIAL_FLAG],["partialRight",PARTIAL_RIGHT_FLAG],["rearg",REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboMarksRange+rsComboSymbolsRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsLowerMisc="(?:"+rsLower+"|"+rsMisc+")",rsUpperMisc="(?:"+rsUpper+"|"+rsMisc+")",rsOptLowerContr="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptUpperContr="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptLowerContr+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsUpperMisc+"+"+rsOptUpperContr+"(?="+[rsBreak,rsUpper+rsLowerMisc,"$"].join("|")+")",rsUpper+"?"+rsLowerMisc+"+"+rsOptLowerContr,rsUpper+"+"+rsOptUpperContr,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),runInContext=function runInContext(context){function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper)return value;if(hasOwnProperty.call(value,"__wrapped__"))return wrapperClone(value)}return new LodashWrapper(value)}function baseLodash(){}function LodashWrapper(value,chainAll){this.__wrapped__=value,this.__actions__=[],this.__chain__=!!chainAll,this.__index__=0,this.__values__=undefined}function LazyWrapper(value){this.__wrapped__=value,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=MAX_ARRAY_LENGTH,this.__views__=[]}function lazyClone(){var result=new LazyWrapper(this.__wrapped__);return result.__actions__=copyArray(this.__actions__),result.__dir__=this.__dir__,result.__filtered__=this.__filtered__,result.__iteratees__=copyArray(this.__iteratees__),result.__takeCount__=this.__takeCount__,result.__views__=copyArray(this.__views__),result}function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1,result.__filtered__=!0}else result=this.clone(),result.__dir__*=-1;return result}function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=0>dir,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||LARGE_ARRAY_SIZE>arrLength||arrLength==length&&takeCount==length)return baseWrapperValue(array,this.__actions__);var result=[];outer:for(;length--&&takeCount>resIndex;){index+=dir;for(var iterIndex=-1,value=array[index];++iterIndexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?undefined:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=number?number:upper),lower!==undefined&&(number=number>=lower?number:lower)),number}function baseClone(value,isDeep,isFull,customizer,key,object,stack){var result;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=initCloneObject(isFunc?{}:value),!isDeep)return copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;stack.set(value,result);var props=isArr?undefined:(isFull?getAllKeys:keys)(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,isDeep,isFull,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexstart&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:toInteger(end),0>end&&(end+=length),end=start>end?0:toLength(end);end>start;)array[start++]=value;return array}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;for(predicate||(predicate=isFlattenable),result||(result=[]);++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=isKey(path,object)?[path]:castPath(path);for(var index=0,length=path.length;null!=object&&length>index;)object=object[toKey(path[index++])];return index&&index==length?object:undefined}function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}function baseGetTag(value){return objectToString.call(value)}function baseGt(value,other){return value>other}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++indexvalue}function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection)}),result}function baseMatches(source){var matchData=getMatchData(source);return 1==matchData.length&&matchData[0][2]?matchesStrictComparable(matchData[0][0],matchData[0][1]):function(object){return object===source||baseIsMatch(object,source,matchData)}}function baseMatchesProperty(path,srcValue){return isKey(path)&&isStrictComparable(srcValue)?matchesStrictComparable(toKey(path),srcValue):function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,undefined,UNORDERED_COMPARE_FLAG|PARTIAL_COMPARE_FLAG)}}function baseMerge(object,source,srcIndex,customizer,stack){object!==source&&baseFor(source,function(srcValue,key){if(isObject(srcValue))stack||(stack=new Stack),baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);else{var newValue=customizer?customizer(object[key],srcValue,key+"",object,source,stack):undefined;newValue===undefined&&(newValue=srcValue),assignMergeValue(object,key,newValue)}},keysIn)}function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=object[key],srcValue=source[key],stacked=stack.get(srcValue);if(stacked)return void assignMergeValue(object,key,stacked);var newValue=customizer?customizer(objValue,srcValue,key+"",object,source,stack):undefined,isCommon=newValue===undefined;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue,isArr||isBuff||isTyped?isArray(objValue)?newValue=objValue:isArrayLikeObject(objValue)?newValue=copyArray(objValue):isBuff?(isCommon=!1,newValue=cloneBuffer(srcValue,!0)):isTyped?(isCommon=!1,newValue=cloneTypedArray(srcValue,!0)):newValue=[]:isPlainObject(srcValue)||isArguments(srcValue)?(newValue=objValue,isArguments(objValue)?newValue=toPlainObject(objValue):(!isObject(objValue)||srcIndex&&isFunction(objValue))&&(newValue=initCloneObject(srcValue))):isCommon=!1}isCommon&&(stack.set(srcValue,newValue),mergeFunc(newValue,srcValue,srcIndex,customizer,stack),stack["delete"](srcValue)),assignMergeValue(object,key,newValue)}function baseNth(array,n){var length=array.length;if(length)return n+=0>n?length:0,isIndex(n,length)?array[n]:undefined}function baseOrderBy(collection,iteratees,orders){var index=-1;iteratees=arrayMap(iteratees.length?iteratees:[identity],baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value)});return{criteria:criteria,index:++index,value:value}});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders)})}function basePick(object,props){return object=Object(object),basePickBy(object,props,function(value,key){return key in object})}function basePickBy(object,props,predicate){for(var index=-1,length=props.length,result={};++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index))splice.call(array,index,1);else if(isKey(index,array))delete array[toKey(index)];else{var path=castPath(index),object=parent(array,path);null!=object&&delete object[toKey(last(path))]}}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||1>n||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSample(collection){return arraySample(values(collection))}function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length))}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=isKey(path,object)?[path]:castPath(path);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function baseSortedUniq(array,iteratee){for(var index=-1,length=array.length,resIndex=0,result=[];++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexindex?values[index]:undefined;assignFunc(result,props[index],value)}return result}function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[]}function castFunction(value){return"function"==typeof value?value:identity}function castPath(value){return isArray(value)?value:stringToPath(value)}function castSlice(array,start,end){var length=array.length;return end=end===undefined?length:end,!start&&end>=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),!0):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),!0):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&other>value||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive)return-1}return 0}function compareMultiple(object,other,orders){for(var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;++index=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndexargsIndex)&&(result[holders[argsIndex]]=args[argsIndex]);for(;rangeLength--;)result[leftIndex++]=args[argsIndex++];return result}function composeArgsRight(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;++argsIndexargsIndex)&&(result[offset+holders[holdersIndex]]=args[argsIndex++]);return result}function copyArray(source,array){var index=-1,length=source.length;for(array||(array=Array(length));++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?undefined:customizer,length=1),object=Object(object);++indexlength&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);if(length-=holders.length,arity>length)return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args)}var Ctor=createCtor(func);return wrapper}function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection),predicate=function(key){return iteratee(iterable[key],key,iterable)}}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++indexlength){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length)}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;return length=args.length,argPos?args=reorder(args,argPos):isFlip&&length>1&&args.reverse(),isAry&&length>ary&&(args.length=ary),this&&this!==root&&this instanceof wrapper&&(fn=Ctor||createCtor(fn)),fn.apply(thisBinding,args)}var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurried=bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG),isFlip=bitmask&FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);return wrapper}function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{})}}function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined)return defaultValue;if(value!==undefined&&(result=value),other!==undefined){if(result===undefined)return other;"string"==typeof value||"string"==typeof other?(value=baseToString(value),other=baseToString(other)):(value=baseToNumber(value),other=baseToNumber(other)),result=operator(value,other)}return result}}function createOver(arrayFunc){return flatRest(function(iteratees){return iteratees=arrayMap(iteratees,baseUnary(getIteratee())),baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args)})})})}function createPadding(length,chars){chars=chars===undefined?" ":baseToString(chars);var charsLength=chars.length;if(2>charsLength)return charsLength?baseRepeat(chars,length):chars;var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(""):result.slice(0,length)}function createPartial(func,bitmask,thisArg,partials){function wrapper(){for(var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;++leftIndexstart?1:-1:toFinite(step),baseRange(start,end,step,fromRight)}}function createRelationalOperation(operator){return function(value,other){return("string"!=typeof value||"string"!=typeof other)&&(value=toNumber(value),other=toNumber(other)),operator(value,other)}}function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG,bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG),bitmask&CURRY_BOUND_FLAG||(bitmask&=~(BIND_FLAG|BIND_KEY_FLAG));var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity],result=wrapFunc.apply(undefined,newData);return isLaziable(func)&&setData(result,newData),result.placeholder=placeholder,setWrapToString(result,func,bitmask)}function createRound(methodName){var func=Math[methodName];return function(number,precision){if(number=toNumber(number),precision=nativeMin(toInteger(precision),292)){var pair=(toString(number)+"e").split("e"),value=func(pair[0]+"e"+(+pair[1]+precision));return pair=(toString(value)+"e").split("e"),+(pair[0]+"e"+(+pair[1]-precision))}return func(number)}}function createToPairs(keysFunc){return function(object){var tag=getTag(object);return tag==mapTag?mapToArray(object):tag==setTag?setToPairs(object):baseToPairs(object,keysFunc(object))}}function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&"function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);var length=partials?partials.length:0;if(length||(bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG),partials=holders=undefined),ary=ary===undefined?ary:nativeMax(toInteger(ary),0),arity=arity===undefined?arity:toInteger(arity),length-=holders?holders.length:0,bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined}var data=isBindKey?undefined:getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&mergeData(newData,data),func=newData[0],bitmask=newData[1],thisArg=newData[2],partials=newData[3],holders=newData[4],arity=newData[9]=null==newData[9]?isBindKey?0:func.length:nativeMax(newData[9]-length,0),!arity&&bitmask&(CURRY_FLAG|CURRY_RIGHT_FLAG)&&(bitmask&=~(CURRY_FLAG|CURRY_RIGHT_FLAG)),bitmask&&bitmask!=BIND_FLAG)result=bitmask==CURRY_FLAG||bitmask==CURRY_RIGHT_FLAG?createCurry(func,bitmask,arity):bitmask!=PARTIAL_FLAG&&bitmask!=(BIND_FLAG|PARTIAL_FLAG)||holders.length?createHybrid.apply(undefined,newData):createPartial(func,bitmask,thisArg,partials);else var result=createBind(func,bitmask,thisArg);var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask)}function equalArrays(array,other,equalFunc,customizer,bitmask,stack){var isPartial=bitmask&PARTIAL_COMPARE_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)?eq(object[index],value):!1}function isKey(value,object){if(isArray(value))return!1;var type=typeof value;return"number"==type||"symbol"==type||"boolean"==type||null==value||isSymbol(value)?!0:reIsPlainProp.test(value)||!reIsDeepProp.test(value)||null!=object&&value in Object(object)}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if("function"!=typeof other||!(funcName in LazyWrapper.prototype))return!1;if(func===other)return!0;var data=getData(other);return!!data&&func===data[0]}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function isStrictComparable(value){return value===value&&!isObject(value)}function matchesStrictComparable(key,srcValue){return function(object){return null==object?!1:object[key]===srcValue&&(srcValue!==undefined||key in Object(object))}}function memoizeCapped(func){var result=memoize(func,function(key){return cache.size===MAX_MEMOIZE_SIZE&&cache.clear(),key}),cache=result.cache;return result}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=(BIND_FLAG|BIND_KEY_FLAG|ARY_FLAG)>newBitmask,isCombo=srcBitmask==ARY_FLAG&&bitmask==CURRY_FLAG||srcBitmask==ARY_FLAG&&bitmask==REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(ARY_FLAG|REARG_FLAG)&&source[7].length<=source[8]&&bitmask==CURRY_FLAG;if(!isCommon&&!isCombo)return data;srcBitmask&BIND_FLAG&&(data[2]=source[2],newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG);var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value,data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4]}return value=source[5],value&&(partials=data[5],data[5]=partials?composeArgsRight(partials,value,source[6]):value,data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6]),value=source[7],value&&(data[7]=value),srcBitmask&ARY_FLAG&&(data[8]=null==data[8]?source[8]:nativeMin(data[8],source[8])),null==data[9]&&(data[9]=source[9]),data[0]=source[0],data[1]=newBitmask,data}function mergeDefaults(objValue,srcValue,key,object,source,stack){return isObject(objValue)&&isObject(srcValue)&&(stack.set(srcValue,objValue),baseMerge(objValue,srcValue,undefined,mergeDefaults,stack),stack["delete"](srcValue)),objValue}function nativeKeysIn(object){var result=[];if(null!=object)for(var key in Object(object))result.push(key);return result}function overRest(func,start,transform){return start=nativeMax(start===undefined?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;for(size=size===undefined?length:size;++indexsize)return[];for(var index=0,resIndex=0,result=Array(nativeCeil(length/size));length>index;)result[resIndex++]=baseSlice(array,index,index+=size);return result}function compact(array){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++indexn?0:n,length)):[]}function dropRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0,0>n?0:n)):[]}function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0,!0):[]}function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!0):[]}function fill(array,value,start,end){var length=array?array.length:0;return length?(start&&"number"!=typeof start&&isIterateeCall(array,value,start)&&(start=0,end=length),baseFill(array,value,start,end)):[]}function findIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=null==fromIndex?0:toInteger(fromIndex);return 0>index&&(index=nativeMax(length+index,0)),baseFindIndex(array,getIteratee(predicate,3),index)}function findLastIndex(array,predicate,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length-1;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>fromIndex?nativeMax(length+index,0):nativeMin(index,length-1)),baseFindIndex(array,getIteratee(predicate,3),index,!0)}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,INFINITY):[]}function flattenDepth(array,depth){var length=array?array.length:0;return length?(depth=depth===undefined?1:toInteger(depth),baseFlatten(array,depth)):[]}function fromPairs(pairs){for(var index=-1,length=pairs?pairs.length:0,result={};++indexindex&&(index=nativeMax(length+index,0)),baseIndexOf(array,value,index)}function initial(array){var length=array?array.length:0;return length?baseSlice(array,0,-1):[]}function join(array,separator){return array?nativeJoin.call(array,separator):""}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;var index=length;return fromIndex!==undefined&&(index=toInteger(fromIndex),index=0>index?nativeMax(length+index,0):nativeMin(index,length-1)),value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,!0)}function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined}function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array}function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array}function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array}function remove(array,predicate){var result=[];if(!array||!array.length)return result;var index=-1,indexes=[],length=array.length;for(predicate=getIteratee(predicate,3);++indexindex&&eq(array[index],value))return index}return-1}function sortedLastIndex(array,value){return baseSortedIndex(array,value,!0)}function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),!0)}function sortedLastIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value,!0)-1;if(eq(array[index],value))return index}return-1}function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[]}function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[]}function tail(array){var length=array?array.length:0;return length?baseSlice(array,1,length):[]}function take(array,n,guard){return array&&array.length?(n=guard||n===undefined?1:toInteger(n),baseSlice(array,0,0>n?0:n)):[]}function takeRight(array,n,guard){var length=array?array.length:0;return length?(n=guard||n===undefined?1:toInteger(n),n=length-n,baseSlice(array,0>n?0:n,length)):[]}function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),!1,!0):[]}function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[]}function uniq(array){return array&&array.length?baseUniq(array):[]}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[]}function uniqWith(array,comparator){return array&&array.length?baseUniq(array,undefined,comparator):[]}function unzip(array){if(!array||!array.length)return[];var length=0;return array=arrayFilter(array,function(group){return isArrayLikeObject(group)?(length=nativeMax(group.length,length),!0):void 0}),baseTimes(length,function(index){return arrayMap(array,baseProperty(index))})}function unzipWith(array,iteratee){if(!array||!array.length)return[];var result=unzip(array);return null==iteratee?result:arrayMap(result,function(group){return apply(iteratee,undefined,group)})}function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue)}function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet)}function chain(value){var result=lodash(value);return result.__chain__=!0,result}function tap(value,interceptor){return interceptor(value),value}function thru(value,interceptor){return interceptor(value)}function wrapperChain(){return chain(this)}function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__)}function wrapperNext(){this.__values__===undefined&&(this.__values__=toArray(this.value()));var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return 0>fromIndex&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?length>=fromIndex&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)}function sampleSize(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)}function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n<1?func.apply(this,arguments):void 0}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),1>=n&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||0>timeSinceLastCall||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return wrapper=null==wrapper?identity:wrapper,partial(wrapper,value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,!1,!0)}function cloneWith(value,customizer){return baseClone(value,!1,!0,customizer)}function cloneDeep(value){return baseClone(value,!0,!0)}function cloneDeepWith(value,customizer){return baseClone(value,!0,!0,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&objectToString.call(value)==boolTag}function isElement(value){return null!=value&&1===value.nodeType&&isObjectLike(value)&&!isPlainObject(value)}function isEmpty(value){if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)?objectToString.call(value)==errorTag||"string"==typeof value.message&&"string"==typeof value.name:!1}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag||tag==proxyTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error(CORE_ERROR_TEXT);return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&objectToString.call(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||objectToString.call(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&MAX_SAFE_INTEGER>=value}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&objectToString.call(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&objectToString.call(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(iteratorSymbol&&value[iteratorSymbol])return iteratorToArray(value[iteratorSymbol]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=0>value?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return properties?baseAssign(result,properties):result}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3), +baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){return null==object?{}:basePickBy(object,getAllKeysIn(object),getIteratee(predicate))}function result(object,path,defaultValue){path=isKey(path,object)?[path]:castPath(path);var index=-1,length=path.length;for(length||(object=undefined,length=1);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?string+createPadding(length-strLength,chars):string}function padStart(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&length>strLength?createPadding(length-strLength,chars)+string:string}function parseInt(string,radix,guard){return guard||null==radix?radix=0:radix&&(radix=+radix),nativeParseInt(toString(string).replace(reTrimStart,""),radix||0)}function repeat(string,n,guard){return n=(guard?isIterateeCall(string,n,guard):n===undefined)?1:toInteger(n),baseRepeat(toString(string),n)}function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2])}function split(string,separator,limit){return limit&&"number"!=typeof limit&&isIterateeCall(string,separator,limit)&&(separator=limit=undefined),(limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(1>end)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=pairs?pairs.length:0,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexn||n>MAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,isProp=isKey(path),result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){var func=isFunc?path:isProp&&null!=value?value[path]:undefined;result[++index]=func?apply(func,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return other>=value}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,props){return null==object?{}:(props=arrayMap(props,toKey),basePick(object,baseDifference(getAllKeysIn(object),props)))}),pick=flatRest(function(object,props){return null==object?{}:basePick(object,arrayMap(props,toKey))}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty, +lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||0>end)?new LazyWrapper(result):(0>start?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=0>end?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,iteratorSymbol&&(lodash.prototype[iteratorSymbol]=wrapperToIterator),lodash},_=runInContext();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(root._=_,define(function(){return _})):freeModule?((freeModule.exports=_)._=_,freeExports._=_):root._=_}.call(this);var UsergridAuthMode=Object.freeze({NONE:"none",USER:"user",APP:"app"}),UsergridDirection=Object.freeze({IN:"connecting",OUT:"connections"}),UsergridHttpMethod=Object.freeze({GET:"GET",PUT:"PUT",POST:"POST",DELETE:"DELETE"}),UsergridQueryOperator=Object.freeze({EQUAL:"=",GREATER_THAN:">",GREATER_THAN_EQUAL_TO:">=",LESS_THAN:"<",LESS_THAN_EQUAL_TO:"<="}),UsergridQuerySortOrder=Object.freeze({ASC:"asc",DESC:"desc"}),UsergridApplicationJSONHeaderValue="application/json";!function(global){function UsergridHelpers(){}var name="UsergridHelpers",overwrittenName=global[name];UsergridHelpers.DefaultHeaders=Object.freeze({"Content-Type":UsergridApplicationJSONHeaderValue,Accept:UsergridApplicationJSONHeaderValue}),UsergridHelpers.validateAndRetrieveClient=function(args){var client=_.first([args,args[0],_.get(args,"client"),Usergrid.isInitialized?Usergrid:void 0].filter(function(client){return client instanceof UsergridClient}));if(!client)throw new Error("this method requires either the Usergrid shared instance to be initialized or a UsergridClient instance as the first argument");return client},UsergridHelpers.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},UsergridHelpers.flattenArgs=function(args){return _.flattenDeep(Array.prototype.slice.call(args))},UsergridHelpers.callback=function(){var args=UsergridHelpers.flattenArgs(arguments).reverse(),emptyFunc=function(){};return _.first(_.flattenDeep([args,_.get(args,"0.callback"),emptyFunc]).filter(_.isFunction))},UsergridHelpers.authForRequests=function(client){var authForRequests=void 0;return _.get(client,"tempAuth.isValid")?(authForRequests=client.tempAuth,client.tempAuth=void 0):_.get(client,"currentUser.auth.isValid")&&client.authMode===UsergridAuthMode.USER?authForRequests=client.currentUser.auth:_.get(client,"appAuth.isValid")&&client.authMode===UsergridAuthMode.APP&&(authForRequests=client.appAuth),authForRequests},UsergridHelpers.userLoginBody=function(options){var body={grant_type:"password",password:options.password};return options.tokenTtl&&(body.ttl=options.tokenTtl),body[options.username?"username":"email"]=options.username?options.username:options.email,body},UsergridHelpers.appLoginBody=function(options){var body={grant_type:"client_credentials",client_id:options.clientId,client_secret:options.clientSecret};return options.tokenTtl&&(body.ttl=options.tokenTtl),body},UsergridHelpers.userResetPasswordBody=function(args){return{oldpassword:_.isPlainObject(args[0])?args[0].oldPassword:_.isString(args[0])?args[0]:void 0,newpassword:_.isPlainObject(args[0])?args[0].newPassword:_.isString(args[1])?args[1]:void 0}},UsergridHelpers.calculateExpiry=function(expires_in){return Date.now()+1e3*(expires_in?expires_in-5:0)};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;return UsergridHelpers.isUUID=function(uuid){return uuid?uuidValueRegex.test(uuid):!1},UsergridHelpers.useQuotesIfRequired=function(value){return _.isFinite(value)||UsergridHelpers.isUUID(value)||_.isBoolean(value)||_.isObject(value)&&!_.isFunction(value)||_.isArray(value)?value:"'"+value+"'"},UsergridHelpers.setReadOnly=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setReadOnly(obj,k)}):_.isPlainObject(obj[key])?Object.freeze(obj[key]):_.isPlainObject(obj)&&void 0===key?Object.freeze(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!1}):obj},UsergridHelpers.setWritable=function(obj,key){return _.isArray(key)?key.forEach(function(k){UsergridHelpers.setWritable(obj,k)}):_.isPlainObject(obj[key])?_.clone(obj[key]):_.isPlainObject(obj)&&void 0===key?_.clone(obj):_.has(obj,key)?Object.defineProperty(obj,key,{writable:!0}):obj},UsergridHelpers.assignPrefabOptions=function(args){return _.isObject(args[0])&&!_.isFunction(args[0])&&_.has(args,"method")&&_.assign(this,args[0]),this},UsergridHelpers.normalize=function(str){return str=str.replace(/\/+/g,"/"),str=str.replace(/:\//g,"://"),str=str.replace(/\/(\?|&|#[^!])/g,"$1"),str=str.replace(/(\?.+)\?/g,"$1&")},UsergridHelpers.urljoin=function(){var input=arguments,options={};"object"==typeof arguments[0]&&(input=arguments[0],options=arguments[1]||{});var joined=[].slice.call(input,0).join("/");return UsergridHelpers.normalize(joined,options)},UsergridHelpers.parseResponseHeaders=function(headerStr){var headers={};if(headerStr)for(var headerPairs=headerStr.split("\r\n"),i=0;i0){var key=headerPair.substring(0,index).toLowerCase();headers[key]=headerPair.substring(index+2)}}return headers},UsergridHelpers.uri=function(client,options){var path="";path=options instanceof UsergridEntity?options.type:options instanceof UsergridQuery?options._type:_.isString(options)?options:_.isArray(options)?_.get(options,"0.type")||_.get(options,"0.path"):options.path||options.type||_.get(options,"entity.type")||_.get(options,"query._type")||_.get(options,"body.type")||_.get(options,"body.path");var uuidOrName="";return options.method!==UsergridHttpMethod.POST&&(uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"entity.name"),_.get(options,"body.uuid"),_.get(options,"body.name"),""].filter(_.isString))),UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,path,uuidOrName)},UsergridHelpers.updateEntityFromRemote=function(entity,usergridResponse){UsergridHelpers.setWritable(entity,["uuid","name","type","created"]),_.assign(entity,usergridResponse.entity),UsergridHelpers.setReadOnly(entity,["uuid","name","type","created"])},UsergridHelpers.headers=function(client,options,defaultHeaders){var returnHeaders={};_.defaults(returnHeaders,options.headers,defaultHeaders),_.assign(returnHeaders,{"User-Agent":"usergrid-js/v"+UsergridSDKVersion});var authForRequests=UsergridHelpers.authForRequests(client);return authForRequests&&_.assign(returnHeaders,{authorization:"Bearer "+authForRequests.token}),returnHeaders},UsergridHelpers.setEntity=function(options,args){return options.entity=_.first([options.entity,args[0]].filter(function(property){return property instanceof UsergridEntity})),void 0!==options.entity&&(options.type=options.entity.type),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setUuidOrName=function(options,args){return options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,_.get(options,"entity.uuid"),_.get(options,"body.uuid"),_.get(options,"entity.name"),_.get(options,"body.name"),_.get(args,"0.uuid"),_.get(args,"0.name"),_.get(args,"2"),_.get(args,"1")].filter(_.isString)),options},UsergridHelpers.setPathOrType=function(options,args){var pathOrType=_.first([args.type,_.get(args,"0.type"),_.get(options,"entity.type"),_.get(args,"body.type"),_.get(options,"body.0.type"),_.isArray(args)?args[0]:void 0].filter(_.isString));return options[/\//.test(pathOrType)?"path":"type"]=pathOrType,options},UsergridHelpers.setQs=function(options,args){return options.path&&(options.qs=_.first([options.qs,args[2],args[1],args[0]].filter(_.isPlainObject))),options},UsergridHelpers.setQuery=function(options,args){return options.query=_.first([options,options.query,args[0]].filter(function(property){return property instanceof UsergridQuery})),options},UsergridHelpers.setAsset=function(options,args){return options.asset=_.first([options.asset,_.get(options,"entity.asset"),args[1],args[0]].filter(function(property){return property instanceof UsergridAsset})),options},UsergridHelpers.setBody=function(options,args){var body=_.first([args.entity,args.body,args[0].entity,args[0].body,args[2],args[1],args[0]].filter(function(property){return _.isObject(property)&&!_.isFunction(property)&&!(property instanceof UsergridQuery)&&!(property instanceof UsergridAsset)}));return body instanceof UsergridEntity?body=body.jsonValue():_.isArray(body)&&body[0]instanceof UsergridEntity&&(body=_.map(body,function(entity){return entity.jsonValue()})),options.body=body,options},UsergridHelpers.buildRequest=function(client,method,args){var options={client:client,method:method,queryParams:args.queryParams||_.get(args,"0.queryParams"),callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions(options,args),UsergridHelpers.setEntity(options,args),!(method!==UsergridHttpMethod.POST&&method!==UsergridHttpMethod.PUT||(UsergridHelpers.setAsset(options,args),options.asset||(UsergridHelpers.setBody(options,args),options.body))))throw new Error("'body' is required when making a "+options.method+" request");return UsergridHelpers.setUuidOrName(options,args),UsergridHelpers.setPathOrType(options,args),UsergridHelpers.setQs(options,args),UsergridHelpers.setQuery(options,args),options.uri=UsergridHelpers.uri(client,options),new UsergridRequest(options)},UsergridHelpers.buildAppAuthRequest=function(client,auth,callback){var requestOptions={client:client,method:UsergridHttpMethod.POST,uri:UsergridHelpers.uri(client,{path:"token"}),body:UsergridHelpers.appLoginBody(auth),callback:callback};return new UsergridRequest(requestOptions)},UsergridHelpers.buildConnectionRequest=function(client,method,args){var options={client:client,method:method,entity:{},to:{},callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(options.from)&&(options.to=options.from),_.isObject(args[0])&&_.has(args[0],"entity")&&_.has(args[0],"to")&&(_.assign(options.entity,args[0].entity),options.relationship=_.get(args,"0.relationship"),_.assign(options.to,args[0].to)),_.isObject(args[0])&&!_.isFunction(args[0])&&_.isString(args[1])&&(_.assign(options.entity,args[0]),options.relationship=_.first([options.relationship,args[1]].filter(_.isString))),_.isObject(args[2])&&!_.isFunction(args[2])&&_.assign(options.to,args[2]),options.entity.uuidOrName=_.first([options.entity.uuidOrName,options.entity.uuid,options.entity.name,args[1]].filter(_.isString)),options.entity.type||(options.entity.type=_.first([options.entity.type,args[0]].filter(_.isString))),options.relationship=_.first([options.relationship,args[2]].filter(_.isString)),_.isString(args[3])&&!UsergridHelpers.isUUID(args[3])&&_.isString(args[4])?options.to.type=args[3]:_.isString(args[2])&&!UsergridHelpers.isUUID(args[2])&&_.isString(args[3])&&_.isObject(args[0])&&!_.isFunction(args[0])&&(options.to.type=args[2]),options.to.uuidOrName=_.first([options.to.uuidOrName,options.to.uuid,options.to.name,args[4],args[3],args[2]].filter(function(property){return _.isString(options.to.type)&&_.isString(property)||UsergridHelpers.isUUID(property)})),!_.isString(options.entity.uuidOrName))throw new Error("source entity 'uuidOrName' is required when connecting or disconnecting entities");if(!_.isString(options.to.uuidOrName))throw new Error("target entity 'uuidOrName' is required when connecting or disconnecting entities");if(!_.isString(options.to.type)&&!UsergridHelpers.isUUID(options.to.uuidOrName))throw new Error("target 'type' (collection name) parameter is required connecting or disconnecting entities by name");return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.entity.type)?options.entity.type:"",_.isString(options.entity.uuidOrName)?options.entity.uuidOrName:"",options.relationship,_.isString(options.to.type)?options.to.type:"",_.isString(options.to.uuidOrName)?options.to.uuidOrName:""),new UsergridRequest(options)},UsergridHelpers.buildGetConnectionRequest=function(client,args){var options={client:client,method:"GET",callback:UsergridHelpers.callback(args)};if(UsergridHelpers.assignPrefabOptions.call(options,args),_.isObject(args[1])&&!_.isFunction(args[1])&&_.assign(options,args[1]),options.direction=_.first([options.direction,args[0]].filter(function(property){return property===UsergridDirection.IN||property===UsergridDirection.OUT})),options.relationship=_.first([options.relationship,args[3],args[2]].filter(_.isString)),options.uuidOrName=_.first([options.uuidOrName,options.uuid,options.name,args[2]].filter(_.isString)),options.type=_.first([options.type,args[1]].filter(_.isString)),!_.isString(options.type))throw new Error("'type' (collection name) parameter is required when retrieving connections");if(!_.isString(options.uuidOrName))throw new Error("target entity 'uuidOrName' is required when retrieving connections");return options.uri=UsergridHelpers.urljoin(client.baseUrl,client.orgId,client.appId,_.isString(options.type)?options.type:"",_.isString(options.uuidOrName)?options.uuidOrName:"",options.direction,options.relationship),new UsergridRequest(options)},global[name]=UsergridHelpers,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),UsergridHelpers},global[name]}(this);var UsergridClientDefaultOptions={baseUrl:"https://api.usergrid.com",authMode:UsergridAuthMode.USER},UsergridClient=function(options){var __appAuth,self=this;if(self.tempAuth=void 0,self.isSharedInstance=!1,2===arguments.length&&(self.orgId=arguments[0],self.appId=arguments[1]),_.defaults(self,options,UsergridClientDefaultOptions),!self.orgId||!self.appId)throw new Error("'orgId' and 'appId' parameters are required when instantiating UsergridClient");return Object.defineProperty(self,"clientId",{enumerable:!1}),Object.defineProperty(self,"clientSecret",{enumerable:!1}),Object.defineProperty(self,"appAuth",{get:function(){return __appAuth},set:function(options){options instanceof UsergridAppAuth?__appAuth=options:"undefined"!=typeof options&&(__appAuth=new UsergridAppAuth(options))}}),self.clientId&&self.clientSecret&&self.setAppAuth(self.clientId,self.clientSecret),self};UsergridClient.prototype={sendRequest:function(usergridRequest){return usergridRequest.sendRequest()},GET:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},PUT:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},POST:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},DELETE:function(){var usergridRequest=UsergridHelpers.buildRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},connect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.POST,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},disconnect:function(){var usergridRequest=UsergridHelpers.buildConnectionRequest(this,UsergridHttpMethod.DELETE,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},getConnections:function(){var usergridRequest=UsergridHelpers.buildGetConnectionRequest(this,UsergridHelpers.flattenArgs(arguments));return this.sendRequest(usergridRequest)},usingAuth:function(auth){var self=this;return _.isString(auth)?self.tempAuth=new UsergridAuth(auth):auth instanceof UsergridAuth?self.tempAuth=auth:self.tempAuth=void 0,self},setAppAuth:function(){this.appAuth=new UsergridAppAuth(UsergridHelpers.flattenArgs(arguments))},authenticateApp:function(options){var self=this,authenticateAppCallback=UsergridHelpers.callback(UsergridHelpers.flattenArgs(arguments)),auth=_.first([options,self.appAuth,new UsergridAppAuth(options),new UsergridAppAuth(self.clientId,self.clientSecret)].filter(function(p){return p instanceof UsergridAppAuth}));if(!(auth instanceof UsergridAppAuth))throw new Error("App auth context was not defined when attempting to call .authenticateApp()");if(!auth.clientId||!auth.clientSecret)throw new Error("authenticateApp() failed because clientId or clientSecret are missing");var callback=function(error,usergridResponse){var token=_.get(usergridResponse.responseJSON,"access_token"),expiresIn=_.get(usergridResponse.responseJSON,"expires_in");usergridResponse.ok&&(self.appAuth||(self.appAuth=auth),self.appAuth.token=token,self.appAuth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.appAuth.tokenTtl=expiresIn),authenticateAppCallback(error,usergridResponse,token)},usergridRequest=UsergridHelpers.buildAppAuthRequest(self,auth,callback);return self.sendRequest(usergridRequest)},authenticateUser:function(options){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),setAsCurrentUser=void 0!==_.last(args.filter(_.isBoolean))?_.last(args.filter(_.isBoolean)):!0,userToAuthenticate=new UsergridUser(options);userToAuthenticate.login(self,function(error,usergridResponse,token){usergridResponse.ok&&setAsCurrentUser&&(self.currentUser=userToAuthenticate),callback(usergridResponse.error,usergridResponse,token)})},downloadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildRequest(self,UsergridHttpMethod.GET,UsergridHelpers.flattenArgs(arguments)),assetContentType=_.get(usergridRequest,"entity.file-metadata.content-type");void 0!==assetContentType&&_.assign(usergridRequest.headers,{Accept:assetContentType});var realDownloadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var entity=usergridRequest.entity;entity.asset=usergridResponse.asset,realDownloadAssetCallback(error,usergridResponse,entity)},self.sendRequest(usergridRequest)},uploadAsset:function(){var self=this,usergridRequest=UsergridHelpers.buildRequest(self,UsergridHttpMethod.PUT,UsergridHelpers.flattenArgs(arguments));if(void 0===usergridRequest.asset)throw new Error("An UsergridAsset was not defined when attempting to call .uploadAsset()");var realUploadAssetCallback=usergridRequest.callback;return usergridRequest.callback=function(error,usergridResponse){var requestEntity=usergridRequest.entity,responseEntity=usergridResponse.entity,requestAsset=usergridRequest.asset;usergridResponse.ok&&void 0!==responseEntity&&(UsergridHelpers.updateEntityFromRemote(requestEntity,usergridResponse),requestEntity.asset=requestAsset,responseEntity&&(responseEntity.asset=requestAsset)),realUploadAssetCallback(error,usergridResponse,requestEntity)},self.sendRequest(usergridRequest)}};var UsergridSDKVersion="2.0.0",UsergridClientSharedInstance=function(){var self=this;return self.isInitialized=!1,self.isSharedInstance=!0,self};UsergridHelpers.inherits(UsergridClientSharedInstance,UsergridClient);var Usergrid=new UsergridClientSharedInstance;Usergrid.initSharedInstance=function(options){return Usergrid.isInitialized?console.log("Usergrid shared instance is already initialized"):(_.assign(Usergrid,new UsergridClient(options)),Usergrid.isInitialized=!0,Usergrid.isSharedInstance=!0),Usergrid},Usergrid.init=Usergrid.initSharedInstance;var UsergridQuery=function(type){var queryString,sort,self=this,query="",urlTerms={},__nextIsNot=!1;return self._type=type,_.assign(self,{type:function(value){return self._type=value,self},collection:function(value){return self._type=value,self},limit:function(value){return self._limit=value,self},cursor:function(value){return self._cursor=value,self},eq:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.EQUAL+" "+UsergridHelpers.useQuotesIfRequired(value)),self},equal:this.eq,gt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThan:this.gt,gte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.GREATER_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},greaterThanOrEqual:this.gte,lt:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThan:this.lt,lte:function(key,value){return query=self.andJoin(key+" "+UsergridQueryOperator.LESS_THAN_EQUAL_TO+" "+UsergridHelpers.useQuotesIfRequired(value)),self},lessThanOrEqual:this.lte,contains:function(key,value){return query=self.andJoin(key+" contains "+UsergridHelpers.useQuotesIfRequired(value)),self},locationWithin:function(distanceInMeters,lat,lng){return query=self.andJoin("location within "+distanceInMeters+" of "+lat+", "+lng),self},asc:function(key){return self.sort(key,UsergridQuerySortOrder.ASC),self},desc:function(key){return self.sort(key,UsergridQuerySortOrder.DESC),self},sort:function(key,order){return sort=key&&order?" order by "+key+" "+order:"",self},fromString:function(string){return queryString=string, +self},urlTerm:function(key,value){return"ql"===key?self.fromString():urlTerms[key]=value,self},andJoin:function(append){return __nextIsNot&&(append="not "+append,__nextIsNot=!1),append?0===query.length?append:_.endsWith(query,"and")||_.endsWith(query,"or")?query+" "+append:query+" and "+append:query},orJoin:function(){return query.length>0&&!_.endsWith(query,"or")?query+" or":query}}),Object.defineProperty(self,"_ql",{get:function(){var ql="select * ";return void 0!==queryString?ql=queryString:(ql+=query.length>0?"where "+(query||""):"",ql+=void 0!==sort?sort:""),ql}}),Object.defineProperty(self,"encodedStringValue",{get:function(){var self=this,limit=self._limit,cursor=self._cursor,requirementsString=self._ql,returnString=void 0;if(void 0!==limit&&(returnString="limit"+UsergridQueryOperator.EQUAL+limit),!_.isEmpty(cursor)){var cursorString="cursor"+UsergridQueryOperator.EQUAL+cursor;_.isEmpty(returnString)?returnString=cursorString:returnString+="&"+cursorString}if(_.forEach(urlTerms,function(value,key){var encodedURLTermString=encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value);_.isEmpty(returnString)?returnString=encodedURLTermString:returnString+="&"+encodedURLTermString}),!_.isEmpty(requirementsString)){var qLString="ql="+encodeURIComponent(requirementsString);_.isEmpty(returnString)?returnString=qLString:returnString+="&"+qLString}return _.isEmpty(returnString)||(returnString="?"+returnString),_.isEmpty(returnString)?void 0:returnString}}),Object.defineProperty(self,"and",{get:function(){return query=self.andJoin(""),self}}),Object.defineProperty(self,"or",{get:function(){return query=self.orJoin(),self}}),Object.defineProperty(self,"not",{get:function(){return __nextIsNot=!0,self}}),self},UsergridRequest=function(options){var self=this,client=UsergridHelpers.validateAndRetrieveClient(options);if(!_.isString(options.type)&&!_.isString(options.path)&&!_.isString(options.uri))throw new Error("one of 'type' (collection name), 'path', or 'uri' parameters are required when initializing a UsergridRequest");if(!_.includes(["GET","PUT","POST","DELETE"],options.method))throw new Error("'method' parameter is required when initializing a UsergridRequest");self.method=options.method,self.callback=options.callback,self.uri=options.uri||UsergridHelpers.uri(client,options),self.entity=options.entity,self.body=options.body,self.asset=options.asset,self.query=options.query,self.queryParams=options.queryParams||options.qs;var defaultHeadersToUse=self.asset?{}:UsergridHelpers.DefaultHeaders;if(self.headers=UsergridHelpers.headers(client,options,defaultHeadersToUse),void 0!==self.query&&(self.uri+=UsergridHelpers.normalize(self.query.encodedStringValue,{})),self.queryParams&&(_.forOwn(self.queryParams,function(value,key){self.uri+="?"+encodeURIComponent(key)+UsergridQueryOperator.EQUAL+encodeURIComponent(value)}),self.uri=UsergridHelpers.normalize(self.uri,{})),self.asset)self.body=new FormData,self.body.append(self.asset.filename,self.asset.data);else try{_.isPlainObject(self.body)?self.body=JSON.stringify(self.body):_.isArray(self.body)&&(self.body=JSON.stringify(self.body))}catch(exception){console.warn("Unable to convert 'UsergridRequest.body' to a JSON String: "+exception)}return self};UsergridRequest.prototype.sendRequest=function(){var self=this,requestPromise=function(){var promise=new Promise,xmlHttpRequest=new XMLHttpRequest;return xmlHttpRequest.open(self.method,self.uri,!0),xmlHttpRequest.onload=function(){promise.done(xmlHttpRequest)},_.forOwn(self.headers,function(value,key){xmlHttpRequest.setRequestHeader(key,value)}),self.method===UsergridHttpMethod.GET&&_.get(self.headers,"Accept")!==UsergridApplicationJSONHeaderValue&&(xmlHttpRequest.responseType="blob"),xmlHttpRequest.send(self.body),promise},responsePromise=function(xmlRequest){var promise=new Promise,usergridResponse=new UsergridResponse(xmlRequest,self);return promise.done(usergridResponse),promise},onCompletePromise=function(usergridResponse){self.callback(usergridResponse.error,usergridResponse)};return Promise.chain([requestPromise,responsePromise]).then(onCompletePromise),self};var UsergridAuth=function(token,expiry){var self=this;self.token=token,self.expiry=expiry||0;var usingToken=token?!0:!1;return Object.defineProperty(self,"hasToken",{get:function(){return void 0!==self.token},configurable:!0}),Object.defineProperty(self,"isExpired",{get:function(){return usingToken?!1:Date.now()>=self.expiry},configurable:!0}),Object.defineProperty(self,"isValid",{get:function(){return!self.isExpired&&self.hasToken},configurable:!0}),Object.defineProperty(self,"tokenTtl",{configurable:!0,writable:!0}),_.assign(self,{destroy:function(){self.token=void 0,self.expiry=0,self.tokenTtl=void 0}}),self},UsergridAppAuth=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);return _.isPlainObject(args[0])?(self.clientId=args[0].clientId,self.clientSecret=args[0].clientSecret,self.tokenTtl=args[0].tokenTtl):(self.clientId=args[0],self.clientSecret=args[1],self.tokenTtl=args[2]),UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridAppAuth,UsergridAuth);var UsergridUserAuth=function(options){var self=this,args=_.flattenDeep(UsergridHelpers.flattenArgs(arguments));return _.isPlainObject(args[0])&&(options=args[0]),self.username=options.username||args[0],self.email=options.email,(options.password||args[1])&&(self.password=options.password||args[1]),self.tokenTtl=options.tokenTtl||args[2],UsergridAuth.call(self),_.assign(self,UsergridAuth),self};UsergridHelpers.inherits(UsergridUserAuth,UsergridAuth);var UsergridEntity=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments);if(0===args.length)throw new Error("A UsergridEntity object cannot be initialized without passing one or more arguments");if(self.asset=void 0,_.isPlainObject(args[0])?_.assign(self,args[0]):(self.type||(self.type=_.isString(args[0])?args[0]:void 0),self.name||(self.name=_.isString(args[1])?args[1]:void 0)),!_.isString(self.type))throw new Error("'type' (or 'collection') parameter is required when initializing a UsergridEntity object");return Object.defineProperty(self,"isUser",{get:function(){return"user"===self.type.toLowerCase()}}),Object.defineProperty(self,"hasAsset",{get:function(){return _.has(self,"file-metadata")}}),UsergridHelpers.setReadOnly(self,["uuid","name","type","created"]),self};UsergridEntity.prototype={jsonValue:function(){var jsonValue={};return _.forOwn(this,function(value,key){jsonValue[key]=value}),jsonValue},putProperty:function(key,value){this[key]=value},putProperties:function(obj){_.assign(this,obj)},removeProperty:function(key){this.removeProperties([key])},removeProperties:function(keys){var self=this;keys.forEach(function(key){delete self[key]})},insert:function(key,value,idx){_.isArray(this[key])||(this[key]=this[key]?[this[key]]:[]),this[key].splice.apply(this[key],[idx,0].concat(value))},append:function(key,value){this.insert(key,value,Number.MAX_VALUE)},prepend:function(key,value){this.insert(key,value,0)},pop:function(key){_.isArray(this[key])&&this[key].pop()},shift:function(key){_.isArray(this[key])&&this[key].shift()},reload:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.GET(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),callback(error,usergridResponse,self)}.bind(self))},save:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),currentAsset=self.asset;client.PUT(self,function(error,usergridResponse){UsergridHelpers.updateEntityFromRemote(self,usergridResponse),self.hasAsset&&(self.asset=currentAsset),callback(error,usergridResponse,self)}.bind(self))},remove:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.DELETE(self,function(error,usergridResponse){callback(error,usergridResponse,self)}.bind(self))},attachAsset:function(asset){this.asset=asset},uploadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.uploadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},downloadAsset:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(_.has(self,"asset.contentType"))client.downloadAsset(self,callback);else{var response=UsergridResponse.responseWithError({name:"asset_not_found",description:"The specified entity does not have a valid asset attached"});callback(response.error,response,self)}},connect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.connect.apply(client,args)},disconnect:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args[0]=this,client.disconnect.apply(client,args)},getConnections:function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args);return args.shift(),args.splice(1,0,this),client.getConnections.apply(client,args)}};var UsergridUser=function(obj){if(!_.has(obj,"email")&&!_.has(obj,"username"))throw new Error("'email' or 'username' property is required when initializing a UsergridUser object");var self=this;return _.assign(self,obj,UsergridEntity),UsergridEntity.call(self,"user"),UsergridHelpers.setWritable(self,"name"),self};UsergridUser.CheckAvailable=function(){var args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args),username=args[0].username||args[1].username,email=args[0].email||args[1].email;if(!username&&!email)throw new Error("'username' or 'email' property is required when checking for available users");var checkQuery=new UsergridQuery("users");username&&checkQuery.eq("username",username),email&&checkQuery.or.eq("email",email),client.GET(checkQuery,function(error,usergridResponse){callback(error,usergridResponse,usergridResponse.entities.length>0)})},UsergridHelpers.inherits(UsergridUser,UsergridEntity),UsergridUser.prototype.uniqueId=function(){var self=this;return _.first([self.uuid,self.username,self.email].filter(_.isString))},UsergridUser.prototype.create=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST(self,function(error,usergridResponse){delete self.password,_.assign(self,usergridResponse.user),callback(error,usergridResponse,self)}.bind(self))},UsergridUser.prototype.login=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);client.POST("token",UsergridHelpers.userLoginBody(self),function(error,usergridResponse){delete self.password;var responseJSON=usergridResponse.responseJSON,token=_.get(responseJSON,"access_token"),expiresIn=_.get(responseJSON,"expires_in");usergridResponse.ok&&(self.auth=new UsergridUserAuth(self),self.auth.token=token,self.auth.expiry=UsergridHelpers.calculateExpiry(expiresIn),self.auth.tokenTtl=expiresIn),callback(error,usergridResponse,token)})},UsergridUser.prototype.logout=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);if(self.auth&&self.auth.isValid){var revokeAll=_.first(args.filter(_.isBoolean))||!1,requestOptions={client:client,path:["users",self.uniqueId(),"revoketoken"+(revokeAll?"s":"")].join("/"),method:UsergridHttpMethod.PUT,callback:function(error,usergridResponse){self.auth.destroy(),callback(error,usergridResponse,usergridResponse.ok)}.bind(self)};revokeAll||(requestOptions.queryParams={token:self.auth.token});var request=new UsergridRequest(requestOptions);client.sendRequest(request)}else{var response=UsergridResponse.responseWithError({name:"no_valid_token",description:"this user does not have a valid token"});callback(response.error,response)}},UsergridUser.prototype.logoutAllSessions=function(){var args=UsergridHelpers.flattenArgs(arguments);return args=_.concat([UsergridHelpers.validateAndRetrieveClient(args),!0],args),this.logout.apply(this,args)},UsergridUser.prototype.resetPassword=function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),client=UsergridHelpers.validateAndRetrieveClient(args),callback=UsergridHelpers.callback(args);args[0]instanceof UsergridClient&&args.shift();var body=UsergridHelpers.userResetPasswordBody(args);if(!body.oldpassword||!body.newpassword)throw new Error("'oldPassword' and 'newPassword' properties are required when resetting a user password");client.PUT(["users",self.uniqueId(),"password"].join("/"),body,callback)};var UsergridResponseError=function(options){var self=this;return _.assign(self,options),self};UsergridResponseError.fromJSON=function(responseErrorObject){var usergridResponseError,error={name:_.get(responseErrorObject,"error")};return error.name&&(_.assign(error,{exception:_.get(responseErrorObject,"exception"),description:_.get(responseErrorObject,"error_description")||_.get(responseErrorObject,"description")}),usergridResponseError=new UsergridResponseError(error)),usergridResponseError};var UsergridResponse=function(xmlRequest,usergridRequest){var self=this;if(self.ok=!1,self.request=usergridRequest,xmlRequest){self.statusCode=parseInt(xmlRequest.status),self.ok=self.statusCode<400,self.headers=UsergridHelpers.parseResponseHeaders(xmlRequest.getAllResponseHeaders());var responseContentType=_.get(self.headers,"content-type");if(responseContentType===UsergridApplicationJSONHeaderValue)try{var responseJSON=JSON.parse(xmlRequest.responseText);responseJSON&&self.parseResponseJSON(responseJSON)}catch(e){}else self.asset=new UsergridAsset(xmlRequest.response)}return self};UsergridResponse.responseWithError=function(options){var usergridResponse=new UsergridResponse;return usergridResponse.error=new UsergridResponseError(options),usergridResponse},UsergridResponse.prototype={parseResponseJSON:function(responseJSON){var self=this;if(self.responseJSON=_.cloneDeep(responseJSON),self.ok){self.cursor=_.get(self,"responseJSON.cursor"),self.hasNextPage=!_.isNil(self.cursor);var entitiesJSON=_.get(responseJSON,"entities");entitiesJSON&&(self.parseResponseEntities(entitiesJSON),delete self.responseJSON.entities)}else self.error=UsergridResponseError.fromJSON(responseJSON);UsergridHelpers.setReadOnly(self.responseJSON)},parseResponseEntities:function(entitiesJSON){var self=this;self.entities=_.map(entitiesJSON,function(entityJSON){var entity=new UsergridEntity(entityJSON);return entity.isUser&&(entity=new UsergridUser(entity)),entity}),self.first=_.first(self.entities),self.entity=self.first,self.last=_.last(self.entities),"/users"===_.get(self,"responseJSON.path")&&(self.user=self.first,self.users=self.entities)},loadNextPage:function(){var self=this,args=UsergridHelpers.flattenArgs(arguments),callback=UsergridHelpers.callback(args),cursor=self.cursor;if(cursor){var client=UsergridHelpers.validateAndRetrieveClient(args),type=_.last(_.get(self,"responseJSON.path").split("/")),limit=_.first(_.get(self,"responseJSON.params.limit")),ql=_.first(_.get(self,"responseJSON.params.ql")),query=new UsergridQuery(type).fromString(ql).cursor(cursor).limit(limit);client.GET(query,callback)}else callback(UsergridResponse.responseWithError({name:"cursor_not_found",description:"Cursor must be present in order perform loadNextPage()."}))}};var UsergridAssetDefaultFileName="file",UsergridAsset=function(fileOrBlob){if(!fileOrBlob instanceof File||!fileOrBlob instanceof Blob)throw new Error("UsergridAsset must be initialized with a 'File' or 'Blob'");var self=this;return self.data=fileOrBlob,self.filename=fileOrBlob.name||UsergridAssetDefaultFileName,self.contentLength=fileOrBlob.size,self.contentType=fileOrBlob.type,self}; \ No newline at end of file