From 8cc5fb168444cf3ef4ebc5cdcdd42c0852c4f56f Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Tue, 27 Mar 2018 15:38:58 +0530 Subject: [PATCH 01/11] #5 fetch all projects --- dist/bundle.js | 28 +++++++++++++++++++++++++--- js/app.js | 27 +++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index c844002..d3f8ca4 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -851,6 +851,8 @@ let head = '[out:xml][timeout:25];' let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' map.on('load', function () { map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) + let projects = getProjects() + console.log(projects[0]) }) // Functions @@ -891,10 +893,9 @@ function getQuery () { * Adds three layers using geojson data * Adds a legend & geometry count to the page * - * @param {function} callback - callback **/ -function getData (callback) { +function getData () { let url = getQuery() $('.loading').css('display', 'inline-block') $.ajax(url) @@ -971,7 +972,6 @@ function getData (callback) { * * @param {string} message - custom error message for different scenarios * @param {number} time - time in milliseconds - * **/ function errorNotice (message, time) { @@ -988,6 +988,28 @@ function errorNotice (message, time) { } } +/** + * Fetches all ative projects using HOTOSM API + * + **/ + +function getProjects () { + let url = 'https://tasks.hotosm.org/api/v1/project/search' + let projects = [] + $.ajax(url) + .done(function (data) { + data.mapResults.features.forEach(function (project) { + projects.push(project.properties.projectId) + console.log(projects) + }) + return projects + }) + .fail(function () { + errorNotice('Too much data to fetch, zoom in further') + }) + +} + // Fetch Data on Click $('#submit').on('click', function () { diff --git a/js/app.js b/js/app.js index 3a4062a..3df3fe6 100644 --- a/js/app.js +++ b/js/app.js @@ -42,6 +42,8 @@ let head = '[out:xml][timeout:25];' let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' map.on('load', function () { map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) + let projects = getProjects() + console.log(projects[0]) }) // Functions @@ -82,10 +84,9 @@ function getQuery () { * Adds three layers using geojson data * Adds a legend & geometry count to the page * - * @param {function} callback - callback **/ -function getData (callback) { +function getData () { let url = getQuery() $('.loading').css('display', 'inline-block') $.ajax(url) @@ -178,6 +179,28 @@ function errorNotice (message, time) { } } +/** + * Fetches all ative projects using HOTOSM API + * + **/ + +function getProjects () { + let url = 'https://tasks.hotosm.org/api/v1/project/search' + let projects = [] + $.ajax(url) + .done(function (data) { + data.mapResults.features.forEach(function (project) { + projects.push(project.properties.projectId) + console.log(projects) + }) + return projects + }) + .fail(function () { + errorNotice('Too much data to fetch, zoom in further') + }) + +} + // Fetch Data on Click $('#submit').on('click', function () { From 49b77eedd5739ad6bb42b3da6eb99b8e361f17db Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Wed, 28 Mar 2018 10:10:50 +0530 Subject: [PATCH 02/11] #5, #7 added a combo box for projects --- dist/bundle.js | 14 +++++++------- index.html | 5 +++++ js/app.js | 14 +++++++------- 3 files changed, 19 insertions(+), 14 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index d3f8ca4..d47aeb3 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -850,9 +850,10 @@ let overpassDataSource = { let head = '[out:xml][timeout:25];' let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' map.on('load', function () { + $('.loading').css('display', 'block') map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) - let projects = getProjects() - console.log(projects[0]) + getProjects() + $('.loading').css('display', 'none') }) // Functions @@ -995,19 +996,18 @@ function errorNotice (message, time) { function getProjects () { let url = 'https://tasks.hotosm.org/api/v1/project/search' - let projects = [] $.ajax(url) .done(function (data) { + let select = document.getElementById('projects') data.mapResults.features.forEach(function (project) { - projects.push(project.properties.projectId) - console.log(projects) + let option = document.createElement('option') + option.text = option.value = project.properties.projectId + select.add(option, 0) }) - return projects }) .fail(function () { errorNotice('Too much data to fetch, zoom in further') }) - } // Fetch Data on Click diff --git a/index.html b/index.html index badaafe..3ae3ce2 100644 --- a/index.html +++ b/index.html @@ -28,6 +28,11 @@

+
+ +
diff --git a/js/app.js b/js/app.js index 3df3fe6..a431e84 100644 --- a/js/app.js +++ b/js/app.js @@ -41,9 +41,10 @@ let overpassDataSource = { let head = '[out:xml][timeout:25];' let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' map.on('load', function () { + $('.loading').css('display', 'block') map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) - let projects = getProjects() - console.log(projects[0]) + getProjects() + $('.loading').css('display', 'none') }) // Functions @@ -186,19 +187,18 @@ function errorNotice (message, time) { function getProjects () { let url = 'https://tasks.hotosm.org/api/v1/project/search' - let projects = [] $.ajax(url) .done(function (data) { + let select = document.getElementById('projects') data.mapResults.features.forEach(function (project) { - projects.push(project.properties.projectId) - console.log(projects) + let option = document.createElement('option') + option.text = option.value = project.properties.projectId + select.add(option, 0) }) - return projects }) .fail(function () { errorNotice('Too much data to fetch, zoom in further') }) - } // Fetch Data on Click From 763bbe1fbb52f0921c1c9b6bfc22a50f62a6dbd5 Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Wed, 28 Mar 2018 10:22:35 +0530 Subject: [PATCH 03/11] #5, #7 event listener for project selection --- dist/bundle.js | 24 +++++------------------- index.html | 18 +++++++++++++++++- js/app.js | 24 +++++------------------- 3 files changed, 27 insertions(+), 39 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index d47aeb3..0e20b7a 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -850,10 +850,7 @@ let overpassDataSource = { let head = '[out:xml][timeout:25];' let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' map.on('load', function () { - $('.loading').css('display', 'block') map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) - getProjects() - $('.loading').css('display', 'none') }) // Functions @@ -990,25 +987,14 @@ function errorNotice (message, time) { } /** - * Fetches all ative projects using HOTOSM API + * Event listener for project selection * **/ -function getProjects () { - let url = 'https://tasks.hotosm.org/api/v1/project/search' - $.ajax(url) - .done(function (data) { - let select = document.getElementById('projects') - data.mapResults.features.forEach(function (project) { - let option = document.createElement('option') - option.text = option.value = project.properties.projectId - select.add(option, 0) - }) - }) - .fail(function () { - errorNotice('Too much data to fetch, zoom in further') - }) -} +document.getElementById('projects').addEventListener('change', function (e) { + let projectID = this.value + console.log(projectID) +}) // Fetch Data on Click diff --git a/index.html b/index.html index 3ae3ce2..e28ef22 100644 --- a/index.html +++ b/index.html @@ -12,7 +12,23 @@ - + diff --git a/js/app.js b/js/app.js index a431e84..badf802 100644 --- a/js/app.js +++ b/js/app.js @@ -41,10 +41,7 @@ let overpassDataSource = { let head = '[out:xml][timeout:25];' let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' map.on('load', function () { - $('.loading').css('display', 'block') map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) - getProjects() - $('.loading').css('display', 'none') }) // Functions @@ -181,25 +178,14 @@ function errorNotice (message, time) { } /** - * Fetches all ative projects using HOTOSM API + * Event listener for project selection * **/ -function getProjects () { - let url = 'https://tasks.hotosm.org/api/v1/project/search' - $.ajax(url) - .done(function (data) { - let select = document.getElementById('projects') - data.mapResults.features.forEach(function (project) { - let option = document.createElement('option') - option.text = option.value = project.properties.projectId - select.add(option, 0) - }) - }) - .fail(function () { - errorNotice('Too much data to fetch, zoom in further') - }) -} +document.getElementById('projects').addEventListener('change', function (e) { + let projectID = this.value + console.log(projectID) +}) // Fetch Data on Click From 964b52af89834a58bf3544fe26817c6368215a0c Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Wed, 28 Mar 2018 10:27:15 +0530 Subject: [PATCH 04/11] #5, #7 project details func --- dist/bundle.js | 12 +++++++++++- js/app.js | 12 +++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index 0e20b7a..64b6cd1 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -993,9 +993,19 @@ function errorNotice (message, time) { document.getElementById('projects').addEventListener('change', function (e) { let projectID = this.value - console.log(projectID) + projDetails(projectID) }) +/** + * Fetches complete details of a particular HOTOSM project + * + * @param {number} projectID - Unique ID of a HOTOSM project + **/ + +function projDetails (projectID) { + console.log('From projDetails: ', projectID) +} + // Fetch Data on Click $('#submit').on('click', function () { diff --git a/js/app.js b/js/app.js index badf802..cf46584 100644 --- a/js/app.js +++ b/js/app.js @@ -184,9 +184,19 @@ function errorNotice (message, time) { document.getElementById('projects').addEventListener('change', function (e) { let projectID = this.value - console.log(projectID) + projDetails(projectID) }) +/** + * Fetches complete details of a particular HOTOSM project + * + * @param {number} projectID - Unique ID of a HOTOSM project + **/ + +function projDetails (projectID) { + console.log('From projDetails: ', projectID) +} + // Fetch Data on Click $('#submit').on('click', function () { From 84ba5f3bd7bbda9f91cba4a5985d51018b80a302 Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Wed, 28 Mar 2018 10:44:29 +0530 Subject: [PATCH 05/11] #5, #7 polygon & mapping entitied for a project --- dist/bundle.js | 29 +++++++++++++++++++---------- js/app.js | 29 +++++++++++++++++++---------- 2 files changed, 38 insertions(+), 20 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index 64b6cd1..8d8e0a8 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -987,23 +987,33 @@ function errorNotice (message, time) { } /** - * Event listener for project selection + * Construct URL to request a particular project details * **/ -document.getElementById('projects').addEventListener('change', function (e) { - let projectID = this.value - projDetails(projectID) -}) +function getProjQuery () { + let projectID = document.getElementById('projects').value + let url = 'https://tasks.hotosm.org/api/v1/project/' + projectID + '?as_file=false' + return url +} /** * Fetches complete details of a particular HOTOSM project * - * @param {number} projectID - Unique ID of a HOTOSM project **/ -function projDetails (projectID) { - console.log('From projDetails: ', projectID) +function getProjDetails () { + let url = getProjQuery() + console.log('From projDetails: ', url) + $.ajax(url) + .done(function (data) { + let polygon = data.areaOfInterest + let entities = data.mappingTypes + console.log(entities) + console.log(polygon) + }) + .fail(function () { + }) } // Fetch Data on Click @@ -1017,8 +1027,7 @@ $('#submit').on('click', function () { 'fromDate': moment($('#fromdate').val()).utc().toISOString(), 'toDate': moment($('#todate').val()).utc().toISOString() } - let url = getQuery() - console.log('from submit before fetching ', url) + getProjDetails() getData() } else { errorNotice('Zoom in further to fetch results') diff --git a/js/app.js b/js/app.js index cf46584..c54b390 100644 --- a/js/app.js +++ b/js/app.js @@ -178,23 +178,33 @@ function errorNotice (message, time) { } /** - * Event listener for project selection + * Construct URL to request a particular project details * **/ -document.getElementById('projects').addEventListener('change', function (e) { - let projectID = this.value - projDetails(projectID) -}) +function getProjQuery () { + let projectID = document.getElementById('projects').value + let url = 'https://tasks.hotosm.org/api/v1/project/' + projectID + '?as_file=false' + return url +} /** * Fetches complete details of a particular HOTOSM project * - * @param {number} projectID - Unique ID of a HOTOSM project **/ -function projDetails (projectID) { - console.log('From projDetails: ', projectID) +function getProjDetails () { + let url = getProjQuery() + console.log('From projDetails: ', url) + $.ajax(url) + .done(function (data) { + let polygon = data.areaOfInterest + let entities = data.mappingTypes + console.log(entities) + console.log(polygon) + }) + .fail(function () { + }) } // Fetch Data on Click @@ -208,8 +218,7 @@ $('#submit').on('click', function () { 'fromDate': moment($('#fromdate').val()).utc().toISOString(), 'toDate': moment($('#todate').val()).utc().toISOString() } - let url = getQuery() - console.log('from submit before fetching ', url) + getProjDetails() getData() } else { errorNotice('Zoom in further to fetch results') From cf90eae4d047f8904b50fbf31037c1d7117ca68d Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Wed, 28 Mar 2018 11:55:02 +0530 Subject: [PATCH 06/11] comments --- dist/bundle.js | 11 +++++++---- js/app.js | 11 +++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index 8d8e0a8..115ec13 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -811,7 +811,7 @@ const osmtogeojson = require('osmtogeojson') const util = require('util') const moment = require('moment') -// Inittialising map +// Initialising map mapboxgl.accessToken = 'pk.eyJ1IjoicnVtYyIsImEiOiJjamJhdHJzODUxMGUyMnFub2l3cTlmMTJnIn0.hTkMVvU1xz2StHhaEYuMIA' let map = new mapboxgl.Map({ @@ -830,9 +830,11 @@ let geocoder = new MapboxGeocoder({ accessToken: mapboxgl.accessToken }) map.addControl(geocoder) + // zoom let nav = new mapboxgl.NavigationControl() map.addControl(nav, 'top-left') + // position attribution to bottom-left map.addControl(new mapboxgl.AttributionControl(), 'bottom-left') @@ -858,7 +860,7 @@ map.on('load', function () { /** * This function frames the overpass query based on the map view and timeframe * - * @returns {string} url - overpass query for fetching data + * @returns {string} url - overpass query for fetching data **/ function getQuery () { @@ -968,8 +970,8 @@ function getData () { /** * Displays error messages for fetch data failures * - * @param {string} message - custom error message for different scenarios - * @param {number} time - time in milliseconds + * @param {string} message - custom error message for different scenarios + * @param {number} time - time in milliseconds **/ function errorNotice (message, time) { @@ -989,6 +991,7 @@ function errorNotice (message, time) { /** * Construct URL to request a particular project details * + * @returns {string} url - project specific url to fetch details **/ function getProjQuery () { diff --git a/js/app.js b/js/app.js index c54b390..2b0be6d 100644 --- a/js/app.js +++ b/js/app.js @@ -2,7 +2,7 @@ const osmtogeojson = require('osmtogeojson') const util = require('util') const moment = require('moment') -// Inittialising map +// Initialising map mapboxgl.accessToken = 'pk.eyJ1IjoicnVtYyIsImEiOiJjamJhdHJzODUxMGUyMnFub2l3cTlmMTJnIn0.hTkMVvU1xz2StHhaEYuMIA' let map = new mapboxgl.Map({ @@ -21,9 +21,11 @@ let geocoder = new MapboxGeocoder({ accessToken: mapboxgl.accessToken }) map.addControl(geocoder) + // zoom let nav = new mapboxgl.NavigationControl() map.addControl(nav, 'top-left') + // position attribution to bottom-left map.addControl(new mapboxgl.AttributionControl(), 'bottom-left') @@ -49,7 +51,7 @@ map.on('load', function () { /** * This function frames the overpass query based on the map view and timeframe * - * @returns {string} url - overpass query for fetching data + * @returns {string} url - overpass query for fetching data **/ function getQuery () { @@ -159,8 +161,8 @@ function getData () { /** * Displays error messages for fetch data failures * - * @param {string} message - custom error message for different scenarios - * @param {number} time - time in milliseconds + * @param {string} message - custom error message for different scenarios + * @param {number} time - time in milliseconds **/ function errorNotice (message, time) { @@ -180,6 +182,7 @@ function errorNotice (message, time) { /** * Construct URL to request a particular project details * + * @returns {string} url - project specific url to fetch details **/ function getProjQuery () { From 9ea9669e328fa8892e9ece52742567c06ff4472c Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Thu, 29 Mar 2018 13:31:58 +0530 Subject: [PATCH 07/11] #8 plugin coords --- dist/bundle.js | 9 +++++++-- js/app.js | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index 115ec13..136f2ec 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -1010,10 +1010,15 @@ function getProjDetails () { console.log('From projDetails: ', url) $.ajax(url) .done(function (data) { - let polygon = data.areaOfInterest + let multiPolygon = data.areaOfInterest let entities = data.mappingTypes console.log(entities) - console.log(polygon) + console.log(multiPolygon) + multiPolygon.coordinates.forEach(function (coords) { + let feat = {'type': 'Polygon', 'coordinates': coords} + console.log(JSON.stringify(feat)) + } + ) }) .fail(function () { }) diff --git a/js/app.js b/js/app.js index 2b0be6d..2fad1a8 100644 --- a/js/app.js +++ b/js/app.js @@ -201,10 +201,15 @@ function getProjDetails () { console.log('From projDetails: ', url) $.ajax(url) .done(function (data) { - let polygon = data.areaOfInterest + let multiPolygon = data.areaOfInterest let entities = data.mappingTypes console.log(entities) - console.log(polygon) + console.log(multiPolygon) + multiPolygon.coordinates.forEach(function (coords) { + let feat = {'type': 'Polygon', 'coordinates': coords} + console.log(JSON.stringify(feat)) + } + ) }) .fail(function () { }) From 3ef601de1c2c5cde5e7f272381ec9953e292227b Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Thu, 29 Mar 2018 14:29:48 +0530 Subject: [PATCH 08/11] #8 query against polygon --- dist/bundle.js | 31 ++++++++++++++++++++++--------- js/app.js | 31 ++++++++++++++++++++++--------- 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index 136f2ec..df8474b 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -859,17 +859,23 @@ map.on('load', function () { /** * This function frames the overpass query based on the map view and timeframe + * @param {string} bbox - space separated polygon coordinates (lat1 lng1 lat2 lng2 ... latn lngn) * * @returns {string} url - overpass query for fetching data **/ -function getQuery () { - let bounds = map.getBounds() - let north = bounds['_ne'].lat - let east = bounds['_ne'].lng - let south = bounds['_sw'].lat - let west = bounds['_sw'].lng - let bbox = south + ',' + west + ',' + north + ',' + east +function getQuery (bbox) { + if (bbox) { + bbox = 'poly:"' + bbox + '"' + } else { + let bounds = map.getBounds() + let north = bounds['_ne'].lat + let east = bounds['_ne'].lng + let south = bounds['_sw'].lat + let west = bounds['_sw'].lng + bbox = south + ',' + west + ',' + north + ',' + east + } + let overpassDate if (formData.fromDate != '' && formData.toDate != '') { @@ -1015,8 +1021,15 @@ function getProjDetails () { console.log(entities) console.log(multiPolygon) multiPolygon.coordinates.forEach(function (coords) { - let feat = {'type': 'Polygon', 'coordinates': coords} - console.log(JSON.stringify(feat)) + let polygon = {'type': 'Polygon', 'coordinates': coords} + let bbox = '' + coords.forEach(function (item) { + item.forEach(function (subItem) { + bbox += subItem[1] + ' ' + subItem[0] + }) + }) + console.log(JSON.stringify(polygon)) + console.log('poly query: ', getQuery(bbox)) } ) }) diff --git a/js/app.js b/js/app.js index 2fad1a8..4221778 100644 --- a/js/app.js +++ b/js/app.js @@ -50,17 +50,23 @@ map.on('load', function () { /** * This function frames the overpass query based on the map view and timeframe + * @param {string} bbox - space separated polygon coordinates (lat1 lng1 lat2 lng2 ... latn lngn) * * @returns {string} url - overpass query for fetching data **/ -function getQuery () { - let bounds = map.getBounds() - let north = bounds['_ne'].lat - let east = bounds['_ne'].lng - let south = bounds['_sw'].lat - let west = bounds['_sw'].lng - let bbox = south + ',' + west + ',' + north + ',' + east +function getQuery (bbox) { + if (bbox) { + bbox = 'poly:"' + bbox + '"' + } else { + let bounds = map.getBounds() + let north = bounds['_ne'].lat + let east = bounds['_ne'].lng + let south = bounds['_sw'].lat + let west = bounds['_sw'].lng + bbox = south + ',' + west + ',' + north + ',' + east + } + let overpassDate if (formData.fromDate != '' && formData.toDate != '') { @@ -206,8 +212,15 @@ function getProjDetails () { console.log(entities) console.log(multiPolygon) multiPolygon.coordinates.forEach(function (coords) { - let feat = {'type': 'Polygon', 'coordinates': coords} - console.log(JSON.stringify(feat)) + let polygon = {'type': 'Polygon', 'coordinates': coords} + let bbox = '' + coords.forEach(function (item) { + item.forEach(function (subItem) { + bbox += subItem[1] + ' ' + subItem[0] + }) + }) + console.log(JSON.stringify(polygon)) + console.log('poly query: ', getQuery(bbox)) } ) }) From 0e63b526c8349961192d27fa2f4e80c32e52c8bc Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Fri, 30 Mar 2018 22:55:15 +0530 Subject: [PATCH 09/11] #7 data for each polygon --- dist/bundle.js | 12 ++++++++---- js/app.js | 12 ++++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index df8474b..d3728ee 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -901,8 +901,8 @@ function getQuery (bbox) { * **/ -function getData () { - let url = getQuery() +function getData (url) { + if (!url) { url = getQuery() } $('.loading').css('display', 'inline-block') $.ajax(url) .done(function (data) { @@ -1018,9 +1018,11 @@ function getProjDetails () { .done(function (data) { let multiPolygon = data.areaOfInterest let entities = data.mappingTypes + let count = 0 console.log(entities) console.log(multiPolygon) multiPolygon.coordinates.forEach(function (coords) { + count++ let polygon = {'type': 'Polygon', 'coordinates': coords} let bbox = '' coords.forEach(function (item) { @@ -1029,7 +1031,8 @@ function getProjDetails () { }) }) console.log(JSON.stringify(polygon)) - console.log('poly query: ', getQuery(bbox)) + console.log(count) + getData(getQuery(bbox)) } ) }) @@ -1049,7 +1052,8 @@ $('#submit').on('click', function () { 'toDate': moment($('#todate').val()).utc().toISOString() } getProjDetails() - getData() + + //getData() } else { errorNotice('Zoom in further to fetch results') } diff --git a/js/app.js b/js/app.js index 4221778..6bd810e 100644 --- a/js/app.js +++ b/js/app.js @@ -92,8 +92,8 @@ function getQuery (bbox) { * **/ -function getData () { - let url = getQuery() +function getData (url) { + if (!url) { url = getQuery() } $('.loading').css('display', 'inline-block') $.ajax(url) .done(function (data) { @@ -209,9 +209,11 @@ function getProjDetails () { .done(function (data) { let multiPolygon = data.areaOfInterest let entities = data.mappingTypes + let count = 0 console.log(entities) console.log(multiPolygon) multiPolygon.coordinates.forEach(function (coords) { + count++ let polygon = {'type': 'Polygon', 'coordinates': coords} let bbox = '' coords.forEach(function (item) { @@ -220,7 +222,8 @@ function getProjDetails () { }) }) console.log(JSON.stringify(polygon)) - console.log('poly query: ', getQuery(bbox)) + console.log(count) + getData(getQuery(bbox)) } ) }) @@ -240,7 +243,8 @@ $('#submit').on('click', function () { 'toDate': moment($('#todate').val()).utc().toISOString() } getProjDetails() - getData() + + //getData() } else { errorNotice('Zoom in further to fetch results') } From f138f9e72047b82bf5159434bd42ae319b75a228 Mon Sep 17 00:00:00 2001 From: Ramya Ragupathy Date: Sat, 31 Mar 2018 21:32:02 +0530 Subject: [PATCH 10/11] #7 terraform --- dist/bundle.js | 22155 ++++++++++++++++++++++++++++++++--------------- js/app.js | 39 +- 2 files changed, 15010 insertions(+), 7184 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index d3728ee..8ebf6ab 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -1,8599 +1,16406 @@ (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return (b64.length * 3 / 4) - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr((len * 3 / 4) - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + var L = 0 + + for (i = 0; i < l; i += 4) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr } -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + parts.push(output) + return parts.join('') } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } +},{}],3:[function(require,module,exports){ +arguments[4][1][0].apply(exports,arguments) +},{"dup":1}],4:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } } -function drainQueue() { - if (draining) { - return; +Object.defineProperty(Buffer.prototype, 'parent', { + get: function () { + if (!(this instanceof Buffer)) { + return undefined } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + return this.buffer + } +}) - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; +Object.defineProperty(Buffer.prototype, 'offset', { + get: function () { + if (!(this instanceof Buffer)) { + return undefined } - currentQueue = null; - draining = false; - runClearTimeout(timeout); + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf } -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) } -}; + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) } -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; -function noop() {} +Buffer.poolSize = 8192 // not used by this implementation -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } -process.listeners = function (name) { return [] } + if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + return fromObject(value) +} -},{}],2:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') } } -},{}],3:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) } -},{}],4:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' } - if (process.noDeprecation === true) { - return fn; + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) } - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) } - return deprecated; -}; + return buf +} +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') } - return debugs[set]; -}; + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; + if (buf.length === 0) { + return buf + } + obj.copy(buf, 0, 0, len) + return buf + } -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + if (obj) { + if (ArrayBuffer.isView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } } -} + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.') +} -function stylizeNoColor(str, styleType) { - return str; +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 } +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} -function arrayToHash(array) { - var hash = {}; +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true +} - array.forEach(function(val, idx) { - hash[val] = true; - }); +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - return hash; -} + if (a === b) return 0 + var x = a.length + var y = b.length -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break } - return ret; } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false } +} - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); + if (list.length === 0) { + return Buffer.alloc(0) } - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (ArrayBuffer.isView(buf)) { + buf = Buffer.from(buf) } - if (isError(value)) { - return formatError(value); + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') } + buf.copy(buffer, pos) + pos += buf.length } + return buffer +} - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; + if (ArrayBuffer.isView(string) || isArrayBuffer(string)) { + return string.byteLength } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); + if (typeof string !== 'string') { + string = '' + string } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } +} +Buffer.byteLength = byteLength - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + if (end === undefined || end > this.length) { + end = this.length } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } + if (end <= 0) { + return '' } - ctx.seen.push(value); + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); + if (end <= start) { + return '' } - ctx.seen.pop(); + if (!encoding) encoding = 'utf8' - return reduceToSingleString(output, base, braces); + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } } +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this } +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this } +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; + return '' } +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } + if (start === undefined) { + start = 0 } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; + if (end === undefined) { + end = target ? target.length : 0 } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } + if (thisStart === undefined) { + thisStart = 0 } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break } } - return name + ': ' + str; + if (x < y) return -1 + if (y < x) return 1 + return 0 } +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') } +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } -function isNullOrUndefined(arg) { - return arg == null; + return -1 } -exports.isNullOrUndefined = isNullOrUndefined; -function isNumber(arg) { - return typeof arg === 'number'; +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 } -exports.isNumber = isNumber; -function isString(arg) { - return typeof arg === 'string'; +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } -exports.isString = isString; -function isSymbol(arg) { - return typeof arg === 'symbol'; +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + var strLen = string.length -function isObject(arg) { - return typeof arg === 'object' && arg !== null; + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i } -exports.isObject = isObject; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } -exports.isDate = isDate; -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } -exports.isFunction = isFunction; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); -function objectToString(o) { - return Object.prototype.toString.call(o); +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + if (!encoding) encoding = 'utf8' -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; + case 'ascii': + return asciiWrite(this, string, offset, length) + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } - return origin; -}; +} -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } } -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":3,"_process":1,"inherits":2}],5:[function(require,module,exports){ -const osmtogeojson = require('osmtogeojson') -const util = require('util') -const moment = require('moment') +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} -// Initialising map +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] -mapboxgl.accessToken = 'pk.eyJ1IjoicnVtYyIsImEiOiJjamJhdHJzODUxMGUyMnFub2l3cTlmMTJnIn0.hTkMVvU1xz2StHhaEYuMIA' -let map = new mapboxgl.Map({ - container: 'map', // container id - style: 'mapbox://styles/mapbox/light-v9', - center: [-122.2014, 37.7758], - zoom: 9, - hash: true, - attributionControl: false -}) + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 -// Adding navigation controls + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint -// geocoder -let geocoder = new MapboxGeocoder({ - accessToken: mapboxgl.accessToken -}) -map.addControl(geocoder) + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } -// zoom -let nav = new mapboxgl.NavigationControl() -map.addControl(nav, 'top-left') + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } -// position attribution to bottom-left -map.addControl(new mapboxgl.AttributionControl(), 'bottom-left') + res.push(codePoint) + i += bytesPerSequence + } -$('#fromdate').val(moment().format('YYYY-MM-DD[T]00:00:01')) -$('#todate').val(moment().format('YYYY-MM-DD[T]HH:mm:ss')) + return decodeCodePointsArray(res) +} -// Set initial values +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 -let formData = {} -let overpassDataSource = { - 'type': 'FeatureCollection', - 'features': [] +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res } -let head = '[out:xml][timeout:25];' -let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' -map.on('load', function () { - map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) -}) +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) -// Functions + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} -/** - * This function frames the overpass query based on the map view and timeframe - * @param {string} bbox - space separated polygon coordinates (lat1 lng1 lat2 lng2 ... latn lngn) - * - * @returns {string} url - overpass query for fetching data - **/ +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) -function getQuery (bbox) { - if (bbox) { - bbox = 'poly:"' + bbox + '"' - } else { - let bounds = map.getBounds() - let north = bounds['_ne'].lat - let east = bounds['_ne'].lng - let south = bounds['_sw'].lat - let west = bounds['_sw'].lng - bbox = south + ',' + west + ',' + north + ',' + east + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) } + return ret +} - let overpassDate +function hexSlice (buf, start, end) { + var len = buf.length - if (formData.fromDate != '' && formData.toDate != '') { - overpassDate = "(changed:'" + formData.fromDate + "','" + formData.toDate + "')" - } else if (formData.fromDate != '' && formData.toDate === '') { - overpassDate = "(changed:'" + formData.fromDate + "')" + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) } + return out +} - // for osm 'https://api.openstreetmap.org/api/0.6/map?bbox='+bbox; +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} - let query = util.format(q, overpassDate, bbox, overpassDate, bbox, overpassDate, bbox) - let url = 'https://www.overpass-api.de/api/interpreter?data=' + query +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end - return url + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf } -/** - * Invokes getQuery() function to frame the overpass query - * Fetches data using the overpass query - * Converts XML data to geojson - * Adds three layers using geojson data - * Adds a legend & geometry count to the page - * - **/ +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} -function getData (url) { - if (!url) { url = getQuery() } - $('.loading').css('display', 'inline-block') - $.ajax(url) - .done(function (data) { - let geojson = osmtogeojson(data) - let ways = geojson.features.filter(function (item) { - if (item.id.startsWith('way')) { - return item - } - }) - let rels = geojson.features.filter(function (item) { - if (item.id.startsWith('relation')) { - return item - } - }) - let nodes = geojson.features.filter(function (item) { - if (item.id.startsWith('node')) { - return item - } - }) - map.getSource('overpassDataSource').setData(geojson) - map.addLayer({ - 'id': 'node', - 'type': 'circle', - 'source': 'overpassDataSource', - 'paint': { - 'circle-radius': 4, - 'circle-color': '#8C5E58', - 'circle-opacity': 0.4 - }, - 'filter': ['==', '$type', 'Point'] - }) - map.addLayer({ - 'id': 'way', - 'type': 'line', - 'source': 'overpassDataSource', - 'paint': { - 'line-color': '#FF7E6B', - 'line-opacity': 0.4 - }, - 'filter': ['==', '$type', 'LineString'] - }) - map.addLayer({ - 'id': 'area', - 'type': 'fill', - 'source': 'overpassDataSource', - 'paint': { - 'fill-color': '#F6E27F', - 'fill-opacity': 0.4 - }, - 'filter': ['==', '$type', 'Polygon'] - }) +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - let countStr = `

Feature breakdown:

- -
- -
- - -

` - document.getElementById('count').classList.add('fill-gray') - document.getElementById('count').innerHTML = countStr - document.getElementById('map-legend').style.display = 'block' - $('.loading').css('display', 'none') - }) - .fail(function () { - errorNotice('Too much data to fetch, zoom in further') - }) + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val } -/** - * Displays error messages for fetch data failures - * - * @param {string} message - custom error message for different scenarios - * @param {number} time - time in milliseconds - **/ +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } -function errorNotice (message, time) { - $('.note').css('display', 'block') - $('.note p').text(message) - if (time) { - window.setTimeout(function () { - $('.note').css('display', 'none') - }, time) - } else { - window.setTimeout(function () { - $('.note').css('display', 'none') - }, 2000) + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul } + + return val } -/** - * Construct URL to request a particular project details - * - * @returns {string} url - project specific url to fetch details - **/ +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} -function getProjQuery () { - let projectID = document.getElementById('projects').value - let url = 'https://tasks.hotosm.org/api/v1/project/' + projectID + '?as_file=false' - return url +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) } -/** - * Fetches complete details of a particular HOTOSM project - * - **/ +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} -function getProjDetails () { - let url = getProjQuery() - console.log('From projDetails: ', url) - $.ajax(url) - .done(function (data) { - let multiPolygon = data.areaOfInterest - let entities = data.mappingTypes - let count = 0 - console.log(entities) - console.log(multiPolygon) - multiPolygon.coordinates.forEach(function (coords) { - count++ - let polygon = {'type': 'Polygon', 'coordinates': coords} - let bbox = '' - coords.forEach(function (item) { - item.forEach(function (subItem) { - bbox += subItem[1] + ' ' + subItem[0] - }) - }) - console.log(JSON.stringify(polygon)) - console.log(count) - getData(getQuery(bbox)) - } - ) - }) - .fail(function () { - }) +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) } -// Fetch Data on Click +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) -$('#submit').on('click', function () { - document.getElementById('count').innerHTML = '' - document.getElementById('count').classList.remove('fill-gray') - let zoom = map.getZoom() - if (zoom >= 5) { - formData = { - 'fromDate': moment($('#fromdate').val()).utc().toISOString(), - 'toDate': moment($('#todate').val()).utc().toISOString() - } - getProjDetails() - - //getData() - } else { - errorNotice('Zoom in further to fetch results') - } -}) + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} -},{"moment":8,"osmtogeojson":11,"util":4}],6:[function(require,module,exports){ -var wgs84 = require('wgs84'); +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -module.exports.geometry = geometry; -module.exports.ring = ringArea; + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 -function geometry(_) { - if (_.type === 'Polygon') return polygonArea(_.coordinates); - else if (_.type === 'MultiPolygon') { - var area = 0; - for (var i = 0; i < _.coordinates.length; i++) { - area += polygonArea(_.coordinates[i]); - } - return area; - } else { - return null; - } -} + if (val >= mul) val -= Math.pow(2, 8 * byteLength) -function polygonArea(coords) { - var area = 0; - if (coords && coords.length > 0) { - area += Math.abs(ringArea(coords[0])); - for (var i = 1; i < coords.length; i++) { - area -= Math.abs(ringArea(coords[i])); - } - } - return area; + return val } -/** - * Calculate the approximate area of the polygon were it projected onto - * the earth. Note that this area will be positive if ring is oriented - * clockwise, otherwise it will be negative. - * - * Reference: - * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for - * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion - * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409 - * - * Returns: - * {float} The approximate signed geodesic area of the polygon in square - * meters. - */ +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -function ringArea(coords) { - var area = 0; + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - if (coords.length > 2) { - var p1, p2; - for (var i = 0; i < coords.length - 1; i++) { - p1 = coords[i]; - p2 = coords[i + 1]; - area += rad(p2[0] - p1[0]) * (2 + Math.sin(rad(p1[1])) + Math.sin(rad(p2[1]))); - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - area = area * wgs84.RADIUS * wgs84.RADIUS / 2; - } + return val +} - return area; +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) } -function rad(_) { - return _ * Math.PI / 180; +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val } -},{"wgs84":13}],7:[function(require,module,exports){ -var geojsonArea = require('geojson-area'); +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} -module.exports = rewind; +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) -function rewind(gj, outer) { - switch ((gj && gj.type) || null) { - case 'FeatureCollection': - gj.features = gj.features.map(curryOuter(rewind, outer)); - return gj; - case 'Feature': - gj.geometry = rewind(gj.geometry, outer); - return gj; - case 'Polygon': - case 'MultiPolygon': - return correct(gj, outer); - default: - return gj; - } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) } -function curryOuter(a, b) { - return function(_) { return a(_, b); }; +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) } -function correct(_, outer) { - if (_.type === 'Polygon') { - _.coordinates = correctRings(_.coordinates, outer); - } else if (_.type === 'MultiPolygon') { - _.coordinates = _.coordinates.map(curryOuter(correctRings, outer)); - } - return _; +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) } -function correctRings(_, outer) { - outer = !!outer; - _[0] = wind(_[0], !outer); - for (var i = 1; i < _.length; i++) { - _[i] = wind(_[i], outer); - } - return _; +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) } -function wind(_, dir) { - return cw(_) === dir ? _ : _.reverse(); +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) } -function cw(_) { - return geojsonArea.ring(_) >= 0; +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) } -},{"geojson-area":6}],8:[function(require,module,exports){ -//! moment.js +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} -;(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - global.moment = factory() -}(this, (function () { 'use strict'; +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } -var hookCallback; + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } -function hooks () { - return hookCallback.apply(null, arguments); + return offset + byteLength } -// This is done to register the method called with moment() -// without creating circular dependencies. -function setHookCallback (callback) { - hookCallback = callback; -} +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } -function isArray(input) { - return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength } -function isObject(input) { - // IE8 will treat undefined and null as object if it wasn't for - // input != null - return input != null && Object.prototype.toString.call(input) === '[object Object]'; +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 } -function isObjectEmpty(obj) { - if (Object.getOwnPropertyNames) { - return (Object.getOwnPropertyNames(obj).length === 0); - } else { - var k; - for (k in obj) { - if (obj.hasOwnProperty(k)) { - return false; - } - } - return true; - } +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 } -function isUndefined(input) { - return input === void 0; +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 } -function isNumber(input) { - return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 } -function isDate(input) { - return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 } -function map(arr, fn) { - var res = [], i; - for (i = 0; i < arr.length; ++i) { - res.push(fn(arr[i], i)); +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 } - return res; -} + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } -function hasOwnProp(a, b) { - return Object.prototype.hasOwnProperty.call(a, b); + return offset + byteLength } -function extend(a, b) { - for (var i in b) { - if (hasOwnProp(b, i)) { - a[i] = b[i]; - } - } +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) - if (hasOwnProp(b, 'toString')) { - a.toString = b.toString; - } + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - if (hasOwnProp(b, 'valueOf')) { - a.valueOf = b.valueOf; + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - return a; + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 } -function createUTC (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, true).utc(); +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) } -function defaultParsingFlags() { - // We need to deep clone this object. - return { - empty : false, - unusedTokens : [], - unusedInput : [], - overflow : -2, - charsLeftOver : 0, - nullInput : false, - invalidMonth : null, - invalidFormat : false, - userInvalidated : false, - iso : false, - parsedDateParts : [], - meridiem : null, - rfc2822 : false, - weekdayMismatch : false - }; +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) } -function getParsingFlags(m) { - if (m._pf == null) { - m._pf = defaultParsingFlags(); - } - return m._pf; +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 } -var some; -if (Array.prototype.some) { - some = Array.prototype.some; -} else { - some = function (fun) { - var t = Object(this); - var len = t.length >>> 0; - - for (var i = 0; i < len; i++) { - if (i in t && fun.call(this, t[i], i, t)) { - return true; - } - } +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} - return false; - }; +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) } -function isValid(m) { - if (m._isValid == null) { - var flags = getParsingFlags(m); - var parsedParts = some.call(flags.parsedDateParts, function (i) { - return i != null; - }); - var isNowValid = !isNaN(m._d.getTime()) && - flags.overflow < 0 && - !flags.empty && - !flags.invalidMonth && - !flags.invalidWeekday && - !flags.weekdayMismatch && - !flags.nullInput && - !flags.invalidFormat && - !flags.userInvalidated && - (!flags.meridiem || (flags.meridiem && parsedParts)); +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start - if (m._strict) { - isNowValid = isNowValid && - flags.charsLeftOver === 0 && - flags.unusedTokens.length === 0 && - flags.bigHour === undefined; - } + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - if (Object.isFrozen == null || !Object.isFrozen(m)) { - m._isValid = isNowValid; - } - else { - return isNowValid; - } - } - return m._isValid; -} + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') -function createInvalid (flags) { - var m = createUTC(NaN); - if (flags != null) { - extend(getParsingFlags(m), flags); + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] } - else { - getParsingFlags(m).userInvalidated = true; + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } } + } else if (typeof val === 'number') { + val = val & 255 + } - return m; -} + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } -// Plugins that add properties should also add the key here (null value), -// so we can properly clone ourselves. -var momentProperties = hooks.momentProperties = []; + if (end <= start) { + return this + } -function copyConfig(to, from) { - var i, prop, val; + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - if (!isUndefined(from._isAMomentObject)) { - to._isAMomentObject = from._isAMomentObject; - } - if (!isUndefined(from._i)) { - to._i = from._i; - } - if (!isUndefined(from._f)) { - to._f = from._f; - } - if (!isUndefined(from._l)) { - to._l = from._l; - } - if (!isUndefined(from._strict)) { - to._strict = from._strict; - } - if (!isUndefined(from._tzm)) { - to._tzm = from._tzm; - } - if (!isUndefined(from._isUTC)) { - to._isUTC = from._isUTC; - } - if (!isUndefined(from._offset)) { - to._offset = from._offset; + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val } - if (!isUndefined(from._pf)) { - to._pf = getParsingFlags(from); + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') } - if (!isUndefined(from._locale)) { - to._locale = from._locale; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] } + } - if (momentProperties.length > 0) { - for (i = 0; i < momentProperties.length; i++) { - prop = momentProperties[i]; - val = from[prop]; - if (!isUndefined(val)) { - to[prop] = val; - } + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue } - } - return to; -} + // valid lead + leadSurrogate = codePoint -var updateInProgress = false; + continue + } -// Moment prototype object -function Moment(config) { - copyConfig(this, config); - this._d = new Date(config._d != null ? config._d.getTime() : NaN); - if (!this.isValid()) { - this._d = new Date(NaN); + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } - // Prevent infinite loop in case updateOffset creates new moment - // objects. - if (updateInProgress === false) { - updateInProgress = true; - hooks.updateOffset(this); - updateInProgress = false; + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') } + } + + return bytes } -function isMoment (obj) { - return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray } -function absFloor (number) { - if (number < 0) { - // -0 -> 0 - return Math.ceil(number) || 0; - } else { - return Math.floor(number); - } +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray } -function toInt(argumentForCoercion) { - var coercedNumber = +argumentForCoercion, - value = 0; +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} - if (coercedNumber !== 0 && isFinite(coercedNumber)) { - value = absFloor(coercedNumber); - } +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} - return value; +// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check +// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 +function isArrayBuffer (obj) { + return obj instanceof ArrayBuffer || + (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && + typeof obj.byteLength === 'number') } -// compare two arrays, return the number of differences -function compareArrays(array1, array2, dontConvert) { - var len = Math.min(array1.length, array2.length), - lengthDiff = Math.abs(array1.length - array2.length), - diffs = 0, - i; - for (i = 0; i < len; i++) { - if ((dontConvert && array1[i] !== array2[i]) || - (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { - diffs++; - } - } - return diffs + lengthDiff; +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare } -function warn(msg) { - if (hooks.suppressDeprecationWarnings === false && - (typeof console !== 'undefined') && console.warn) { - console.warn('Deprecation warning: ' + msg); - } +},{"base64-js":2,"ieee754":7}],5:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; } +exports.isArray = isArray; -function deprecate(msg, fn) { - var firstTime = true; +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - return extend(function () { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(null, msg); - } - if (firstTime) { - var args = []; - var arg; - for (var i = 0; i < arguments.length; i++) { - arg = ''; - if (typeof arguments[i] === 'object') { - arg += '\n[' + i + '] '; - for (var key in arguments[0]) { - arg += key + ': ' + arguments[0][key] + ', '; - } - arg = arg.slice(0, -2); // Remove trailing comma and space - } else { - arg = arguments[i]; - } - args.push(arg); - } - warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); - firstTime = false; - } - return fn.apply(this, arguments); - }, fn); +function isNull(arg) { + return arg === null; } +exports.isNull = isNull; -var deprecations = {}; +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; -function deprecateSimple(name, msg) { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(name, msg); - } - if (!deprecations[name]) { - warn(msg); - deprecations[name] = true; - } +function isNumber(arg) { + return typeof arg === 'number'; } +exports.isNumber = isNumber; -hooks.suppressDeprecationWarnings = false; -hooks.deprecationHandler = null; +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -function isFunction(input) { - return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; +function isSymbol(arg) { + return typeof arg === 'symbol'; } +exports.isSymbol = isSymbol; -function set (config) { - var prop, i; - for (i in config) { - prop = config[i]; - if (isFunction(prop)) { - this[i] = prop; - } else { - this['_' + i] = prop; - } - } - this._config = config; - // Lenient ordinal parsing accepts just a number in addition to - // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. - // TODO: Remove "ordinalParse" fallback in next major release. - this._dayOfMonthOrdinalParseLenient = new RegExp( - (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + - '|' + (/\d{1,2}/).source); +function isUndefined(arg) { + return arg === void 0; } +exports.isUndefined = isUndefined; -function mergeConfigs(parentConfig, childConfig) { - var res = extend({}, parentConfig), prop; - for (prop in childConfig) { - if (hasOwnProp(childConfig, prop)) { - if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { - res[prop] = {}; - extend(res[prop], parentConfig[prop]); - extend(res[prop], childConfig[prop]); - } else if (childConfig[prop] != null) { - res[prop] = childConfig[prop]; - } else { - delete res[prop]; - } - } - } - for (prop in parentConfig) { - if (hasOwnProp(parentConfig, prop) && - !hasOwnProp(childConfig, prop) && - isObject(parentConfig[prop])) { - // make sure changes to properties don't modify parent config - res[prop] = extend({}, res[prop]); - } - } - return res; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; } +exports.isRegExp = isRegExp; -function Locale(config) { - if (config != null) { - this.set(config); - } +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +exports.isObject = isObject; -var keys; +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -if (Object.keys) { - keys = Object.keys; -} else { - keys = function (obj) { - var i, res = []; - for (i in obj) { - if (hasOwnProp(obj, i)) { - res.push(i); - } - } - return res; - }; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); } +exports.isError = isError; -var defaultCalendar = { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' -}; +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; -function calendar (key, mom, now) { - var output = this._calendar[key] || this._calendar['sameElse']; - return isFunction(output) ? output.call(mom, now) : output; +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; } +exports.isPrimitive = isPrimitive; -var defaultLongDateFormat = { - LTS : 'h:mm:ss A', - LT : 'h:mm A', - L : 'MM/DD/YYYY', - LL : 'MMMM D, YYYY', - LLL : 'MMMM D, YYYY h:mm A', - LLLL : 'dddd, MMMM D, YYYY h:mm A' -}; +exports.isBuffer = Buffer.isBuffer; -function longDateFormat (key) { - var format = this._longDateFormat[key], - formatUpper = this._longDateFormat[key.toUpperCase()]; +function objectToString(o) { + return Object.prototype.toString.call(o); +} - if (format || !formatUpper) { - return format; - } +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":9}],6:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { - return val.slice(1); - }); +var objectCreate = Object.create || objectCreatePolyfill +var objectKeys = Object.keys || objectKeysPolyfill +var bind = Function.prototype.bind || functionBindPolyfill - return this._longDateFormat[key]; +function EventEmitter() { + if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { + this._events = objectCreate(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; } +module.exports = EventEmitter; -var defaultInvalidDate = 'Invalid date'; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; -function invalidDate () { - return this._invalidDate; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +var hasDefineProperty; +try { + var o = {}; + if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); + hasDefineProperty = o.x === 0; +} catch (err) { hasDefineProperty = false } +if (hasDefineProperty) { + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + // check whether the input is a positive number (whose value is zero or + // greater and not a NaN). + if (typeof arg !== 'number' || arg < 0 || arg !== arg) + throw new TypeError('"defaultMaxListeners" must be a positive number'); + defaultMaxListeners = arg; + } + }); +} else { + EventEmitter.defaultMaxListeners = defaultMaxListeners; } -var defaultOrdinal = '%d'; -var defaultDayOfMonthOrdinalParse = /\d{1,2}/; +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; -function ordinal (number) { - return this._ordinal.replace('%d', number); +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; } -var defaultRelativeTime = { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); }; -function relativeTime (number, withoutSuffix, string, isFuture) { - var output = this._relativeTime[string]; - return (isFunction(output)) ? - output(number, withoutSuffix, string, isFuture) : - output.replace(/%d/i, number); +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } } -function pastFuture (diff, output) { - var format = this._relativeTime[diff > 0 ? 'future' : 'past']; - return isFunction(format) ? format(output) : format.replace(/%s/i, output); +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } } -var aliases = {}; +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events; + var doError = (type === 'error'); -function addUnitAlias (unit, shorthand) { - var lowerCase = unit.toLowerCase(); - aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; -} + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; -function normalizeUnits(units) { - return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; -} + // If there is no 'error' event listener then throw. + if (doError) { + if (arguments.length > 1) + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Unhandled "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } -function normalizeObjectUnits(inputObject) { - var normalizedInput = {}, - normalizedProp, - prop; + handler = events[type]; - for (prop in inputObject) { - if (hasOwnProp(inputObject, prop)) { - normalizedProp = normalizeUnits(prop); - if (normalizedProp) { - normalizedInput[normalizedProp] = inputObject[prop]; - } + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = objectCreate(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' "' + String(type) + '" listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit.'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + if (typeof console === 'object' && console.warn) { + console.warn('%s: %s', w.name, w.message); } + } } + } - return normalizedInput; + return target; } -var priorities = {}; +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; -function addUnitPriority(unit, priority) { - priorities[unit] = priority; -} +EventEmitter.prototype.on = EventEmitter.prototype.addListener; -function getPrioritizedUnits(unitsObj) { - var units = []; - for (var u in unitsObj) { - units.push({unit: u, priority: priorities[u]}); +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + switch (arguments.length) { + case 0: + return this.listener.call(this.target); + case 1: + return this.listener.call(this.target, arguments[0]); + case 2: + return this.listener.call(this.target, arguments[0], arguments[1]); + case 3: + return this.listener.call(this.target, arguments[0], arguments[1], + arguments[2]); + default: + var args = new Array(arguments.length); + for (var i = 0; i < args.length; ++i) + args[i] = arguments[i]; + this.listener.apply(this.target, args); } - units.sort(function (a, b) { - return a.priority - b.priority; - }); - return units; + } } -function zeroFill(number, targetLength, forceSign) { - var absNumber = '' + Math.abs(number), - zerosToFill = targetLength - absNumber.length, - sign = number >= 0; - return (sign ? (forceSign ? '+' : '') : '-') + - Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = bind.call(onceWrapper, state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; } -var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; -var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; -var formatFunctions = {}; +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; -var formatTokenFunctions = {}; + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); -// token: 'M' -// padded: ['MM', 2] -// ordinal: 'Mo' -// callback: function () { this.month() + 1 } -function addFormatToken (token, padded, ordinal, callback) { - var func = callback; - if (typeof callback === 'string') { - func = function () { - return this[callback](); - }; - } - if (token) { - formatTokenFunctions[token] = func; - } - if (padded) { - formatTokenFunctions[padded[0]] = function () { - return zeroFill(func.apply(this, arguments), padded[1], padded[2]); - }; - } - if (ordinal) { - formatTokenFunctions[ordinal] = function () { - return this.localeData().ordinal(func.apply(this, arguments), token); - }; - } -} - -function removeFormattingTokens(input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|\]$/g, ''); - } - return input.replace(/\\/g, ''); -} + events = this._events; + if (!events) + return this; -function makeFormatFunction(format) { - var array = format.match(formattingTokens), i, length; + list = events[type]; + if (!list) + return this; - for (i = 0, length = array.length; i < length; i++) { - if (formatTokenFunctions[array[i]]) { - array[i] = formatTokenFunctions[array[i]]; - } else { - array[i] = removeFormattingTokens(array[i]); + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); } - } + } else if (typeof list !== 'function') { + position = -1; - return function (mom) { - var output = '', i; - for (i = 0; i < length; i++) { - output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } } - return output; - }; -} - -// format date using native date object -function formatMoment(m, format) { - if (!m.isValid()) { - return m.localeData().invalidDate(); - } - - format = expandFormat(format, m.localeData()); - formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); - return formatFunctions[format](m); -} + if (position < 0) + return this; -function expandFormat(format, locale) { - var i = 5; + if (position === 0) + list.shift(); + else + spliceOne(list, position); - function replaceLongDateFormatTokens(input) { - return locale.longDateFormat(input) || input; - } + if (list.length === 1) + events[type] = list[0]; - localFormattingTokens.lastIndex = 0; - while (i >= 0 && localFormattingTokens.test(format)) { - format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); - localFormattingTokens.lastIndex = 0; - i -= 1; - } + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } - return format; -} + return this; + }; -var match1 = /\d/; // 0 - 9 -var match2 = /\d\d/; // 00 - 99 -var match3 = /\d{3}/; // 000 - 999 -var match4 = /\d{4}/; // 0000 - 9999 -var match6 = /[+-]?\d{6}/; // -999999 - 999999 -var match1to2 = /\d\d?/; // 0 - 99 -var match3to4 = /\d\d\d\d?/; // 999 - 9999 -var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 -var match1to3 = /\d{1,3}/; // 0 - 999 -var match1to4 = /\d{1,4}/; // 0 - 9999 -var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; -var matchUnsigned = /\d+/; // 0 - inf -var matchSigned = /[+-]?\d+/; // -inf - inf + events = this._events; + if (!events) + return this; -var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z -var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = objectCreate(null); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else + delete events[type]; + } + return this; + } -var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = objectKeys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = objectCreate(null); + this._eventsCount = 0; + return this; + } -// any word (or two) characters or numbers including two/three word month in arabic. -// includes scottish gaelic two word and hyphenated months -var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; + listeners = events[type]; -var regexes = {}; + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } -function addRegexToken (token, regex, strictRegex) { - regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { - return (isStrict && strictRegex) ? strictRegex : regex; + return this; }; -} -function getParseRegexForToken (token, config) { - if (!hasOwnProp(regexes, token)) { - return new RegExp(unescapeFormat(token)); - } +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; - return regexes[token](config._strict, config._locale); -} + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } -// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript -function unescapeFormat(s) { - return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { - return p1 || p2 || p3 || p4; - })); -} + return ret; +}; -function regexEscape(s) { - return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); -} +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; -var tokens = {}; +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; -function addParseToken (token, callback) { - var i, func = callback; - if (typeof token === 'string') { - token = [token]; - } - if (isNumber(callback)) { - func = function (input, array) { - array[callback] = toInt(input); - }; - } - for (i = 0; i < token.length; i++) { - tokens[token[i]] = func; + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; } + } + + return 0; } -function addWeekParseToken (token, callback) { - addParseToken(token, function (input, array, config, token) { - config._w = config._w || {}; - callback(input, config._w, config, token); - }); +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); } -function addTimeToArrayFromToken(token, input, config) { - if (input != null && hasOwnProp(tokens, token)) { - tokens[token](input, config._a, config, token); - } +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; } -var YEAR = 0; -var MONTH = 1; -var DATE = 2; -var HOUR = 3; -var MINUTE = 4; -var SECOND = 5; -var MILLISECOND = 6; -var WEEK = 7; -var WEEKDAY = 8; +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} -// FORMATTING +function objectCreatePolyfill(proto) { + var F = function() {}; + F.prototype = proto; + return new F; +} +function objectKeysPolyfill(obj) { + var keys = []; + for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { + keys.push(k); + } + return k; +} +function functionBindPolyfill(context) { + var fn = this; + return function () { + return fn.apply(context, arguments); + }; +} -addFormatToken('Y', 0, 0, function () { - var y = this.year(); - return y <= 9999 ? '' + y : '+' + y; -}); +},{}],7:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} -addFormatToken(0, ['YY', 2], 0, function () { - return this.year() % 100; -}); +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 -addFormatToken(0, ['YYYY', 4], 0, 'year'); -addFormatToken(0, ['YYYYY', 5], 0, 'year'); -addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + value = Math.abs(value) -// ALIASES + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } -addUnitAlias('year', 'y'); + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } -// PRIORITIES + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -addUnitPriority('year', 1); + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -// PARSING + buffer[offset + i - d] |= s * 128 +} -addRegexToken('Y', matchSigned); -addRegexToken('YY', match1to2, match2); -addRegexToken('YYYY', match1to4, match4); -addRegexToken('YYYYY', match1to6, match6); -addRegexToken('YYYYYY', match1to6, match6); +},{}],8:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} -addParseToken(['YYYYY', 'YYYYYY'], YEAR); -addParseToken('YYYY', function (input, array) { - array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); -}); -addParseToken('YY', function (input, array) { - array[YEAR] = hooks.parseTwoDigitYear(input); -}); -addParseToken('Y', function (input, array) { - array[YEAR] = parseInt(input, 10); -}); +},{}],9:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ -// HELPERS +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} -function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } -function isLeapYear(year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -// HOOKS +},{}],10:[function(require,module,exports){ +var toString = {}.toString; -hooks.parseTwoDigitYear = function (input) { - return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; -// MOMENTS +},{}],11:[function(require,module,exports){ +(function (process){ +'use strict'; -var getSetYear = makeGetSet('FullYear', true); +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} -function getIsLeapYear () { - return isLeapYear(this.year()); +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } } -function makeGetSet (unit, keepTime) { - return function (value) { - if (value != null) { - set$1(this, unit, value); - hooks.updateOffset(this, keepTime); - return this; - } else { - return get(this, unit); - } - }; -} -function get (mom, unit) { - return mom.isValid() ? - mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; -} +}).call(this,require('_process')) +},{"_process":12}],12:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; -function set$1 (mom, unit, value) { - if (mom.isValid() && !isNaN(value)) { - if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { - mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; } - else { - mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; } -} - -// MOMENTS - -function stringGet (units) { - units = normalizeUnits(units); - if (isFunction(this[units])) { - return this[units](); +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } } - return this; -} -function stringSet (units, value) { - if (typeof units === 'object') { - units = normalizeObjectUnits(units); - var prioritized = getPrioritizedUnits(units); - for (var i = 0; i < prioritized.length; i++) { - this[prioritized[i].unit](units[prioritized[i].unit]); - } - } else { - units = normalizeUnits(units); - if (isFunction(this[units])) { - return this[units](value); +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); } } - return this; + + + } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -function mod(n, x) { - return ((n % x) + x) % x; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } } -var indexOf; +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; -if (Array.prototype.indexOf) { - indexOf = Array.prototype.indexOf; -} else { - indexOf = function (o) { - // I know - var i; - for (i = 0; i < this.length; ++i) { - if (this[i] === o) { - return i; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); } } - return -1; - }; + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); } -function daysInMonth(year, month) { - if (isNaN(year) || isNaN(month)) { - return NaN; +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } } - var modMonth = mod(month, 12); - year += (month - modMonth) / 12; - return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; } +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; -// FORMATTING +function noop() {} -addFormatToken('M', ['MM', 2], 'Mo', function () { - return this.month() + 1; -}); +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; -addFormatToken('MMM', 0, 0, function (format) { - return this.localeData().monthsShort(this, format); -}); +process.listeners = function (name) { return [] } -addFormatToken('MMMM', 0, 0, function (format) { - return this.localeData().months(this, format); -}); +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; -// ALIASES +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -addUnitAlias('month', 'M'); +},{}],13:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); -// PRIORITY +},{"./lib/_stream_duplex.js":14}],14:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -addUnitPriority('month', 8); +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. -// PARSING +'use strict'; -addRegexToken('M', match1to2); -addRegexToken('MM', match1to2, match2); -addRegexToken('MMM', function (isStrict, locale) { - return locale.monthsShortRegex(isStrict); -}); -addRegexToken('MMMM', function (isStrict, locale) { - return locale.monthsRegex(isStrict); -}); +/**/ -addParseToken(['M', 'MM'], function (input, array) { - array[MONTH] = toInt(input) - 1; -}); +var pna = require('process-nextick-args'); +/**/ -addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { - var month = config._locale.monthsParse(input, token, config._strict); - // if we didn't find a month name, mark the date as invalid. - if (month != null) { - array[MONTH] = month; - } else { - getParsingFlags(config).invalidMonth = input; - } -}); +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ -// LOCALES +module.exports = Duplex; -var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; -var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); -function localeMonths (m, format) { - if (!m) { - return isArray(this._months) ? this._months : - this._months['standalone']; - } - return isArray(this._months) ? this._months[m.month()] : - this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; -} +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ -var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); -function localeMonthsShort (m, format) { - if (!m) { - return isArray(this._monthsShort) ? this._monthsShort : - this._monthsShort['standalone']; - } - return isArray(this._monthsShort) ? this._monthsShort[m.month()] : - this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; -} +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); -function handleStrictParse(monthName, format, strict) { - var i, ii, mom, llc = monthName.toLocaleLowerCase(); - if (!this._monthsParse) { - // this is not used - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - for (i = 0; i < 12; ++i) { - mom = createUTC([2000, i]); - this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); - this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); - } - } +util.inherits(Duplex, Readable); - if (strict) { - if (format === 'MMM') { - ii = indexOf.call(this._shortMonthsParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._longMonthsParse, llc); - return ii !== -1 ? ii : null; - } - } else { - if (format === 'MMM') { - ii = indexOf.call(this._shortMonthsParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._longMonthsParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._longMonthsParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortMonthsParse, llc); - return ii !== -1 ? ii : null; - } - } +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } -function localeMonthsParse (monthName, format, strict) { - var i, mom, regex; +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - if (this._monthsParseExact) { - return handleStrictParse.call(this, monthName, format, strict); - } + Readable.call(this, options); + Writable.call(this, options); - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - } + if (options && options.readable === false) this.readable = false; - // TODO: add sorting - // Sorting makes sure if one month (or abbr) is a prefix of another - // see sorting in computeMonthsParse - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, i]); - if (strict && !this._longMonthsParse[i]) { - this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); - this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); - } - if (!strict && !this._monthsParse[i]) { - regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); - this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { - return i; - } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { - return i; - } else if (!strict && this._monthsParse[i].test(monthName)) { - return i; - } - } -} + if (options && options.writable === false) this.writable = false; -// MOMENTS + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; -function setMonth (mom, value) { - var dayOfMonth; + this.once('end', onend); +} - if (!mom.isValid()) { - // No op - return mom; - } +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - if (typeof value === 'string') { - if (/^\d+$/.test(value)) { - value = toInt(value); - } else { - value = mom.localeData().monthsParse(value); - // TODO: Another silent failure? - if (!isNumber(value)) { - return mom; - } - } - } + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} - dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); - mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); - return mom; +function onEndNT(self) { + self.end(); } -function getSetMonth (value) { - if (value != null) { - setMonth(this, value); - hooks.updateOffset(this, true); - return this; - } else { - return get(this, 'Month'); +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; } -} -function getDaysInMonth () { - return daysInMonth(this.year(), this.month()); -} + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); -var defaultMonthsShortRegex = matchWord; -function monthsShortRegex (isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, '_monthsRegex')) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsShortStrictRegex; - } else { - return this._monthsShortRegex; - } - } else { - if (!hasOwnProp(this, '_monthsShortRegex')) { - this._monthsShortRegex = defaultMonthsShortRegex; - } - return this._monthsShortStrictRegex && isStrict ? - this._monthsShortStrictRegex : this._monthsShortRegex; - } -} +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); -var defaultMonthsRegex = matchWord; -function monthsRegex (isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, '_monthsRegex')) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsStrictRegex; - } else { - return this._monthsRegex; - } - } else { - if (!hasOwnProp(this, '_monthsRegex')) { - this._monthsRegex = defaultMonthsRegex; - } - return this._monthsStrictRegex && isStrict ? - this._monthsStrictRegex : this._monthsRegex; - } + pna.nextTick(cb, err); +}; + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } +},{"./_stream_readable":16,"./_stream_writable":18,"core-util-is":5,"inherits":8,"process-nextick-args":11}],15:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -function computeMonthsParse () { - function cmpLenRev(a, b) { - return b.length - a.length; - } +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - var shortPieces = [], longPieces = [], mixedPieces = [], - i, mom; - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, i]); - shortPieces.push(this.monthsShort(mom, '')); - longPieces.push(this.months(mom, '')); - mixedPieces.push(this.months(mom, '')); - mixedPieces.push(this.monthsShort(mom, '')); - } - // Sorting makes sure if one month (or abbr) is a prefix of another it - // will match the longer piece. - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - for (i = 0; i < 12; i++) { - shortPieces[i] = regexEscape(shortPieces[i]); - longPieces[i] = regexEscape(longPieces[i]); - } - for (i = 0; i < 24; i++) { - mixedPieces[i] = regexEscape(mixedPieces[i]); - } +'use strict'; - this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._monthsShortRegex = this._monthsRegex; - this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); - this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); -} +module.exports = PassThrough; -function createDate (y, m, d, h, M, s, ms) { - // can't just apply() to create a date: - // https://stackoverflow.com/q/181348 - var date = new Date(y, m, d, h, M, s, ms); +var Transform = require('./_stream_transform'); - // the date constructor remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { - date.setFullYear(y); - } - return date; -} +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ -function createUTCDate (y) { - var date = new Date(Date.UTC.apply(null, arguments)); +util.inherits(PassThrough, Transform); - // the Date.UTC function remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { - date.setUTCFullYear(y); - } - return date; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); } -// start-of-first-week - start-of-year -function firstWeekOffset(year, dow, doy) { - var // first-week day -- which january is always in the first week (4 for iso, 1 for other) - fwd = 7 + dow - doy, - // first-week day local weekday -- which local weekday is fwd - fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":17,"core-util-is":5,"inherits":8}],16:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - return -fwdlw + fwd - 1; -} +'use strict'; -// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday -function dayOfYearFromWeeks(year, week, weekday, dow, doy) { - var localWeekday = (7 + weekday - dow) % 7, - weekOffset = firstWeekOffset(year, dow, doy), - dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, - resYear, resDayOfYear; +/**/ - if (dayOfYear <= 0) { - resYear = year - 1; - resDayOfYear = daysInYear(resYear) + dayOfYear; - } else if (dayOfYear > daysInYear(year)) { - resYear = year + 1; - resDayOfYear = dayOfYear - daysInYear(year); - } else { - resYear = year; - resDayOfYear = dayOfYear; - } +var pna = require('process-nextick-args'); +/**/ - return { - year: resYear, - dayOfYear: resDayOfYear - }; -} +module.exports = Readable; -function weekOfYear(mom, dow, doy) { - var weekOffset = firstWeekOffset(mom.year(), dow, doy), - week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, - resWeek, resYear; +/**/ +var isArray = require('isarray'); +/**/ - if (week < 1) { - resYear = mom.year() - 1; - resWeek = week + weeksInYear(resYear, dow, doy); - } else if (week > weeksInYear(mom.year(), dow, doy)) { - resWeek = week - weeksInYear(mom.year(), dow, doy); - resYear = mom.year() + 1; - } else { - resYear = mom.year(); - resWeek = week; - } +/**/ +var Duplex; +/**/ - return { - week: resWeek, - year: resYear - }; +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -function weeksInYear(year, dow, doy) { - var weekOffset = firstWeekOffset(year, dow, doy), - weekOffsetNext = firstWeekOffset(year + 1, dow, doy); - return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } } -// FORMATTING +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); -addFormatToken('w', ['ww', 2], 'wo', 'week'); -addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + if (!(this instanceof Readable)) return new Readable(options); -// ALIASES + this._readableState = new ReadableState(options, this); -addUnitAlias('week', 'w'); -addUnitAlias('isoWeek', 'W'); + // legacy + this.readable = true; -// PRIORITIES + if (options) { + if (typeof options.read === 'function') this._read = options.read; -addUnitPriority('week', 5); -addUnitPriority('isoWeek', 5); + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } -// PARSING + Stream.call(this); +} -addRegexToken('w', match1to2); -addRegexToken('ww', match1to2, match2); -addRegexToken('W', match1to2); -addRegexToken('WW', match1to2, match2); +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } -addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { - week[token.substr(0, 1)] = toInt(input); + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } }); -// HELPERS +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; -// LOCALES +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } -function localeWeek (mom) { - return weekOfYear(mom, this._week.dow, this._week.doy).week; -} + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; -var defaultLocaleWeek = { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 1st is the first week of the year. +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); }; -function localeFirstDayOfWeek () { - return this._week.dow; -} +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -function localeFirstDayOfYear () { - return this._week.doy; + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); } -// MOMENTS +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); -function getSetWeek (input) { - var week = this.localeData().week(this); - return input == null ? week : this.add((input - week) * 7, 'd'); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); } -function getSetISOWeek (input) { - var week = weekOfYear(this, 1, 4).week; - return input == null ? week : this.add((input - week) * 7, 'd'); +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } -// FORMATTING +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} -addFormatToken('d', 0, 'do', 'day'); +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; -addFormatToken('dd', 0, 0, function (format) { - return this.localeData().weekdaysMin(this, format); -}); +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; -addFormatToken('ddd', 0, 0, function (format) { - return this.localeData().weekdaysShort(this, format); -}); +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} -addFormatToken('dddd', 0, 0, function (format) { - return this.localeData().weekdays(this, format); -}); +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} -addFormatToken('e', 0, 0, 'weekday'); -addFormatToken('E', 0, 0, 'isoWeekday'); +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; -// ALIASES + if (n !== 0) state.emittedReadable = false; -addUnitAlias('day', 'd'); -addUnitAlias('weekday', 'e'); -addUnitAlias('isoWeekday', 'E'); + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } -// PRIORITY -addUnitPriority('day', 11); -addUnitPriority('weekday', 11); -addUnitPriority('isoWeekday', 11); + n = howMuchToRead(n, state); -// PARSING + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } -addRegexToken('d', match1to2); -addRegexToken('e', match1to2); -addRegexToken('E', match1to2); -addRegexToken('dd', function (isStrict, locale) { - return locale.weekdaysMinRegex(isStrict); -}); -addRegexToken('ddd', function (isStrict, locale) { - return locale.weekdaysShortRegex(isStrict); -}); -addRegexToken('dddd', function (isStrict, locale) { - return locale.weekdaysRegex(isStrict); -}); + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } -addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { - var weekday = config._locale.weekdaysParse(input, token, config._strict); - // if we didn't get a weekday name, mark the date as invalid - if (weekday != null) { - week.d = weekday; - } else { - getParsingFlags(config).invalidWeekday = input; - } -}); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } -addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { - week[token] = toInt(input); -}); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -// HELPERS + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } -function parseWeekday(input, locale) { - if (typeof input !== 'string') { - return input; - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - if (!isNaN(input)) { - return parseInt(input, 10); - } + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } - input = locale.weekdaysParse(input); - if (typeof input === 'number') { - return input; - } + if (ret !== null) this.emit('data', ret); - return null; -} + return ret; +}; -function parseIsoWeekday(input, locale) { - if (typeof input === 'string') { - return locale.weekdaysParse(input) % 7 || 7; +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - return isNaN(input) ? null : input; + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } } -// LOCALES - -var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); -function localeWeekdays (m, format) { - if (!m) { - return isArray(this._weekdays) ? this._weekdays : - this._weekdays['standalone']; - } - return isArray(this._weekdays) ? this._weekdays[m.day()] : - this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); } -var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); -function localeWeekdaysShort (m) { - return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } } -var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); -function localeWeekdaysMin (m) { - return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; } -function handleStrictParse$1(weekdayName, format, strict) { - var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._shortWeekdaysParse = []; - this._minWeekdaysParse = []; +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; - for (i = 0; i < 7; ++i) { - mom = createUTC([2000, 1]).day(i); - this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); - this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); - this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); - } - } +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - if (strict) { - if (format === 'dddd') { - ii = indexOf.call(this._weekdaysParse, llc); - return ii !== -1 ? ii : null; - } else if (format === 'ddd') { - ii = indexOf.call(this._shortWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } - } else { - if (format === 'dddd') { - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else if (format === 'ddd') { - ii = indexOf.call(this._shortWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._minWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } - } -} + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); -function localeWeekdaysParse (weekdayName, format, strict) { - var i, mom, regex; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - if (this._weekdaysParseExact) { - return handleStrictParse$1.call(this, weekdayName, format, strict); - } + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._minWeekdaysParse = []; - this._shortWeekdaysParse = []; - this._fullWeekdaysParse = []; + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } + } - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already + function onend() { + debug('onend'); + dest.end(); + } - mom = createUTC([2000, 1]).day(i); - if (strict && !this._fullWeekdaysParse[i]) { - this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); - this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); - this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); - } - if (!this._weekdaysParse[i]) { - regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); - this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { - return i; - } + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); } -} + } -// MOMENTS + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } -function getSetDayOfWeek (input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); - if (input != null) { - input = parseWeekday(input, this.localeData()); - return this.add(input - day, 'd'); - } else { - return day; - } -} + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); -function getSetLocaleDayOfWeek (input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; - return input == null ? weekday : this.add(input - weekday, 'd'); -} + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); -function getSetISODayOfWeek (input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - // behaves the same as moment#day except - // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) - // as a setter, sunday should belong to the previous week. + // tell the dest that it's being piped to + dest.emit('pipe', src); - if (input != null) { - var weekday = parseIsoWeekday(input, this.localeData()); - return this.day(this.day() % 7 ? weekday : weekday - 7); - } else { - return this.day() || 7; - } -} + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } -var defaultWeekdaysRegex = matchWord; -function weekdaysRegex (isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysStrictRegex; - } else { - return this._weekdaysRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysRegex')) { - this._weekdaysRegex = defaultWeekdaysRegex; - } - return this._weekdaysStrictRegex && isStrict ? - this._weekdaysStrictRegex : this._weekdaysRegex; - } -} + return dest; +}; -var defaultWeekdaysShortRegex = matchWord; -function weekdaysShortRegex (isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysShortStrictRegex; - } else { - return this._weekdaysShortRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysShortRegex')) { - this._weekdaysShortRegex = defaultWeekdaysShortRegex; - } - return this._weekdaysShortStrictRegex && isStrict ? - this._weekdaysShortStrictRegex : this._weekdaysShortRegex; +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } + }; } -var defaultWeekdaysMinRegex = matchWord; -function weekdaysMinRegex (isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysMinStrictRegex; - } else { - return this._weekdaysMinRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysMinRegex')) { - this._weekdaysMinRegex = defaultWeekdaysMinRegex; - } - return this._weekdaysMinStrictRegex && isStrict ? - this._weekdaysMinStrictRegex : this._weekdaysMinRegex; - } -} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; -function computeWeekdaysParse () { - function cmpLenRev(a, b) { - return b.length - a.length; - } + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], - i, mom, minp, shortp, longp; - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, 1]).day(i); - minp = this.weekdaysMin(mom, ''); - shortp = this.weekdaysShort(mom, ''); - longp = this.weekdays(mom, ''); - minPieces.push(minp); - shortPieces.push(shortp); - longPieces.push(longp); - mixedPieces.push(minp); - mixedPieces.push(shortp); - mixedPieces.push(longp); - } - // Sorting makes sure if one weekday (or abbr) is a prefix of another it - // will match the longer piece. - minPieces.sort(cmpLenRev); - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - for (i = 0; i < 7; i++) { - shortPieces[i] = regexEscape(shortPieces[i]); - longPieces[i] = regexEscape(longPieces[i]); - mixedPieces[i] = regexEscape(mixedPieces[i]); - } + if (!dest) dest = state.pipes; - this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._weekdaysShortRegex = this._weekdaysRegex; - this._weekdaysMinRegex = this._weekdaysRegex; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } - this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); - this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); - this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); -} + // slow case. multiple pipe destinations. -// FORMATTING + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; -function hFormat() { - return this.hours() % 12 || 12; -} + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } -function kFormat() { - return this.hours() || 24; -} + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; -addFormatToken('H', ['HH', 2], 0, 'hour'); -addFormatToken('h', ['hh', 2], 0, hFormat); -addFormatToken('k', ['kk', 2], 0, kFormat); + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; -addFormatToken('hmm', 0, 0, function () { - return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); -}); + dest.emit('unpipe', this, unpipeInfo); -addFormatToken('hmmss', 0, 0, function () { - return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + - zeroFill(this.seconds(), 2); -}); + return this; +}; -addFormatToken('Hmm', 0, 0, function () { - return '' + this.hours() + zeroFill(this.minutes(), 2); -}); +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } -addFormatToken('Hmmss', 0, 0, function () { - return '' + this.hours() + zeroFill(this.minutes(), 2) + - zeroFill(this.seconds(), 2); -}); + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; -function meridiem (token, lowercase) { - addFormatToken(token, 0, 0, function () { - return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); - }); +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); } -meridiem('a', true); -meridiem('A', false); +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; -// ALIASES +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} -addUnitAlias('hour', 'h'); +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } -// PRIORITY -addUnitPriority('hour', 13); + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} -// PARSING +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; -function matchMeridiem (isStrict, locale) { - return locale._meridiemParse; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } -addRegexToken('a', matchMeridiem); -addRegexToken('A', matchMeridiem); -addRegexToken('H', match1to2); -addRegexToken('h', match1to2); -addRegexToken('k', match1to2); -addRegexToken('HH', match1to2, match2); -addRegexToken('hh', match1to2, match2); -addRegexToken('kk', match1to2, match2); +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; -addRegexToken('hmm', match3to4); -addRegexToken('hmmss', match5to6); -addRegexToken('Hmm', match3to4); -addRegexToken('Hmmss', match5to6); + var state = this._readableState; + var paused = false; -addParseToken(['H', 'HH'], HOUR); -addParseToken(['k', 'kk'], function (input, array, config) { - var kInput = toInt(input); - array[HOUR] = kInput === 24 ? 0 : kInput; -}); -addParseToken(['a', 'A'], function (input, array, config) { - config._isPm = config._locale.isPM(input); - config._meridiem = input; -}); -addParseToken(['h', 'hh'], function (input, array, config) { - array[HOUR] = toInt(input); - getParsingFlags(config).bigHour = true; -}); -addParseToken('hmm', function (input, array, config) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); - getParsingFlags(config).bigHour = true; -}); -addParseToken('hmmss', function (input, array, config) { - var pos1 = input.length - 4; - var pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); - getParsingFlags(config).bigHour = true; -}); -addParseToken('Hmm', function (input, array, config) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); -}); -addParseToken('Hmmss', function (input, array, config) { - var pos1 = input.length - 4; - var pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); -}); + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -// LOCALES + _this.push(null); + }); -function localeIsPM (input) { - // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays - // Using charAt should be more compatible. - return ((input + '').toLowerCase().charAt(0) === 'p'); -} + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; -function localeMeridiem (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'pm' : 'PM'; - } else { - return isLower ? 'am' : 'AM'; - } -} + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); -// MOMENTS + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } -// Setting the hour should keep the time, because the user explicitly -// specified which hour he wants. So trying to maintain the same hour (in -// a new timezone) makes sense. Adding/subtracting hours does not follow -// this rule. -var getSetHour = makeGetSet('Hours', true); + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } -var baseConfig = { - calendar: defaultCalendar, - longDateFormat: defaultLongDateFormat, - invalidDate: defaultInvalidDate, - ordinal: defaultOrdinal, - dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, - relativeTime: defaultRelativeTime, + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - months: defaultLocaleMonths, - monthsShort: defaultLocaleMonthsShort, + return this; +}; - week: defaultLocaleWeek, +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - weekdays: defaultLocaleWeekdays, - weekdaysMin: defaultLocaleWeekdaysMin, - weekdaysShort: defaultLocaleWeekdaysShort, + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - meridiemParse: defaultLocaleMeridiemParse -}; +function endReadable(stream) { + var state = stream._readableState; -// internal storage for locale config files -var locales = {}; -var localeFamilies = {}; -var globalLocale; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); -function normalizeLocale(key) { - return key ? key.toLowerCase().replace('_', '-') : key; + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } } -// pick the locale from the array -// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each -// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root -function chooseLocale(names) { - var i = 0, j, next, locale, split; +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - while (i < names.length) { - split = normalizeLocale(names[i]).split('-'); - j = split.length; - next = normalizeLocale(names[i + 1]); - next = next ? next.split('-') : null; - while (j > 0) { - locale = loadLocale(split.slice(0, j).join('-')); - if (locale) { - return locale; - } - if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { - //the next array item is better than a shallower substring of this one - break; - } - j--; - } - i++; - } - return globalLocale; +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } -function loadLocale(name) { - var oldLocale = null; - // TODO: Find a better way to register and load all the locales in Node - if (!locales[name] && (typeof module !== 'undefined') && - module && module.exports) { - try { - oldLocale = globalLocale._abbr; - var aliasedRequire = require; - aliasedRequire('./locale/' + name); - getSetGlobalLocale(oldLocale); - } catch (e) {} - } - return locales[name]; +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":14,"./internal/streams/BufferList":19,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"events":6,"inherits":8,"isarray":10,"process-nextick-args":11,"safe-buffer":26,"string_decoder/":28,"util":3}],17:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -// This function will load locale and then set the global locale. If -// no arguments are passed in, it will simply return the current global -// locale key. -function getSetGlobalLocale (key, values) { - var data; - if (key) { - if (isUndefined(values)) { - data = getLocale(key); - } - else { - data = defineLocale(key, values); - } +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - if (data) { - // moment.duration._locale = moment._locale = data; - globalLocale = data; - } - else { - if ((typeof console !== 'undefined') && console.warn) { - //warn user if arguments are passed but the locale could not be set - console.warn('Locale ' + key + ' not found. Did you forget to load it?'); - } - } - } +'use strict'; - return globalLocale._abbr; +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } } -function defineLocale (name, config) { - if (config !== null) { - var locale, parentConfig = baseConfig; - config.abbr = name; - if (locales[name] != null) { - deprecateSimple('defineLocaleOverride', - 'use moment.updateLocale(localeName, config) to change ' + - 'an existing locale. moment.defineLocale(localeName, ' + - 'config) should only be used for creating a new locale ' + - 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); - parentConfig = locales[name]._config; - } else if (config.parentLocale != null) { - if (locales[config.parentLocale] != null) { - parentConfig = locales[config.parentLocale]._config; - } else { - locale = loadLocale(config.parentLocale); - if (locale != null) { - parentConfig = locale._config; - } else { - if (!localeFamilies[config.parentLocale]) { - localeFamilies[config.parentLocale] = []; - } - localeFamilies[config.parentLocale].push({ - name: name, - config: config - }); - return null; - } - } - } - locales[name] = new Locale(mergeConfigs(parentConfig, config)); +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - if (localeFamilies[name]) { - localeFamilies[name].forEach(function (x) { - defineLocale(x.name, x.config); - }); - } + Duplex.call(this, options); - // backwards compat for now: also set the locale - // make sure we set the locale AFTER all child locales have been - // created, so we won't end up with the child locale set. - getSetGlobalLocale(name); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - return locales[name]; - } else { - // useful for testing - delete locales[name]; - return null; - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); } -function updateLocale(name, config) { - if (config != null) { - var locale, tmpLocale, parentConfig = baseConfig; - // MERGE - tmpLocale = loadLocale(name); - if (tmpLocale != null) { - parentConfig = tmpLocale._config; - } - config = mergeConfigs(parentConfig, config); - locale = new Locale(config); - locale.parentLocale = locales[name]; - locales[name] = locale; +function prefinish() { + var _this = this; - // backwards compat for now: also set the locale - getSetGlobalLocale(name); - } else { - // pass null for config to unupdate, useful for tests - if (locales[name] != null) { - if (locales[name].parentLocale != null) { - locales[name] = locales[name].parentLocale; - } else if (locales[name] != null) { - delete locales[name]; - } - } - } - return locales[name]; + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } } -// returns locale data -function getLocale (key) { - var locale; +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; - if (key && key._locale && key._locale._abbr) { - key = key._locale._abbr; - } +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; - if (!key) { - return globalLocale; - } +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; - if (!isArray(key)) { - //short-circuit everything else - locale = loadLocale(key); - if (locale) { - return locale; - } - key = [key]; - } +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - return chooseLocale(key); -} + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; -function listLocales() { - return keys(locales); +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); } +},{"./_stream_duplex":14,"core-util-is":5,"inherits":8}],18:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -function checkOverflow (m) { - var overflow; - var a = m._a; +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - if (a && getParsingFlags(m).overflow === -2) { - overflow = - a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : - a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : - a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : - a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : - a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : - a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : - -1; +'use strict'; - if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { - overflow = DATE; - } - if (getParsingFlags(m)._overflowWeeks && overflow === -1) { - overflow = WEEK; - } - if (getParsingFlags(m)._overflowWeekday && overflow === -1) { - overflow = WEEKDAY; - } +/**/ - getParsingFlags(m).overflow = overflow; - } +var pna = require('process-nextick-args'); +/**/ - return m; +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; } -// Pick the first defined of two or three arguments. -function defaults(a, b, c) { - if (a != null) { - return a; - } - if (b != null) { - return b; - } - return c; +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; } +/* */ -function currentDateArray(config) { - // hooks is actually the exported moment object - var nowValue = new Date(hooks.now()); - if (config._useUTC) { - return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; - } - return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -// convert an array to a date. -// the array should mirror the parameters below -// note: all values past the year are optional and will default to the lowest possible value. -// [year, month, day , hour, minute, second, millisecond] -function configFromArray (config) { - var i, date, input = [], currentDate, expectedWeekday, yearToUse; +/**/ - if (config._d) { - return; - } +var destroyImpl = require('./internal/streams/destroy'); - currentDate = currentDateArray(config); +util.inherits(Writable, Stream); - //compute day of the year from weeks and weekdays - if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { - dayOfYearFromWeekInfo(config); - } +function nop() {} - //if the day of the year is set, figure out what it is - if (config._dayOfYear != null) { - yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); - if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { - getParsingFlags(config)._overflowDayOfYear = true; - } + options = options || {}; - date = createUTCDate(yearToUse, 0, config._dayOfYear); - config._a[MONTH] = date.getUTCMonth(); - config._a[DATE] = date.getUTCDate(); - } + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; - // Default to current date. - // * if no year, month, day of month are given, default to today - // * if day of month is given, default month and year - // * if month is given, default only year - // * if year is given, don't default anything - for (i = 0; i < 3 && config._a[i] == null; ++i) { - config._a[i] = input[i] = currentDate[i]; - } + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // Zero out whatever was not defaulted, including time - for (; i < 7; i++) { - config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; - } + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - // Check for 24:00:00.000 - if (config._a[HOUR] === 24 && - config._a[MINUTE] === 0 && - config._a[SECOND] === 0 && - config._a[MILLISECOND] === 0) { - config._nextDay = true; - config._a[HOUR] = 0; - } + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; - config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); - expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - // Apply timezone offset from input. The actual utcOffset can be changed - // with parseZone. - if (config._tzm != null) { - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - } + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - if (config._nextDay) { - config._a[HOUR] = 24; - } + // if _final has been called + this.finalCalled = false; - // check for mismatching day of week - if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { - getParsingFlags(config).weekdayMismatch = true; - } -} + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; -function dayOfYearFromWeekInfo(config) { - var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; + // has it been destroyed + this.destroyed = false; - w = config._w; - if (w.GG != null || w.W != null || w.E != null) { - dow = 1; - doy = 4; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - // TODO: We need to take the current isoWeekYear, but that depends on - // how we interpret now (local, utc, fixed offset). So create - // a now version of current config (take local/utc/offset flags, and - // create now). - weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); - week = defaults(w.W, 1); - weekday = defaults(w.E, 1); - if (weekday < 1 || weekday > 7) { - weekdayOverflow = true; - } - } else { - dow = config._locale._week.dow; - doy = config._locale._week.doy; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - var curWeek = weekOfYear(createLocal(), dow, doy); + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + // a flag to see when we're in the middle of a write. + this.writing = false; - // Default to current week. - week = defaults(w.w, curWeek.week); + // when true all writes will be buffered until .uncork() call + this.corked = 0; - if (w.d != null) { - // weekday -- low day numbers are considered next week - weekday = w.d; - if (weekday < 0 || weekday > 6) { - weekdayOverflow = true; - } - } else if (w.e != null) { - // local weekday -- counting starts from begining of week - weekday = w.e + dow; - if (w.e < 0 || w.e > 6) { - weekdayOverflow = true; - } - } else { - // default to begining of week - weekday = dow; - } - } - if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { - getParsingFlags(config)._overflowWeeks = true; - } else if (weekdayOverflow != null) { - getParsingFlags(config)._overflowWeekday = true; - } else { - temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); - config._a[YEAR] = temp.year; - config._dayOfYear = temp.dayOfYear; - } -} + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; -// iso 8601 regex -// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) -var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; -var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; -var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; -var isoDates = [ - ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], - ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], - ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], - ['GGGG-[W]WW', /\d{4}-W\d\d/, false], - ['YYYY-DDD', /\d{4}-\d{3}/], - ['YYYY-MM', /\d{4}-\d\d/, false], - ['YYYYYYMMDD', /[+-]\d{10}/], - ['YYYYMMDD', /\d{8}/], - // YYYYMM is NOT allowed by the standard - ['GGGG[W]WWE', /\d{4}W\d{3}/], - ['GGGG[W]WW', /\d{4}W\d{2}/, false], - ['YYYYDDD', /\d{7}/] -]; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; -// iso time formats and regexes -var isoTimes = [ - ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], - ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], - ['HH:mm:ss', /\d\d:\d\d:\d\d/], - ['HH:mm', /\d\d:\d\d/], - ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], - ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], - ['HHmmss', /\d\d\d\d\d\d/], - ['HHmm', /\d\d\d\d/], - ['HH', /\d\d/] -]; + // the amount that is being written when _write is called. + this.writelen = 0; -var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + this.bufferedRequest = null; + this.lastBufferedRequest = null; -// date from iso format -function configFromISO(config) { - var i, l, - string = config._i, - match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), - allowTime, dateFormat, timeFormat, tzFormat; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - if (match) { - getParsingFlags(config).iso = true; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - for (i = 0, l = isoDates.length; i < l; i++) { - if (isoDates[i][1].exec(match[1])) { - dateFormat = isoDates[i][0]; - allowTime = isoDates[i][2] !== false; - break; - } - } - if (dateFormat == null) { - config._isValid = false; - return; - } - if (match[3]) { - for (i = 0, l = isoTimes.length; i < l; i++) { - if (isoTimes[i][1].exec(match[3])) { - // match[2] should be 'T' or space - timeFormat = (match[2] || ' ') + isoTimes[i][0]; - break; - } - } - if (timeFormat == null) { - config._isValid = false; - return; - } - } - if (!allowTime && timeFormat != null) { - config._isValid = false; - return; - } - if (match[4]) { - if (tzRegex.exec(match[4])) { - tzFormat = 'Z'; - } else { - config._isValid = false; - return; - } - } - config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); - configFromStringAndFormat(config); - } else { - config._isValid = false; - } + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); } -// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 -var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; -function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { - var result = [ - untruncateYear(yearStr), - defaultLocaleMonthsShort.indexOf(monthStr), - parseInt(dayStr, 10), - parseInt(hourStr, 10), - parseInt(minuteStr, 10) - ]; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); - if (secondStr) { - result.push(parseInt(secondStr, 10)); - } +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; - return result; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; } -function untruncateYear(yearStr) { - var year = parseInt(yearStr, 10); - if (year <= 49) { - return 2000 + year; - } else if (year <= 999) { - return 1900 + year; - } - return year; +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); } -function preprocessRFC2822(s) { - // Remove comments and folding whitespace and replace multiple-spaces with a single space - return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim(); +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); } -function checkWeekday(weekdayStr, parsedInput, config) { - if (weekdayStr) { - // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. - var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), - weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); - if (weekdayProvided !== weekdayActual) { - getParsingFlags(config).weekdayMismatch = true; - config._isValid = false; - return false; - } - } - return true; +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; } -var obsOffsets = { - UT: 0, - GMT: 0, - EDT: -4 * 60, - EST: -5 * 60, - CDT: -5 * 60, - CST: -6 * 60, - MDT: -6 * 60, - MST: -7 * 60, - PDT: -7 * 60, - PST: -8 * 60 +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; }; -function calculateOffset(obsOffset, militaryOffset, numOffset) { - if (obsOffset) { - return obsOffsets[obsOffset]; - } else if (militaryOffset) { - // the only allowed military tz is Z - return 0; - } else { - var hm = parseInt(numOffset, 10); - var m = hm % 100, h = (hm - m) / 100; - return h * 60 + m; - } -} +Writable.prototype.cork = function () { + var state = this._writableState; -// date and time from ref 2822 format -function configFromRFC2822(config) { - var match = rfc2822.exec(preprocessRFC2822(config._i)); - if (match) { - var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); - if (!checkWeekday(match[1], parsedArray, config)) { - return; - } + state.corked++; +}; - config._a = parsedArray; - config._tzm = calculateOffset(match[8], match[9], match[10]); +Writable.prototype.uncork = function () { + var state = this._writableState; - config._d = createUTCDate.apply(null, config._a); - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + if (state.corked) { + state.corked--; - getParsingFlags(config).rfc2822 = true; + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; } else { - config._isValid = false; + state.bufferedRequest = state.lastBufferedRequest; } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; } -// date from iso format or fallback -function configFromString(config) { - var matched = aspNetJsonRegex.exec(config._i); +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} - if (matched !== null) { - config._d = new Date(+matched[1]); - return; - } +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; - configFromISO(config); - if (config._isValid === false) { - delete config._isValid; - } else { - return; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - configFromRFC2822(config); - if (config._isValid === false) { - delete config._isValid; + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ } else { - return; + afterWrite(stream, state, finished, cb); } - - // Final attempt, use Input Fallback - hooks.createFromInputFallback(config); + } } -hooks.createFromInputFallback = deprecate( - 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + - 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + - 'discouraged and will be removed in an upcoming major release. Please refer to ' + - 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', - function (config) { - config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); - } -); - -// constant that refers to the ISO standard -hooks.ISO_8601 = function () {}; +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} -// constant that refers to the RFC 2822 form -hooks.RFC_2822 = function () {}; +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} -// date from string and format string -function configFromStringAndFormat(config) { - // TODO: Move this to another part of the creation flow to prevent circular deps - if (config._f === hooks.ISO_8601) { - configFromISO(config); - return; +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); } - if (config._f === hooks.RFC_2822) { - configFromRFC2822(config); - return; + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } } - config._a = []; - getParsingFlags(config).empty = true; - // This array is used to make a Date, either with `new Date` or `Date.UTC` - var string = '' + config._i, - i, parsedInput, tokens, token, skipped, - stringLength = string.length, - totalParsedInputLength = 0; + if (entry === null) state.lastBufferedRequest = null; + } - tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; - // console.log('token', token, 'parsedInput', parsedInput, - // 'regex', getParseRegexForToken(token, config)); - if (parsedInput) { - skipped = string.substr(0, string.indexOf(parsedInput)); - if (skipped.length > 0) { - getParsingFlags(config).unusedInput.push(skipped); - } - string = string.slice(string.indexOf(parsedInput) + parsedInput.length); - totalParsedInputLength += parsedInput.length; - } - // don't parse if it's not a known token - if (formatTokenFunctions[token]) { - if (parsedInput) { - getParsingFlags(config).empty = false; - } - else { - getParsingFlags(config).unusedTokens.push(token); - } - addTimeToArrayFromToken(token, parsedInput, config); - } - else if (config._strict && !parsedInput) { - getParsingFlags(config).unusedTokens.push(token); - } - } +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; - // add remaining unparsed input length to the string - getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; - if (string.length > 0) { - getParsingFlags(config).unusedInput.push(string); - } +Writable.prototype._writev = null; - // clear _12h flag if hour is <= 12 - if (config._a[HOUR] <= 12 && - getParsingFlags(config).bigHour === true && - config._a[HOUR] > 0) { - getParsingFlags(config).bigHour = undefined; - } +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - getParsingFlags(config).parsedDateParts = config._a.slice(0); - getParsingFlags(config).meridiem = config._meridiem; - // handle meridiem - config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - configFromArray(config); - checkOverflow(config); -} + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } -function meridiemFixWrap (locale, hour, meridiem) { - var isPm; + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; - if (meridiem == null) { - // nothing to do - return hour; +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); } - if (locale.meridiemHour != null) { - return locale.meridiemHour(hour, meridiem); - } else if (locale.isPM != null) { - // Fallback - isPm = locale.isPM(meridiem); - if (isPm && hour < 12) { - hour += 12; - } - if (!isPm && hour === 12) { - hour = 0; - } - return hour; + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); } else { - // this is not supposed to happen - return hour; + state.prefinished = true; + stream.emit('prefinish'); } + } } -// date from string and array of format strings -function configFromStringAndArray(config) { - var tempConfig, - bestMoment, +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} - scoreToBeat, - i, - currentScore; +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} - if (config._f.length === 0) { - getParsingFlags(config).invalidFormat = true; - config._d = new Date(NaN); - return; +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; } - for (i = 0; i < config._f.length; i++) { - currentScore = 0; - tempConfig = copyConfig({}, config); - if (config._useUTC != null) { - tempConfig._useUTC = config._useUTC; - } - tempConfig._f = config._f[i]; - configFromStringAndFormat(tempConfig); + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); - if (!isValid(tempConfig)) { - continue; - } +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":14,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"inherits":8,"process-nextick-args":11,"safe-buffer":26,"util-deprecate":29}],19:[function(require,module,exports){ +'use strict'; - // if there is any input that was not parsed add a penalty for that format - currentScore += getParsingFlags(tempConfig).charsLeftOver; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - //or tokens - currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; +var Buffer = require('safe-buffer').Buffer; +var util = require('util'); - getParsingFlags(tempConfig).score = currentScore; +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} - if (scoreToBeat == null || currentScore < scoreToBeat) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - } - } +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); - extend(config, bestMoment || tempConfig); -} + this.head = null; + this.tail = null; + this.length = 0; + } -function configFromObject(config) { - if (config._d) { - return; - } + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - var i = normalizeObjectUnits(config._i); - config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { - return obj && parseInt(obj, 10); - }); + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - configFromArray(config); -} + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; -function createFromConfig (config) { - var res = new Moment(checkOverflow(prepareConfig(config))); - if (res._nextDay) { - // Adding is smart enough around DST - res.add(1, 'd'); - res._nextDay = undefined; + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; } + return ret; + }; - return res; + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; } +},{"safe-buffer":26,"util":3}],20:[function(require,module,exports){ +'use strict'; -function prepareConfig (config) { - var input = config._i, - format = config._f; +/**/ - config._locale = config._locale || getLocale(config._l); +var pna = require('process-nextick-args'); +/**/ - if (input === null || (format === undefined && input === '')) { - return createInvalid({nullInput: true}); - } +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; - if (typeof input === 'string') { - config._i = input = config._locale.preparse(input); - } + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - if (isMoment(input)) { - return new Moment(checkOverflow(input)); - } else if (isDate(input)) { - config._d = input; - } else if (isArray(format)) { - configFromStringAndArray(config); - } else if (format) { - configFromStringAndFormat(config); - } else { - configFromInput(config); + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); } + return this; + } - if (!isValid(config)) { - config._d = null; + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); } + }); - return config; + return this; } -function configFromInput(config) { - var input = config._i; - if (isUndefined(input)) { - config._d = new Date(hooks.now()); - } else if (isDate(input)) { - config._d = new Date(input.valueOf()); - } else if (typeof input === 'string') { - configFromString(config); - } else if (isArray(input)) { - config._a = map(input.slice(0), function (obj) { - return parseInt(obj, 10); - }); - configFromArray(config); - } else if (isObject(input)) { - configFromObject(config); - } else if (isNumber(input)) { - // from milliseconds - config._d = new Date(input); - } else { - hooks.createFromInputFallback(config); - } -} - -function createLocalOrUTC (input, format, locale, strict, isUTC) { - var c = {}; +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - if (locale === true || locale === false) { - strict = locale; - locale = undefined; - } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} - if ((isObject(input) && isObjectEmpty(input)) || - (isArray(input) && input.length === 0)) { - input = undefined; - } - // object construction must be done this way. - // https://github.com/moment/moment/issues/1423 - c._isAMomentObject = true; - c._useUTC = c._isUTC = isUTC; - c._l = locale; - c._i = input; - c._f = format; - c._strict = strict; +function emitErrorNT(self, err) { + self.emit('error', err); +} - return createFromConfig(c); +module.exports = { + destroy: destroy, + undestroy: undestroy +}; +},{"process-nextick-args":11}],21:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":6}],22:[function(require,module,exports){ +module.exports = require('./readable').PassThrough + +},{"./readable":23}],23:[function(require,module,exports){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":14,"./lib/_stream_passthrough.js":15,"./lib/_stream_readable.js":16,"./lib/_stream_transform.js":17,"./lib/_stream_writable.js":18}],24:[function(require,module,exports){ +module.exports = require('./readable').Transform + +},{"./readable":23}],25:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); + +},{"./lib/_stream_writable.js":18}],26:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer } -function createLocal (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, false); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -var prototypeMin = deprecate( - 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other < this ? this : other; - } else { - return createInvalid(); - } - } -); +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -var prototypeMax = deprecate( - 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other > this ? this : other; - } else { - return createInvalid(); - } - } -); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} -// Pick a moment m from moments so that m[fn](other) is true for all -// other. This relies on the function fn to be transitive. -// -// moments should either be an array of moment objects or an array, whose -// first element is an array of moment objects. -function pickBy(fn, moments) { - var res, i; - if (moments.length === 1 && isArray(moments[0])) { - moments = moments[0]; - } - if (!moments.length) { - return createLocal(); - } - res = moments[0]; - for (i = 1; i < moments.length; ++i) { - if (!moments[i].isValid() || moments[i][fn](res)) { - res = moments[i]; - } +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) } - return res; + } else { + buf.fill(0) + } + return buf } -// TODO: Use [].sort instead? -function min () { - var args = [].slice.call(arguments, 0); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - return pickBy('isBefore', args); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) } -function max () { - var args = [].slice.call(arguments, 0); +},{"buffer":4}],27:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - return pickBy('isAfter', args); -} +module.exports = Stream; -var now = function () { - return Date.now ? Date.now() : +(new Date()); -}; +var EE = require('events').EventEmitter; +var inherits = require('inherits'); -var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); -function isDurationValid(m) { - for (var key in m) { - if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { - return false; - } - } +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; - var unitHasDecimal = false; - for (var i = 0; i < ordering.length; ++i) { - if (m[ordering[i]]) { - if (unitHasDecimal) { - return false; // only allow non-integers for smallest unit - } - if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { - unitHasDecimal = true; - } - } - } - return true; -} -function isValid$1() { - return this._isValid; -} +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. -function createInvalid$1() { - return createDuration(NaN); +function Stream() { + EE.call(this); } -function Duration (duration) { - var normalizedInput = normalizeObjectUnits(duration), - years = normalizedInput.year || 0, - quarters = normalizedInput.quarter || 0, - months = normalizedInput.month || 0, - weeks = normalizedInput.week || 0, - days = normalizedInput.day || 0, - hours = normalizedInput.hour || 0, - minutes = normalizedInput.minute || 0, - seconds = normalizedInput.second || 0, - milliseconds = normalizedInput.millisecond || 0; +Stream.prototype.pipe = function(dest, options) { + var source = this; - this._isValid = isDurationValid(normalizedInput); + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } - // representation for dateAddRemove - this._milliseconds = +milliseconds + - seconds * 1e3 + // 1000 - minutes * 6e4 + // 1000 * 60 - hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 - // Because of dateAddRemove treats 24 hours as different from a - // day when working around DST, we need to store them separately - this._days = +days + - weeks * 7; - // It is impossible to translate months into days without knowing - // which months you are are talking about, so we have to store - // it separately. - this._months = +months + - quarters * 3 + - years * 12; + source.on('data', ondata); - this._data = {}; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - this._locale = getLocale(); + dest.on('drain', ondrain); - this._bubble(); -} + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } -function isDuration (obj) { - return obj instanceof Duration; -} + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; -function absRound (number) { - if (number < 0) { - return Math.round(-1 * number) * -1; - } else { - return Math.round(number); - } -} + dest.end(); + } -// FORMATTING -function offset (token, separator) { - addFormatToken(token, 0, 0, function () { - var offset = this.utcOffset(); - var sign = '+'; - if (offset < 0) { - offset = -offset; - sign = '-'; - } - return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); - }); -} + function onclose() { + if (didOnEnd) return; + didOnEnd = true; -offset('Z', ':'); -offset('ZZ', ''); + if (typeof dest.destroy === 'function') dest.destroy(); + } -// PARSING + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } -addRegexToken('Z', matchShortOffset); -addRegexToken('ZZ', matchShortOffset); -addParseToken(['Z', 'ZZ'], function (input, array, config) { - config._useUTC = true; - config._tzm = offsetFromString(matchShortOffset, input); -}); + source.on('error', onerror); + dest.on('error', onerror); -// HELPERS + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); -// timezone chunker -// '+10:00' > ['10', '00'] -// '-1530' > ['-15', '30'] -var chunkOffset = /([\+\-]|\d\d)/gi; + source.removeListener('end', onend); + source.removeListener('close', onclose); -function offsetFromString(matcher, string) { - var matches = (string || '').match(matcher); + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - if (matches === null) { - return null; - } + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - var chunk = matches[matches.length - 1] || []; - var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; - var minutes = +(parts[1] * 60) + toInt(parts[2]); + dest.removeListener('close', cleanup); + } - return minutes === 0 ? - 0 : - parts[0] === '+' ? minutes : -minutes; -} + source.on('end', cleanup); + source.on('close', cleanup); -// Return a moment from input, that is local/utc/zone equivalent to model. -function cloneWithOffset(input, model) { - var res, diff; - if (model._isUTC) { - res = model.clone(); - diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); - // Use low-level api, because this fn is low-level api. - res._d.setTime(res._d.valueOf() + diff); - hooks.updateOffset(res, false); - return res; - } else { - return createLocal(input).local(); - } -} + dest.on('close', cleanup); -function getDateOffset (m) { - // On Firefox.24 Date#getTimezoneOffset returns a floating point. - // https://github.com/moment/moment/pull/1871 - return -Math.round(m._d.getTimezoneOffset() / 15) * 15; -} + dest.emit('pipe', source); -// HOOKS + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; -// This function will be called whenever a moment is mutated. -// It is intended to keep the offset in sync with the timezone. -hooks.updateOffset = function () {}; +},{"events":6,"inherits":8,"readable-stream/duplex.js":13,"readable-stream/passthrough.js":22,"readable-stream/readable.js":23,"readable-stream/transform.js":24,"readable-stream/writable.js":25}],28:[function(require,module,exports){ +'use strict'; -// MOMENTS +var Buffer = require('safe-buffer').Buffer; -// keepLocalTime = true means only change the timezone, without -// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> -// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset -// +0200, so we adjust the time as needed, to be valid. -// -// Keeping the time actually adds/subtracts (one hour) -// from the actual represented time. That is why we call updateOffset -// a second time. In case it wants us to change the offset again -// _changeInProgress == true case, then we have to adjust, because -// there is no such time in the given timezone. -function getSetOffset (input, keepLocalTime, keepMinutes) { - var offset = this._offset || 0, - localAdjust; - if (!this.isValid()) { - return input != null ? this : NaN; - } - if (input != null) { - if (typeof input === 'string') { - input = offsetFromString(matchShortOffset, input); - if (input === null) { - return this; - } - } else if (Math.abs(input) < 16 && !keepMinutes) { - input = input * 60; - } - if (!this._isUTC && keepLocalTime) { - localAdjust = getDateOffset(this); - } - this._offset = input; - this._isUTC = true; - if (localAdjust != null) { - this.add(localAdjust, 'm'); - } - if (offset !== input) { - if (!keepLocalTime || this._changeInProgress) { - addSubtract(this, createDuration(input - offset, 'm'), 1, false); - } else if (!this._changeInProgress) { - this._changeInProgress = true; - hooks.updateOffset(this, true); - this._changeInProgress = null; - } - } - return this; - } else { - return this._isUTC ? offset : getDateOffset(this); - } -} +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; -function getSetZone (input, keepLocalTime) { - if (input != null) { - if (typeof input !== 'string') { - input = -input; - } +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; - this.utcOffset(input, keepLocalTime); +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - return this; - } else { - return -this.utcOffset(); - } -} +StringDecoder.prototype.end = utf8End; -function setOffsetToUTC (keepLocalTime) { - return this.utcOffset(0, keepLocalTime); -} +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; -function setOffsetToLocal (keepLocalTime) { - if (this._isUTC) { - this.utcOffset(0, keepLocalTime); - this._isUTC = false; +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; - if (keepLocalTime) { - this.subtract(getDateOffset(this), 'm'); - } +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return -1; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } - return this; -} - -function setOffsetToParsedOffset () { - if (this._tzm != null) { - this.utcOffset(this._tzm, false, true); - } else if (typeof this._i === 'string') { - var tZone = offsetFromString(matchOffset, this._i); - if (tZone != null) { - this.utcOffset(tZone); - } - else { - this.utcOffset(0, true); - } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } } - return this; + } } -function hasAlignedHourOffset (input) { - if (!this.isValid()) { - return false; +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character for each buffered byte of a (partial) +// character needs to be added to the output. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } } - input = input ? createLocal(input).utcOffset() : 0; - - return (this.utcOffset() - input) % 60 === 0; -} - -function isDaylightSavingTime () { - return ( - this.utcOffset() > this.clone().month(0).utcOffset() || - this.utcOffset() > this.clone().month(5).utcOffset() - ); + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; } -function isDaylightSavingTimeShifted () { - if (!isUndefined(this._isDSTShifted)) { - return this._isDSTShifted; - } - - var c = {}; - - copyConfig(c, this); - c = prepareConfig(c); - - if (c._a) { - var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); - this._isDSTShifted = this.isValid() && - compareArrays(c._a, other.toArray()) > 0; - } else { - this._isDSTShifted = false; - } - - return this._isDSTShifted; +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); } -function isLocal () { - return this.isValid() ? !this._isUTC : false; +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; } -function isUtcOffset () { - return this.isValid() ? this._isUTC : false; +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); } -function isUtc () { - return this.isValid() ? this._isUTC && this._offset === 0 : false; +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } +},{"safe-buffer":26}],29:[function(require,module,exports){ +(function (global){ -// ASP.NET json date format regex -var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; - -// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html -// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere -// and further modified to allow for strings containing both week and day -var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; - -function createDuration (input, key) { - var duration = input, - // matching against regexp is expensive, do it on demand - match = null, - sign, - ret, - diffRes; +/** + * Module exports. + */ - if (isDuration(input)) { - duration = { - ms : input._milliseconds, - d : input._days, - M : input._months - }; - } else if (isNumber(input)) { - duration = {}; - if (key) { - duration[key] = input; - } else { - duration.milliseconds = input; - } - } else if (!!(match = aspNetRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : 0, - d : toInt(match[DATE]) * sign, - h : toInt(match[HOUR]) * sign, - m : toInt(match[MINUTE]) * sign, - s : toInt(match[SECOND]) * sign, - ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match - }; - } else if (!!(match = isoRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1; - duration = { - y : parseIso(match[2], sign), - M : parseIso(match[3], sign), - w : parseIso(match[4], sign), - d : parseIso(match[5], sign), - h : parseIso(match[6], sign), - m : parseIso(match[7], sign), - s : parseIso(match[8], sign) - }; - } else if (duration == null) {// checks for null or undefined - duration = {}; - } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { - diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); +module.exports = deprecate; - duration = {}; - duration.ms = diffRes.milliseconds; - duration.M = diffRes.months; - } +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ - ret = new Duration(duration); +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } - if (isDuration(input) && hasOwnProp(input, '_locale')) { - ret._locale = input._locale; + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; } + return fn.apply(this, arguments); + } - return ret; + return deprecated; } -createDuration.fn = Duration.prototype; -createDuration.invalid = createInvalid$1; +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ -function parseIso (inp, sign) { - // We'd normally use ~~inp for this, but unfortunately it also - // converts floats to ints. - // inp may be undefined, so careful calling replace on it. - var res = inp && parseFloat(inp.replace(',', '.')); - // apply sign while we're at it - return (isNaN(res) ? 0 : res) * sign; +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; } -function positiveMomentsDifference(base, other) { - var res = {milliseconds: 0, months: 0}; - - res.months = other.month() - base.month() + - (other.year() - base.year()) * 12; - if (base.clone().add(res.months, 'M').isAfter(other)) { - --res.months; - } - - res.milliseconds = +other - +(base.clone().add(res.months, 'M')); - - return res; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],30:[function(require,module,exports){ +arguments[4][8][0].apply(exports,arguments) +},{"dup":8}],31:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; } +},{}],32:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -function momentsDifference(base, other) { - var res; - if (!(base.isValid() && other.isValid())) { - return {milliseconds: 0, months: 0}; +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); } + return objects.join(' '); + } - other = cloneWithOffset(other, base); - if (base.isBefore(other)) { - res = positiveMomentsDifference(base, other); + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; } else { - res = positiveMomentsDifference(other, base); - res.milliseconds = -res.milliseconds; - res.months = -res.months; + str += ' ' + inspect(x); } + } + return str; +}; - return res; -} - -// TODO: remove 'name' arg after deprecation is removed -function createAdder(direction, name) { - return function (val, period) { - var dur, tmp; - //invert the arguments, but complain about it - if (period !== null && !isNaN(+period)) { - deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + - 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); - tmp = val; val = period; period = tmp; - } - val = typeof val === 'string' ? +val : val; - dur = createDuration(val, period); - addSubtract(this, dur, direction); - return this; +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); }; -} + } -function addSubtract (mom, duration, isAdding, updateOffset) { - var milliseconds = duration._milliseconds, - days = absRound(duration._days), - months = absRound(duration._months); + if (process.noDeprecation === true) { + return fn; + } - if (!mom.isValid()) { - // No op - return; + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; } + return fn.apply(this, arguments); + } - updateOffset = updateOffset == null ? true : updateOffset; + return deprecated; +}; - if (months) { - setMonth(mom, get(mom, 'Month') + months * isAdding); - } - if (days) { - set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); - } - if (milliseconds) { - mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); - } - if (updateOffset) { - hooks.updateOffset(mom, days || months); + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; } -} + } + return debugs[set]; +}; -var add = createAdder(1, 'add'); -var subtract = createAdder(-1, 'subtract'); -function getCalendarFormat(myMoment, now) { - var diff = myMoment.diff(now, 'days', true); - return diff < -6 ? 'sameElse' : - diff < -1 ? 'lastWeek' : - diff < 0 ? 'lastDay' : - diff < 1 ? 'sameDay' : - diff < 2 ? 'nextDay' : - diff < 7 ? 'nextWeek' : 'sameElse'; +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } +exports.inspect = inspect; -function calendar$1 (time, formats) { - // We want to compare the start of today, vs this. - // Getting start-of-today depends on whether we're local/utc/offset or not. - var now = time || createLocal(), - sod = cloneWithOffset(now, this).startOf('day'), - format = hooks.calendarFormat(this, sod) || 'sameElse'; - var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; - return this.format(output || this.localeData().calendar(format, this, createLocal(now))); +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } } -function clone () { - return new Moment(this); + +function stylizeNoColor(str, styleType) { + return str; } -function isAfter (input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); - if (units === 'millisecond') { - return this.valueOf() > localInput.valueOf(); - } else { - return localInput.valueOf() < this.clone().startOf(units).valueOf(); - } -} -function isBefore (input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); - if (units === 'millisecond') { - return this.valueOf() < localInput.valueOf(); - } else { - return this.clone().endOf(units).valueOf() < localInput.valueOf(); - } -} +function arrayToHash(array) { + var hash = {}; -function isBetween (from, to, units, inclusivity) { - inclusivity = inclusivity || '()'; - return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && - (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units)); + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; } -function isSame (input, units) { - var localInput = isMoment(input) ? input : createLocal(input), - inputMs; - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units || 'millisecond'); - if (units === 'millisecond') { - return this.valueOf() === localInput.valueOf(); - } else { - inputMs = localInput.valueOf(); - return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); } -} + return ret; + } -function isSameOrAfter (input, units) { - return this.isSame(input, units) || this.isAfter(input,units); -} + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } -function isSameOrBefore (input, units) { - return this.isSame(input, units) || this.isBefore(input,units); -} + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); -function diff (input, units, asFloat) { - var that, - zoneDelta, - output; + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - if (!this.isValid()) { - return NaN; + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); } + } - that = cloneWithOffset(input, this); + var base = '', array = false, braces = ['{', '}']; - if (!that.isValid()) { - return NaN; - } + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } - zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - units = normalizeUnits(units); + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - switch (units) { - case 'year': output = monthDiff(this, that) / 12; break; - case 'month': output = monthDiff(this, that); break; - case 'quarter': output = monthDiff(this, that) / 3; break; - case 'second': output = (this - that) / 1e3; break; // 1000 - case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 - case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 - case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst - case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst - default: output = this - that; - } + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - return asFloat ? output : absFloor(output); -} + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } -function monthDiff (a, b) { - // difference in months - var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), - // b is in (anchor - 1 month, anchor + 1 month) - anchor = a.clone().add(wholeMonthDiff, 'months'), - anchor2, adjust; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - if (b - anchor < 0) { - anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor - anchor2); + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { - anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor2 - anchor); + return ctx.stylize('[Object]', 'special'); } + } - //check for negative zero, return zero if negative zero - return -(wholeMonthDiff + adjust) || 0; -} + ctx.seen.push(value); -hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; -hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } -function toString () { - return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); -} + ctx.seen.pop(); -function toISOString(keepOffset) { - if (!this.isValid()) { - return null; - } - var utc = keepOffset !== true; - var m = utc ? this.clone().utc() : this; - if (m.year() < 0 || m.year() > 9999) { - return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); - } - if (isFunction(Date.prototype.toISOString)) { - // native implementation is ~50x faster, use it when we can - if (utc) { - return this.toDate().toISOString(); - } else { - return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); - } - } - return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); + return reduceToSingleString(output, base, braces); } -/** - * Return a human readable representation of a moment that can - * also be evaluated to get a new moment which is the same - * - * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects - */ -function inspect () { - if (!this.isValid()) { - return 'moment.invalid(/* ' + this._i + ' */)'; - } - var func = 'moment'; - var zone = ''; - if (!this.isLocal()) { - func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; - zone = 'Z'; - } - var prefix = '[' + func + '("]'; - var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; - var datetime = '-MM-DD[T]HH:mm:ss.SSS'; - var suffix = zone + '[")]'; - return this.format(prefix + year + datetime + suffix); +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); } -function format (inputString) { - if (!inputString) { - inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; - } - var output = formatMoment(this, inputString); - return this.localeData().postformat(output); + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } -function from (time, withoutSuffix) { - if (this.isValid() && - ((isMoment(time) && time.isValid()) || - createLocal(time).isValid())) { - return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); - } else { - return this.localeData().invalidDate(); - } -} -function fromNow (withoutSuffix) { - return this.from(createLocal(), withoutSuffix); -} - -function to (time, withoutSuffix) { - if (this.isValid() && - ((isMoment(time) && time.isValid()) || - createLocal(time).isValid())) { - return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); } else { - return this.localeData().invalidDate(); + output.push(''); } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; } -function toNow (withoutSuffix) { - return this.to(createLocal(), withoutSuffix); -} - -// If passed a locale key, it will set the locale for this -// instance. Otherwise, it will return the locale configuration -// variables for this instance. -function locale (key) { - var newLocaleData; - if (key === undefined) { - return this._locale._abbr; +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); } else { - newLocaleData = getLocale(key); - if (newLocaleData != null) { - this._locale = newLocaleData; - } - return this; + str = ctx.stylize('[Getter]', 'special'); } -} - -var lang = deprecate( - 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', - function (key) { - if (key === undefined) { - return this.localeData(); + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); } else { - return this.locale(key); + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); } + } + } else { + str = ctx.stylize('[Circular]', 'special'); } -); + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } -function localeData () { - return this._locale; + return name + ': ' + str; } -function startOf (units) { - units = normalizeUnits(units); - // the following switch intentionally omits break keywords - // to utilize falling through the cases. - switch (units) { - case 'year': - this.month(0); - /* falls through */ - case 'quarter': - case 'month': - this.date(1); - /* falls through */ - case 'week': - case 'isoWeek': - case 'day': - case 'date': - this.hours(0); - /* falls through */ - case 'hour': - this.minutes(0); - /* falls through */ - case 'minute': - this.seconds(0); - /* falls through */ - case 'second': - this.milliseconds(0); - } - // weeks are a special case - if (units === 'week') { - this.weekday(0); - } - if (units === 'isoWeek') { - this.isoWeekday(1); - } +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - // quarters are also special - if (units === 'quarter') { - this.month(Math.floor(this.month() / 3) * 3); - } + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - return this; + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } -function endOf (units) { - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond') { - return this; - } - - // 'date' is an alias for 'day', so it should be considered as such. - if (units === 'date') { - units = 'day'; - } - return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); } +exports.isArray = isArray; -function valueOf () { - return this._d.valueOf() - ((this._offset || 0) * 60000); +function isBoolean(arg) { + return typeof arg === 'boolean'; } +exports.isBoolean = isBoolean; -function unix () { - return Math.floor(this.valueOf() / 1000); +function isNull(arg) { + return arg === null; } +exports.isNull = isNull; -function toDate () { - return new Date(this.valueOf()); +function isNullOrUndefined(arg) { + return arg == null; } +exports.isNullOrUndefined = isNullOrUndefined; -function toArray () { - var m = this; - return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; +function isNumber(arg) { + return typeof arg === 'number'; } +exports.isNumber = isNumber; -function toObject () { - var m = this; - return { - years: m.year(), - months: m.month(), - date: m.date(), - hours: m.hours(), - minutes: m.minutes(), - seconds: m.seconds(), - milliseconds: m.milliseconds() - }; +function isString(arg) { + return typeof arg === 'string'; } +exports.isString = isString; -function toJSON () { - // new Date(NaN).toJSON() === null - return this.isValid() ? this.toISOString() : null; +function isSymbol(arg) { + return typeof arg === 'symbol'; } +exports.isSymbol = isSymbol; -function isValid$2 () { - return isValid(this); +function isUndefined(arg) { + return arg === void 0; } +exports.isUndefined = isUndefined; -function parsingFlags () { - return extend({}, getParsingFlags(this)); +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; } +exports.isRegExp = isRegExp; -function invalidAt () { - return getParsingFlags(this).overflow; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +exports.isObject = isObject; -function creationData() { - return { - input: this._i, - format: this._f, - locale: this._locale, - isUTC: this._isUTC, - strict: this._strict - }; +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; } +exports.isDate = isDate; -// FORMATTING +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -addFormatToken(0, ['gg', 2], 0, function () { - return this.weekYear() % 100; -}); - -addFormatToken(0, ['GG', 2], 0, function () { - return this.isoWeekYear() % 100; -}); - -function addWeekYearFormatToken (token, getter) { - addFormatToken(0, [token, token.length], 0, getter); -} - -addWeekYearFormatToken('gggg', 'weekYear'); -addWeekYearFormatToken('ggggg', 'weekYear'); -addWeekYearFormatToken('GGGG', 'isoWeekYear'); -addWeekYearFormatToken('GGGGG', 'isoWeekYear'); - -// ALIASES - -addUnitAlias('weekYear', 'gg'); -addUnitAlias('isoWeekYear', 'GG'); - -// PRIORITY - -addUnitPriority('weekYear', 1); -addUnitPriority('isoWeekYear', 1); - - -// PARSING - -addRegexToken('G', matchSigned); -addRegexToken('g', matchSigned); -addRegexToken('GG', match1to2, match2); -addRegexToken('gg', match1to2, match2); -addRegexToken('GGGG', match1to4, match4); -addRegexToken('gggg', match1to4, match4); -addRegexToken('GGGGG', match1to6, match6); -addRegexToken('ggggg', match1to6, match6); - -addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { - week[token.substr(0, 2)] = toInt(input); -}); - -addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { - week[token] = hooks.parseTwoDigitYear(input); -}); - -// MOMENTS - -function getSetWeekYear (input) { - return getSetWeekYearHelper.call(this, - input, - this.week(), - this.weekday(), - this.localeData()._week.dow, - this.localeData()._week.doy); -} - -function getSetISOWeekYear (input) { - return getSetWeekYearHelper.call(this, - input, this.isoWeek(), this.isoWeekday(), 1, 4); +function isFunction(arg) { + return typeof arg === 'function'; } +exports.isFunction = isFunction; -function getISOWeeksInYear () { - return weeksInYear(this.year(), 1, 4); +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; } +exports.isPrimitive = isPrimitive; -function getWeeksInYear () { - var weekInfo = this.localeData()._week; - return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); -} +exports.isBuffer = require('./support/isBuffer'); -function getSetWeekYearHelper(input, week, weekday, dow, doy) { - var weeksTarget; - if (input == null) { - return weekOfYear(this, dow, doy).year; - } else { - weeksTarget = weeksInYear(input, dow, doy); - if (week > weeksTarget) { - week = weeksTarget; - } - return setWeekAll.call(this, input, week, weekday, dow, doy); - } +function objectToString(o) { + return Object.prototype.toString.call(o); } -function setWeekAll(weekYear, week, weekday, dow, doy) { - var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), - date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); - this.year(date.getUTCFullYear()); - this.month(date.getUTCMonth()); - this.date(date.getUTCDate()); - return this; +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); } -// FORMATTING -addFormatToken('Q', 0, 'Qo', 'quarter'); +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; -// ALIASES +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} -addUnitAlias('quarter', 'Q'); -// PRIORITY +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; -addUnitPriority('quarter', 7); -// PARSING +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); -addRegexToken('Q', match1); -addParseToken('Q', function (input, array) { - array[MONTH] = (toInt(input) - 1) * 3; -}); +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; -// MOMENTS + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; -function getSetQuarter (input) { - return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -// FORMATTING +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":31,"_process":12,"inherits":30}],33:[function(require,module,exports){ +(function (process){ +const osmtogeojson = require('osmtogeojson') +const util = require('util') +const moment = require('moment') +const geojsonMerge = require('@mapbox/geojson-merge') +const terraformer = require('terraformer') -addFormatToken('D', ['DD', 2], 'Do', 'date'); +// Initialising map -// ALIASES +mapboxgl.accessToken = 'pk.eyJ1IjoicnVtYyIsImEiOiJjamJhdHJzODUxMGUyMnFub2l3cTlmMTJnIn0.hTkMVvU1xz2StHhaEYuMIA' +let map = new mapboxgl.Map({ + container: 'map', // container id + style: 'mapbox://styles/mapbox/light-v9', + center: [-122.2014, 37.7758], + zoom: 9, + hash: true, + attributionControl: false +}) -addUnitAlias('date', 'D'); +// Adding navigation controls -// PRIOROITY -addUnitPriority('date', 9); +// geocoder +let geocoder = new MapboxGeocoder({ + accessToken: mapboxgl.accessToken +}) +map.addControl(geocoder) -// PARSING +// zoom +let nav = new mapboxgl.NavigationControl() +map.addControl(nav, 'top-left') -addRegexToken('D', match1to2); -addRegexToken('DD', match1to2, match2); -addRegexToken('Do', function (isStrict, locale) { - // TODO: Remove "ordinalParse" fallback in next major release. - return isStrict ? - (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : - locale._dayOfMonthOrdinalParseLenient; -}); +// position attribution to bottom-left +map.addControl(new mapboxgl.AttributionControl(), 'bottom-left') -addParseToken(['D', 'DD'], DATE); -addParseToken('Do', function (input, array) { - array[DATE] = toInt(input.match(match1to2)[0]); -}); +$('#fromdate').val(moment().format('YYYY-MM-DD[T]00:00:01')) +$('#todate').val(moment().format('YYYY-MM-DD[T]HH:mm:ss')) -// MOMENTS +// Set initial values -var getSetDayOfMonth = makeGetSet('Date', true); +let prevGeojson = '' +let formData = {} +let overpassDataSource = { + 'type': 'FeatureCollection', + 'features': [] +} -// FORMATTING +let head = '[out:xml][timeout:25];' +let q = head + '(node %s (%s));(way %s(%s));(rel %s (%s));out body;>;out body qt;' +map.on('load', function () { + map.addSource('overpassDataSource', {type: 'geojson', data: overpassDataSource}) +}) -addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); +// Functions -// ALIASES +/** + * This function frames the overpass query based on the map view and timeframe + * @param {string} bbox - space separated polygon coordinates (lat1 lng1 lat2 lng2 ... latn lngn) + * + * @returns {string} url - overpass query for fetching data + **/ -addUnitAlias('dayOfYear', 'DDD'); +function getQuery (bbox) { + if (bbox) { + //bbox = 'poly:"' + bbox + '"' + bbox = bbox[1] + ',' + bbox[0] + ',' + bbox[3] + ',' + bbox[2] + } else { + let bounds = map.getBounds() + let north = bounds['_ne'].lat + let east = bounds['_ne'].lng + let south = bounds['_sw'].lat + let west = bounds['_sw'].lng + bbox = south + ',' + west + ',' + north + ',' + east + } -// PRIORITY -addUnitPriority('dayOfYear', 4); + let overpassDate -// PARSING + if (formData.fromDate != '' && formData.toDate != '') { + overpassDate = "(changed:'" + formData.fromDate + "','" + formData.toDate + "')" + } else if (formData.fromDate != '' && formData.toDate === '') { + overpassDate = "(changed:'" + formData.fromDate + "')" + } -addRegexToken('DDD', match1to3); -addRegexToken('DDDD', match3); -addParseToken(['DDD', 'DDDD'], function (input, array, config) { - config._dayOfYear = toInt(input); -}); + // for osm 'https://api.openstreetmap.org/api/0.6/map?bbox='+bbox; -// HELPERS + let query = util.format(q, overpassDate, bbox, overpassDate, bbox, overpassDate, bbox) + let url = 'https://www.overpass-api.de/api/interpreter?data=' + query -// MOMENTS + return url +} -function getSetDayOfYear (input) { - var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; - return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); +/** + * Invokes getQuery() function to frame the overpass query + * Fetches data using the overpass query + * Converts XML data to geojson + * Adds three layers using geojson data + * Adds a legend & geometry count to the page + * + **/ + +function getData (url) { + if (!url) { url = getQuery() } + $('.loading').css('display', 'inline-block') + $.ajax(url) + .done(function (data) { + let geojson = osmtogeojson(data) + let ways = geojson.features.filter(function (item) { + if (item.id.startsWith('way')) { + return item + } + }) + let rels = geojson.features.filter(function (item) { + if (item.id.startsWith('relation')) { + return item + } + }) + let nodes = geojson.features.filter(function (item) { + if (item.id.startsWith('node')) { + return item + } + }) + map.getSource('overpassDataSource').setData(geojson) + map.addLayer({ + 'id': 'node', + 'type': 'circle', + 'source': 'overpassDataSource', + 'paint': { + 'circle-radius': 4, + 'circle-color': '#8C5E58', + 'circle-opacity': 0.4 + }, + 'filter': ['==', '$type', 'Point'] + }) + map.addLayer({ + 'id': 'way', + 'type': 'line', + 'source': 'overpassDataSource', + 'paint': { + 'line-color': '#FF7E6B', + 'line-opacity': 0.4 + }, + 'filter': ['==', '$type', 'LineString'] + }) + map.addLayer({ + 'id': 'area', + 'type': 'fill', + 'source': 'overpassDataSource', + 'paint': { + 'fill-color': '#F6E27F', + 'fill-opacity': 0.4 + }, + 'filter': ['==', '$type', 'Polygon'] + }) + + let countStr = `

Feature breakdown:

+ +
+ +
+ + +

` + document.getElementById('count').classList.add('fill-gray') + document.getElementById('count').innerHTML = countStr + document.getElementById('map-legend').style.display = 'block' + $('.loading').css('display', 'none') + }) + .fail(function () { + errorNotice('Too much data to fetch, zoom in further') + }) } -// FORMATTING +/** + * Displays error messages for fetch data failures + * + * @param {string} message - custom error message for different scenarios + * @param {number} time - time in milliseconds + **/ -addFormatToken('m', ['mm', 2], 0, 'minute'); +function errorNotice (message, time) { + $('.note').css('display', 'block') + $('.note p').text(message) + if (time) { + window.setTimeout(function () { + $('.note').css('display', 'none') + }, time) + } else { + window.setTimeout(function () { + $('.note').css('display', 'none') + }, 2000) + } +} -// ALIASES +/** + * Construct URL to request a particular project details + * + * @returns {string} url - project specific url to fetch details + **/ -addUnitAlias('minute', 'm'); +function getProjQuery () { + let projectID = document.getElementById('projects').value + let url = 'https://tasks.hotosm.org/api/v1/project/' + projectID + '?as_file=false' + return url +} -// PRIORITY +/** + * Fetches complete details of a particular HOTOSM project + * + **/ -addUnitPriority('minute', 14); +function getProjDetails () { + let url = getProjQuery() + console.log('From projDetails: ', url) + $.ajax(url) + .done(function (data) { + let multiPolygon = data.areaOfInterest + let entities = data.mappingTypes + let count = 0 + console.log(entities) + console.log(multiPolygon) + multiPolygon.coordinates.forEach(function (coords) { + count++ + let polygon = {'type': 'Polygon', 'coordinates': coords} + // let bbox = '' + // coords.forEach(function (item) { + // item.forEach(function (subItem) { + // bbox += subItem[1] + ' ' + subItem[0] + // }) + // }) + console.log(JSON.stringify(polygon)) + console.log(count) + let polygonTerraform = new terraformer.Primitive(polygon) + let polygonBbox = polygonTerraform.bbox() + console.log('bbox of a polygon ', polygonBbox) + let polygonUrl = getQuery(polygonBbox) + console.log(polygonUrl) + $.ajax(polygonUrl) + .done(function (data) { + let geojson = osmtogeojson(data) + var mergedStream = geojsonMerge.merge([ prevGeojson, geojson.features ]) + mergedStream.pipe(process.stdout) + console.log(mergedStream) -// PARSING + }) + .fail(function () { + errorNotice('Too much data to fetch, zoom in further') + }) + } + ) + }) + .fail(function () { + }) +} -addRegexToken('m', match1to2); -addRegexToken('mm', match1to2, match2); -addParseToken(['m', 'mm'], MINUTE); +// Fetch Data on Click -// MOMENTS +$('#submit').on('click', function () { + document.getElementById('count').innerHTML = '' + document.getElementById('count').classList.remove('fill-gray') + let zoom = map.getZoom() + if (zoom >= 5) { + formData = { + 'fromDate': moment($('#fromdate').val()).utc().toISOString(), + 'toDate': moment($('#todate').val()).utc().toISOString() + } + getProjDetails() -var getSetMinute = makeGetSet('Minutes', false); + // getData() + } else { + errorNotice('Zoom in further to fetch results') + } +}) -// FORMATTING +}).call(this,require('_process')) +},{"@mapbox/geojson-merge":34,"_process":12,"moment":41,"osmtogeojson":44,"terraformer":46,"util":32}],34:[function(require,module,exports){ +var normalize = require('geojson-normalize'); +var geojsonStream = require('geojson-stream'); +var fs = require('fs'); -addFormatToken('s', ['ss', 2], 0, 'second'); +/** + * Merge a series of GeoJSON objects into one FeatureCollection containing all + * features in all files. The objects can be any valid GeoJSON root object, + * including FeatureCollection, Feature, and Geometry types. + * + * @param {Array} inputs a list of GeoJSON objects of any type + * @return {Object} a geojson FeatureCollection. + * * @example + * var geojsonMerge = require('@mapbox/geojson-merge'); + * + * var mergedStream = geojsonMerge.merge([ + * { type: 'Point', coordinates: [0, 1] }, + * { type: 'Feature', geometry: { type: 'Point', coordinates: [0, 1] }, properties: {} } + * ]); + * + * mergedStream.pipe(process.stdout); + */ +function merge (inputs) { + var output = { + type: 'FeatureCollection', + features: [] + }; + for (var i = 0; i < inputs.length; i++) { + var normalized = normalize(inputs[i]); + for (var j = 0; j < normalized.features.length; j++) { + output.features.push(normalized.features[j]); + } + } + return output; +} -// ALIASES +/** + * Merge GeoJSON files containing GeoJSON FeatureCollections + * into a single stream of a FeatureCollection as a JSON string. + * + * This is more limited than merge - it only supports FeatureCollections + * as input - but more performant, since it can operate on GeoJSON files + * larger than what you can keep in memory at one time. + * @param {Array} inputs a list of filenames of GeoJSON files + * @returns {Stream} output: a stringified JSON of a FeatureCollection. + * @example + * var geojsonMerge = require('@mapbox/geojson-merge'); + * + * var mergedStream = geojsonMerge.mergeFeatureCollectionStream([ + * 'features.geojson', + * 'otherFeatures.geojson']) + * + * mergedStream.pipe(process.stdout); + */ +function mergeFeatureCollectionStream (inputs) { + var out = geojsonStream.stringify(); + inputs.forEach(function(file) { + fs.createReadStream(file) + .pipe(geojsonStream.parse()) + .pipe(out); + }); + return out; +} -addUnitAlias('second', 's'); +module.exports.merge = merge; +module.exports.mergeFeatureCollectionStream = mergeFeatureCollectionStream; + +},{"fs":1,"geojson-normalize":37,"geojson-stream":39}],35:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +var Parser = require('jsonparse') + , through = require('through') + +/* + + the value of this.stack that creationix's jsonparse has is weird. + + it makes this code ugly, but his problem is way harder that mine, + so i'll forgive him. + +*/ + +exports.parse = function (path, map) { + var header, footer + var parser = new Parser() + var stream = through(function (chunk) { + if('string' === typeof chunk) + chunk = new Buffer(chunk) + parser.write(chunk) + }, + function (data) { + if(data) + stream.write(data) + if (header) + stream.emit('header', header) + if (footer) + stream.emit('footer', footer) + stream.queue(null) + }) + + if('string' === typeof path) + path = path.split('.').map(function (e) { + if (e === '$*') + return {emitKey: true} + else if (e === '*') + return true + else if (e === '') // '..'.split('.') returns an empty string + return {recurse: true} + else + return e + }) -// PRIORITY -addUnitPriority('second', 15); + var count = 0, _key + if(!path || !path.length) + path = null -// PARSING + parser.onValue = function (value) { + if (!this.root) + stream.root = value -addRegexToken('s', match1to2); -addRegexToken('ss', match1to2, match2); -addParseToken(['s', 'ss'], SECOND); + if(! path) return -// MOMENTS + var i = 0 // iterates on path + var j = 0 // iterates on stack + var emitKey = false; + var emitPath = false; + while (i < path.length) { + var key = path[i] + var c + j++ -var getSetSecond = makeGetSet('Seconds', false); + if (key && !key.recurse) { + c = (j === this.stack.length) ? this : this.stack[j] + if (!c) return + if (! check(key, c.key)) { + setHeaderFooter(c.key, value) + return + } + emitKey = !!key.emitKey; + emitPath = !!key.emitPath; + i++ + } else { + i++ + var nextKey = path[i] + if (! nextKey) return + while (true) { + c = (j === this.stack.length) ? this : this.stack[j] + if (!c) return + if (check(nextKey, c.key)) { + i++; + if (!Object.isFrozen(this.stack[j])) + this.stack[j].value = null + break + } else { + setHeaderFooter(c.key, value) + } + j++ + } + } -// FORMATTING + } -addFormatToken('S', 0, 0, function () { - return ~~(this.millisecond() / 100); -}); + // emit header + if (header) { + stream.emit('header', header); + header = false; + } + if (j !== this.stack.length) return -addFormatToken(0, ['SS', 2], 0, function () { - return ~~(this.millisecond() / 10); -}); + count ++ + var actualPath = this.stack.slice(1).map(function(element) { return element.key }).concat([this.key]) + var data = this.value[this.key] + if(null != data) + if(null != (data = map ? map(data, actualPath) : data)) { + if (emitKey || emitPath) { + data = { value: data }; + if (emitKey) + data["key"] = this.key; + if (emitPath) + data["path"] = actualPath; + } -addFormatToken(0, ['SSS', 3], 0, 'millisecond'); -addFormatToken(0, ['SSSS', 4], 0, function () { - return this.millisecond() * 10; -}); -addFormatToken(0, ['SSSSS', 5], 0, function () { - return this.millisecond() * 100; -}); -addFormatToken(0, ['SSSSSS', 6], 0, function () { - return this.millisecond() * 1000; -}); -addFormatToken(0, ['SSSSSSS', 7], 0, function () { - return this.millisecond() * 10000; -}); -addFormatToken(0, ['SSSSSSSS', 8], 0, function () { - return this.millisecond() * 100000; -}); -addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { - return this.millisecond() * 1000000; -}); + stream.queue(data) + } + delete this.value[this.key] + for(var k in this.stack) + if (!Object.isFrozen(this.stack[k])) + this.stack[k].value = null + } + parser._onToken = parser.onToken; + + parser.onToken = function (token, value) { + parser._onToken(token, value); + if (this.stack.length === 0) { + if (stream.root) { + if(!path) + stream.queue(stream.root) + count = 0; + stream.root = null; + } + } + } + parser.onError = function (err) { + if(err.message.indexOf("at position") > -1) + err.message = "Invalid JSON (" + err.message + ")"; + stream.emit('error', err) + } -// ALIASES + return stream -addUnitAlias('millisecond', 'ms'); + function setHeaderFooter(key, value) { + // header has not been emitted yet + if (header !== false) { + header = header || {} + header[key] = value + } -// PRIORITY + // footer has not been emitted yet but header has + if (footer !== false && header === false) { + footer = footer || {} + footer[key] = value + } + } +} -addUnitPriority('millisecond', 16); +function check (x, y) { + if ('string' === typeof x) + return y == x + else if (x && 'function' === typeof x.exec) + return x.exec(y) + else if ('boolean' === typeof x || 'object' === typeof x) + return x + else if ('function' === typeof x) + return x(y) + return false +} -// PARSING +exports.stringify = function (op, sep, cl, indent) { + indent = indent || 0 + if (op === false){ + op = '' + sep = '\n' + cl = '' + } else if (op == null) { -addRegexToken('S', match1to3, match1); -addRegexToken('SS', match1to3, match2); -addRegexToken('SSS', match1to3, match3); + op = '[\n' + sep = '\n,\n' + cl = '\n]\n' -var token; -for (token = 'SSSS'; token.length <= 9; token += 'S') { - addRegexToken(token, matchUnsigned); -} + } -function parseMs(input, array) { - array[MILLISECOND] = toInt(('0.' + input) * 1000); -} + //else, what ever you like -for (token = 'S'; token.length <= 9; token += 'S') { - addParseToken(token, parseMs); -} -// MOMENTS + var stream + , first = true + , anyData = false + stream = through(function (data) { + anyData = true + try { + var json = JSON.stringify(data, null, indent) + } catch (err) { + return stream.emit('error', err) + } + if(first) { first = false ; stream.queue(op + json)} + else stream.queue(sep + json) + }, + function (data) { + if(!anyData) + stream.queue(op) + stream.queue(cl) + stream.queue(null) + }) + + return stream +} + +exports.stringifyObject = function (op, sep, cl, indent) { + indent = indent || 0 + if (op === false){ + op = '' + sep = '\n' + cl = '' + } else if (op == null) { + + op = '{\n' + sep = '\n,\n' + cl = '\n}\n' -var getSetMillisecond = makeGetSet('Milliseconds', false); + } -// FORMATTING + //else, what ever you like -addFormatToken('z', 0, 0, 'zoneAbbr'); -addFormatToken('zz', 0, 0, 'zoneName'); + var first = true + var anyData = false + var stream = through(function (data) { + anyData = true + var json = JSON.stringify(data[0]) + ':' + JSON.stringify(data[1], null, indent) + if(first) { first = false ; this.queue(op + json)} + else this.queue(sep + json) + }, + function (data) { + if(!anyData) this.queue(op) + this.queue(cl) -// MOMENTS + this.queue(null) + }) -function getZoneAbbr () { - return this._isUTC ? 'UTC' : ''; + return stream } -function getZoneName () { - return this._isUTC ? 'Coordinated Universal Time' : ''; -} -var proto = Moment.prototype; -proto.add = add; -proto.calendar = calendar$1; -proto.clone = clone; -proto.diff = diff; -proto.endOf = endOf; -proto.format = format; -proto.from = from; -proto.fromNow = fromNow; -proto.to = to; -proto.toNow = toNow; -proto.get = stringGet; -proto.invalidAt = invalidAt; -proto.isAfter = isAfter; -proto.isBefore = isBefore; -proto.isBetween = isBetween; -proto.isSame = isSame; -proto.isSameOrAfter = isSameOrAfter; -proto.isSameOrBefore = isSameOrBefore; -proto.isValid = isValid$2; -proto.lang = lang; -proto.locale = locale; -proto.localeData = localeData; -proto.max = prototypeMax; -proto.min = prototypeMin; -proto.parsingFlags = parsingFlags; -proto.set = stringSet; -proto.startOf = startOf; -proto.subtract = subtract; -proto.toArray = toArray; -proto.toObject = toObject; -proto.toDate = toDate; -proto.toISOString = toISOString; -proto.inspect = inspect; -proto.toJSON = toJSON; -proto.toString = toString; -proto.unix = unix; -proto.valueOf = valueOf; -proto.creationData = creationData; -proto.year = getSetYear; -proto.isLeapYear = getIsLeapYear; -proto.weekYear = getSetWeekYear; -proto.isoWeekYear = getSetISOWeekYear; -proto.quarter = proto.quarters = getSetQuarter; -proto.month = getSetMonth; -proto.daysInMonth = getDaysInMonth; -proto.week = proto.weeks = getSetWeek; -proto.isoWeek = proto.isoWeeks = getSetISOWeek; -proto.weeksInYear = getWeeksInYear; -proto.isoWeeksInYear = getISOWeeksInYear; -proto.date = getSetDayOfMonth; -proto.day = proto.days = getSetDayOfWeek; -proto.weekday = getSetLocaleDayOfWeek; -proto.isoWeekday = getSetISODayOfWeek; -proto.dayOfYear = getSetDayOfYear; -proto.hour = proto.hours = getSetHour; -proto.minute = proto.minutes = getSetMinute; -proto.second = proto.seconds = getSetSecond; -proto.millisecond = proto.milliseconds = getSetMillisecond; -proto.utcOffset = getSetOffset; -proto.utc = setOffsetToUTC; -proto.local = setOffsetToLocal; -proto.parseZone = setOffsetToParsedOffset; -proto.hasAlignedHourOffset = hasAlignedHourOffset; -proto.isDST = isDaylightSavingTime; -proto.isLocal = isLocal; -proto.isUtcOffset = isUtcOffset; -proto.isUtc = isUtc; -proto.isUTC = isUtc; -proto.zoneAbbr = getZoneAbbr; -proto.zoneName = getZoneName; -proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); -proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); -proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); -proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); -proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); +}).call(this,require("buffer").Buffer) +},{"buffer":4,"jsonparse":40,"through":47}],36:[function(require,module,exports){ +var wgs84 = require('wgs84'); -function createUnix (input) { - return createLocal(input * 1000); -} +module.exports.geometry = geometry; +module.exports.ring = ringArea; -function createInZone () { - return createLocal.apply(null, arguments).parseZone(); +function geometry(_) { + if (_.type === 'Polygon') return polygonArea(_.coordinates); + else if (_.type === 'MultiPolygon') { + var area = 0; + for (var i = 0; i < _.coordinates.length; i++) { + area += polygonArea(_.coordinates[i]); + } + return area; + } else { + return null; + } } -function preParsePostFormat (string) { - return string; +function polygonArea(coords) { + var area = 0; + if (coords && coords.length > 0) { + area += Math.abs(ringArea(coords[0])); + for (var i = 1; i < coords.length; i++) { + area -= Math.abs(ringArea(coords[i])); + } + } + return area; } -var proto$1 = Locale.prototype; - -proto$1.calendar = calendar; -proto$1.longDateFormat = longDateFormat; -proto$1.invalidDate = invalidDate; -proto$1.ordinal = ordinal; -proto$1.preparse = preParsePostFormat; -proto$1.postformat = preParsePostFormat; -proto$1.relativeTime = relativeTime; -proto$1.pastFuture = pastFuture; -proto$1.set = set; - -proto$1.months = localeMonths; -proto$1.monthsShort = localeMonthsShort; -proto$1.monthsParse = localeMonthsParse; -proto$1.monthsRegex = monthsRegex; -proto$1.monthsShortRegex = monthsShortRegex; -proto$1.week = localeWeek; -proto$1.firstDayOfYear = localeFirstDayOfYear; -proto$1.firstDayOfWeek = localeFirstDayOfWeek; +/** + * Calculate the approximate area of the polygon were it projected onto + * the earth. Note that this area will be positive if ring is oriented + * clockwise, otherwise it will be negative. + * + * Reference: + * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for + * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion + * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409 + * + * Returns: + * {float} The approximate signed geodesic area of the polygon in square + * meters. + */ -proto$1.weekdays = localeWeekdays; -proto$1.weekdaysMin = localeWeekdaysMin; -proto$1.weekdaysShort = localeWeekdaysShort; -proto$1.weekdaysParse = localeWeekdaysParse; +function ringArea(coords) { + var area = 0; -proto$1.weekdaysRegex = weekdaysRegex; -proto$1.weekdaysShortRegex = weekdaysShortRegex; -proto$1.weekdaysMinRegex = weekdaysMinRegex; + if (coords.length > 2) { + var p1, p2; + for (var i = 0; i < coords.length - 1; i++) { + p1 = coords[i]; + p2 = coords[i + 1]; + area += rad(p2[0] - p1[0]) * (2 + Math.sin(rad(p1[1])) + Math.sin(rad(p2[1]))); + } -proto$1.isPM = localeIsPM; -proto$1.meridiem = localeMeridiem; + area = area * wgs84.RADIUS * wgs84.RADIUS / 2; + } -function get$1 (format, index, field, setter) { - var locale = getLocale(); - var utc = createUTC().set(setter, index); - return locale[field](utc, format); + return area; } -function listMonthsImpl (format, index, field) { - if (isNumber(format)) { - index = format; - format = undefined; - } +function rad(_) { + return _ * Math.PI / 180; +} - format = format || ''; +},{"wgs84":48}],37:[function(require,module,exports){ +module.exports = normalize; - if (index != null) { - return get$1(format, index, field, 'month'); - } +var types = { + Point: 'geometry', + MultiPoint: 'geometry', + LineString: 'geometry', + MultiLineString: 'geometry', + Polygon: 'geometry', + MultiPolygon: 'geometry', + GeometryCollection: 'geometry', + Feature: 'feature', + FeatureCollection: 'featurecollection' +}; - var i; - var out = []; - for (i = 0; i < 12; i++) { - out[i] = get$1(format, i, field, 'month'); +/** + * Normalize a GeoJSON feature into a FeatureCollection. + * + * @param {object} gj geojson data + * @returns {object} normalized geojson data + */ +function normalize(gj) { + if (!gj || !gj.type) return null; + var type = types[gj.type]; + if (!type) return null; + + if (type === 'geometry') { + return { + type: 'FeatureCollection', + features: [{ + type: 'Feature', + properties: {}, + geometry: gj + }] + }; + } else if (type === 'feature') { + return { + type: 'FeatureCollection', + features: [gj] + }; + } else if (type === 'featurecollection') { + return gj; } - return out; } -// () -// (5) -// (fmt, 5) -// (fmt) -// (true) -// (true, 5) -// (true, fmt, 5) -// (true, fmt) -function listWeekdaysImpl (localeSorted, format, index, field) { - if (typeof localeSorted === 'boolean') { - if (isNumber(format)) { - index = format; - format = undefined; - } - - format = format || ''; - } else { - format = localeSorted; - index = format; - localeSorted = false; +},{}],38:[function(require,module,exports){ +var geojsonArea = require('geojson-area'); - if (isNumber(format)) { - index = format; - format = undefined; - } +module.exports = rewind; - format = format || ''; +function rewind(gj, outer) { + switch ((gj && gj.type) || null) { + case 'FeatureCollection': + gj.features = gj.features.map(curryOuter(rewind, outer)); + return gj; + case 'Feature': + gj.geometry = rewind(gj.geometry, outer); + return gj; + case 'Polygon': + case 'MultiPolygon': + return correct(gj, outer); + default: + return gj; } +} - var locale = getLocale(), - shift = localeSorted ? locale._week.dow : 0; - - if (index != null) { - return get$1(format, (index + shift) % 7, field, 'day'); - } +function curryOuter(a, b) { + return function(_) { return a(_, b); }; +} - var i; - var out = []; - for (i = 0; i < 7; i++) { - out[i] = get$1(format, (i + shift) % 7, field, 'day'); +function correct(_, outer) { + if (_.type === 'Polygon') { + _.coordinates = correctRings(_.coordinates, outer); + } else if (_.type === 'MultiPolygon') { + _.coordinates = _.coordinates.map(curryOuter(correctRings, outer)); } - return out; -} - -function listMonths (format, index) { - return listMonthsImpl(format, index, 'months'); -} - -function listMonthsShort (format, index) { - return listMonthsImpl(format, index, 'monthsShort'); + return _; } -function listWeekdays (localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); +function correctRings(_, outer) { + outer = !!outer; + _[0] = wind(_[0], !outer); + for (var i = 1; i < _.length; i++) { + _[i] = wind(_[i], outer); + } + return _; } -function listWeekdaysShort (localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); +function wind(_, dir) { + return cw(_) === dir ? _ : _.reverse(); } -function listWeekdaysMin (localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); +function cw(_) { + return geojsonArea.ring(_) >= 0; } -getSetGlobalLocale('en', { - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal : function (number) { - var b = number % 10, - output = (toInt(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; - } -}); +},{"geojson-area":36}],39:[function(require,module,exports){ +var JSONStream = require('JSONStream'); -// Side effect imports +var open = '{"type":"FeatureCollection","features":[', + close = ']}'; -hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); -hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); +module.exports.parse = function() { + var jsonstream = JSONStream.parse('features.*'); + return jsonstream; +}; -var mathAbs = Math.abs; +module.exports.stringify = function() { + var jsonstream = JSONStream.stringify(open, '\n,\n', close); + return jsonstream; +}; -function abs () { - var data = this._data; +},{"JSONStream":35}],40:[function(require,module,exports){ +(function (Buffer){ +/*global Buffer*/ +// Named constants with unique integer values +var C = {}; +// Tokens +var LEFT_BRACE = C.LEFT_BRACE = 0x1; +var RIGHT_BRACE = C.RIGHT_BRACE = 0x2; +var LEFT_BRACKET = C.LEFT_BRACKET = 0x3; +var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4; +var COLON = C.COLON = 0x5; +var COMMA = C.COMMA = 0x6; +var TRUE = C.TRUE = 0x7; +var FALSE = C.FALSE = 0x8; +var NULL = C.NULL = 0x9; +var STRING = C.STRING = 0xa; +var NUMBER = C.NUMBER = 0xb; +// Tokenizer States +var START = C.START = 0x11; +var STOP = C.STOP = 0x12; +var TRUE1 = C.TRUE1 = 0x21; +var TRUE2 = C.TRUE2 = 0x22; +var TRUE3 = C.TRUE3 = 0x23; +var FALSE1 = C.FALSE1 = 0x31; +var FALSE2 = C.FALSE2 = 0x32; +var FALSE3 = C.FALSE3 = 0x33; +var FALSE4 = C.FALSE4 = 0x34; +var NULL1 = C.NULL1 = 0x41; +var NULL2 = C.NULL2 = 0x42; +var NULL3 = C.NULL3 = 0x43; +var NUMBER1 = C.NUMBER1 = 0x51; +var NUMBER3 = C.NUMBER3 = 0x53; +var STRING1 = C.STRING1 = 0x61; +var STRING2 = C.STRING2 = 0x62; +var STRING3 = C.STRING3 = 0x63; +var STRING4 = C.STRING4 = 0x64; +var STRING5 = C.STRING5 = 0x65; +var STRING6 = C.STRING6 = 0x66; +// Parser States +var VALUE = C.VALUE = 0x71; +var KEY = C.KEY = 0x72; +// Parser Modes +var OBJECT = C.OBJECT = 0x81; +var ARRAY = C.ARRAY = 0x82; +// Character constants +var BACK_SLASH = "\\".charCodeAt(0); +var FORWARD_SLASH = "\/".charCodeAt(0); +var BACKSPACE = "\b".charCodeAt(0); +var FORM_FEED = "\f".charCodeAt(0); +var NEWLINE = "\n".charCodeAt(0); +var CARRIAGE_RETURN = "\r".charCodeAt(0); +var TAB = "\t".charCodeAt(0); + +var STRING_BUFFER_SIZE = 64 * 1024; + +function Parser() { + this.tState = START; + this.value = undefined; + + this.string = undefined; // string data + this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE); + this.stringBufferOffset = 0; + this.unicode = undefined; // unicode escapes + this.highSurrogate = undefined; + + this.key = undefined; + this.mode = undefined; + this.stack = []; + this.state = VALUE; + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached + + // Stream offset + this.offset = -1; +} + +// Slow code to string converter (only used when throwing syntax errors) +Parser.toknam = function (code) { + var keys = Object.keys(C); + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + if (C[key] === code) { return key; } + } + return code && ("0x" + code.toString(16)); +}; - this._milliseconds = mathAbs(this._milliseconds); - this._days = mathAbs(this._days); - this._months = mathAbs(this._months); +var proto = Parser.prototype; +proto.onError = function (err) { throw err; }; +proto.charError = function (buffer, i) { + this.tState = STOP; + this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState))); +}; +proto.appendStringChar = function (char) { + if (this.stringBufferOffset >= STRING_BUFFER_SIZE) { + this.string += this.stringBuffer.toString('utf8'); + this.stringBufferOffset = 0; + } - data.milliseconds = mathAbs(data.milliseconds); - data.seconds = mathAbs(data.seconds); - data.minutes = mathAbs(data.minutes); - data.hours = mathAbs(data.hours); - data.months = mathAbs(data.months); - data.years = mathAbs(data.years); + this.stringBuffer[this.stringBufferOffset++] = char; +}; +proto.appendStringBuf = function (buf, start, end) { + var size = buf.length; + if (typeof start === 'number') { + if (typeof end === 'number') { + if (end < 0) { + // adding a negative end decreeses the size + size = buf.length - start + end; + } else { + size = end - start; + } + } else { + size = buf.length - start; + } + } - return this; -} + if (size < 0) { + size = 0; + } -function addSubtract$1 (duration, input, value, direction) { - var other = createDuration(input, value); + if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) { + this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); + this.stringBufferOffset = 0; + } - duration._milliseconds += direction * other._milliseconds; - duration._days += direction * other._days; - duration._months += direction * other._months; + buf.copy(this.stringBuffer, this.stringBufferOffset, start, end); + this.stringBufferOffset += size; +}; +proto.write = function (buffer) { + if (typeof buffer === "string") buffer = new Buffer(buffer); + var n; + for (var i = 0, l = buffer.length; i < l; i++) { + if (this.tState === START){ + n = buffer[i]; + this.offset++; + if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // { + }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // } + }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [ + }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ] + }else if(n === 0x3a){ this.onToken(COLON, ":"); // : + }else if(n === 0x2c){ this.onToken(COMMA, ","); // , + }else if(n === 0x74){ this.tState = TRUE1; // t + }else if(n === 0x66){ this.tState = FALSE1; // f + }else if(n === 0x6e){ this.tState = NULL1; // n + }else if(n === 0x22){ // " + this.string = ""; + this.stringBufferOffset = 0; + this.tState = STRING1; + }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // - + }else{ + if (n >= 0x30 && n < 0x40) { // 1-9 + this.string = String.fromCharCode(n); this.tState = NUMBER3; + } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) { + // whitespace + } else { + return this.charError(buffer, i); + } + } + }else if (this.tState === STRING1){ // After open quote + n = buffer[i]; // get current byte from buffer + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j]; + } - return duration._bubble(); -} + this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]); + this.bytes_in_sequence = this.bytes_remaining = 0; + i = i + j - 1; + } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (n <= 193 || n > 244) { + return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState))); + } + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split + for (var k = 0; k <= (buffer.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length; + i = buffer.length - 1; + } else { + this.appendStringBuf(buffer, i, i + this.bytes_in_sequence); + i = i + this.bytes_in_sequence - 1; + } + } else if (n === 0x22) { + this.tState = START; + this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); + this.stringBufferOffset = 0; + this.onToken(STRING, this.string); + this.offset += Buffer.byteLength(this.string, 'utf8') + 1; + this.string = undefined; + } + else if (n === 0x5c) { + this.tState = STRING2; + } + else if (n >= 0x20) { this.appendStringChar(n); } + else { + return this.charError(buffer, i); + } + }else if (this.tState === STRING2){ // After backslash + n = buffer[i]; + if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1; + }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1; + }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1; + }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1; + }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1; + }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1; + }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1; + }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1; + }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3; + }else{ + return this.charError(buffer, i); + } + }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes + n = buffer[i]; + // 0-9 A-F a-f + if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) { + this.unicode += String.fromCharCode(n); + if (this.tState++ === STRING6) { + var intVal = parseInt(this.unicode, 16); + this.unicode = undefined; + if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate + this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal))); + this.highSurrogate = undefined; + } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate + this.highSurrogate = intVal; + } else { + if (this.highSurrogate !== undefined) { + this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))); + this.highSurrogate = undefined; + } + this.appendStringBuf(new Buffer(String.fromCharCode(intVal))); + } + this.tState = STRING1; + } + } else { + return this.charError(buffer, i); + } + } else if (this.tState === NUMBER1 || this.tState === NUMBER3) { + n = buffer[i]; + + switch (n) { + case 0x30: // 0 + case 0x31: // 1 + case 0x32: // 2 + case 0x33: // 3 + case 0x34: // 4 + case 0x35: // 5 + case 0x36: // 6 + case 0x37: // 7 + case 0x38: // 8 + case 0x39: // 9 + case 0x2e: // . + case 0x65: // e + case 0x45: // E + case 0x2b: // + + case 0x2d: // - + this.string += String.fromCharCode(n); + this.tState = NUMBER3; + break; + default: + this.tState = START; + var result = Number(this.string); -// supports only 2.0-style add(1, 's') or add(duration) -function add$1 (input, value) { - return addSubtract$1(this, input, value, 1); -} + if (isNaN(result)){ + return this.charError(buffer, i); + } -// supports only 2.0-style subtract(1, 's') or subtract(duration) -function subtract$1 (input, value) { - return addSubtract$1(this, input, value, -1); -} + if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) { + // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number + this.onToken(STRING, this.string); + } else { + this.onToken(NUMBER, result); + } -function absCeil (number) { - if (number < 0) { - return Math.floor(number); - } else { - return Math.ceil(number); + this.offset += this.string.length - 1; + this.string = undefined; + i--; + break; + } + }else if (this.tState === TRUE1){ // r + if (buffer[i] === 0x72) { this.tState = TRUE2; } + else { return this.charError(buffer, i); } + }else if (this.tState === TRUE2){ // u + if (buffer[i] === 0x75) { this.tState = TRUE3; } + else { return this.charError(buffer, i); } + }else if (this.tState === TRUE3){ // e + if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE1){ // a + if (buffer[i] === 0x61) { this.tState = FALSE2; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE2){ // l + if (buffer[i] === 0x6c) { this.tState = FALSE3; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE3){ // s + if (buffer[i] === 0x73) { this.tState = FALSE4; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE4){ // e + if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL1){ // u + if (buffer[i] === 0x75) { this.tState = NULL2; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL2){ // l + if (buffer[i] === 0x6c) { this.tState = NULL3; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL3){ // l + if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; } + else { return this.charError(buffer, i); } } -} - -function bubble () { - var milliseconds = this._milliseconds; - var days = this._days; - var months = this._months; - var data = this._data; - var seconds, minutes, hours, years, monthsFromDays; + } +}; +proto.onToken = function (token, value) { + // Override this to get events +}; - // if we have a mix of positive and negative values, bubble down first - // check: https://github.com/moment/moment/issues/2166 - if (!((milliseconds >= 0 && days >= 0 && months >= 0) || - (milliseconds <= 0 && days <= 0 && months <= 0))) { - milliseconds += absCeil(monthsToDays(months) + days) * 864e5; - days = 0; - months = 0; +proto.parseError = function (token, value) { + this.tState = STOP; + this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state))); +}; +proto.push = function () { + this.stack.push({value: this.value, key: this.key, mode: this.mode}); +}; +proto.pop = function () { + var value = this.value; + var parent = this.stack.pop(); + this.value = parent.value; + this.key = parent.key; + this.mode = parent.mode; + this.emit(value); + if (!this.mode) { this.state = VALUE; } +}; +proto.emit = function (value) { + if (this.mode) { this.state = COMMA; } + this.onValue(value); +}; +proto.onValue = function (value) { + // Override me +}; +proto.onToken = function (token, value) { + if(this.state === VALUE){ + if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){ + if (this.value) { + this.value[this.key] = value; + } + this.emit(value); + }else if(token === LEFT_BRACE){ + this.push(); + if (this.value) { + this.value = this.value[this.key] = {}; + } else { + this.value = {}; + } + this.key = undefined; + this.state = KEY; + this.mode = OBJECT; + }else if(token === LEFT_BRACKET){ + this.push(); + if (this.value) { + this.value = this.value[this.key] = []; + } else { + this.value = []; + } + this.key = 0; + this.mode = ARRAY; + this.state = VALUE; + }else if(token === RIGHT_BRACE){ + if (this.mode === OBJECT) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else if(token === RIGHT_BRACKET){ + if (this.mode === ARRAY) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else{ + return this.parseError(token, value); + } + }else if(this.state === KEY){ + if (token === STRING) { + this.key = value; + this.state = COLON; + } else if (token === RIGHT_BRACE) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else if(this.state === COLON){ + if (token === COLON) { this.state = VALUE; } + else { return this.parseError(token, value); } + }else if(this.state === COMMA){ + if (token === COMMA) { + if (this.mode === ARRAY) { this.key++; this.state = VALUE; } + else if (this.mode === OBJECT) { this.state = KEY; } + + } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) { + this.pop(); + } else { + return this.parseError(token, value); } + }else{ + return this.parseError(token, value); + } +}; - // The following code bubbles up values, see the tests for - // examples of what that means. - data.milliseconds = milliseconds % 1000; - - seconds = absFloor(milliseconds / 1000); - data.seconds = seconds % 60; - - minutes = absFloor(seconds / 60); - data.minutes = minutes % 60; - - hours = absFloor(minutes / 60); - data.hours = hours % 24; +Parser.C = C; - days += absFloor(hours / 24); +module.exports = Parser; - // convert days to months - monthsFromDays = absFloor(daysToMonths(days)); - months += monthsFromDays; - days -= absCeil(monthsToDays(monthsFromDays)); +}).call(this,require("buffer").Buffer) +},{"buffer":4}],41:[function(require,module,exports){ +//! moment.js - // 12 months -> 1 year - years = absFloor(months / 12); - months %= 12; +;(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.moment = factory() +}(this, (function () { 'use strict'; - data.days = days; - data.months = months; - data.years = years; +var hookCallback; - return this; +function hooks () { + return hookCallback.apply(null, arguments); } -function daysToMonths (days) { - // 400 years have 146097 days (taking into account leap year rules) - // 400 years have 12 months === 4800 - return days * 4800 / 146097; +// This is done to register the method called with moment() +// without creating circular dependencies. +function setHookCallback (callback) { + hookCallback = callback; } -function monthsToDays (months) { - // the reverse of daysToMonths - return months * 146097 / 4800; +function isArray(input) { + return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; } -function as (units) { - if (!this.isValid()) { - return NaN; - } - var days; - var months; - var milliseconds = this._milliseconds; - - units = normalizeUnits(units); +function isObject(input) { + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return input != null && Object.prototype.toString.call(input) === '[object Object]'; +} - if (units === 'month' || units === 'year') { - days = this._days + milliseconds / 864e5; - months = this._months + daysToMonths(days); - return units === 'month' ? months : months / 12; +function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return (Object.getOwnPropertyNames(obj).length === 0); } else { - // handle milliseconds separately because of floating point math errors (issue #1867) - days = this._days + Math.round(monthsToDays(this._months)); - switch (units) { - case 'week' : return days / 7 + milliseconds / 6048e5; - case 'day' : return days + milliseconds / 864e5; - case 'hour' : return days * 24 + milliseconds / 36e5; - case 'minute' : return days * 1440 + milliseconds / 6e4; - case 'second' : return days * 86400 + milliseconds / 1000; - // Math.floor prevents floating point math errors here - case 'millisecond': return Math.floor(days * 864e5) + milliseconds; - default: throw new Error('Unknown unit ' + units); + var k; + for (k in obj) { + if (obj.hasOwnProperty(k)) { + return false; + } } + return true; } } -// TODO: Use this.as('ms')? -function valueOf$1 () { - if (!this.isValid()) { - return NaN; - } - return ( - this._milliseconds + - this._days * 864e5 + - (this._months % 12) * 2592e6 + - toInt(this._months / 12) * 31536e6 - ); +function isUndefined(input) { + return input === void 0; } -function makeAs (alias) { - return function () { - return this.as(alias); - }; +function isNumber(input) { + return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; } -var asMilliseconds = makeAs('ms'); -var asSeconds = makeAs('s'); -var asMinutes = makeAs('m'); -var asHours = makeAs('h'); -var asDays = makeAs('d'); -var asWeeks = makeAs('w'); -var asMonths = makeAs('M'); -var asYears = makeAs('y'); - -function clone$1 () { - return createDuration(this); +function isDate(input) { + return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } -function get$2 (units) { - units = normalizeUnits(units); - return this.isValid() ? this[units + 's']() : NaN; +function map(arr, fn) { + var res = [], i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); + } + return res; } -function makeGetter(name) { - return function () { - return this.isValid() ? this._data[name] : NaN; - }; +function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); } -var milliseconds = makeGetter('milliseconds'); -var seconds = makeGetter('seconds'); -var minutes = makeGetter('minutes'); -var hours = makeGetter('hours'); -var days = makeGetter('days'); -var months = makeGetter('months'); -var years = makeGetter('years'); +function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } -function weeks () { - return absFloor(this.days() / 7); -} + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } -var round = Math.round; -var thresholds = { - ss: 44, // a few seconds to seconds - s : 45, // seconds to minute - m : 45, // minutes to hour - h : 22, // hours to day - d : 26, // days to month - M : 11 // months to year -}; + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } -// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize -function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { - return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + return a; } -function relativeTime$1 (posNegDuration, withoutSuffix, locale) { - var duration = createDuration(posNegDuration).abs(); - var seconds = round(duration.as('s')); - var minutes = round(duration.as('m')); - var hours = round(duration.as('h')); - var days = round(duration.as('d')); - var months = round(duration.as('M')); - var years = round(duration.as('y')); - - var a = seconds <= thresholds.ss && ['s', seconds] || - seconds < thresholds.s && ['ss', seconds] || - minutes <= 1 && ['m'] || - minutes < thresholds.m && ['mm', minutes] || - hours <= 1 && ['h'] || - hours < thresholds.h && ['hh', hours] || - days <= 1 && ['d'] || - days < thresholds.d && ['dd', days] || - months <= 1 && ['M'] || - months < thresholds.M && ['MM', months] || - years <= 1 && ['y'] || ['yy', years]; - - a[2] = withoutSuffix; - a[3] = +posNegDuration > 0; - a[4] = locale; - return substituteTimeAgo.apply(null, a); +function createUTC (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); } -// This function allows you to set the rounding function for relative time strings -function getSetRelativeTimeRounding (roundingFunction) { - if (roundingFunction === undefined) { - return round; - } - if (typeof(roundingFunction) === 'function') { - round = roundingFunction; - return true; - } - return false; +function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty : false, + unusedTokens : [], + unusedInput : [], + overflow : -2, + charsLeftOver : 0, + nullInput : false, + invalidMonth : null, + invalidFormat : false, + userInvalidated : false, + iso : false, + parsedDateParts : [], + meridiem : null, + rfc2822 : false, + weekdayMismatch : false + }; } -// This function allows you to set a threshold for relative time strings -function getSetRelativeTimeThreshold (threshold, limit) { - if (thresholds[threshold] === undefined) { - return false; - } - if (limit === undefined) { - return thresholds[threshold]; - } - thresholds[threshold] = limit; - if (threshold === 's') { - thresholds.ss = limit - 1; +function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); } - return true; + return m._pf; } -function humanize (withSuffix) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } - - var locale = this.localeData(); - var output = relativeTime$1(this, !withSuffix, locale); +var some; +if (Array.prototype.some) { + some = Array.prototype.some; +} else { + some = function (fun) { + var t = Object(this); + var len = t.length >>> 0; - if (withSuffix) { - output = locale.pastFuture(+this, output); - } + for (var i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } - return locale.postformat(output); + return false; + }; } -var abs$1 = Math.abs; +function isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m); + var parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }); + var isNowValid = !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); -function sign(x) { - return ((x > 0) - (x < 0)) || +x; -} + if (m._strict) { + isNowValid = isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } -function toISOString$1() { - // for ISO strings we do not use the normal bubbling rules: - // * milliseconds bubble up until they become hours - // * days do not bubble at all - // * months bubble up until they become years - // This is because there is no context-free conversion between hours and days - // (think of clock changes) - // and also not between days and months (28-31 days per month) - if (!this.isValid()) { - return this.localeData().invalidDate(); + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } + else { + return isNowValid; + } } + return m._isValid; +} - var seconds = abs$1(this._milliseconds) / 1000; - var days = abs$1(this._days); - var months = abs$1(this._months); - var minutes, hours, years; - - // 3600 seconds -> 60 minutes -> 1 hour - minutes = absFloor(seconds / 60); - hours = absFloor(minutes / 60); - seconds %= 60; - minutes %= 60; +function createInvalid (flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } + else { + getParsingFlags(m).userInvalidated = true; + } - // 12 months -> 1 year - years = absFloor(months / 12); - months %= 12; + return m; +} +// Plugins that add properties should also add the key here (null value), +// so we can properly clone ourselves. +var momentProperties = hooks.momentProperties = []; - // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js - var Y = years; - var M = months; - var D = days; - var h = hours; - var m = minutes; - var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; - var total = this.asSeconds(); +function copyConfig(to, from) { + var i, prop, val; - if (!total) { - // this is the same as C#'s (Noda) and python (isodate)... - // but not other JS (goog.date) - return 'P0D'; + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; } - var totalSign = total < 0 ? '-' : ''; - var ymSign = sign(this._months) !== sign(total) ? '-' : ''; - var daysSign = sign(this._days) !== sign(total) ? '-' : ''; - var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; - - return totalSign + 'P' + - (Y ? ymSign + Y + 'Y' : '') + - (M ? ymSign + M + 'M' : '') + - (D ? daysSign + D + 'D' : '') + - ((h || m || s) ? 'T' : '') + - (h ? hmsSign + h + 'H' : '') + - (m ? hmsSign + m + 'M' : '') + - (s ? hmsSign + s + 'S' : ''); -} - -var proto$2 = Duration.prototype; + if (momentProperties.length > 0) { + for (i = 0; i < momentProperties.length; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } -proto$2.isValid = isValid$1; -proto$2.abs = abs; -proto$2.add = add$1; -proto$2.subtract = subtract$1; -proto$2.as = as; -proto$2.asMilliseconds = asMilliseconds; -proto$2.asSeconds = asSeconds; -proto$2.asMinutes = asMinutes; -proto$2.asHours = asHours; -proto$2.asDays = asDays; -proto$2.asWeeks = asWeeks; -proto$2.asMonths = asMonths; -proto$2.asYears = asYears; -proto$2.valueOf = valueOf$1; -proto$2._bubble = bubble; -proto$2.clone = clone$1; -proto$2.get = get$2; -proto$2.milliseconds = milliseconds; -proto$2.seconds = seconds; -proto$2.minutes = minutes; -proto$2.hours = hours; -proto$2.days = days; -proto$2.weeks = weeks; -proto$2.months = months; -proto$2.years = years; -proto$2.humanize = humanize; -proto$2.toISOString = toISOString$1; -proto$2.toString = toISOString$1; -proto$2.toJSON = toISOString$1; -proto$2.locale = locale; -proto$2.localeData = localeData; + return to; +} -proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); -proto$2.lang = lang; +var updateInProgress = false; -// Side effect imports +// Moment prototype object +function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } +} -// FORMATTING +function isMoment (obj) { + return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); +} -addFormatToken('X', 0, 0, 'unix'); -addFormatToken('x', 0, 0, 'valueOf'); +function absFloor (number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } +} -// PARSING +function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; -addRegexToken('x', matchSigned); -addRegexToken('X', matchTimestamp); -addParseToken('X', function (input, array, config) { - config._d = new Date(parseFloat(input, 10) * 1000); -}); -addParseToken('x', function (input, array, config) { - config._d = new Date(toInt(input)); -}); + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } -// Side effect imports + return value; +} +// compare two arrays, return the number of differences +function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ((dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { + diffs++; + } + } + return diffs + lengthDiff; +} -hooks.version = '2.21.0'; +function warn(msg) { + if (hooks.suppressDeprecationWarnings === false && + (typeof console !== 'undefined') && console.warn) { + console.warn('Deprecation warning: ' + msg); + } +} -setHookCallback(createLocal); +function deprecate(msg, fn) { + var firstTime = true; -hooks.fn = proto; -hooks.min = min; -hooks.max = max; -hooks.now = now; -hooks.utc = createUTC; -hooks.unix = createUnix; -hooks.months = listMonths; -hooks.isDate = isDate; -hooks.locale = getSetGlobalLocale; -hooks.invalid = createInvalid; -hooks.duration = createDuration; -hooks.isMoment = isMoment; -hooks.weekdays = listWeekdays; -hooks.parseZone = createInZone; -hooks.localeData = getLocale; -hooks.isDuration = isDuration; -hooks.monthsShort = listMonthsShort; -hooks.weekdaysMin = listWeekdaysMin; -hooks.defineLocale = defineLocale; -hooks.updateLocale = updateLocale; -hooks.locales = listLocales; -hooks.weekdaysShort = listWeekdaysShort; -hooks.normalizeUnits = normalizeUnits; -hooks.relativeTimeRounding = getSetRelativeTimeRounding; -hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; -hooks.calendarFormat = getCalendarFormat; -hooks.prototype = proto; + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = []; + var arg; + for (var i = 0; i < arguments.length; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (var key in arguments[0]) { + arg += key + ': ' + arguments[0][key] + ', '; + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); +} -// currently HTML5 input type only supports 24-hour formats -hooks.HTML5_FMT = { - DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // - DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // - DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // - DATE: 'YYYY-MM-DD', // - TIME: 'HH:mm', // - TIME_SECONDS: 'HH:mm:ss', // - TIME_MS: 'HH:mm:ss.SSS', // - WEEK: 'YYYY-[W]WW', // - MONTH: 'YYYY-MM' // -}; +var deprecations = {}; -return hooks; +function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } +} -}))); +hooks.suppressDeprecationWarnings = false; +hooks.deprecationHandler = null; -},{}],9:[function(require,module,exports){ -module.exports = require('./polygon-features.json') +function isFunction(input) { + return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; +} -},{"./polygon-features.json":10}],10:[function(require,module,exports){ -module.exports=[ - { - "key": "building", - "polygon": "all" - }, - { - "key": "highway", - "polygon": "whitelist", - "values": [ - "services", - "rest_area", - "escape", - "elevator" - ] - }, - { - "key": "natural", - "polygon": "blacklist", - "values": [ - "coastline", - "cliff", - "ridge", - "arete", - "tree_row" - ] - }, - { - "key": "landuse", - "polygon": "all" - }, - { - "key": "waterway", - "polygon": "whitelist", - "values": [ - "riverbank", - "dock", - "boatyard", - "dam" - ] - }, - { - "key": "amenity", - "polygon": "all" - }, - { - "key": "leisure", - "polygon": "all" - }, - { - "key": "barrier", - "polygon": "whitelist", - "values": [ - "city_wall", - "ditch", - "hedge", - "retaining_wall", - "wall", - "spikes" - ] - }, - { - "key": "railway", - "polygon": "whitelist", - "values": [ - "station", - "turntable", - "roundhouse", - "platform" - ] - }, - { - "key": "area", - "polygon": "all" - }, - { - "key": "boundary", - "polygon": "all" - }, - { - "key": "man_made", - "polygon": "blacklist", - "values": [ - "cutline", - "embankment", - "pipeline" - ] - }, - { - "key": "power", - "polygon": "whitelist", - "values": [ - "plant", - "substation", - "generator", - "transformer" - ] - }, - { - "key": "place", - "polygon": "all" - }, - { - "key": "shop", - "polygon": "all" - }, - { - "key": "aeroway", - "polygon": "blacklist", - "values": [ - "taxiway" - ] - }, - { - "key": "tourism", - "polygon": "all" - }, - { - "key": "historic", - "polygon": "all" - }, - { - "key": "public_transport", - "polygon": "all" - }, - { - "key": "office", - "polygon": "all" - }, - { - "key": "building:part", - "polygon": "all" - }, - { - "key": "military", - "polygon": "all" - }, - { - "key": "ruins", - "polygon": "all" - }, - { - "key": "area:highway", - "polygon": "all" - }, - { - "key": "craft", - "polygon": "all" - }, - { - "key": "golf", - "polygon": "all" - }, - { - "key": "indoor", - "polygon": "all" +function set (config) { + var prop, i; + for (i in config) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } } -] + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + (/\d{1,2}/).source); +} -},{}],11:[function(require,module,exports){ -var _ = require("./lodash.custom.js"); -var rewind = require("geojson-rewind"); +function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if (hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop])) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; +} -// see https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features -var polygonFeatures = {}; -require("osm-polygon-features").forEach(function(tags) { - if (tags.polygon === "all") - polygonFeatures[tags.key] = true; - else { - var list = (tags.polygon === "whitelist") ? "included_values" : "excluded_values", - tagValuesObj = {}; - tags.values.forEach(function(value) { tagValuesObj[value] = true; }); - polygonFeatures[tags.key] = {}; - polygonFeatures[tags.key][list] = tagValuesObj; - } -}); +function Locale(config) { + if (config != null) { + this.set(config); + } +} -var osmtogeojson = {}; +var keys; -osmtogeojson = function( data, options ) { +if (Object.keys) { + keys = Object.keys; +} else { + keys = function (obj) { + var i, res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; +} - options = _.merge( - { - verbose: false, - flatProperties: false, - uninterestingTags: { - "source": true, - "source_ref": true, - "source:ref": true, - "history": true, - "attribution": true, - "created_by": true, - "tiger:county": true, - "tiger:tlid": true, - "tiger:upload_uuid": true - }, - polygonFeatures: polygonFeatures, - }, - options - ); +var defaultCalendar = { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' +}; - var result; - if ( ((typeof XMLDocument !== "undefined") && data instanceof XMLDocument || - (typeof XMLDocument === "undefined") && data.childNodes) ) - result = _osmXML2geoJSON(data); - else - result = _overpassJSON2geoJSON(data); - return result; +function calendar (key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; +} - function _overpassJSON2geoJSON(json) { - // sort elements - var nodes = new Array(); - var ways = new Array(); - var rels = new Array(); - // helper functions - function centerGeometry(object) { - var pseudoNode = _.clone(object); - pseudoNode.lat = object.center.lat; - pseudoNode.lon = object.center.lon; - pseudoNode.__is_center_placeholder = true; - nodes.push(pseudoNode); +var defaultLongDateFormat = { + LTS : 'h:mm:ss A', + LT : 'h:mm A', + L : 'MM/DD/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY h:mm A', + LLLL : 'dddd, MMMM D, YYYY h:mm A' +}; + +function longDateFormat (key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; + + if (format || !formatUpper) { + return format; } - function boundsGeometry(object) { - var pseudoWay = _.clone(object); - pseudoWay.nodes = []; - function addPseudoNode(lat,lon,i) { - var pseudoNode = { - type:"node", - id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i, - lat: lat, - lon: lon + + this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { + return val.slice(1); + }); + + return this._longDateFormat[key]; +} + +var defaultInvalidDate = 'Invalid date'; + +function invalidDate () { + return this._invalidDate; +} + +var defaultOrdinal = '%d'; +var defaultDayOfMonthOrdinalParse = /\d{1,2}/; + +function ordinal (number) { + return this._ordinal.replace('%d', number); +} + +var defaultRelativeTime = { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' +}; + +function relativeTime (number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return (isFunction(output)) ? + output(number, withoutSuffix, string, isFuture) : + output.replace(/%d/i, number); +} + +function pastFuture (diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); +} + +var aliases = {}; + +function addUnitAlias (unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; +} + +function normalizeUnits(units) { + return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; +} + +function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; + + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } } - pseudoWay.nodes.push(pseudoNode.id); - nodes.push(pseudoNode); - } - addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.minlon,1); - addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.minlon,2); - addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.maxlon,3); - addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.maxlon,4); - pseudoWay.nodes.push(pseudoWay.nodes[0]); - pseudoWay.__is_bounds_placeholder = true; - ways.push(pseudoWay); } - function fullGeometryWay(way) { - function addFullGeometryNode(lat,lon,id) { - var geometryNode = { - type:"node", - id: id, - lat: lat, - lon: lon, - __is_uninteresting: true - } - nodes.push(geometryNode); - } - if (!_.isArray(way.nodes)) { - way.nodes = way.geometry.map(function(nd) { - if (nd !== null) // have to skip ref-less nodes - return "_anonymous@"+nd.lat+"/"+nd.lon; - else - return "_anonymous@unknown_location"; - }); - } - way.geometry.forEach(function(nd, i) { - if (nd) { - addFullGeometryNode( - nd.lat, - nd.lon, - way.nodes[i] - ); - } - }); + + return normalizedInput; +} + +var priorities = {}; + +function addUnitPriority(unit, priority) { + priorities[unit] = priority; +} + +function getPrioritizedUnits(unitsObj) { + var units = []; + for (var u in unitsObj) { + units.push({unit: u, priority: priorities[u]}); } - function fullGeometryRelation(rel) { - function addFullGeometryNode(lat,lon,id) { - var geometryNode = { - type:"node", - id: id, - lat: lat, - lon: lon + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; +} + +function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; +} + +var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; + +var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; + +var formatFunctions = {}; + +var formatTokenFunctions = {}; + +// token: 'M' +// padded: ['MM', 2] +// ordinal: 'Mo' +// callback: function () { this.month() + 1 } +function addFormatToken (token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; + } +} + +function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); +} + +function makeFormatFunction(format) { + var array = format.match(formattingTokens), i, length; + + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); } - nodes.push(geometryNode); - } - function addFullGeometryWay(geometry,id) { - // shared multipolygon ways cannot be defined multiple times with the same id. - if (ways.some(function (way) { // todo: this is slow :( - return way.type == "way" && way.id == id; - })) return; - var geometryWay = { - type: "way", - id: id, - nodes:[] + } + + return function (mom) { + var output = '', i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; } - function addFullGeometryWayPseudoNode(lat,lon) { - // todo? do not save the same pseudo node multiple times - var geometryPseudoNode = { - type:"node", - id: "_anonymous@"+lat+"/"+lon, - lat: lat, - lon: lon, - __is_uninteresting: true - } - geometryWay.nodes.push(geometryPseudoNode.id); - nodes.push(geometryPseudoNode); - } - geometry.forEach(function(nd) { - if (nd) { - addFullGeometryWayPseudoNode( - nd.lat, - nd.lon - ); - } else { - geometryWay.nodes.push(undefined); - } - }); - ways.push(geometryWay); - } - rel.members.forEach(function(member, i) { - if (member.type == "node") { - if (member.lat) { - addFullGeometryNode( - member.lat, - member.lon, - member.ref - ); - } - } else if (member.type == "way") { - if (member.geometry) { - member.ref = "_fullGeom"+member.ref; - addFullGeometryWay( - member.geometry, - member.ref - ); - } - } - }); + return output; + }; +} + +// format date using native date object +function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); } - // create copies of individual json objects to make sure the original data doesn't get altered - // todo: cloning is slow: see if this can be done differently! - for (var i=0;i 0 - }); - if (rel.center) - centerGeometry(rel); - if (has_full_geometry) - fullGeometryRelation(rel); - else if (rel.bounds) - boundsGeometry(rel); - break; - default: - // type=area (from coord-query) is an example for this case. - } + + format = expandFormat(format, m.localeData()); + formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); + + return formatFunctions[format](m); +} + +function expandFormat(format, locale) { + var i = 5; + + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; } - return _convert2geoJSON(nodes,ways,rels); - } - function _osmXML2geoJSON(xml) { - // sort elements - var nodes = new Array(); - var ways = new Array(); - var rels = new Array(); - // helper function - function copy_attribute( x, o, attr ) { - if (x.hasAttribute(attr)) - o[attr] = x.getAttribute(attr); + + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); + localFormattingTokens.lastIndex = 0; + i -= 1; } - function centerGeometry(object, centroid) { - var pseudoNode = _.clone(object); - copy_attribute(centroid, pseudoNode, 'lat'); - copy_attribute(centroid, pseudoNode, 'lon'); - pseudoNode.__is_center_placeholder = true; - nodes.push(pseudoNode); + + return format; +} + +var match1 = /\d/; // 0 - 9 +var match2 = /\d\d/; // 00 - 99 +var match3 = /\d{3}/; // 000 - 999 +var match4 = /\d{4}/; // 0000 - 9999 +var match6 = /[+-]?\d{6}/; // -999999 - 999999 +var match1to2 = /\d\d?/; // 0 - 99 +var match3to4 = /\d\d\d\d?/; // 999 - 9999 +var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 +var match1to3 = /\d{1,3}/; // 0 - 999 +var match1to4 = /\d{1,4}/; // 0 - 9999 +var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 + +var matchUnsigned = /\d+/; // 0 - inf +var matchSigned = /[+-]?\d+/; // -inf - inf + +var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z +var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z + +var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 + +// any word (or two) characters or numbers including two/three word month in arabic. +// includes scottish gaelic two word and hyphenated months +var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; + +var regexes = {}; + +function addRegexToken (token, regex, strictRegex) { + regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { + return (isStrict && strictRegex) ? strictRegex : regex; + }; +} + +function getParseRegexForToken (token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); } - function boundsGeometry(object, bounds) { - var pseudoWay = _.clone(object); - pseudoWay.nodes = []; - function addPseudoNode(lat,lon,i) { - var pseudoNode = { - type:"node", - id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i, - lat: lat, - lon: lon - } - pseudoWay.nodes.push(pseudoNode.id); - nodes.push(pseudoNode); - } - addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('minlon'),1); - addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('minlon'),2); - addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('maxlon'),3); - addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('maxlon'),4); - pseudoWay.nodes.push(pseudoWay.nodes[0]); - pseudoWay.__is_bounds_placeholder = true; - ways.push(pseudoWay); + + return regexes[token](config._strict, config._locale); +} + +// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript +function unescapeFormat(s) { + return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + })); +} + +function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); +} + +var tokens = {}; + +function addParseToken (token, callback) { + var i, func = callback; + if (typeof token === 'string') { + token = [token]; } - function fullGeometryWay(way, nds) { - function addFullGeometryNode(lat,lon,id) { - var geometryNode = { - type:"node", - id: id, - lat: lat, - lon: lon, - __is_uninteresting: true - } - nodes.push(geometryNode); - return geometryNode.id; - } - if (!_.isArray(way.nodes)) { - way.nodes = []; - _.each( nds, function( nd, i ) { - way.nodes.push("_anonymous@"+nd.getAttribute('lat')+"/"+nd.getAttribute('lon')); - }); - } - _.each( nds, function( nd, i ) { - if (nd.getAttribute('lat')) { - addFullGeometryNode( - nd.getAttribute('lat'), - nd.getAttribute('lon'), - way.nodes[i] - ); - } - }); + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; } - function fullGeometryRelation(rel, members) { - function addFullGeometryNode(lat,lon,id) { - var geometryNode = { - type:"node", - id: id, - lat: lat, - lon: lon - } - nodes.push(geometryNode); - } - function addFullGeometryWay(nds,id) { - // shared multipolygon ways cannot be defined multiple times with the same id. - if (ways.some(function (way) { // todo: this is slow :( - return way.type == "way" && way.id == id; - })) return; - var geometryWay = { - type: "way", - id: id, - nodes:[] - } - function addFullGeometryWayPseudoNode(lat,lon) { - // todo? do not save the same pseudo node multiple times - var geometryPseudoNode = { - type:"node", - id: "_anonymous@"+lat+"/"+lon, - lat: lat, - lon: lon, - __is_uninteresting: true - } - geometryWay.nodes.push(geometryPseudoNode.id); - nodes.push(geometryPseudoNode); - } - _.each(nds, function(nd) { - if (nd.getAttribute('lat')) { - addFullGeometryWayPseudoNode( - nd.getAttribute('lat'), - nd.getAttribute('lon') - ); - } else { - geometryWay.nodes.push(undefined); - } - }); - ways.push(geometryWay); - } - _.each( members, function( member, i ) { - if (rel.members[i].type == "node") { - if (member.getAttribute('lat')) { - addFullGeometryNode( - member.getAttribute('lat'), - member.getAttribute('lon'), - rel.members[i].ref - ); - } - } else if (rel.members[i].type == "way") { - if (member.getElementsByTagName('nd').length > 0) { - rel.members[i].ref = "_fullGeom"+rel.members[i].ref; - addFullGeometryWay( - member.getElementsByTagName('nd'), - rel.members[i].ref - ); - } - } - }); + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; } - // nodes - _.each( xml.getElementsByTagName('node'), function( node, i ) { - var tags = {}; - _.each( node.getElementsByTagName('tag'), function( tag ) { - tags[tag.getAttribute('k')] = tag.getAttribute('v'); - }); - var nodeObject = { - 'type': 'node' - }; - copy_attribute( node, nodeObject, 'id' ); - copy_attribute( node, nodeObject, 'lat' ); - copy_attribute( node, nodeObject, 'lon' ); - copy_attribute( node, nodeObject, 'version' ); - copy_attribute( node, nodeObject, 'timestamp' ); - copy_attribute( node, nodeObject, 'changeset' ); - copy_attribute( node, nodeObject, 'uid' ); - copy_attribute( node, nodeObject, 'user' ); - if (!_.isEmpty(tags)) - nodeObject.tags = tags; - nodes.push(nodeObject); - }); - // ways - var centroid,bounds; - _.each( xml.getElementsByTagName('way'), function( way, i ) { - var tags = {}; - var wnodes = []; - _.each( way.getElementsByTagName('tag'), function( tag ) { - tags[tag.getAttribute('k')] = tag.getAttribute('v'); - }); - var has_full_geometry = false; - _.each( way.getElementsByTagName('nd'), function( nd, i ) { - var id; - if (id = nd.getAttribute('ref')) - wnodes[i] = id; - if (!has_full_geometry && nd.getAttribute('lat')) - has_full_geometry = true; - }); - var wayObject = { - "type": "way" - }; - copy_attribute( way, wayObject, 'id' ); - copy_attribute( way, wayObject, 'version' ); - copy_attribute( way, wayObject, 'timestamp' ); - copy_attribute( way, wayObject, 'changeset' ); - copy_attribute( way, wayObject, 'uid' ); - copy_attribute( way, wayObject, 'user' ); - if (wnodes.length > 0) - wayObject.nodes = wnodes; - if (!_.isEmpty(tags)) - wayObject.tags = tags; - if (centroid = way.getElementsByTagName('center')[0]) - centerGeometry(wayObject,centroid); - if (has_full_geometry) - fullGeometryWay(wayObject, way.getElementsByTagName('nd')); - else if (bounds = way.getElementsByTagName('bounds')[0]) - boundsGeometry(wayObject,bounds); - ways.push(wayObject); +} + +function addWeekParseToken (token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); }); - // relations - _.each( xml.getElementsByTagName('relation'), function( relation, i ) { - var tags = {}; - var members = []; - _.each( relation.getElementsByTagName('tag'), function( tag ) { - tags[tag.getAttribute('k')] = tag.getAttribute('v'); - }); - var has_full_geometry = false; - _.each( relation.getElementsByTagName('member'), function( member, i ) { - members[i] = {}; - copy_attribute( member, members[i], 'ref' ); - copy_attribute( member, members[i], 'role' ); - copy_attribute( member, members[i], 'type' ); - if (!has_full_geometry && - (members[i].type == 'node' && member.getAttribute('lat')) || - (members[i].type == 'way' && member.getElementsByTagName('nd').length>0) ) - has_full_geometry = true; - }); - var relObject = { - "type": "relation" +} + +function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } +} + +var YEAR = 0; +var MONTH = 1; +var DATE = 2; +var HOUR = 3; +var MINUTE = 4; +var SECOND = 5; +var MILLISECOND = 6; +var WEEK = 7; +var WEEKDAY = 8; + +// FORMATTING + +addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? '' + y : '+' + y; +}); + +addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; +}); + +addFormatToken(0, ['YYYY', 4], 0, 'year'); +addFormatToken(0, ['YYYYY', 5], 0, 'year'); +addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + +// ALIASES + +addUnitAlias('year', 'y'); + +// PRIORITIES + +addUnitPriority('year', 1); + +// PARSING + +addRegexToken('Y', matchSigned); +addRegexToken('YY', match1to2, match2); +addRegexToken('YYYY', match1to4, match4); +addRegexToken('YYYYY', match1to6, match6); +addRegexToken('YYYYYY', match1to6, match6); + +addParseToken(['YYYYY', 'YYYYYY'], YEAR); +addParseToken('YYYY', function (input, array) { + array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); +}); +addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); +}); +addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); +}); + +// HELPERS + +function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; +} + +function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +// HOOKS + +hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); +}; + +// MOMENTS + +var getSetYear = makeGetSet('FullYear', true); + +function getIsLeapYear () { + return isLeapYear(this.year()); +} + +function makeGetSet (unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; +} + +function get (mom, unit) { + return mom.isValid() ? + mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; +} + +function set$1 (mom, unit, value) { + if (mom.isValid() && !isNaN(value)) { + if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); + } + else { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } + } +} + +// MOMENTS + +function stringGet (units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; +} + + +function stringSet (units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units); + for (var i = 0; i < prioritized.length; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; +} + +function mod(n, x) { + return ((n % x) + x) % x; +} + +var indexOf; + +if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; +} else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; +} + +function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); +} + +// FORMATTING + +addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; +}); + +addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); +}); + +addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); +}); + +// ALIASES + +addUnitAlias('month', 'M'); + +// PRIORITY + +addUnitPriority('month', 8); + +// PARSING + +addRegexToken('M', match1to2); +addRegexToken('MM', match1to2, match2); +addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); +}); +addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); +}); + +addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; +}); + +addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } +}); + +// LOCALES + +var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; +var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); +function localeMonths (m, format) { + if (!m) { + return isArray(this._months) ? this._months : + this._months['standalone']; + } + return isArray(this._months) ? this._months[m.month()] : + this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; +} + +var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); +function localeMonthsShort (m, format) { + if (!m) { + return isArray(this._monthsShort) ? this._monthsShort : + this._monthsShort['standalone']; + } + return isArray(this._monthsShort) ? this._monthsShort[m.month()] : + this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; +} + +function handleStrictParse(monthName, format, strict) { + var i, ii, mom, llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } +} + +function localeMonthsParse (monthName, format, strict) { + var i, mom, regex; + + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } + + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); + this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); + } + if (!strict && !this._monthsParse[i]) { + regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } +} + +// MOMENTS + +function setMonth (mom, value) { + var dayOfMonth; + + if (!mom.isValid()) { + // No op + return mom; + } + + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; +} + +function getSetMonth (value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } +} + +function getDaysInMonth () { + return daysInMonth(this.year(), this.month()); +} + +var defaultMonthsShortRegex = matchWord; +function monthsShortRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict ? + this._monthsShortStrictRegex : this._monthsShortRegex; + } +} + +var defaultMonthsRegex = matchWord; +function monthsRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict ? + this._monthsStrictRegex : this._monthsRegex; + } +} + +function computeMonthsParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var shortPieces = [], longPieces = [], mixedPieces = [], + i, mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, '')); + longPieces.push(this.months(mom, '')); + mixedPieces.push(this.months(mom, '')); + mixedPieces.push(this.monthsShort(mom, '')); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); +} + +function createDate (y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date = new Date(y, m, d, h, M, s, ms); + + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { + date.setFullYear(y); + } + return date; +} + +function createUTCDate (y) { + var date = new Date(Date.UTC.apply(null, arguments)); + + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + return date; +} + +// start-of-first-week - start-of-year +function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + + return -fwdlw + fwd - 1; +} + +// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday +function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, resDayOfYear; + + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + + return { + year: resYear, + dayOfYear: resDayOfYear + }; +} + +function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, resYear; + + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + + return { + week: resWeek, + year: resYear + }; +} + +function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; +} + +// FORMATTING + +addFormatToken('w', ['ww', 2], 'wo', 'week'); +addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + +// ALIASES + +addUnitAlias('week', 'w'); +addUnitAlias('isoWeek', 'W'); + +// PRIORITIES + +addUnitPriority('week', 5); +addUnitPriority('isoWeek', 5); + +// PARSING + +addRegexToken('w', match1to2); +addRegexToken('ww', match1to2, match2); +addRegexToken('W', match1to2); +addRegexToken('WW', match1to2, match2); + +addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); +}); + +// HELPERS + +// LOCALES + +function localeWeek (mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; +} + +var defaultLocaleWeek = { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 1st is the first week of the year. +}; + +function localeFirstDayOfWeek () { + return this._week.dow; +} + +function localeFirstDayOfYear () { + return this._week.doy; +} + +// MOMENTS + +function getSetWeek (input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); +} + +function getSetISOWeek (input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); +} + +// FORMATTING + +addFormatToken('d', 0, 'do', 'day'); + +addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); +}); + +addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); +}); + +addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); +}); + +addFormatToken('e', 0, 0, 'weekday'); +addFormatToken('E', 0, 0, 'isoWeekday'); + +// ALIASES + +addUnitAlias('day', 'd'); +addUnitAlias('weekday', 'e'); +addUnitAlias('isoWeekday', 'E'); + +// PRIORITY +addUnitPriority('day', 11); +addUnitPriority('weekday', 11); +addUnitPriority('isoWeekday', 11); + +// PARSING + +addRegexToken('d', match1to2); +addRegexToken('e', match1to2); +addRegexToken('E', match1to2); +addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); +}); +addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); +}); +addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); +}); + +addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } +}); + +addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); +}); + +// HELPERS + +function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } + + if (!isNaN(input)) { + return parseInt(input, 10); + } + + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } + + return null; +} + +function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; +} + +// LOCALES + +var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); +function localeWeekdays (m, format) { + if (!m) { + return isArray(this._weekdays) ? this._weekdays : + this._weekdays['standalone']; + } + return isArray(this._weekdays) ? this._weekdays[m.day()] : + this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; +} + +var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); +function localeWeekdaysShort (m) { + return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; +} + +var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); +function localeWeekdaysMin (m) { + return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; +} + +function handleStrictParse$1(weekdayName, format, strict) { + var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } +} + +function localeWeekdaysParse (weekdayName, format, strict) { + var i, mom, regex; + + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); + this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); + this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); + } + if (!this._weekdaysParse[i]) { + regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } +} + +// MOMENTS + +function getSetDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } +} + +function getSetLocaleDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); +} + +function getSetISODayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } +} + +var defaultWeekdaysRegex = matchWord; +function weekdaysRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict ? + this._weekdaysStrictRegex : this._weekdaysRegex; + } +} + +var defaultWeekdaysShortRegex = matchWord; +function weekdaysShortRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict ? + this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + } +} + +var defaultWeekdaysMinRegex = matchWord; +function weekdaysMinRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict ? + this._weekdaysMinStrictRegex : this._weekdaysMinRegex; + } +} + + +function computeWeekdaysParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], + i, mom, minp, shortp, longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = this.weekdaysMin(mom, ''); + shortp = this.weekdaysShort(mom, ''); + longp = this.weekdays(mom, ''); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 7; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + + this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); + this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); +} + +// FORMATTING + +function hFormat() { + return this.hours() % 12 || 12; +} + +function kFormat() { + return this.hours() || 24; +} + +addFormatToken('H', ['HH', 2], 0, 'hour'); +addFormatToken('h', ['hh', 2], 0, hFormat); +addFormatToken('k', ['kk', 2], 0, kFormat); + +addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); +}); + +addFormatToken('hmmss', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); +}); + +addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); +}); + +addFormatToken('Hmmss', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); +}); + +function meridiem (token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); + }); +} + +meridiem('a', true); +meridiem('A', false); + +// ALIASES + +addUnitAlias('hour', 'h'); + +// PRIORITY +addUnitPriority('hour', 13); + +// PARSING + +function matchMeridiem (isStrict, locale) { + return locale._meridiemParse; +} + +addRegexToken('a', matchMeridiem); +addRegexToken('A', matchMeridiem); +addRegexToken('H', match1to2); +addRegexToken('h', match1to2); +addRegexToken('k', match1to2); +addRegexToken('HH', match1to2, match2); +addRegexToken('hh', match1to2, match2); +addRegexToken('kk', match1to2, match2); + +addRegexToken('hmm', match3to4); +addRegexToken('hmmss', match5to6); +addRegexToken('Hmm', match3to4); +addRegexToken('Hmmss', match5to6); + +addParseToken(['H', 'HH'], HOUR); +addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; +}); +addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; +}); +addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; +}); +addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; +}); +addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; +}); +addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); +}); +addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); +}); + +// LOCALES + +function localeIsPM (input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return ((input + '').toLowerCase().charAt(0) === 'p'); +} + +var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; +function localeMeridiem (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } +} + + +// MOMENTS + +// Setting the hour should keep the time, because the user explicitly +// specified which hour he wants. So trying to maintain the same hour (in +// a new timezone) makes sense. Adding/subtracting hours does not follow +// this rule. +var getSetHour = makeGetSet('Hours', true); + +var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + + week: defaultLocaleWeek, + + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + + meridiemParse: defaultLocaleMeridiemParse +}; + +// internal storage for locale config files +var locales = {}; +var localeFamilies = {}; +var globalLocale; + +function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; +} + +// pick the locale from the array +// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each +// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root +function chooseLocale(names) { + var i = 0, j, next, locale, split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return globalLocale; +} + +function loadLocale(name) { + var oldLocale = null; + // TODO: Find a better way to register and load all the locales in Node + if (!locales[name] && (typeof module !== 'undefined') && + module && module.exports) { + try { + oldLocale = globalLocale._abbr; + var aliasedRequire = require; + aliasedRequire('./locale/' + name); + getSetGlobalLocale(oldLocale); + } catch (e) {} + } + return locales[name]; +} + +// This function will load locale and then set the global locale. If +// no arguments are passed in, it will simply return the current global +// locale key. +function getSetGlobalLocale (key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } + else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } + else { + if ((typeof console !== 'undefined') && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn('Locale ' + key + ' not found. Did you forget to load it?'); + } + } + } + + return globalLocale._abbr; +} + +function defineLocale (name, config) { + if (config !== null) { + var locale, parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + deprecateSimple('defineLocaleOverride', + 'use moment.updateLocale(localeName, config) to change ' + + 'an existing locale. moment.defineLocale(localeName, ' + + 'config) should only be used for creating a new locale ' + + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } +} + +function updateLocale(name, config) { + if (config != null) { + var locale, tmpLocale, parentConfig = baseConfig; + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; +} + +// returns locale data +function getLocale (key) { + var locale; + + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + + return chooseLocale(key); +} + +function listLocales() { + return keys(locales); +} + +function checkOverflow (m) { + var overflow; + var a = m._a; + + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : + a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : + a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : + a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : + a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : + a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : + -1; + + if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + + getParsingFlags(m).overflow = overflow; + } + + return m; +} + +// Pick the first defined of two or three arguments. +function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; +} + +function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; +} + +// convert an array to a date. +// the array should mirror the parameters below +// note: all values past the year are optional and will default to the lowest possible value. +// [year, month, day , hour, minute, second, millisecond] +function configFromArray (config) { + var i, date, input = [], currentDate, expectedWeekday, yearToUse; + + if (config._d) { + return; + } + + currentDate = currentDateArray(config); + + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + + if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { + getParsingFlags(config)._overflowDayOfYear = true; + } + + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } + + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; + } + + // Check for 24:00:00.000 + if (config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); + expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); + + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } + + // check for mismatching day of week + if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { + getParsingFlags(config).weekdayMismatch = true; + } +} + +function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; + + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; + + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + var curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from begining of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to begining of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } +} + +// iso 8601 regex +// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) +var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; +var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + +var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; + +var isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], + ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], + ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], + ['GGGG-[W]WW', /\d{4}-W\d\d/, false], + ['YYYY-DDD', /\d{4}-\d{3}/], + ['YYYY-MM', /\d{4}-\d\d/, false], + ['YYYYYYMMDD', /[+-]\d{10}/], + ['YYYYMMDD', /\d{8}/], + // YYYYMM is NOT allowed by the standard + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/] +]; + +// iso time formats and regexes +var isoTimes = [ + ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], + ['HH:mm:ss', /\d\d:\d\d:\d\d/], + ['HH:mm', /\d\d:\d\d/], + ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], + ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], + ['HHmmss', /\d\d\d\d\d\d/], + ['HHmm', /\d\d\d\d/], + ['HH', /\d\d/] +]; + +var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + +// date from iso format +function configFromISO(config) { + var i, l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, dateFormat, timeFormat, tzFormat; + + if (match) { + getParsingFlags(config).iso = true; + + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } +} + +// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 +var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; + +function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10) + ]; + + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + + return result; +} + +function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; +} + +function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim(); +} + +function checkWeekday(weekdayStr, parsedInput, config) { + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; + } + } + return true; +} + +var obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 +}; + +function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10); + var m = hm % 100, h = (hm - m) / 100; + return h * 60 + m; + } +} + +// date and time from ref 2822 format +function configFromRFC2822(config) { + var match = rfc2822.exec(preprocessRFC2822(config._i)); + if (match) { + var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); + if (!checkWeekday(match[1], parsedArray, config)) { + return; + } + + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); + + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } +} + +// date from iso format or fallback +function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); + + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } + + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); +} + +hooks.createFromInputFallback = deprecate( + 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + + 'discouraged and will be removed in an upcoming major release. Please refer to ' + + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } +); + +// constant that refers to the ISO standard +hooks.ISO_8601 = function () {}; + +// constant that refers to the RFC 2822 form +hooks.RFC_2822 = function () {}; + +// date from string and format string +function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, parsedInput, tokens, token, skipped, + stringLength = string.length, + totalParsedInputLength = 0; + + tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; + + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; + // console.log('token', token, 'parsedInput', parsedInput, + // 'regex', getParseRegexForToken(token, config)); + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } + else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } + else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } + + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } + + // clear _12h flag if hour is <= 12 + if (config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0) { + getParsingFlags(config).bigHour = undefined; + } + + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + + configFromArray(config); + checkOverflow(config); +} + + +function meridiemFixWrap (locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } +} + +// date from string and array of format strings +function configFromStringAndArray(config) { + var tempConfig, + bestMoment, + + scoreToBeat, + i, + currentScore; + + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (!isValid(tempConfig)) { + continue; + } + + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; + + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (scoreToBeat == null || currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + + extend(config, bestMoment || tempConfig); +} + +function configFromObject(config) { + if (config._d) { + return; + } + + var i = normalizeObjectUnits(config._i); + config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { + return obj && parseInt(obj, 10); + }); + + configFromArray(config); +} + +function createFromConfig (config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } + + return res; +} + +function prepareConfig (config) { + var input = config._i, + format = config._f; + + config._locale = config._locale || getLocale(config._l); + + if (input === null || (format === undefined && input === '')) { + return createInvalid({nullInput: true}); + } + + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } + + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } + + if (!isValid(config)) { + config._d = null; + } + + return config; +} + +function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } +} + +function createLocalOrUTC (input, format, locale, strict, isUTC) { + var c = {}; + + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } + + if ((isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0)) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; + + return createFromConfig(c); +} + +function createLocal (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); +} + +var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } +); + +var prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } +); + +// Pick a moment m from moments so that m[fn](other) is true for all +// other. This relies on the function fn to be transitive. +// +// moments should either be an array of moment objects or an array, whose +// first element is an array of moment objects. +function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; +} + +// TODO: Use [].sort instead? +function min () { + var args = [].slice.call(arguments, 0); + + return pickBy('isBefore', args); +} + +function max () { + var args = [].slice.call(arguments, 0); + + return pickBy('isAfter', args); +} + +var now = function () { + return Date.now ? Date.now() : +(new Date()); +}; + +var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; + +function isDurationValid(m) { + for (var key in m) { + if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { + return false; + } + } + + var unitHasDecimal = false; + for (var i = 0; i < ordering.length; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } + + return true; +} + +function isValid$1() { + return this._isValid; +} + +function createInvalid$1() { + return createDuration(NaN); +} + +function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + this._isValid = isDurationValid(normalizedInput); + + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); +} + +function isDuration (obj) { + return obj instanceof Duration; +} + +function absRound (number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } +} + +// FORMATTING + +function offset (token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(); + var sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); + }); +} + +offset('Z', ':'); +offset('ZZ', ''); + +// PARSING + +addRegexToken('Z', matchShortOffset); +addRegexToken('ZZ', matchShortOffset); +addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); +}); + +// HELPERS + +// timezone chunker +// '+10:00' > ['10', '00'] +// '-1530' > ['-15', '30'] +var chunkOffset = /([\+\-]|\d\d)/gi; + +function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher); + + if (matches === null) { + return null; + } + + var chunk = matches[matches.length - 1] || []; + var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + var minutes = +(parts[1] * 60) + toInt(parts[2]); + + return minutes === 0 ? + 0 : + parts[0] === '+' ? minutes : -minutes; +} + +// Return a moment from input, that is local/utc/zone equivalent to model. +function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } +} + +function getDateOffset (m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset() / 15) * 15; +} + +// HOOKS + +// This function will be called whenever a moment is mutated. +// It is intended to keep the offset in sync with the timezone. +hooks.updateOffset = function () {}; + +// MOMENTS + +// keepLocalTime = true means only change the timezone, without +// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> +// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset +// +0200, so we adjust the time as needed, to be valid. +// +// Keeping the time actually adds/subtracts (one hour) +// from the actual represented time. That is why we call updateOffset +// a second time. In case it wants us to change the offset again +// _changeInProgress == true case, then we have to adjust, because +// there is no such time in the given timezone. +function getSetOffset (input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract(this, createDuration(input - offset, 'm'), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } +} + +function getSetZone (input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } +} + +function setOffsetToUTC (keepLocalTime) { + return this.utcOffset(0, keepLocalTime); +} + +function setOffsetToLocal (keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; +} + +function setOffsetToParsedOffset () { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } + else { + this.utcOffset(0, true); + } + } + return this; +} + +function hasAlignedHourOffset (input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + + return (this.utcOffset() - input) % 60 === 0; +} + +function isDaylightSavingTime () { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); +} + +function isDaylightSavingTimeShifted () { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = this.isValid() && + compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; +} + +function isLocal () { + return this.isValid() ? !this._isUTC : false; +} + +function isUtcOffset () { + return this.isValid() ? this._isUTC : false; +} + +function isUtc () { + return this.isValid() ? this._isUTC && this._offset === 0 : false; +} + +// ASP.NET json date format regex +var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; + +// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html +// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere +// and further modified to allow for strings containing both week and day +var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + +function createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (isNumber(input)) { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match + }; + } else if (!!(match = isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + w : parseIso(match[4], sign), + d : parseIso(match[5], sign), + h : parseIso(match[6], sign), + m : parseIso(match[7], sign), + s : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + return ret; +} + +createDuration.fn = Duration.prototype; +createDuration.invalid = createInvalid$1; + +function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; +} + +function positiveMomentsDifference(base, other) { + var res = {milliseconds: 0, months: 0}; + + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + + return res; +} + +function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return {milliseconds: 0, months: 0}; + } + + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; +} + +// TODO: remove 'name' arg after deprecation is removed +function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); + tmp = val; val = period; period = tmp; + } + + val = typeof val === 'string' ? +val : val; + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; +} + +function addSubtract (mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); + + if (!mom.isValid()) { + // No op + return; + } + + updateOffset = updateOffset == null ? true : updateOffset; + + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } +} + +var add = createAdder(1, 'add'); +var subtract = createAdder(-1, 'subtract'); + +function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 ? 'sameElse' : + diff < -1 ? 'lastWeek' : + diff < 0 ? 'lastDay' : + diff < 1 ? 'sameDay' : + diff < 2 ? 'nextDay' : + diff < 7 ? 'nextWeek' : 'sameElse'; +} + +function calendar$1 (time, formats) { + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse'; + + var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); + + return this.format(output || this.localeData().calendar(format, this, createLocal(now))); +} + +function clone () { + return new Moment(this); +} + +function isAfter (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } +} + +function isBefore (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } +} + +function isBetween (from, to, units, inclusivity) { + inclusivity = inclusivity || '()'; + return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && + (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units)); +} + +function isSame (input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units || 'millisecond'); + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + } +} + +function isSameOrAfter (input, units) { + return this.isSame(input, units) || this.isAfter(input,units); +} + +function isSameOrBefore (input, units) { + return this.isSame(input, units) || this.isBefore(input,units); +} + +function diff (input, units, asFloat) { + var that, + zoneDelta, + output; + + if (!this.isValid()) { + return NaN; + } + + that = cloneWithOffset(input, this); + + if (!that.isValid()) { + return NaN; + } + + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + + units = normalizeUnits(units); + + switch (units) { + case 'year': output = monthDiff(this, that) / 12; break; + case 'month': output = monthDiff(this, that); break; + case 'quarter': output = monthDiff(this, that) / 3; break; + case 'second': output = (this - that) / 1e3; break; // 1000 + case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 + case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 + case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst + case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: output = this - that; + } + + return asFloat ? output : absFloor(output); +} + +function monthDiff (a, b) { + // difference in months + var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } + + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; +} + +hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; +hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + +function toString () { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); +} + +function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true; + var m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { + return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); + } + } + return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); +} + +/** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ +function inspect () { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment'; + var zone = ''; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + var prefix = '[' + func + '("]'; + var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; + var datetime = '-MM-DD[T]HH:mm:ss.SSS'; + var suffix = zone + '[")]'; + + return this.format(prefix + year + datetime + suffix); +} + +function format (inputString) { + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); +} + +function from (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } +} + +function fromNow (withoutSuffix) { + return this.from(createLocal(), withoutSuffix); +} + +function to (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } +} + +function toNow (withoutSuffix) { + return this.to(createLocal(), withoutSuffix); +} + +// If passed a locale key, it will set the locale for this +// instance. Otherwise, it will return the locale configuration +// variables for this instance. +function locale (key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } +} + +var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } +); + +function localeData () { + return this._locale; +} + +function startOf (units) { + units = normalizeUnits(units); + // the following switch intentionally omits break keywords + // to utilize falling through the cases. + switch (units) { + case 'year': + this.month(0); + /* falls through */ + case 'quarter': + case 'month': + this.date(1); + /* falls through */ + case 'week': + case 'isoWeek': + case 'day': + case 'date': + this.hours(0); + /* falls through */ + case 'hour': + this.minutes(0); + /* falls through */ + case 'minute': + this.seconds(0); + /* falls through */ + case 'second': + this.milliseconds(0); + } + + // weeks are a special case + if (units === 'week') { + this.weekday(0); + } + if (units === 'isoWeek') { + this.isoWeekday(1); + } + + // quarters are also special + if (units === 'quarter') { + this.month(Math.floor(this.month() / 3) * 3); + } + + return this; +} + +function endOf (units) { + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond') { + return this; + } + + // 'date' is an alias for 'day', so it should be considered as such. + if (units === 'date') { + units = 'day'; + } + + return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); +} + +function valueOf () { + return this._d.valueOf() - ((this._offset || 0) * 60000); +} + +function unix () { + return Math.floor(this.valueOf() / 1000); +} + +function toDate () { + return new Date(this.valueOf()); +} + +function toArray () { + var m = this; + return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; +} + +function toObject () { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds() + }; +} + +function toJSON () { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; +} + +function isValid$2 () { + return isValid(this); +} + +function parsingFlags () { + return extend({}, getParsingFlags(this)); +} + +function invalidAt () { + return getParsingFlags(this).overflow; +} + +function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict + }; +} + +// FORMATTING + +addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; +}); + +addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; +}); + +function addWeekYearFormatToken (token, getter) { + addFormatToken(0, [token, token.length], 0, getter); +} + +addWeekYearFormatToken('gggg', 'weekYear'); +addWeekYearFormatToken('ggggg', 'weekYear'); +addWeekYearFormatToken('GGGG', 'isoWeekYear'); +addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + +// ALIASES + +addUnitAlias('weekYear', 'gg'); +addUnitAlias('isoWeekYear', 'GG'); + +// PRIORITY + +addUnitPriority('weekYear', 1); +addUnitPriority('isoWeekYear', 1); + + +// PARSING + +addRegexToken('G', matchSigned); +addRegexToken('g', matchSigned); +addRegexToken('GG', match1to2, match2); +addRegexToken('gg', match1to2, match2); +addRegexToken('GGGG', match1to4, match4); +addRegexToken('gggg', match1to4, match4); +addRegexToken('GGGGG', match1to6, match6); +addRegexToken('ggggg', match1to6, match6); + +addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); +}); + +addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); +}); + +// MOMENTS + +function getSetWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy); +} + +function getSetISOWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, this.isoWeek(), this.isoWeekday(), 1, 4); +} + +function getISOWeeksInYear () { + return weeksInYear(this.year(), 1, 4); +} + +function getWeeksInYear () { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); +} + +function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } +} + +function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; +} + +// FORMATTING + +addFormatToken('Q', 0, 'Qo', 'quarter'); + +// ALIASES + +addUnitAlias('quarter', 'Q'); + +// PRIORITY + +addUnitPriority('quarter', 7); + +// PARSING + +addRegexToken('Q', match1); +addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; +}); + +// MOMENTS + +function getSetQuarter (input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); +} + +// FORMATTING + +addFormatToken('D', ['DD', 2], 'Do', 'date'); + +// ALIASES + +addUnitAlias('date', 'D'); + +// PRIOROITY +addUnitPriority('date', 9); + +// PARSING + +addRegexToken('D', match1to2); +addRegexToken('DD', match1to2, match2); +addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict ? + (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : + locale._dayOfMonthOrdinalParseLenient; +}); + +addParseToken(['D', 'DD'], DATE); +addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); +}); + +// MOMENTS + +var getSetDayOfMonth = makeGetSet('Date', true); + +// FORMATTING + +addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + +// ALIASES + +addUnitAlias('dayOfYear', 'DDD'); + +// PRIORITY +addUnitPriority('dayOfYear', 4); + +// PARSING + +addRegexToken('DDD', match1to3); +addRegexToken('DDDD', match3); +addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); +}); + +// HELPERS + +// MOMENTS + +function getSetDayOfYear (input) { + var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; + return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); +} + +// FORMATTING + +addFormatToken('m', ['mm', 2], 0, 'minute'); + +// ALIASES + +addUnitAlias('minute', 'm'); + +// PRIORITY + +addUnitPriority('minute', 14); + +// PARSING + +addRegexToken('m', match1to2); +addRegexToken('mm', match1to2, match2); +addParseToken(['m', 'mm'], MINUTE); + +// MOMENTS + +var getSetMinute = makeGetSet('Minutes', false); + +// FORMATTING + +addFormatToken('s', ['ss', 2], 0, 'second'); + +// ALIASES + +addUnitAlias('second', 's'); + +// PRIORITY + +addUnitPriority('second', 15); + +// PARSING + +addRegexToken('s', match1to2); +addRegexToken('ss', match1to2, match2); +addParseToken(['s', 'ss'], SECOND); + +// MOMENTS + +var getSetSecond = makeGetSet('Seconds', false); + +// FORMATTING + +addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); +}); + +addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); +}); + +addFormatToken(0, ['SSS', 3], 0, 'millisecond'); +addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; +}); +addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; +}); +addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; +}); +addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; +}); +addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; +}); +addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; +}); + + +// ALIASES + +addUnitAlias('millisecond', 'ms'); + +// PRIORITY + +addUnitPriority('millisecond', 16); + +// PARSING + +addRegexToken('S', match1to3, match1); +addRegexToken('SS', match1to3, match2); +addRegexToken('SSS', match1to3, match3); + +var token; +for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); +} + +function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); +} + +for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); +} +// MOMENTS + +var getSetMillisecond = makeGetSet('Milliseconds', false); + +// FORMATTING + +addFormatToken('z', 0, 0, 'zoneAbbr'); +addFormatToken('zz', 0, 0, 'zoneName'); + +// MOMENTS + +function getZoneAbbr () { + return this._isUTC ? 'UTC' : ''; +} + +function getZoneName () { + return this._isUTC ? 'Coordinated Universal Time' : ''; +} + +var proto = Moment.prototype; + +proto.add = add; +proto.calendar = calendar$1; +proto.clone = clone; +proto.diff = diff; +proto.endOf = endOf; +proto.format = format; +proto.from = from; +proto.fromNow = fromNow; +proto.to = to; +proto.toNow = toNow; +proto.get = stringGet; +proto.invalidAt = invalidAt; +proto.isAfter = isAfter; +proto.isBefore = isBefore; +proto.isBetween = isBetween; +proto.isSame = isSame; +proto.isSameOrAfter = isSameOrAfter; +proto.isSameOrBefore = isSameOrBefore; +proto.isValid = isValid$2; +proto.lang = lang; +proto.locale = locale; +proto.localeData = localeData; +proto.max = prototypeMax; +proto.min = prototypeMin; +proto.parsingFlags = parsingFlags; +proto.set = stringSet; +proto.startOf = startOf; +proto.subtract = subtract; +proto.toArray = toArray; +proto.toObject = toObject; +proto.toDate = toDate; +proto.toISOString = toISOString; +proto.inspect = inspect; +proto.toJSON = toJSON; +proto.toString = toString; +proto.unix = unix; +proto.valueOf = valueOf; +proto.creationData = creationData; +proto.year = getSetYear; +proto.isLeapYear = getIsLeapYear; +proto.weekYear = getSetWeekYear; +proto.isoWeekYear = getSetISOWeekYear; +proto.quarter = proto.quarters = getSetQuarter; +proto.month = getSetMonth; +proto.daysInMonth = getDaysInMonth; +proto.week = proto.weeks = getSetWeek; +proto.isoWeek = proto.isoWeeks = getSetISOWeek; +proto.weeksInYear = getWeeksInYear; +proto.isoWeeksInYear = getISOWeeksInYear; +proto.date = getSetDayOfMonth; +proto.day = proto.days = getSetDayOfWeek; +proto.weekday = getSetLocaleDayOfWeek; +proto.isoWeekday = getSetISODayOfWeek; +proto.dayOfYear = getSetDayOfYear; +proto.hour = proto.hours = getSetHour; +proto.minute = proto.minutes = getSetMinute; +proto.second = proto.seconds = getSetSecond; +proto.millisecond = proto.milliseconds = getSetMillisecond; +proto.utcOffset = getSetOffset; +proto.utc = setOffsetToUTC; +proto.local = setOffsetToLocal; +proto.parseZone = setOffsetToParsedOffset; +proto.hasAlignedHourOffset = hasAlignedHourOffset; +proto.isDST = isDaylightSavingTime; +proto.isLocal = isLocal; +proto.isUtcOffset = isUtcOffset; +proto.isUtc = isUtc; +proto.isUTC = isUtc; +proto.zoneAbbr = getZoneAbbr; +proto.zoneName = getZoneName; +proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); +proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); +proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); +proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); +proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); + +function createUnix (input) { + return createLocal(input * 1000); +} + +function createInZone () { + return createLocal.apply(null, arguments).parseZone(); +} + +function preParsePostFormat (string) { + return string; +} + +var proto$1 = Locale.prototype; + +proto$1.calendar = calendar; +proto$1.longDateFormat = longDateFormat; +proto$1.invalidDate = invalidDate; +proto$1.ordinal = ordinal; +proto$1.preparse = preParsePostFormat; +proto$1.postformat = preParsePostFormat; +proto$1.relativeTime = relativeTime; +proto$1.pastFuture = pastFuture; +proto$1.set = set; + +proto$1.months = localeMonths; +proto$1.monthsShort = localeMonthsShort; +proto$1.monthsParse = localeMonthsParse; +proto$1.monthsRegex = monthsRegex; +proto$1.monthsShortRegex = monthsShortRegex; +proto$1.week = localeWeek; +proto$1.firstDayOfYear = localeFirstDayOfYear; +proto$1.firstDayOfWeek = localeFirstDayOfWeek; + +proto$1.weekdays = localeWeekdays; +proto$1.weekdaysMin = localeWeekdaysMin; +proto$1.weekdaysShort = localeWeekdaysShort; +proto$1.weekdaysParse = localeWeekdaysParse; + +proto$1.weekdaysRegex = weekdaysRegex; +proto$1.weekdaysShortRegex = weekdaysShortRegex; +proto$1.weekdaysMinRegex = weekdaysMinRegex; + +proto$1.isPM = localeIsPM; +proto$1.meridiem = localeMeridiem; + +function get$1 (format, index, field, setter) { + var locale = getLocale(); + var utc = createUTC().set(setter, index); + return locale[field](utc, format); +} + +function listMonthsImpl (format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); + } + + var i; + var out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); + } + return out; +} + +// () +// (5) +// (fmt, 5) +// (fmt) +// (true) +// (true, 5) +// (true, fmt, 5) +// (true, fmt) +function listWeekdaysImpl (localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; + + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); + } + + var i; + var out = []; + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; +} + +function listMonths (format, index) { + return listMonthsImpl(format, index, 'months'); +} + +function listMonthsShort (format, index) { + return listMonthsImpl(format, index, 'monthsShort'); +} + +function listWeekdays (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); +} + +function listWeekdaysShort (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); +} + +function listWeekdaysMin (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); +} + +getSetGlobalLocale('en', { + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (toInt(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + } +}); + +// Side effect imports + +hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); +hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); + +var mathAbs = Math.abs; + +function abs () { + var data = this._data; + + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + + return this; +} + +function addSubtract$1 (duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); +} + +// supports only 2.0-style add(1, 's') or add(duration) +function add$1 (input, value) { + return addSubtract$1(this, input, value, 1); +} + +// supports only 2.0-style subtract(1, 's') or subtract(duration) +function subtract$1 (input, value) { + return addSubtract$1(this, input, value, -1); +} + +function absCeil (number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } +} + +function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years, monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if (!((milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0))) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; +} + +function daysToMonths (days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return days * 4800 / 146097; +} + +function monthsToDays (months) { + // the reverse of daysToMonths + return months * 146097 / 4800; +} + +function as (units) { + if (!this.isValid()) { + return NaN; + } + var days; + var months; + var milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + return units === 'month' ? months : months / 12; + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } + } +} + +// TODO: Use this.as('ms')? +function valueOf$1 () { + if (!this.isValid()) { + return NaN; + } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); +} + +function makeAs (alias) { + return function () { + return this.as(alias); + }; +} + +var asMilliseconds = makeAs('ms'); +var asSeconds = makeAs('s'); +var asMinutes = makeAs('m'); +var asHours = makeAs('h'); +var asDays = makeAs('d'); +var asWeeks = makeAs('w'); +var asMonths = makeAs('M'); +var asYears = makeAs('y'); + +function clone$1 () { + return createDuration(this); +} + +function get$2 (units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; +} + +function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; +} + +var milliseconds = makeGetter('milliseconds'); +var seconds = makeGetter('seconds'); +var minutes = makeGetter('minutes'); +var hours = makeGetter('hours'); +var days = makeGetter('days'); +var months = makeGetter('months'); +var years = makeGetter('years'); + +function weeks () { + return absFloor(this.days() / 7); +} + +var round = Math.round; +var thresholds = { + ss: 44, // a few seconds to seconds + s : 45, // seconds to minute + m : 45, // minutes to hour + h : 22, // hours to day + d : 26, // days to month + M : 11 // months to year +}; + +// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize +function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); +} + +function relativeTime$1 (posNegDuration, withoutSuffix, locale) { + var duration = createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); + + var a = seconds <= thresholds.ss && ['s', seconds] || + seconds < thresholds.s && ['ss', seconds] || + minutes <= 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours <= 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days <= 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months <= 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years <= 1 && ['y'] || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); +} + +// This function allows you to set the rounding function for relative time strings +function getSetRelativeTimeRounding (roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof(roundingFunction) === 'function') { + round = roundingFunction; + return true; + } + return false; +} + +// This function allows you to set a threshold for relative time strings +function getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; +} + +function humanize (withSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var locale = this.localeData(); + var output = relativeTime$1(this, !withSuffix, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); +} + +var abs$1 = Math.abs; + +function sign(x) { + return ((x > 0) - (x < 0)) || +x; +} + +function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var seconds = abs$1(this._milliseconds) / 1000; + var days = abs$1(this._days); + var months = abs$1(this._months); + var minutes, hours, years; + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = years; + var M = months; + var D = days; + var h = hours; + var m = minutes; + var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + var total = this.asSeconds(); + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + var totalSign = total < 0 ? '-' : ''; + var ymSign = sign(this._months) !== sign(total) ? '-' : ''; + var daysSign = sign(this._days) !== sign(total) ? '-' : ''; + var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; + + return totalSign + 'P' + + (Y ? ymSign + Y + 'Y' : '') + + (M ? ymSign + M + 'M' : '') + + (D ? daysSign + D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? hmsSign + h + 'H' : '') + + (m ? hmsSign + m + 'M' : '') + + (s ? hmsSign + s + 'S' : ''); +} + +var proto$2 = Duration.prototype; + +proto$2.isValid = isValid$1; +proto$2.abs = abs; +proto$2.add = add$1; +proto$2.subtract = subtract$1; +proto$2.as = as; +proto$2.asMilliseconds = asMilliseconds; +proto$2.asSeconds = asSeconds; +proto$2.asMinutes = asMinutes; +proto$2.asHours = asHours; +proto$2.asDays = asDays; +proto$2.asWeeks = asWeeks; +proto$2.asMonths = asMonths; +proto$2.asYears = asYears; +proto$2.valueOf = valueOf$1; +proto$2._bubble = bubble; +proto$2.clone = clone$1; +proto$2.get = get$2; +proto$2.milliseconds = milliseconds; +proto$2.seconds = seconds; +proto$2.minutes = minutes; +proto$2.hours = hours; +proto$2.days = days; +proto$2.weeks = weeks; +proto$2.months = months; +proto$2.years = years; +proto$2.humanize = humanize; +proto$2.toISOString = toISOString$1; +proto$2.toString = toISOString$1; +proto$2.toJSON = toISOString$1; +proto$2.locale = locale; +proto$2.localeData = localeData; + +proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); +proto$2.lang = lang; + +// Side effect imports + +// FORMATTING + +addFormatToken('X', 0, 0, 'unix'); +addFormatToken('x', 0, 0, 'valueOf'); + +// PARSING + +addRegexToken('x', matchSigned); +addRegexToken('X', matchTimestamp); +addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input, 10) * 1000); +}); +addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); +}); + +// Side effect imports + + +hooks.version = '2.21.0'; + +setHookCallback(createLocal); + +hooks.fn = proto; +hooks.min = min; +hooks.max = max; +hooks.now = now; +hooks.utc = createUTC; +hooks.unix = createUnix; +hooks.months = listMonths; +hooks.isDate = isDate; +hooks.locale = getSetGlobalLocale; +hooks.invalid = createInvalid; +hooks.duration = createDuration; +hooks.isMoment = isMoment; +hooks.weekdays = listWeekdays; +hooks.parseZone = createInZone; +hooks.localeData = getLocale; +hooks.isDuration = isDuration; +hooks.monthsShort = listMonthsShort; +hooks.weekdaysMin = listWeekdaysMin; +hooks.defineLocale = defineLocale; +hooks.updateLocale = updateLocale; +hooks.locales = listLocales; +hooks.weekdaysShort = listWeekdaysShort; +hooks.normalizeUnits = normalizeUnits; +hooks.relativeTimeRounding = getSetRelativeTimeRounding; +hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; +hooks.calendarFormat = getCalendarFormat; +hooks.prototype = proto; + +// currently HTML5 input type only supports 24-hour formats +hooks.HTML5_FMT = { + DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // + DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // + DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // + DATE: 'YYYY-MM-DD', // + TIME: 'HH:mm', // + TIME_SECONDS: 'HH:mm:ss', // + TIME_MS: 'HH:mm:ss.SSS', // + WEEK: 'YYYY-[W]WW', // + MONTH: 'YYYY-MM' // +}; + +return hooks; + +}))); + +},{}],42:[function(require,module,exports){ +module.exports = require('./polygon-features.json') + +},{"./polygon-features.json":43}],43:[function(require,module,exports){ +module.exports=[ + { + "key": "building", + "polygon": "all" + }, + { + "key": "highway", + "polygon": "whitelist", + "values": [ + "services", + "rest_area", + "escape", + "elevator" + ] + }, + { + "key": "natural", + "polygon": "blacklist", + "values": [ + "coastline", + "cliff", + "ridge", + "arete", + "tree_row" + ] + }, + { + "key": "landuse", + "polygon": "all" + }, + { + "key": "waterway", + "polygon": "whitelist", + "values": [ + "riverbank", + "dock", + "boatyard", + "dam" + ] + }, + { + "key": "amenity", + "polygon": "all" + }, + { + "key": "leisure", + "polygon": "all" + }, + { + "key": "barrier", + "polygon": "whitelist", + "values": [ + "city_wall", + "ditch", + "hedge", + "retaining_wall", + "wall", + "spikes" + ] + }, + { + "key": "railway", + "polygon": "whitelist", + "values": [ + "station", + "turntable", + "roundhouse", + "platform" + ] + }, + { + "key": "area", + "polygon": "all" + }, + { + "key": "boundary", + "polygon": "all" + }, + { + "key": "man_made", + "polygon": "blacklist", + "values": [ + "cutline", + "embankment", + "pipeline" + ] + }, + { + "key": "power", + "polygon": "whitelist", + "values": [ + "plant", + "substation", + "generator", + "transformer" + ] + }, + { + "key": "place", + "polygon": "all" + }, + { + "key": "shop", + "polygon": "all" + }, + { + "key": "aeroway", + "polygon": "blacklist", + "values": [ + "taxiway" + ] + }, + { + "key": "tourism", + "polygon": "all" + }, + { + "key": "historic", + "polygon": "all" + }, + { + "key": "public_transport", + "polygon": "all" + }, + { + "key": "office", + "polygon": "all" + }, + { + "key": "building:part", + "polygon": "all" + }, + { + "key": "military", + "polygon": "all" + }, + { + "key": "ruins", + "polygon": "all" + }, + { + "key": "area:highway", + "polygon": "all" + }, + { + "key": "craft", + "polygon": "all" + }, + { + "key": "golf", + "polygon": "all" + }, + { + "key": "indoor", + "polygon": "all" + } +] + +},{}],44:[function(require,module,exports){ +var _ = require("./lodash.custom.js"); +var rewind = require("geojson-rewind"); + +// see https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features +var polygonFeatures = {}; +require("osm-polygon-features").forEach(function(tags) { + if (tags.polygon === "all") + polygonFeatures[tags.key] = true; + else { + var list = (tags.polygon === "whitelist") ? "included_values" : "excluded_values", + tagValuesObj = {}; + tags.values.forEach(function(value) { tagValuesObj[value] = true; }); + polygonFeatures[tags.key] = {}; + polygonFeatures[tags.key][list] = tagValuesObj; + } +}); + +var osmtogeojson = {}; + +osmtogeojson = function( data, options ) { + + options = _.merge( + { + verbose: false, + flatProperties: false, + uninterestingTags: { + "source": true, + "source_ref": true, + "source:ref": true, + "history": true, + "attribution": true, + "created_by": true, + "tiger:county": true, + "tiger:tlid": true, + "tiger:upload_uuid": true + }, + polygonFeatures: polygonFeatures, + }, + options + ); + + var result; + if ( ((typeof XMLDocument !== "undefined") && data instanceof XMLDocument || + (typeof XMLDocument === "undefined") && data.childNodes) ) + result = _osmXML2geoJSON(data); + else + result = _overpassJSON2geoJSON(data); + return result; + + function _overpassJSON2geoJSON(json) { + // sort elements + var nodes = new Array(); + var ways = new Array(); + var rels = new Array(); + // helper functions + function centerGeometry(object) { + var pseudoNode = _.clone(object); + pseudoNode.lat = object.center.lat; + pseudoNode.lon = object.center.lon; + pseudoNode.__is_center_placeholder = true; + nodes.push(pseudoNode); + } + function boundsGeometry(object) { + var pseudoWay = _.clone(object); + pseudoWay.nodes = []; + function addPseudoNode(lat,lon,i) { + var pseudoNode = { + type:"node", + id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i, + lat: lat, + lon: lon + } + pseudoWay.nodes.push(pseudoNode.id); + nodes.push(pseudoNode); + } + addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.minlon,1); + addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.minlon,2); + addPseudoNode(pseudoWay.bounds.maxlat,pseudoWay.bounds.maxlon,3); + addPseudoNode(pseudoWay.bounds.minlat,pseudoWay.bounds.maxlon,4); + pseudoWay.nodes.push(pseudoWay.nodes[0]); + pseudoWay.__is_bounds_placeholder = true; + ways.push(pseudoWay); + } + function fullGeometryWay(way) { + function addFullGeometryNode(lat,lon,id) { + var geometryNode = { + type:"node", + id: id, + lat: lat, + lon: lon, + __is_uninteresting: true + } + nodes.push(geometryNode); + } + if (!_.isArray(way.nodes)) { + way.nodes = way.geometry.map(function(nd) { + if (nd !== null) // have to skip ref-less nodes + return "_anonymous@"+nd.lat+"/"+nd.lon; + else + return "_anonymous@unknown_location"; + }); + } + way.geometry.forEach(function(nd, i) { + if (nd) { + addFullGeometryNode( + nd.lat, + nd.lon, + way.nodes[i] + ); + } + }); + } + function fullGeometryRelation(rel) { + function addFullGeometryNode(lat,lon,id) { + var geometryNode = { + type:"node", + id: id, + lat: lat, + lon: lon + } + nodes.push(geometryNode); + } + function addFullGeometryWay(geometry,id) { + // shared multipolygon ways cannot be defined multiple times with the same id. + if (ways.some(function (way) { // todo: this is slow :( + return way.type == "way" && way.id == id; + })) return; + var geometryWay = { + type: "way", + id: id, + nodes:[] + } + function addFullGeometryWayPseudoNode(lat,lon) { + // todo? do not save the same pseudo node multiple times + var geometryPseudoNode = { + type:"node", + id: "_anonymous@"+lat+"/"+lon, + lat: lat, + lon: lon, + __is_uninteresting: true + } + geometryWay.nodes.push(geometryPseudoNode.id); + nodes.push(geometryPseudoNode); + } + geometry.forEach(function(nd) { + if (nd) { + addFullGeometryWayPseudoNode( + nd.lat, + nd.lon + ); + } else { + geometryWay.nodes.push(undefined); + } + }); + ways.push(geometryWay); + } + rel.members.forEach(function(member, i) { + if (member.type == "node") { + if (member.lat) { + addFullGeometryNode( + member.lat, + member.lon, + member.ref + ); + } + } else if (member.type == "way") { + if (member.geometry) { + member.ref = "_fullGeom"+member.ref; + addFullGeometryWay( + member.geometry, + member.ref + ); + } + } + }); + } + // create copies of individual json objects to make sure the original data doesn't get altered + // todo: cloning is slow: see if this can be done differently! + for (var i=0;i 0 + }); + if (rel.center) + centerGeometry(rel); + if (has_full_geometry) + fullGeometryRelation(rel); + else if (rel.bounds) + boundsGeometry(rel); + break; + default: + // type=area (from coord-query) is an example for this case. + } + } + return _convert2geoJSON(nodes,ways,rels); + } + function _osmXML2geoJSON(xml) { + // sort elements + var nodes = new Array(); + var ways = new Array(); + var rels = new Array(); + // helper function + function copy_attribute( x, o, attr ) { + if (x.hasAttribute(attr)) + o[attr] = x.getAttribute(attr); + } + function centerGeometry(object, centroid) { + var pseudoNode = _.clone(object); + copy_attribute(centroid, pseudoNode, 'lat'); + copy_attribute(centroid, pseudoNode, 'lon'); + pseudoNode.__is_center_placeholder = true; + nodes.push(pseudoNode); + } + function boundsGeometry(object, bounds) { + var pseudoWay = _.clone(object); + pseudoWay.nodes = []; + function addPseudoNode(lat,lon,i) { + var pseudoNode = { + type:"node", + id: "_"+pseudoWay.type+"/"+pseudoWay.id+"bounds"+i, + lat: lat, + lon: lon + } + pseudoWay.nodes.push(pseudoNode.id); + nodes.push(pseudoNode); + } + addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('minlon'),1); + addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('minlon'),2); + addPseudoNode(bounds.getAttribute('maxlat'),bounds.getAttribute('maxlon'),3); + addPseudoNode(bounds.getAttribute('minlat'),bounds.getAttribute('maxlon'),4); + pseudoWay.nodes.push(pseudoWay.nodes[0]); + pseudoWay.__is_bounds_placeholder = true; + ways.push(pseudoWay); + } + function fullGeometryWay(way, nds) { + function addFullGeometryNode(lat,lon,id) { + var geometryNode = { + type:"node", + id: id, + lat: lat, + lon: lon, + __is_uninteresting: true + } + nodes.push(geometryNode); + return geometryNode.id; + } + if (!_.isArray(way.nodes)) { + way.nodes = []; + _.each( nds, function( nd, i ) { + way.nodes.push("_anonymous@"+nd.getAttribute('lat')+"/"+nd.getAttribute('lon')); + }); + } + _.each( nds, function( nd, i ) { + if (nd.getAttribute('lat')) { + addFullGeometryNode( + nd.getAttribute('lat'), + nd.getAttribute('lon'), + way.nodes[i] + ); + } + }); + } + function fullGeometryRelation(rel, members) { + function addFullGeometryNode(lat,lon,id) { + var geometryNode = { + type:"node", + id: id, + lat: lat, + lon: lon + } + nodes.push(geometryNode); + } + function addFullGeometryWay(nds,id) { + // shared multipolygon ways cannot be defined multiple times with the same id. + if (ways.some(function (way) { // todo: this is slow :( + return way.type == "way" && way.id == id; + })) return; + var geometryWay = { + type: "way", + id: id, + nodes:[] + } + function addFullGeometryWayPseudoNode(lat,lon) { + // todo? do not save the same pseudo node multiple times + var geometryPseudoNode = { + type:"node", + id: "_anonymous@"+lat+"/"+lon, + lat: lat, + lon: lon, + __is_uninteresting: true + } + geometryWay.nodes.push(geometryPseudoNode.id); + nodes.push(geometryPseudoNode); + } + _.each(nds, function(nd) { + if (nd.getAttribute('lat')) { + addFullGeometryWayPseudoNode( + nd.getAttribute('lat'), + nd.getAttribute('lon') + ); + } else { + geometryWay.nodes.push(undefined); + } + }); + ways.push(geometryWay); + } + _.each( members, function( member, i ) { + if (rel.members[i].type == "node") { + if (member.getAttribute('lat')) { + addFullGeometryNode( + member.getAttribute('lat'), + member.getAttribute('lon'), + rel.members[i].ref + ); + } + } else if (rel.members[i].type == "way") { + if (member.getElementsByTagName('nd').length > 0) { + rel.members[i].ref = "_fullGeom"+rel.members[i].ref; + addFullGeometryWay( + member.getElementsByTagName('nd'), + rel.members[i].ref + ); + } + } + }); + } + // nodes + _.each( xml.getElementsByTagName('node'), function( node, i ) { + var tags = {}; + _.each( node.getElementsByTagName('tag'), function( tag ) { + tags[tag.getAttribute('k')] = tag.getAttribute('v'); + }); + var nodeObject = { + 'type': 'node' + }; + copy_attribute( node, nodeObject, 'id' ); + copy_attribute( node, nodeObject, 'lat' ); + copy_attribute( node, nodeObject, 'lon' ); + copy_attribute( node, nodeObject, 'version' ); + copy_attribute( node, nodeObject, 'timestamp' ); + copy_attribute( node, nodeObject, 'changeset' ); + copy_attribute( node, nodeObject, 'uid' ); + copy_attribute( node, nodeObject, 'user' ); + if (!_.isEmpty(tags)) + nodeObject.tags = tags; + nodes.push(nodeObject); + }); + // ways + var centroid,bounds; + _.each( xml.getElementsByTagName('way'), function( way, i ) { + var tags = {}; + var wnodes = []; + _.each( way.getElementsByTagName('tag'), function( tag ) { + tags[tag.getAttribute('k')] = tag.getAttribute('v'); + }); + var has_full_geometry = false; + _.each( way.getElementsByTagName('nd'), function( nd, i ) { + var id; + if (id = nd.getAttribute('ref')) + wnodes[i] = id; + if (!has_full_geometry && nd.getAttribute('lat')) + has_full_geometry = true; + }); + var wayObject = { + "type": "way" + }; + copy_attribute( way, wayObject, 'id' ); + copy_attribute( way, wayObject, 'version' ); + copy_attribute( way, wayObject, 'timestamp' ); + copy_attribute( way, wayObject, 'changeset' ); + copy_attribute( way, wayObject, 'uid' ); + copy_attribute( way, wayObject, 'user' ); + if (wnodes.length > 0) + wayObject.nodes = wnodes; + if (!_.isEmpty(tags)) + wayObject.tags = tags; + if (centroid = way.getElementsByTagName('center')[0]) + centerGeometry(wayObject,centroid); + if (has_full_geometry) + fullGeometryWay(wayObject, way.getElementsByTagName('nd')); + else if (bounds = way.getElementsByTagName('bounds')[0]) + boundsGeometry(wayObject,bounds); + ways.push(wayObject); + }); + // relations + _.each( xml.getElementsByTagName('relation'), function( relation, i ) { + var tags = {}; + var members = []; + _.each( relation.getElementsByTagName('tag'), function( tag ) { + tags[tag.getAttribute('k')] = tag.getAttribute('v'); + }); + var has_full_geometry = false; + _.each( relation.getElementsByTagName('member'), function( member, i ) { + members[i] = {}; + copy_attribute( member, members[i], 'ref' ); + copy_attribute( member, members[i], 'role' ); + copy_attribute( member, members[i], 'type' ); + if (!has_full_geometry && + (members[i].type == 'node' && member.getAttribute('lat')) || + (members[i].type == 'way' && member.getElementsByTagName('nd').length>0) ) + has_full_geometry = true; + }); + var relObject = { + "type": "relation" + } + copy_attribute( relation, relObject, 'id' ); + copy_attribute( relation, relObject, 'version' ); + copy_attribute( relation, relObject, 'timestamp' ); + copy_attribute( relation, relObject, 'changeset' ); + copy_attribute( relation, relObject, 'uid' ); + copy_attribute( relation, relObject, 'user' ); + if (members.length > 0) + relObject.members = members; + if (!_.isEmpty(tags)) + relObject.tags = tags; + if (centroid = relation.getElementsByTagName('center')[0]) + centerGeometry(relObject,centroid); + if (has_full_geometry) + fullGeometryRelation(relObject, relation.getElementsByTagName('member')); + else if (bounds = relation.getElementsByTagName('bounds')[0]) + boundsGeometry(relObject,bounds); + rels.push(relObject); + }); + return _convert2geoJSON(nodes,ways,rels); + } + function _convert2geoJSON(nodes,ways,rels) { + + // helper function that checks if there are any tags other than "created_by", "source", etc. or any tag provided in ignore_tags + function has_interesting_tags(t, ignore_tags) { + if (typeof ignore_tags !== "object") + ignore_tags={}; + if (typeof options.uninterestingTags === "function") + return !options.uninterestingTags(t, ignore_tags); + for (var k in t) + if (!(options.uninterestingTags[k]===true) && + !(ignore_tags[k]===true || ignore_tags[k]===t[k])) + return true; + return false; + }; + // helper function to extract meta information + function build_meta_information(object) { + var res = { + "timestamp": object.timestamp, + "version": object.version, + "changeset": object.changeset, + "user": object.user, + "uid": object.uid + }; + for (var k in res) + if (res[k] === undefined) + delete res[k]; + return res; + } + + // some data processing (e.g. filter nodes only used for ways) + var nodeids = new Object(); + for (var i=0;i y) != (yj > y)) && + (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + if (intersect) inside = !inside; + } + return inside; + }; + // stolen from iD/relation.js + var o, outer; + // todo: all this coordinate mapping makes this unneccesarily slow. + // see the "todo: this is slow! :(" above. + inner = mapCoordinates(inner); + /*for (o = 0; o < outers.length; o++) { + outer = mapCoordinates(outers[o]); + if (polygonContainsPolygon(outer, inner)) + return o; + }*/ + for (o = 0; o < outers.length; o++) { + outer = mapCoordinates(outers[o]); + if (polygonIntersectsPolygon(outer, inner)) + return o; + } + } + mp = outers.map(function(o) {return [o];}); + for (var j=0; j0.1.0*/); + return geojson; + } + function _isPolygonFeature( tags ) { + var polygonFeatures = options.polygonFeatures; + if (typeof polygonFeatures === "function") + return polygonFeatures(tags); + // explicitely tagged non-areas + if ( tags['area'] === 'no' ) + return false; + // assuming that a typical OSM way has in average less tags than + // the polygonFeatures list, this way around should be faster + for ( var key in tags ) { + var val = tags[key]; + var pfk = polygonFeatures[key]; + // continue with next if tag is unknown or not "categorizing" + if ( typeof pfk === 'undefined' ) + continue; + // continue with next if tag is explicitely un-set ("building=no") + if ( val === 'no' ) + continue; + // check polygon features for: general acceptance, included or excluded values + if ( pfk === true ) + return true; + if ( pfk.included_values && pfk.included_values[val] === true ) + return true; + if ( pfk.excluded_values && pfk.excluded_values[val] !== true ) + return true; + } + // if no tags matched, this ain't no area. + return false; + } +}; + +// for backwards compatibility +osmtogeojson.toGeojson = osmtogeojson; + +module.exports = osmtogeojson; + +},{"./lodash.custom.js":45,"geojson-rewind":38,"osm-polygon-features":42}],45:[function(require,module,exports){ +(function (global){ +/** + * @license + * Lo-Dash 2.4.1 (Custom Build) + * Build: `lodash exports="node" include="clone,merge,isEmpty,isArray,compact,each" -d` + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.5.2 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used to pool arrays and objects used internally */ + var arrayPool = []; + + /** Used internally to indicate various things */ + var indicatorObject = {}; + + /** Used as the max size of the `arrayPool` and `objectPool` */ + var maxPoolSize = 40; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to detected named functions */ + var reFuncName = /^\s*function[ \n\r\t]+\w/; + + /** Used to detect functions containing a `this` reference */ + var reThis = /\bthis\b/; + + /** Used to fix the JScript [[DontEnum]] bug */ + var shadowedProps = [ + 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', + 'toLocaleString', 'toString', 'valueOf' + ]; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Used to identify object classifications that `_.clone` supports */ + var cloneableClasses = {}; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used as the property descriptor for `__bindData__` */ + var descriptor = { + 'configurable': false, + 'enumerable': false, + 'value': null, + 'writable': false + }; + + /** Used as the data object for `iteratorTemplate` */ + var iteratorData = { + 'args': '', + 'array': null, + 'bottom': '', + 'firstArg': '', + 'init': '', + 'keys': null, + 'loop': '', + 'shadowedProps': null, + 'support': null, + 'top': '', + 'useHas': false + }; + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used as a reference to the global object */ + var root = (objectTypes[typeof window] && window) || this; + + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports` */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Gets an array from the array pool or creates a new one if the pool is empty. + * + * @private + * @returns {Array} The array from the pool. + */ + function getArray() { + return arrayPool.pop() || []; + } + + /** + * Checks if `value` is a DOM node in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`. + */ + function isNode(value) { + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings + return typeof value.toString != 'function' && typeof (value + '') == 'string'; + } + + /** + * Releases the given array back to the array pool. + * + * @private + * @param {Array} [array] The array to release. + */ + function releaseArray(array) { + array.length = 0; + if (arrayPool.length < maxPoolSize) { + arrayPool.push(array); + } + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used instead of `Array#slice` to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|string} collection The collection to slice. + * @param {number} start The start index. + * @param {number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Used for `Array` method references. + * + * Normally `Array.prototype` would suffice, however, using an array literal + * avoids issues in Narwhal. + */ + var arrayRef = []; + + /** Used for native method references */ + var errorProto = Error.prototype, + objectProto = Object.prototype, + stringProto = String.prototype; + + /** Used to resolve the internal [[Class]] of values */ + var toString = objectProto.toString; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + /** Native method shortcuts */ + var fnToString = Function.prototype.toString, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectProto.hasOwnProperty, + push = arrayRef.push, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + unshift = arrayRef.unshift; + + /** Used to set meta data on functions */ + var defineProperty = (function() { + // IE 8 only accepts DOM elements + try { + var o = {}, + func = isNative(func = Object.defineProperty) && func, + result = func(o, o, o) && func; + } catch(e) { } + return result; + }()); + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[funcClass] = Function; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; + + /** Used to avoid iterating non-enumerable properties in IE < 9 */ + var nonEnumProps = {}; + nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; + nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; + nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; + nonEnumProps[objectClass] = { 'constructor': true }; + + (function() { + var length = shadowedProps.length; + while (length--) { + var key = shadowedProps[length]; + for (var className in nonEnumProps) { + if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) { + nonEnumProps[className][key] = false; + } + } + } + }()); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps the given value to enable intuitive + * method chaining. + * + * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * Chaining is supported in custom builds as long as the `value` method is + * implicitly or explicitly included in the build. + * + * The chainable wrapper functions are: + * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, + * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, + * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, + * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, + * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, + * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, + * and `zip` + * + * The non-chainable wrapper functions are: + * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, + * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, + * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, + * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, + * `template`, `unescape`, `uniqueId`, and `value` + * + * The wrapper functions `first` and `last` return wrapped values when `n` is + * provided, otherwise they return unwrapped values. + * + * Explicit chaining can be enabled by using the `_.chain` method. + * + * @name _ + * @constructor + * @category Chaining + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(num) { + * return num * num; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash() { + // no operation performed + } + + /** + * An object used to flag environments features. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + (function() { + var ctor = function() { this.x = 1; }, + object = { '0': 1, 'length': 1 }, + props = []; + + ctor.prototype = { 'valueOf': 1, 'y': 1 }; + for (var key in new ctor) { props.push(key); } + for (key in arguments) { } + + /** + * Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). + * + * @memberOf _.support + * @type boolean + */ + support.argsClass = toString.call(arguments) == argsClass; + + /** + * Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5). + * + * @memberOf _.support + * @type boolean + */ + support.argsObject = arguments.constructor == Object && !(arguments instanceof Array); + + /** + * Detect if `name` or `message` properties of `Error.prototype` are + * enumerable by default. (IE < 9, Safari < 5.1) + * + * @memberOf _.support + * @type boolean + */ + support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); + + /** + * Detect if `prototype` properties are enumerable by default. + * + * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 + * (if the prototype or a property on the prototype has been set) + * incorrectly sets a function's `prototype` property [[Enumerable]] + * value to `true`. + * + * @memberOf _.support + * @type boolean + */ + support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = !isNative(root.WinRTError) && reThis.test(function() { return this; }); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * Detect if `arguments` object indexes are non-enumerable + * (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1). + * + * @memberOf _.support + * @type boolean + */ + support.nonEnumArgs = key != 0; + + /** + * Detect if properties shadowing those on `Object.prototype` are non-enumerable. + * + * In IE < 9 an objects own properties, shadowing non-enumerable ones, are + * made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). + * + * @memberOf _.support + * @type boolean + */ + support.nonEnumShadows = !/valueOf/.test(props); + + /** + * Detect if own properties are iterated after inherited properties (all but IE < 9). + * + * @memberOf _.support + * @type boolean + */ + support.ownLast = props[0] != 'x'; + + /** + * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. + * + * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` + * and `splice()` functions that fail to remove the last element, `value[0]`, + * of array-like objects even though the `length` property is set to `0`. + * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` + * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. + * + * @memberOf _.support + * @type boolean + */ + support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); + + /** + * Detect lack of support for accessing string characters by index. + * + * IE < 8 can't access characters by index and IE 8 can only access + * characters by index on string literals. + * + * @memberOf _.support + * @type boolean + */ + support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; + + /** + * Detect if a DOM node's [[Class]] is resolvable (all but IE < 9) + * and that the JS engine errors when attempting to coerce an object to + * a string without a `toString` function. + * + * @memberOf _.support + * @type boolean + */ + try { + support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); + } catch(e) { + support.nodeClass = true; + } + }(1)); + + /*--------------------------------------------------------------------------*/ + + /** + * The template used to create iterator functions. + * + * @private + * @param {Object} data The data object used to populate the text. + * @returns {string} Returns the interpolated text. + */ + var iteratorTemplate = function(obj) { + + var __p = 'var index, iterable = ' + + (obj.firstArg) + + ', result = ' + + (obj.init) + + ';\nif (!iterable) return result;\n' + + (obj.top) + + ';'; + if (obj.array) { + __p += '\nvar length = iterable.length; index = -1;\nif (' + + (obj.array) + + ') { '; + if (support.unindexedChars) { + __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; + } + __p += '\n while (++index < length) {\n ' + + (obj.loop) + + ';\n }\n}\nelse { '; + } else if (support.nonEnumArgs) { + __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + + (obj.loop) + + ';\n }\n } else { '; + } + + if (support.enumPrototypes) { + __p += '\n var skipProto = typeof iterable == \'function\';\n '; + } + + if (support.enumErrorProps) { + __p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n '; + } + + var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); } + + if (obj.useHas && obj.keys) { + __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n'; + if (conditions.length) { + __p += ' if (' + + (conditions.join(' && ')) + + ') {\n '; + } + __p += + (obj.loop) + + '; '; + if (conditions.length) { + __p += '\n }'; + } + __p += '\n } '; + } else { + __p += '\n for (index in iterable) {\n'; + if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) { + __p += ' if (' + + (conditions.join(' && ')) + + ') {\n '; + } + __p += + (obj.loop) + + '; '; + if (conditions.length) { + __p += '\n }'; + } + __p += '\n } '; + if (support.nonEnumShadows) { + __p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n '; + for (k = 0; k < 7; k++) { + __p += '\n index = \'' + + (obj.shadowedProps[k]) + + '\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))'; + if (!obj.useHas) { + __p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])'; + } + __p += ') {\n ' + + (obj.loop) + + ';\n } '; + } + __p += '\n } '; + } + + } + + if (obj.array || support.nonEnumArgs) { + __p += '\n}'; + } + __p += + (obj.bottom) + + ';\nreturn result'; + + return __p + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.bind` that creates the bound function and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new bound function. + */ + function baseBind(bindData) { + var func = bindData[0], + partialArgs = bindData[2], + thisArg = bindData[4]; + + function bound() { + // `Function#bind` spec + // http://es5.github.io/#x15.3.4.5 + if (partialArgs) { + // avoid `arguments` object deoptimizations by using `slice` instead + // of `Array.prototype.slice.call` and not assigning `arguments` to a + // variable as a ternary expression + var args = slice(partialArgs); + push.apply(args, arguments); } - copy_attribute( relation, relObject, 'id' ); - copy_attribute( relation, relObject, 'version' ); - copy_attribute( relation, relObject, 'timestamp' ); - copy_attribute( relation, relObject, 'changeset' ); - copy_attribute( relation, relObject, 'uid' ); - copy_attribute( relation, relObject, 'user' ); - if (members.length > 0) - relObject.members = members; - if (!_.isEmpty(tags)) - relObject.tags = tags; - if (centroid = relation.getElementsByTagName('center')[0]) - centerGeometry(relObject,centroid); - if (has_full_geometry) - fullGeometryRelation(relObject, relation.getElementsByTagName('member')); - else if (bounds = relation.getElementsByTagName('bounds')[0]) - boundsGeometry(relObject,bounds); - rels.push(relObject); - }); - return _convert2geoJSON(nodes,ways,rels); + // mimic the constructor's `return` behavior + // http://es5.github.io/#x13.2.2 + if (this instanceof bound) { + // ensure `new bound` is an instance of `func` + var thisBinding = baseCreate(func.prototype), + result = func.apply(thisBinding, args || arguments); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisArg, args || arguments); + } + setBindData(bound, bindData); + return bound; } - function _convert2geoJSON(nodes,ways,rels) { - // helper function that checks if there are any tags other than "created_by", "source", etc. or any tag provided in ignore_tags - function has_interesting_tags(t, ignore_tags) { - if (typeof ignore_tags !== "object") - ignore_tags={}; - if (typeof options.uninterestingTags === "function") - return !options.uninterestingTags(t, ignore_tags); - for (var k in t) - if (!(options.uninterestingTags[k]===true) && - !(ignore_tags[k]===true || ignore_tags[k]===t[k])) - return true; - return false; - }; - // helper function to extract meta information - function build_meta_information(object) { - var res = { - "timestamp": object.timestamp, - "version": object.version, - "changeset": object.changeset, - "user": object.user, - "uid": object.uid - }; - for (var k in res) - if (res[k] === undefined) - delete res[k]; - return res; + /** + * The base implementation of `_.clone` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, callback, stackA, stackB) { + if (callback) { + var result = callback(value); + if (typeof result != 'undefined') { + return result; + } } + // inspect [[Class]] + var isObj = isObject(value); + if (isObj) { + var className = toString.call(value); + if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) { + return value; + } + var ctor = ctorByClass[className]; + switch (className) { + case boolClass: + case dateClass: + return new ctor(+value); - // some data processing (e.g. filter nodes only used for ways) - var nodeids = new Object(); - for (var i=0;i y) != (yj > y)) && - (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - if (intersect) inside = !inside; - } - return inside; - }; - // stolen from iD/relation.js - var o, outer; - // todo: all this coordinate mapping makes this unneccesarily slow. - // see the "todo: this is slow! :(" above. - inner = mapCoordinates(inner); - /*for (o = 0; o < outers.length; o++) { - outer = mapCoordinates(outers[o]); - if (polygonContainsPolygon(outer, inner)) - return o; - }*/ - for (o = 0; o < outers.length; o++) { - outer = mapCoordinates(outers[o]); - if (polygonIntersectsPolygon(outer, inner)) - return o; + } + if (!found) { + var isShallow; + if (callback) { + result = callback(value, source); + if ((isShallow = typeof result != 'undefined')) { + value = result; } } - mp = outers.map(function(o) {return [o];}); - for (var j=0; j0.1.0*/); - return geojson; - } - function _isPolygonFeature( tags ) { - var polygonFeatures = options.polygonFeatures; - if (typeof polygonFeatures === "function") - return polygonFeatures(tags); - // explicitely tagged non-areas - if ( tags['area'] === 'no' ) - return false; - // assuming that a typical OSM way has in average less tags than - // the polygonFeatures list, this way around should be faster - for ( var key in tags ) { - var val = tags[key]; - var pfk = polygonFeatures[key]; - // continue with next if tag is unknown or not "categorizing" - if ( typeof pfk === 'undefined' ) - continue; - // continue with next if tag is explicitely un-set ("building=no") - if ( val === 'no' ) - continue; - // check polygon features for: general acceptance, included or excluded values - if ( pfk === true ) - return true; - if ( pfk.included_values && pfk.included_values[val] === true ) - return true; - if ( pfk.excluded_values && pfk.excluded_values[val] !== true ) - return true; + // append partial left arguments + if (isPartial) { + push.apply(bindData[2] || (bindData[2] = []), partialArgs); + } + // append partial right arguments + if (isPartialRight) { + unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); + } + // merge flags + bindData[1] |= bitmask; + return createWrapper.apply(null, bindData); } - // if no tags matched, this ain't no area. - return false; + // fast path for `_.bind` + var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; + return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); } -}; - -// for backwards compatibility -osmtogeojson.toGeojson = osmtogeojson; - -module.exports = osmtogeojson; -},{"./lodash.custom.js":12,"geojson-rewind":7,"osm-polygon-features":9}],12:[function(require,module,exports){ -(function (global){ -/** - * @license - * Lo-Dash 2.4.1 (Custom Build) - * Build: `lodash exports="node" include="clone,merge,isEmpty,isArray,compact,each" -d` - * Copyright 2012-2013 The Dojo Foundation - * Based on Underscore.js 1.5.2 - * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ -;(function() { + /** + * Creates compiled iteration functions. + * + * @private + * @param {...Object} [options] The compile options object(s). + * @param {string} [options.array] Code to determine if the iterable is an array or array-like. + * @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop. + * @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration. + * @param {string} [options.args] A comma separated string of iteration function arguments. + * @param {string} [options.top] Code to execute before the iteration branches. + * @param {string} [options.loop] Code to execute in the object loop. + * @param {string} [options.bottom] Code to execute after the iteration branches. + * @returns {Function} Returns the compiled function. + */ + function createIterator() { + // data properties + iteratorData.shadowedProps = shadowedProps; - /** Used to pool arrays and objects used internally */ - var arrayPool = []; + // iterator options + iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = ''; + iteratorData.init = 'iterable'; + iteratorData.useHas = true; - /** Used internally to indicate various things */ - var indicatorObject = {}; + // merge options into a template data object + for (var object, index = 0; object = arguments[index]; index++) { + for (var key in object) { + iteratorData[key] = object[key]; + } + } + var args = iteratorData.args; + iteratorData.firstArg = /^[^,]+/.exec(args)[0]; - /** Used as the max size of the `arrayPool` and `objectPool` */ - var maxPoolSize = 40; + // create the function factory + var factory = Function( + 'baseCreateCallback, errorClass, errorProto, hasOwnProperty, ' + + 'indicatorObject, isArguments, isArray, isString, keys, objectProto, ' + + 'objectTypes, nonEnumProps, stringClass, stringProto, toString', + 'return function(' + args + ') {\n' + iteratorTemplate(iteratorData) + '\n}' + ); - /** Used to match regexp flags from their coerced string values */ - var reFlags = /\w*$/; + // return the compiled function + return factory( + baseCreateCallback, errorClass, errorProto, hasOwnProperty, + indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto, + objectTypes, nonEnumProps, stringClass, stringProto, toString + ); + } - /** Used to detected named functions */ - var reFuncName = /^\s*function[ \n\r\t]+\w/; + /** + * Checks if `value` is a native function. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. + */ + function isNative(value) { + return typeof value == 'function' && reNative.test(value); + } - /** Used to detect functions containing a `this` reference */ - var reThis = /\bthis\b/; + /** + * Sets `this` binding data on a given function. + * + * @private + * @param {Function} func The function to set data on. + * @param {Array} value The data array to set. + */ + var setBindData = !defineProperty ? noop : function(func, value) { + descriptor.value = value; + defineProperty(func, '__bindData__', descriptor); + }; - /** Used to fix the JScript [[DontEnum]] bug */ - var shadowedProps = [ - 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', - 'toLocaleString', 'toString', 'valueOf' - ]; + /** + * A fallback implementation of `isPlainObject` which checks if a given value + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var ctor, + result; - /** `Object#toString` result shortcuts */ - var argsClass = '[object Arguments]', - arrayClass = '[object Array]', - boolClass = '[object Boolean]', - dateClass = '[object Date]', - errorClass = '[object Error]', - funcClass = '[object Function]', - numberClass = '[object Number]', - objectClass = '[object Object]', - regexpClass = '[object RegExp]', - stringClass = '[object String]'; + // avoid non Object objects, `arguments` objects, and DOM elements + if (!(value && toString.call(value) == objectClass) || + (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) || + (!support.argsClass && isArguments(value)) || + (!support.nodeClass && isNode(value))) { + return false; + } + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + if (support.ownLast) { + forIn(value, function(value, key, object) { + result = hasOwnProperty.call(object, key); + return false; + }); + return result !== false; + } + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return typeof result == 'undefined' || hasOwnProperty.call(value, result); + } - /** Used to identify object classifications that `_.clone` supports */ - var cloneableClasses = {}; - cloneableClasses[funcClass] = false; - cloneableClasses[argsClass] = cloneableClasses[arrayClass] = - cloneableClasses[boolClass] = cloneableClasses[dateClass] = - cloneableClasses[numberClass] = cloneableClasses[objectClass] = - cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + /*--------------------------------------------------------------------------*/ - /** Used as the property descriptor for `__bindData__` */ - var descriptor = { - 'configurable': false, - 'enumerable': false, - 'value': null, - 'writable': false - }; + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == argsClass || false; + } + // fallback for browsers that can't detect `arguments` objects by [[Class]] + if (!support.argsClass) { + isArguments = function(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false; + }; + } - /** Used as the data object for `iteratorTemplate` */ - var iteratorData = { - 'args': '', - 'array': null, - 'bottom': '', - 'firstArg': '', - 'init': '', - 'keys': null, - 'loop': '', - 'shadowedProps': null, - 'support': null, - 'top': '', - 'useHas': false + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == arrayClass || false; }; - /** Used to determine if values are of the language type Object */ - var objectTypes = { - 'boolean': false, - 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false - }; + /** + * A fallback implementation of `Object.keys` which produces an array of the + * given object's own enumerable property names. + * + * @private + * @type Function + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + */ + var shimKeys = createIterator({ + 'args': 'object', + 'init': '[]', + 'top': 'if (!(objectTypes[typeof object])) return result', + 'loop': 'result.push(index)' + }); - /** Used as a reference to the global object */ - var root = (objectTypes[typeof window] && window) || this; + /** + * Creates an array composed of the own enumerable property names of an object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (!isObject(object)) { + return []; + } + if ((support.enumPrototypes && typeof object == 'function') || + (support.nonEnumArgs && object.length && isArguments(object))) { + return shimKeys(object); + } + return nativeKeys(object); + }; - /** Detect free variable `exports` */ - var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ + var eachIteratorOptions = { + 'args': 'collection, callback, thisArg', + 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)", + 'array': "typeof length == 'number'", + 'keys': keys, + 'loop': 'if (callback(iterable[index], index, collection) === false) return result' + }; - /** Detect free variable `module` */ - var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + /** Reusable iterator options for `assign` and `defaults` */ + var defaultsIteratorOptions = { + 'args': 'object, source, guard', + 'top': + 'var args = arguments,\n' + + ' argsIndex = 0,\n' + + " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + + 'while (++argsIndex < argsLength) {\n' + + ' iterable = args[argsIndex];\n' + + ' if (iterable && objectTypes[typeof iterable]) {', + 'keys': keys, + 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", + 'bottom': ' }\n}' + }; - /** Detect the popular CommonJS extension `module.exports` */ - var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + /** Reusable iterator options for `forIn` and `forOwn` */ + var forOwnIteratorOptions = { + 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, + 'array': false + }; - /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ - var freeGlobal = objectTypes[typeof global] && global; - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - root = freeGlobal; - } + /** + * A function compiled to iterate `arguments` objects, arrays, objects, and + * strings consistenly across environments, executing the callback for each + * element in the collection. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index|key, collection). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @private + * @type Function + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + */ + var baseEach = createIterator(eachIteratorOptions); /*--------------------------------------------------------------------------*/ /** - * Gets an array from the array pool or creates a new one if the pool is empty. + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources will overwrite property assignments of previous + * sources. If a callback is provided it will be executed to produce the + * assigned values. The callback is bound to `thisArg` and invoked with two + * arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @type Function + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize assigning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); + * // => { 'name': 'fred', 'employer': 'slate' } + * + * var defaults = _.partialRight(_.assign, function(a, b) { + * return typeof a == 'undefined' ? b : a; + * }); + * + * var object = { 'name': 'barney' }; + * defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var assign = createIterator(defaultsIteratorOptions, { + 'top': + defaultsIteratorOptions.top.replace(';', + ';\n' + + "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + + ' var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + + "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + + ' callback = args[--argsLength];\n' + + '}' + ), + 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' + }); + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects will also + * be cloned, otherwise they will be assigned by reference. If a callback + * is provided it will be executed to produce the cloned values. If the + * callback returns `undefined` cloning will be handled by the method instead. + * The callback is bound to `thisArg` and invoked with one argument; (value). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var shallow = _.clone(characters); + * shallow[0] === characters[0]; + * // => true + * + * var deep = _.clone(characters, true); + * deep[0] === characters[0]; + * // => false * - * @private - * @returns {Array} The array from the pool. + * _.mixin({ + * 'clone': _.partialRight(_.clone, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }) + * }); + * + * var clone = _.clone(document.body); + * clone.childNodes.length; + * // => 0 */ - function getArray() { - return arrayPool.pop() || []; + function clone(value, isDeep, callback, thisArg) { + // allows working with "Collections" methods without using their `index` + // and `collection` arguments for `isDeep` and `callback` + if (typeof isDeep != 'boolean' && isDeep != null) { + thisArg = callback; + callback = isDeep; + isDeep = false; + } + return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** - * Checks if `value` is a DOM node in IE < 9. + * Iterates over own and inherited enumerable properties of an object, + * executing the callback for each property. The callback is bound to `thisArg` + * and invoked with three arguments; (value, key, object). Callbacks may exit + * iteration early by explicitly returning `false`. * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`. + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forIn(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) */ - function isNode(value) { - // IE < 9 presents DOM nodes as `Object` objects except they have `toString` - // methods that are `typeof` "string" and still can coerce nodes to strings - return typeof value.toString != 'function' && typeof (value + '') == 'string'; - } + var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { + 'useHas': false + }); /** - * Releases the given array back to the array pool. + * Iterates over own enumerable properties of an object, executing the callback + * for each property. The callback is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by + * explicitly returning `false`. * - * @private - * @param {Array} [array] The array to release. + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) */ - function releaseArray(array) { - array.length = 0; - if (arrayPool.length < maxPoolSize) { - arrayPool.push(array); - } - } + var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); /** - * Slices the `collection` from the `start` index up to, but not including, - * the `end` index. + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". * - * Note: This function is used instead of `Array#slice` to support node lists - * in IE < 9 and to ensure dense arrays are returned. + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if the `value` is empty, else `false`. + * @example * - * @private - * @param {Array|Object|string} collection The collection to slice. - * @param {number} start The start index. - * @param {number} end The end index. - * @returns {Array} Returns the new array. + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true */ - function slice(array, start, end) { - start || (start = 0); - if (typeof end == 'undefined') { - end = array ? array.length : 0; + function isEmpty(value) { + var result = true; + if (!value) { + return result; } - var index = -1, - length = end - start || 0, - result = Array(length < 0 ? 0 : length); + var className = toString.call(value), + length = value.length; - while (++index < length) { - result[index] = array[start + index]; + if ((className == arrayClass || className == stringClass || + (support.argsClass ? className == argsClass : isArguments(value))) || + (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { + return !length; } + forOwn(value, function() { + return (result = false); + }); return result; } - /*--------------------------------------------------------------------------*/ - - /** - * Used for `Array` method references. - * - * Normally `Array.prototype` would suffice, however, using an array literal - * avoids issues in Narwhal. - */ - var arrayRef = []; - - /** Used for native method references */ - var errorProto = Error.prototype, - objectProto = Object.prototype, - stringProto = String.prototype; - - /** Used to resolve the internal [[Class]] of values */ - var toString = objectProto.toString; - - /** Used to detect if a method is native */ - var reNative = RegExp('^' + - String(toString) - .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - .replace(/toString| for [^\]]+/g, '.*?') + '$' - ); - - /** Native method shortcuts */ - var fnToString = Function.prototype.toString, - getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, - hasOwnProperty = objectProto.hasOwnProperty, - push = arrayRef.push, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - unshift = arrayRef.unshift; - - /** Used to set meta data on functions */ - var defineProperty = (function() { - // IE 8 only accepts DOM elements - try { - var o = {}, - func = isNative(func = Object.defineProperty) && func, - result = func(o, o, o) && func; - } catch(e) { } - return result; - }()); - - /* Native method shortcuts for methods with the same name as other `lodash` methods */ - var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, - nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, - nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys; - - /** Used to lookup a built-in constructor by [[Class]] */ - var ctorByClass = {}; - ctorByClass[arrayClass] = Array; - ctorByClass[boolClass] = Boolean; - ctorByClass[dateClass] = Date; - ctorByClass[funcClass] = Function; - ctorByClass[objectClass] = Object; - ctorByClass[numberClass] = Number; - ctorByClass[regexpClass] = RegExp; - ctorByClass[stringClass] = String; - - /** Used to avoid iterating non-enumerable properties in IE < 9 */ - var nonEnumProps = {}; - nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; - nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; - nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; - nonEnumProps[objectClass] = { 'constructor': true }; - - (function() { - var length = shadowedProps.length; - while (length--) { - var key = shadowedProps[length]; - for (var className in nonEnumProps) { - if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) { - nonEnumProps[className][key] = false; - } - } - } - }()); - - /*--------------------------------------------------------------------------*/ - /** - * Creates a `lodash` object which wraps the given value to enable intuitive - * method chaining. - * - * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: - * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, - * and `unshift` + * Checks if `value` is a function. * - * Chaining is supported in custom builds as long as the `value` method is - * implicitly or explicitly included in the build. + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a function, else `false`. + * @example * - * The chainable wrapper functions are: - * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, - * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, - * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, - * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, - * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, - * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, - * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, - * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, - * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, - * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, - * and `zip` + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + // fallback for older versions of Chrome and Safari + if (isFunction(/x/)) { + isFunction = function(value) { + return typeof value == 'function' && toString.call(value) == funcClass; + }; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * - * The non-chainable wrapper functions are: - * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, - * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, - * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, - * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, - * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, - * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, - * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, - * `template`, `unescape`, `uniqueId`, and `value` + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an object, else `false`. + * @example * - * The wrapper functions `first` and `last` return wrapped values when `n` is - * provided, otherwise they return unwrapped values. + * _.isObject({}); + * // => true * - * Explicit chaining can be enabled by using the `_.chain` method. + * _.isObject([1, 2, 3]); + * // => true * - * @name _ - * @constructor - * @category Chaining - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns a `lodash` instance. - * @example + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.io/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return !!(value && objectTypes[typeof value]); + } + + /** + * Checks if `value` is an object created by the `Object` constructor. * - * var wrapped = _([1, 2, 3]); + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example * - * // returns an unwrapped value - * wrapped.reduce(function(sum, num) { - * return sum + num; - * }); - * // => 6 + * function Shape() { + * this.x = 0; + * this.y = 0; + * } * - * // returns a wrapped value - * var squares = wrapped.map(function(num) { - * return num * num; - * }); + * _.isPlainObject(new Shape); + * // => false * - * _.isArray(squares); + * _.isPlainObject([1, 2, 3]); * // => false * - * _.isArray(squares.value()); + * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true */ - function lodash() { - // no operation performed - } + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; /** - * An object used to flag environments features. + * Checks if `value` is a string. * * @static * @memberOf _ - * @type Object + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a string, else `false`. + * @example + * + * _.isString('fred'); + * // => true */ - var support = lodash.support = {}; - - (function() { - var ctor = function() { this.x = 1; }, - object = { '0': 1, 'length': 1 }, - props = []; - - ctor.prototype = { 'valueOf': 1, 'y': 1 }; - for (var key in new ctor) { props.push(key); } - for (key in arguments) { } - - /** - * Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). - * - * @memberOf _.support - * @type boolean - */ - support.argsClass = toString.call(arguments) == argsClass; - - /** - * Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5). - * - * @memberOf _.support - * @type boolean - */ - support.argsObject = arguments.constructor == Object && !(arguments instanceof Array); - - /** - * Detect if `name` or `message` properties of `Error.prototype` are - * enumerable by default. (IE < 9, Safari < 5.1) - * - * @memberOf _.support - * @type boolean - */ - support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); - - /** - * Detect if `prototype` properties are enumerable by default. - * - * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 - * (if the prototype or a property on the prototype has been set) - * incorrectly sets a function's `prototype` property [[Enumerable]] - * value to `true`. - * - * @memberOf _.support - * @type boolean - */ - support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); - - /** - * Detect if functions can be decompiled by `Function#toString` - * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). - * - * @memberOf _.support - * @type boolean - */ - support.funcDecomp = !isNative(root.WinRTError) && reThis.test(function() { return this; }); + function isString(value) { + return typeof value == 'string' || + value && typeof value == 'object' && toString.call(value) == stringClass || false; + } - /** - * Detect if `Function#name` is supported (all but IE). - * - * @memberOf _.support - * @type boolean - */ - support.funcNames = typeof Function.name == 'string'; + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * will overwrite property assignments of previous sources. If a callback is + * provided it will be executed to produce the merged values of the destination + * and source properties. If the callback returns `undefined` merging will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize merging properties. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * var names = { + * 'characters': [ + * { 'name': 'barney' }, + * { 'name': 'fred' } + * ] + * }; + * + * var ages = { + * 'characters': [ + * { 'age': 36 }, + * { 'age': 40 } + * ] + * }; + * + * _.merge(names, ages); + * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } + * + * var food = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var otherFood = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(food, otherFood, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } + */ + function merge(object) { + var args = arguments, + length = 2; - /** - * Detect if `arguments` object indexes are non-enumerable - * (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1). - * - * @memberOf _.support - * @type boolean - */ - support.nonEnumArgs = key != 0; + if (!isObject(object)) { + return object; + } + // allows working with `_.reduce` and `_.reduceRight` without using + // their `index` and `collection` arguments + if (typeof args[2] != 'number') { + length = args.length; + } + if (length > 3 && typeof args[length - 2] == 'function') { + var callback = baseCreateCallback(args[--length - 1], args[length--], 2); + } else if (length > 2 && typeof args[length - 1] == 'function') { + callback = args[--length]; + } + var sources = slice(arguments, 1, length), + index = -1, + stackA = getArray(), + stackB = getArray(); - /** - * Detect if properties shadowing those on `Object.prototype` are non-enumerable. - * - * In IE < 9 an objects own properties, shadowing non-enumerable ones, are - * made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). - * - * @memberOf _.support - * @type boolean - */ - support.nonEnumShadows = !/valueOf/.test(props); + while (++index < length) { + baseMerge(object, sources[index], callback, stackA, stackB); + } + releaseArray(stackA); + releaseArray(stackB); + return object; + } - /** - * Detect if own properties are iterated after inherited properties (all but IE < 9). - * - * @memberOf _.support - * @type boolean - */ - support.ownLast = props[0] != 'x'; + /*--------------------------------------------------------------------------*/ - /** - * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. - * - * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` - * and `splice()` functions that fail to remove the last element, `value[0]`, - * of array-like objects even though the `length` property is set to `0`. - * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` - * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. - * - * @memberOf _.support - * @type boolean - */ - support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); + /** + * Iterates over elements of a collection, executing the callback for each + * element. The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). Callbacks 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 `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); + * // => logs each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + * // => logs each number and returns the object (property order is not guaranteed across environments) + */ + function forEach(collection, callback, thisArg) { + if (callback && typeof thisArg == 'undefined' && isArray(collection)) { + var index = -1, + length = collection.length; - /** - * Detect lack of support for accessing string characters by index. - * - * IE < 8 can't access characters by index and IE 8 can only access - * characters by index on string literals. - * - * @memberOf _.support - * @type boolean - */ - support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; + while (++index < length) { + if (callback(collection[index], index, collection) === false) { + break; + } + } + } else { + baseEach(collection, callback, thisArg); + } + return collection; + } - /** - * Detect if a DOM node's [[Class]] is resolvable (all but IE < 9) - * and that the JS engine errors when attempting to coerce an object to - * a string without a `toString` function. - * - * @memberOf _.support - * @type boolean - */ - try { - support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); - } catch(e) { - support.nodeClass = true; + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a 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, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } } - }(1)); + return result; + } /*--------------------------------------------------------------------------*/ /** - * The template used to create iterator functions. + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * provided to the bound function. * - * @private - * @param {Object} data The data object used to populate the text. - * @returns {string} Returns the interpolated text. + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'fred' }, 'hi'); + * func(); + * // => 'hi fred' */ - var iteratorTemplate = function(obj) { + function bind(func, thisArg) { + return arguments.length > 2 + ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) + : createWrapper(func, 1, null, null, thisArg); + } - var __p = 'var index, iterable = ' + - (obj.firstArg) + - ', result = ' + - (obj.init) + - ';\nif (!iterable) return result;\n' + - (obj.top) + - ';'; - if (obj.array) { - __p += '\nvar length = iterable.length; index = -1;\nif (' + - (obj.array) + - ') { '; - if (support.unindexedChars) { - __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; - } - __p += '\n while (++index < length) {\n ' + - (obj.loop) + - ';\n }\n}\nelse { '; - } else if (support.nonEnumArgs) { - __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + - (obj.loop) + - ';\n }\n } else { '; - } + /*--------------------------------------------------------------------------*/ - if (support.enumPrototypes) { - __p += '\n var skipProto = typeof iterable == \'function\';\n '; - } + /** + * This method returns the first argument provided to it. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'name': 'fred' }; + * _.identity(object) === object; + * // => true + */ + function identity(value) { + return value; + } - if (support.enumErrorProps) { - __p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n '; - } + /** + * A no-operation function. + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var object = { 'name': 'fred' }; + * _.noop(object) === undefined; + * // => true + */ + function noop() { + // no operation performed + } - var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); } + /*--------------------------------------------------------------------------*/ - if (obj.useHas && obj.keys) { - __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n'; - if (conditions.length) { - __p += ' if (' + - (conditions.join(' && ')) + - ') {\n '; - } - __p += - (obj.loop) + - '; '; - if (conditions.length) { - __p += '\n }'; - } - __p += '\n } '; - } else { - __p += '\n for (index in iterable) {\n'; - if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) { - __p += ' if (' + - (conditions.join(' && ')) + - ') {\n '; - } - __p += - (obj.loop) + - '; '; - if (conditions.length) { - __p += '\n }'; - } - __p += '\n } '; - if (support.nonEnumShadows) { - __p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n '; - for (k = 0; k < 7; k++) { - __p += '\n index = \'' + - (obj.shadowedProps[k]) + - '\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))'; - if (!obj.useHas) { - __p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])'; - } - __p += ') {\n ' + - (obj.loop) + - ';\n } '; - } - __p += '\n } '; - } + lodash.assign = assign; + lodash.bind = bind; + lodash.compact = compact; + lodash.forEach = forEach; + lodash.forIn = forIn; + lodash.forOwn = forOwn; + lodash.keys = keys; + lodash.merge = merge; - } + lodash.each = forEach; + lodash.extend = assign; - if (obj.array || support.nonEnumArgs) { - __p += '\n}'; - } - __p += - (obj.bottom) + - ';\nreturn result'; + /*--------------------------------------------------------------------------*/ - return __p - }; + // add functions that return unwrapped values when chaining + lodash.clone = clone; + lodash.identity = identity; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isEmpty = isEmpty; + lodash.isFunction = isFunction; + lodash.isObject = isObject; + lodash.isPlainObject = isPlainObject; + lodash.isString = isString; + lodash.noop = noop; /*--------------------------------------------------------------------------*/ /** - * The base implementation of `_.bind` that creates the bound function and - * sets its meta data. + * The semantic version number. * - * @private - * @param {Array} bindData The bind data array. - * @returns {Function} Returns the new bound function. + * @static + * @memberOf _ + * @type string */ - function baseBind(bindData) { - var func = bindData[0], - partialArgs = bindData[2], - thisArg = bindData[4]; + lodash.VERSION = '2.4.1'; - function bound() { - // `Function#bind` spec - // http://es5.github.io/#x15.3.4.5 - if (partialArgs) { - // avoid `arguments` object deoptimizations by using `slice` instead - // of `Array.prototype.slice.call` and not assigning `arguments` to a - // variable as a ternary expression - var args = slice(partialArgs); - push.apply(args, arguments); - } - // mimic the constructor's `return` behavior - // http://es5.github.io/#x13.2.2 - if (this instanceof bound) { - // ensure `new bound` is an instance of `func` - var thisBinding = baseCreate(func.prototype), - result = func.apply(thisBinding, args || arguments); - return isObject(result) ? result : thisBinding; - } - return func.apply(thisArg, args || arguments); - } - setBindData(bound, bindData); - return bound; - } + /*--------------------------------------------------------------------------*/ - /** - * The base implementation of `_.clone` without argument juggling or support - * for `thisArg` binding. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep=false] Specify a deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates clones with source counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, callback, stackA, stackB) { - if (callback) { - var result = callback(value); - if (typeof result != 'undefined') { - return result; - } + if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = lodash)._ = lodash; } - // inspect [[Class]] - var isObj = isObject(value); - if (isObj) { - var className = toString.call(value); - if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) { - return value; - } - var ctor = ctorByClass[className]; - switch (className) { - case boolClass: - case dateClass: - return new ctor(+value); - - case numberClass: - case stringClass: - return new ctor(value); - case regexpClass: - result = ctor(value.source, reFlags.exec(value)); - result.lastIndex = value.lastIndex; - return result; - } - } else { - return value; - } - var isArr = isArray(value); - if (isDeep) { - // check for circular references and return corresponding clone - var initedStack = !stackA; - stackA || (stackA = getArray()); - stackB || (stackB = getArray()); + } - var length = stackA.length; - while (length--) { - if (stackA[length] == value) { - return stackB[length]; - } - } - result = isArr ? ctor(value.length) : {}; - } - else { - result = isArr ? slice(value) : assign({}, value); - } - // add array properties assigned by `RegExp#exec` - if (isArr) { - if (hasOwnProperty.call(value, 'index')) { - result.index = value.index; - } - if (hasOwnProperty.call(value, 'input')) { - result.input = value.input; - } - } - // exit for shallow clone - if (!isDeep) { - return result; - } - // add the source value to the stack of traversed objects - // and associate it with its clone - stackA.push(value); - stackB.push(result); +}.call(this)); - // recursively populate clone (susceptible to call stack limits) - (isArr ? baseEach : forOwn)(value, function(objValue, key) { - result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); - }); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],46:[function(require,module,exports){ +(function (root, factory) { - if (initedStack) { - releaseArray(stackA); - releaseArray(stackB); - } - return result; + // Node. + if(typeof module === 'object' && typeof module.exports === 'object') { + exports = module.exports = factory(); } - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(prototype, properties) { - return isObject(prototype) ? nativeCreate(prototype) : {}; + // Browser Global. + if(typeof window === "object") { + root.Terraformer = factory(); } - // fallback for browsers without `Object.create` - if (!nativeCreate) { - baseCreate = (function() { - function Object() {} - return function(prototype) { - if (isObject(prototype)) { - Object.prototype = prototype; - var result = new Object; - Object.prototype = null; + +}(this, function(){ + var exports = {}, + EarthRadius = 6378137, + DegreesPerRadian = 57.295779513082320, + RadiansPerDegree = 0.017453292519943, + MercatorCRS = { + "type": "link", + "properties": { + "href": "http://spatialreference.org/ref/sr-org/6928/ogcwkt/", + "type": "ogcwkt" + } + }, + GeographicCRS = { + "type": "link", + "properties": { + "href": "http://spatialreference.org/ref/epsg/4326/ogcwkt/", + "type": "ogcwkt" } - return result || root.Object(); }; - }()); + + /* + Internal: isArray function + */ + function isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; } - /** - * The base implementation of `_.createCallback` without support for creating - * "_.pluck" or "_.where" style callbacks. - * - * @private - * @param {*} [func=identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of the created callback. - * @param {number} [argCount] The number of arguments the callback accepts. - * @returns {Function} Returns a callback function. - */ - function baseCreateCallback(func, thisArg, argCount) { - if (typeof func != 'function') { - return identity; - } - // exit early for no `thisArg` or already bound by `Function#bind` - if (typeof thisArg == 'undefined' || !('prototype' in func)) { - return func; + /* + Internal: safe warning + */ + function warn() { + var args = Array.prototype.slice.apply(arguments); + + if (typeof console !== undefined && console.warn) { + console.warn.apply(console, args); } - var bindData = func.__bindData__; - if (typeof bindData == 'undefined') { - if (support.funcNames) { - bindData = !func.name; - } - bindData = bindData || !support.funcDecomp; - if (!bindData) { - var source = fnToString.call(func); - if (!support.funcNames) { - bindData = !reFuncName.test(source); - } - if (!bindData) { - // checks if `func` references the `this` keyword and stores the result - bindData = reThis.test(source); - setBindData(func, bindData); - } + } + + /* + Internal: Extend one object with another. + */ + function extend(destination, source) { + for (var k in source) { + if (source.hasOwnProperty(k)) { + destination[k] = source[k]; } } - // exit early if there are no `this` references or `func` is bound - if (bindData === false || (bindData !== true && bindData[1] & 1)) { - return func; - } - switch (argCount) { - case 1: return function(value) { - return func.call(thisArg, value); - }; - case 2: return function(a, b) { - return func.call(thisArg, a, b); - }; - case 3: return function(value, index, collection) { - return func.call(thisArg, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - } - return bind(func, thisArg); + return destination; } - /** - * The base implementation of `createWrapper` that creates the wrapper and - * sets its meta data. - * - * @private - * @param {Array} bindData The bind data array. - * @returns {Function} Returns the new function. - */ - function baseCreateWrapper(bindData) { - var func = bindData[0], - bitmask = bindData[1], - partialArgs = bindData[2], - partialRightArgs = bindData[3], - thisArg = bindData[4], - arity = bindData[5]; + /* + Public: Calculate an bounding box for a geojson object + */ + function calculateBounds (geojson) { + if(geojson.type){ + switch (geojson.type) { + case 'Point': + return [ geojson.coordinates[0], geojson.coordinates[1], geojson.coordinates[0], geojson.coordinates[1]]; + + case 'MultiPoint': + return calculateBoundsFromArray(geojson.coordinates); + + case 'LineString': + return calculateBoundsFromArray(geojson.coordinates); + + case 'MultiLineString': + return calculateBoundsFromNestedArrays(geojson.coordinates); - var isBind = bitmask & 1, - isBindKey = bitmask & 2, - isCurry = bitmask & 4, - isCurryBound = bitmask & 8, - key = func; + case 'Polygon': + return calculateBoundsFromNestedArrays(geojson.coordinates); - function bound() { - var thisBinding = isBind ? thisArg : this; - if (partialArgs) { - var args = slice(partialArgs); - push.apply(args, arguments); + case 'MultiPolygon': + return calculateBoundsFromNestedArrayOfArrays(geojson.coordinates); + + case 'Feature': + return geojson.geometry? calculateBounds(geojson.geometry) : null; + + case 'FeatureCollection': + return calculateBoundsForFeatureCollection(geojson); + + case 'GeometryCollection': + return calculateBoundsForGeometryCollection(geojson); + + default: + throw new Error("Unknown type: " + geojson.type); } - if (partialRightArgs || isCurry) { - args || (args = slice(arguments)); - if (partialRightArgs) { - push.apply(args, partialRightArgs); + } + return null; + } + + /* + Internal: Calculate an bounding box from an nested array of positions + [ + [ + [ [lng, lat],[lng, lat],[lng, lat] ] + ] + [ + [lng, lat],[lng, lat],[lng, lat] + ] + [ + [lng, lat],[lng, lat],[lng, lat] + ] + ] + */ + function calculateBoundsFromNestedArrays (array) { + var x1 = null, x2 = null, y1 = null, y2 = null; + + for (var i = 0; i < array.length; i++) { + var inner = array[i]; + + for (var j = 0; j < inner.length; j++) { + var lonlat = inner[j]; + + var lon = lonlat[0]; + var lat = lonlat[1]; + + if (x1 === null) { + x1 = lon; + } else if (lon < x1) { + x1 = lon; } - if (isCurry && args.length < arity) { - bitmask |= 16 & ~32; - return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); + + if (x2 === null) { + x2 = lon; + } else if (lon > x2) { + x2 = lon; + } + + if (y1 === null) { + y1 = lat; + } else if (lat < y1) { + y1 = lat; + } + + if (y2 === null) { + y2 = lat; + } else if (lat > y2) { + y2 = lat; } } - args || (args = arguments); - if (isBindKey) { - func = thisBinding[key]; - } - if (this instanceof bound) { - thisBinding = baseCreate(func.prototype); - var result = func.apply(thisBinding, args); - return isObject(result) ? result : thisBinding; - } - return func.apply(thisBinding, args); } - setBindData(bound, bindData); - return bound; - } - /** - * The base implementation of `_.merge` without argument juggling or support - * for `thisArg` binding. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} [callback] The function to customize merging properties. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - */ - function baseMerge(object, source, callback, stackA, stackB) { - (isArray(source) ? forEach : forOwn)(source, function(source, key) { - var found, - isArr, - result = source, - value = object[key]; + return [x1, y1, x2, y2 ]; + } - if (source && ((isArr = isArray(source)) || isPlainObject(source))) { - // avoid merging previously merged cyclic sources - var stackLength = stackA.length; - while (stackLength--) { - if ((found = stackA[stackLength] == source)) { - value = stackB[stackLength]; - break; - } - } - if (!found) { - var isShallow; - if (callback) { - result = callback(value, source); - if ((isShallow = typeof result != 'undefined')) { - value = result; - } + /* + Internal: Calculate a bounding box from an array of arrays of arrays + [ + [ [lng, lat],[lng, lat],[lng, lat] ] + [ [lng, lat],[lng, lat],[lng, lat] ] + [ [lng, lat],[lng, lat],[lng, lat] ] + ] + */ + function calculateBoundsFromNestedArrayOfArrays (array) { + var x1 = null, x2 = null, y1 = null, y2 = null; + + for (var i = 0; i < array.length; i++) { + var inner = array[i]; + + for (var j = 0; j < inner.length; j++) { + var innerinner = inner[j]; + for (var k = 0; k < innerinner.length; k++) { + var lonlat = innerinner[k]; + + var lon = lonlat[0]; + var lat = lonlat[1]; + + if (x1 === null) { + x1 = lon; + } else if (lon < x1) { + x1 = lon; } - if (!isShallow) { - value = isArr - ? (isArray(value) ? value : []) - : (isPlainObject(value) ? value : {}); + + if (x2 === null) { + x2 = lon; + } else if (lon > x2) { + x2 = lon; } - // add `source` and associated `value` to the stack of traversed objects - stackA.push(source); - stackB.push(value); - // recursively merge objects and arrays (susceptible to call stack limits) - if (!isShallow) { - baseMerge(value, source, callback, stackA, stackB); + if (y1 === null) { + y1 = lat; + } else if (lat < y1) { + y1 = lat; } - } - } - else { - if (callback) { - result = callback(value, source); - if (typeof result == 'undefined') { - result = source; + + if (y2 === null) { + y2 = lat; + } else if (lat > y2) { + y2 = lat; } } - if (typeof result != 'undefined') { - value = result; - } } - object[key] = value; - }); + } + + return [x1, y1, x2, y2]; } - /** - * Creates a function that, when called, either curries or invokes `func` - * with an optional `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of method flags to compose. - * The bitmask may be composed of the following flags: - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` - * 8 - `_.curry` (bound) - * 16 - `_.partial` - * 32 - `_.partialRight` - * @param {Array} [partialArgs] An array of arguments to prepend to those - * provided to the new function. - * @param {Array} [partialRightArgs] An array of arguments to append to those - * provided to the new function. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new function. - */ - function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { - var isBind = bitmask & 1, - isBindKey = bitmask & 2, - isCurry = bitmask & 4, - isCurryBound = bitmask & 8, - isPartial = bitmask & 16, - isPartialRight = bitmask & 32; + /* + Internal: Calculate a bounding box from an array of positions + [ + [lng, lat],[lng, lat],[lng, lat] + ] + */ + function calculateBoundsFromArray (array) { + var x1 = null, x2 = null, y1 = null, y2 = null; + + for (var i = 0; i < array.length; i++) { + var lonlat = array[i]; + var lon = lonlat[0]; + var lat = lonlat[1]; + + if (x1 === null) { + x1 = lon; + } else if (lon < x1) { + x1 = lon; + } - if (!isBindKey && !isFunction(func)) { - throw new TypeError; + if (x2 === null) { + x2 = lon; + } else if (lon > x2) { + x2 = lon; + } + + if (y1 === null) { + y1 = lat; + } else if (lat < y1) { + y1 = lat; + } + + if (y2 === null) { + y2 = lat; + } else if (lat > y2) { + y2 = lat; + } } - if (isPartial && !partialArgs.length) { - bitmask &= ~16; - isPartial = partialArgs = false; + + return [x1, y1, x2, y2 ]; + } + + /* + Internal: Calculate an bounding box for a feature collection + */ + function calculateBoundsForFeatureCollection(featureCollection){ + var extents = [], extent; + for (var i = featureCollection.features.length - 1; i >= 0; i--) { + extent = calculateBounds(featureCollection.features[i].geometry); + extents.push([extent[0],extent[1]]); + extents.push([extent[2],extent[3]]); } - if (isPartialRight && !partialRightArgs.length) { - bitmask &= ~32; - isPartialRight = partialRightArgs = false; + + return calculateBoundsFromArray(extents); + } + + /* + Internal: Calculate an bounding box for a geometry collection + */ + function calculateBoundsForGeometryCollection(geometryCollection){ + var extents = [], extent; + + for (var i = geometryCollection.geometries.length - 1; i >= 0; i--) { + extent = calculateBounds(geometryCollection.geometries[i]); + extents.push([extent[0],extent[1]]); + extents.push([extent[2],extent[3]]); } - var bindData = func && func.__bindData__; - if (bindData && bindData !== true) { - // clone `bindData` - bindData = slice(bindData); - if (bindData[2]) { - bindData[2] = slice(bindData[2]); + + return calculateBoundsFromArray(extents); + } + + function calculateEnvelope(geojson){ + var bounds = calculateBounds(geojson); + return { + x: bounds[0], + y: bounds[1], + w: Math.abs(bounds[0] - bounds[2]), + h: Math.abs(bounds[1] - bounds[3]) + }; + } + + /* + Internal: Convert radians to degrees. Used by spatial reference converters. + */ + function radToDeg(rad) { + return rad * DegreesPerRadian; + } + + /* + Internal: Convert degrees to radians. Used by spatial reference converters. + */ + function degToRad(deg) { + return deg * RadiansPerDegree; + } + + /* + Internal: Loop over each array in a geojson object and apply a function to it. Used by spatial reference converters. + */ + function eachPosition(coordinates, func) { + for (var i = 0; i < coordinates.length; i++) { + // we found a number so lets convert this pair + if(typeof coordinates[i][0] === "number"){ + coordinates[i] = func(coordinates[i]); } - if (bindData[3]) { - bindData[3] = slice(bindData[3]); + // we found an coordinates array it again and run THIS function against it + if(typeof coordinates[i] === "object"){ + coordinates[i] = eachPosition(coordinates[i], func); } - // set `thisBinding` is not previously bound - if (isBind && !(bindData[1] & 1)) { - bindData[4] = thisArg; + } + return coordinates; + } + + /* + Public: Convert a GeoJSON Position object to Geographic (4326) + */ + function positionToGeographic(position) { + var x = position[0]; + var y = position[1]; + return [radToDeg(x / EarthRadius) - (Math.floor((radToDeg(x / EarthRadius) + 180) / 360) * 360), radToDeg((Math.PI / 2) - (2 * Math.atan(Math.exp(-1.0 * y / EarthRadius))))]; + } + + /* + Public: Convert a GeoJSON Position object to Web Mercator (102100) + */ + function positionToMercator(position) { + var lng = position[0]; + var lat = Math.max(Math.min(position[1], 89.99999), -89.99999); + return [degToRad(lng) * EarthRadius, EarthRadius/2.0 * Math.log( (1.0 + Math.sin(degToRad(lat))) / (1.0 - Math.sin(degToRad(lat))) )]; + } + + /* + Public: Apply a function agaist all positions in a geojson object. Used by spatial reference converters. + */ + function applyConverter(geojson, converter, noCrs){ + if(geojson.type === "Point") { + geojson.coordinates = converter(geojson.coordinates); + } else if(geojson.type === "Feature") { + geojson.geometry = applyConverter(geojson.geometry, converter, true); + } else if(geojson.type === "FeatureCollection") { + for (var f = 0; f < geojson.features.length; f++) { + geojson.features[f] = applyConverter(geojson.features[f], converter, true); } - // set if previously bound but not currently (subsequent curried functions) - if (!isBind && bindData[1] & 1) { - bitmask |= 8; + } else if(geojson.type === "GeometryCollection") { + for (var g = 0; g < geojson.geometries.length; g++) { + geojson.geometries[g] = applyConverter(geojson.geometries[g], converter, true); } - // set curried arity if not yet set - if (isCurry && !(bindData[1] & 4)) { - bindData[5] = arity; + } else { + geojson.coordinates = eachPosition(geojson.coordinates, converter); + } + + if(!noCrs){ + if(converter === positionToMercator){ + geojson.crs = MercatorCRS; } - // append partial left arguments - if (isPartial) { - push.apply(bindData[2] || (bindData[2] = []), partialArgs); + } + + if(converter === positionToGeographic){ + delete geojson.crs; + } + + return geojson; + } + + /* + Public: Convert a GeoJSON object to ESRI Web Mercator (102100) + */ + function toMercator(geojson) { + return applyConverter(geojson, positionToMercator); + } + + /* + Convert a GeoJSON object to Geographic coordinates (WSG84, 4326) + */ + function toGeographic(geojson) { + return applyConverter(geojson, positionToGeographic); + } + + + /* + Internal: -1,0,1 comparison function + */ + function cmp(a, b) { + if(a < b) { + return -1; + } else if(a > b) { + return 1; + } else { + return 0; + } + } + + /* + Internal: used for sorting + */ + function compSort(p1, p2) { + if (p1[0] > p2[0]) { + return -1; + } else if (p1[0] < p2[0]) { + return 1; + } else if (p1[1] > p2[1]) { + return -1; + } else if (p1[1] < p2[1]) { + return 1; + } else { + return 0; + } + } + + + /* + Internal: used to determine turn + */ + function turn(p, q, r) { + // Returns -1, 0, 1 if p,q,r forms a right, straight, or left turn. + return cmp((q[0] - p[0]) * (r[1] - p[1]) - (r[0] - p[0]) * (q[1] - p[1]), 0); + } + + /* + Internal: used to determine euclidean distance between two points + */ + function euclideanDistance(p, q) { + // Returns the squared Euclidean distance between p and q. + var dx = q[0] - p[0]; + var dy = q[1] - p[1]; + + return dx * dx + dy * dy; + } + + function nextHullPoint(points, p) { + // Returns the next point on the convex hull in CCW from p. + var q = p; + for(var r in points) { + var t = turn(p, q, points[r]); + if(t === -1 || t === 0 && euclideanDistance(p, points[r]) > euclideanDistance(p, q)) { + q = points[r]; } - // append partial right arguments - if (isPartialRight) { - unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); + } + return q; + } + + function convexHull(points) { + // implementation of the Jarvis March algorithm + // adapted from http://tixxit.wordpress.com/2009/12/09/jarvis-march/ + + if(points.length === 0) { + return []; + } else if(points.length === 1) { + return points; + } + + // Returns the points on the convex hull of points in CCW order. + var hull = [points.sort(compSort)[0]]; + + for(var p = 0; p < hull.length; p++) { + var q = nextHullPoint(points, hull[p]); + + if(q !== hull[0]) { + hull.push(q); + } + } + + return hull; + } + + function isConvex(points) { + var ltz; + + for (var i = 0; i < points.length - 3; i++) { + var p1 = points[i]; + var p2 = points[i + 1]; + var p3 = points[i + 2]; + var v = [p2[0] - p1[0], p2[1] - p1[1]]; + + // p3.x * v.y - p3.y * v.x + v.x * p1.y - v.y * p1.x + var res = p3[0] * v[1] - p3[1] * v[0] + v[0] * p1[1] - v[1] * p1[0]; + + if (i === 0) { + if (res < 0) { + ltz = true; + } else { + ltz = false; + } + } else { + if (ltz && (res > 0) || !ltz && (res < 0)) { + return false; + } + } + } + + return true; + } + + function coordinatesContainPoint(coordinates, point) { + var contains = false; + for(var i = -1, l = coordinates.length, j = l - 1; ++i < l; j = i) { + if (((coordinates[i][1] <= point[1] && point[1] < coordinates[j][1]) || + (coordinates[j][1] <= point[1] && point[1] < coordinates[i][1])) && + (point[0] < (coordinates[j][0] - coordinates[i][0]) * (point[1] - coordinates[i][1]) / (coordinates[j][1] - coordinates[i][1]) + coordinates[i][0])) { + contains = !contains; + } + } + return contains; + } + + function polygonContainsPoint(polygon, point) { + if (polygon && polygon.length) { + if (polygon.length === 1) { // polygon with no holes + return coordinatesContainPoint(polygon[0], point); + } else { // polygon with holes + if (coordinatesContainPoint(polygon[0], point)) { + for (var i = 1; i < polygon.length; i++) { + if (coordinatesContainPoint(polygon[i], point)) { + return false; // found in hole + } + } + + return true; + } else { + return false; + } } - // merge flags - bindData[1] |= bitmask; - return createWrapper.apply(null, bindData); + } else { + return false; } - // fast path for `_.bind` - var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; - return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); } - /** - * Creates compiled iteration functions. - * - * @private - * @param {...Object} [options] The compile options object(s). - * @param {string} [options.array] Code to determine if the iterable is an array or array-like. - * @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop. - * @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration. - * @param {string} [options.args] A comma separated string of iteration function arguments. - * @param {string} [options.top] Code to execute before the iteration branches. - * @param {string} [options.loop] Code to execute in the object loop. - * @param {string} [options.bottom] Code to execute after the iteration branches. - * @returns {Function} Returns the compiled function. - */ - function createIterator() { - // data properties - iteratorData.shadowedProps = shadowedProps; + function edgeIntersectsEdge(a1, a2, b1, b2) { + var ua_t = (b2[0] - b1[0]) * (a1[1] - b1[1]) - (b2[1] - b1[1]) * (a1[0] - b1[0]); + var ub_t = (a2[0] - a1[0]) * (a1[1] - b1[1]) - (a2[1] - a1[1]) * (a1[0] - b1[0]); + var u_b = (b2[1] - b1[1]) * (a2[0] - a1[0]) - (b2[0] - b1[0]) * (a2[1] - a1[1]); - // iterator options - iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = ''; - iteratorData.init = 'iterable'; - iteratorData.useHas = true; + if ( u_b !== 0 ) { + var ua = ua_t / u_b; + var ub = ub_t / u_b; - // merge options into a template data object - for (var object, index = 0; object = arguments[index]; index++) { - for (var key in object) { - iteratorData[key] = object[key]; + if ( 0 <= ua && ua <= 1 && 0 <= ub && ub <= 1 ) { + return true; } } - var args = iteratorData.args; - iteratorData.firstArg = /^[^,]+/.exec(args)[0]; - // create the function factory - var factory = Function( - 'baseCreateCallback, errorClass, errorProto, hasOwnProperty, ' + - 'indicatorObject, isArguments, isArray, isString, keys, objectProto, ' + - 'objectTypes, nonEnumProps, stringClass, stringProto, toString', - 'return function(' + args + ') {\n' + iteratorTemplate(iteratorData) + '\n}' - ); + return false; + } - // return the compiled function - return factory( - baseCreateCallback, errorClass, errorProto, hasOwnProperty, - indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto, - objectTypes, nonEnumProps, stringClass, stringProto, toString - ); + function isNumber(n) { + return !isNaN(parseFloat(n)) && isFinite(n); } - /** - * Checks if `value` is a native function. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. - */ - function isNative(value) { - return typeof value == 'function' && reNative.test(value); + function arraysIntersectArrays(a, b) { + if (isNumber(a[0][0])) { + if (isNumber(b[0][0])) { + for (var i = 0; i < a.length - 1; i++) { + for (var j = 0; j < b.length - 1; j++) { + if (edgeIntersectsEdge(a[i], a[i + 1], b[j], b[j + 1])) { + return true; + } + } + } + } else { + for (var k = 0; k < b.length; k++) { + if (arraysIntersectArrays(a, b[k])) { + return true; + } + } + } + } else { + for (var l = 0; l < a.length; l++) { + if (arraysIntersectArrays(a[l], b)) { + return true; + } + } + } + return false; } - /** - * Sets `this` binding data on a given function. - * - * @private - * @param {Function} func The function to set data on. - * @param {Array} value The data array to set. - */ - var setBindData = !defineProperty ? noop : function(func, value) { - descriptor.value = value; - defineProperty(func, '__bindData__', descriptor); - }; + /* + Internal: Returns a copy of coordinates for s closed polygon + */ + function closedPolygon(coordinates) { + var outer = [ ]; - /** - * A fallback implementation of `isPlainObject` which checks if a given value - * is an object created by the `Object` constructor, assuming objects created - * by the `Object` constructor have no inherited enumerable properties and that - * there are no `Object.prototype` extensions. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - */ - function shimIsPlainObject(value) { - var ctor, - result; + for (var i = 0; i < coordinates.length; i++) { + var inner = coordinates[i].slice(); + if (pointsEqual(inner[0], inner[inner.length - 1]) === false) { + inner.push(inner[0]); + } - // avoid non Object objects, `arguments` objects, and DOM elements - if (!(value && toString.call(value) == objectClass) || - (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) || - (!support.argsClass && isArguments(value)) || - (!support.nodeClass && isNode(value))) { - return false; + outer.push(inner); } - // IE < 9 iterates inherited properties before own properties. If the first - // iterated property is an object's own property then there are no inherited - // enumerable properties. - if (support.ownLast) { - forIn(value, function(value, key, object) { - result = hasOwnProperty.call(object, key); + + return outer; + } + + function pointsEqual(a, b) { + for (var i = 0; i < a.length; i++) { + + if (a[i] !== b[i]) { return false; - }); - return result !== false; + } } - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - forIn(value, function(value, key) { - result = key; - }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); + + return true; } - /*--------------------------------------------------------------------------*/ + function coordinatesEqual(a, b) { + if (a.length !== b.length) { + return false; + } - /** - * Checks if `value` is an `arguments` object. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. - * @example - * - * (function() { return _.isArguments(arguments); })(1, 2, 3); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - toString.call(value) == argsClass || false; + var na = a.slice().sort(compSort); + var nb = b.slice().sort(compSort); + + for (var i = 0; i < na.length; i++) { + if (na[i].length !== nb[i].length) { + return false; + } + for (var j = 0; j < na.length; j++) { + if (na[i][j] !== nb[i][j]) { + return false; + } + } + } + + return true; } - // fallback for browsers that can't detect `arguments` objects by [[Class]] - if (!support.argsClass) { - isArguments = function(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false; - }; + + /* + Internal: An array of variables that will be excluded form JSON objects. + */ + var excludeFromJSON = ["length"]; + + /* + Internal: Base GeoJSON Primitive + */ + function Primitive(geojson){ + if(geojson){ + switch (geojson.type) { + case 'Point': + return new Point(geojson); + + case 'MultiPoint': + return new MultiPoint(geojson); + + case 'LineString': + return new LineString(geojson); + + case 'MultiLineString': + return new MultiLineString(geojson); + + case 'Polygon': + return new Polygon(geojson); + + case 'MultiPolygon': + return new MultiPolygon(geojson); + + case 'Feature': + return new Feature(geojson); + + case 'FeatureCollection': + return new FeatureCollection(geojson); + + case 'GeometryCollection': + return new GeometryCollection(geojson); + + default: + throw new Error("Unknown type: " + geojson.type); + } + } } - /** - * Checks if `value` is an array. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an array, else `false`. - * @example - * - * (function() { return _.isArray(arguments); })(); - * // => false - * - * _.isArray([1, 2, 3]); - * // => true - */ - var isArray = nativeIsArray || function(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - toString.call(value) == arrayClass || false; + Primitive.prototype.toMercator = function(){ + return toMercator(this); }; - /** - * A fallback implementation of `Object.keys` which produces an array of the - * given object's own enumerable property names. - * - * @private - * @type Function - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names. - */ - var shimKeys = createIterator({ - 'args': 'object', - 'init': '[]', - 'top': 'if (!(objectTypes[typeof object])) return result', - 'loop': 'result.push(index)' - }); + Primitive.prototype.toGeographic = function(){ + return toGeographic(this); + }; - /** - * Creates an array composed of the own enumerable property names of an object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names. - * @example - * - * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); - * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) - */ - var keys = !nativeKeys ? shimKeys : function(object) { - if (!isObject(object)) { - return []; - } - if ((support.enumPrototypes && typeof object == 'function') || - (support.nonEnumArgs && object.length && isArguments(object))) { - return shimKeys(object); + Primitive.prototype.envelope = function(){ + return calculateEnvelope(this); + }; + + Primitive.prototype.bbox = function(){ + return calculateBounds(this); + }; + + Primitive.prototype.convexHull = function(){ + var coordinates = [ ], i, j; + if (this.type === 'Point') { + return null; + } else if (this.type === 'LineString' || this.type === 'MultiPoint') { + if (this.coordinates && this.coordinates.length >= 3) { + coordinates = this.coordinates; + } else { + return null; + } + } else if (this.type === 'Polygon' || this.type === 'MultiLineString') { + if (this.coordinates && this.coordinates.length > 0) { + for (i = 0; i < this.coordinates.length; i++) { + coordinates = coordinates.concat(this.coordinates[i]); + } + if(coordinates.length < 3){ + return null; + } + } else { + return null; + } + } else if (this.type === 'MultiPolygon') { + if (this.coordinates && this.coordinates.length > 0) { + for (i = 0; i < this.coordinates.length; i++) { + for (j = 0; j < this.coordinates[i].length; j++) { + coordinates = coordinates.concat(this.coordinates[i][j]); + } + } + if(coordinates.length < 3){ + return null; + } + } else { + return null; + } + } else if(this.type === "Feature"){ + var primitive = new Primitive(this.geometry); + return primitive.convexHull(); } - return nativeKeys(object); - }; - /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ - var eachIteratorOptions = { - 'args': 'collection, callback, thisArg', - 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)", - 'array': "typeof length == 'number'", - 'keys': keys, - 'loop': 'if (callback(iterable[index], index, collection) === false) return result' + return new Polygon({ + type: 'Polygon', + coordinates: closedPolygon([convexHull(coordinates)]) + }); }; - /** Reusable iterator options for `assign` and `defaults` */ - var defaultsIteratorOptions = { - 'args': 'object, source, guard', - 'top': - 'var args = arguments,\n' + - ' argsIndex = 0,\n' + - " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + - 'while (++argsIndex < argsLength) {\n' + - ' iterable = args[argsIndex];\n' + - ' if (iterable && objectTypes[typeof iterable]) {', - 'keys': keys, - 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", - 'bottom': ' }\n}' + Primitive.prototype.toJSON = function(){ + var obj = {}; + for (var key in this) { + if (this.hasOwnProperty(key) && excludeFromJSON.indexOf(key) === -1) { + obj[key] = this[key]; + } + } + obj.bbox = calculateBounds(this); + return obj; }; - /** Reusable iterator options for `forIn` and `forOwn` */ - var forOwnIteratorOptions = { - 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, - 'array': false + Primitive.prototype.contains = function(primitive){ + return new Primitive(primitive).within(this); }; - /** - * A function compiled to iterate `arguments` objects, arrays, objects, and - * strings consistenly across environments, executing the callback for each - * element in the collection. The callback is bound to `thisArg` and invoked - * with three arguments; (value, index|key, collection). Callbacks may exit - * iteration early by explicitly returning `false`. - * - * @private - * @type Function - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - */ - var baseEach = createIterator(eachIteratorOptions); + Primitive.prototype.within = function(primitive) { + var coordinates, i, contains; - /*--------------------------------------------------------------------------*/ + // if we are passed a feature, use the polygon inside instead + if (primitive.type === 'Feature') { + primitive = primitive.geometry; + } - /** - * Assigns own enumerable properties of source object(s) to the destination - * object. Subsequent sources will overwrite property assignments of previous - * sources. If a callback is provided it will be executed to produce the - * assigned values. The callback is bound to `thisArg` and invoked with two - * arguments; (objectValue, sourceValue). - * - * @static - * @memberOf _ - * @type Function - * @alias extend - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param {Function} [callback] The function to customize assigning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the destination object. - * @example - * - * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); - * // => { 'name': 'fred', 'employer': 'slate' } - * - * var defaults = _.partialRight(_.assign, function(a, b) { - * return typeof a == 'undefined' ? b : a; - * }); - * - * var object = { 'name': 'barney' }; - * defaults(object, { 'name': 'fred', 'employer': 'slate' }); - * // => { 'name': 'barney', 'employer': 'slate' } - */ - var assign = createIterator(defaultsIteratorOptions, { - 'top': - defaultsIteratorOptions.top.replace(';', - ';\n' + - "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + - ' var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + - "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + - ' callback = args[--argsLength];\n' + - '}' - ), - 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' - }); + // point.within(point) :: equality + if (primitive.type === "Point") { + if (this.type === "Point") { + return pointsEqual(this.coordinates, primitive.coordinates); - /** - * Creates a clone of `value`. If `isDeep` is `true` nested objects will also - * be cloned, otherwise they will be assigned by reference. If a callback - * is provided it will be executed to produce the cloned values. If the - * callback returns `undefined` cloning will be handled by the method instead. - * The callback is bound to `thisArg` and invoked with one argument; (value). - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to clone. - * @param {boolean} [isDeep=false] Specify a deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the cloned value. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * var shallow = _.clone(characters); - * shallow[0] === characters[0]; - * // => true - * - * var deep = _.clone(characters, true); - * deep[0] === characters[0]; - * // => false - * - * _.mixin({ - * 'clone': _.partialRight(_.clone, function(value) { - * return _.isElement(value) ? value.cloneNode(false) : undefined; - * }) - * }); - * - * var clone = _.clone(document.body); - * clone.childNodes.length; - * // => 0 - */ - function clone(value, isDeep, callback, thisArg) { - // allows working with "Collections" methods without using their `index` - // and `collection` arguments for `isDeep` and `callback` - if (typeof isDeep != 'boolean' && isDeep != null) { - thisArg = callback; - callback = isDeep; - isDeep = false; + } } - return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); - } - /** - * Iterates over own and inherited enumerable properties of an object, - * executing the callback for each property. The callback is bound to `thisArg` - * and invoked with three arguments; (value, key, object). Callbacks may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * Shape.prototype.move = function(x, y) { - * this.x += x; - * this.y += y; - * }; - * - * _.forIn(new Shape, function(value, key) { - * console.log(key); - * }); - * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) - */ - var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { - 'useHas': false - }); + // point.within(multilinestring) + if (primitive.type === "MultiLineString") { + if (this.type === "Point") { + for (i = 0; i < primitive.coordinates.length; i++) { + var linestring = { type: "LineString", coordinates: primitive.coordinates[i] }; + + if (this.within(linestring)) { + return true; + } + } + } + } + + // point.within(linestring), point.within(multipoint) + if (primitive.type === "LineString" || primitive.type === "MultiPoint") { + if (this.type === "Point") { + for (i = 0; i < primitive.coordinates.length; i++) { + if (this.coordinates.length !== primitive.coordinates[i].length) { + return false; + } + + if (pointsEqual(this.coordinates, primitive.coordinates[i])) { + return true; + } + } + } + } + + if (primitive.type === "Polygon") { + // polygon.within(polygon) + if (this.type === "Polygon") { + // check for equal polygons + if (primitive.coordinates.length === this.coordinates.length) { + for (i = 0; i < this.coordinates.length; i++) { + if (coordinatesEqual(this.coordinates[i], primitive.coordinates[i])) { + return true; + } + } + } + + if (this.coordinates.length && polygonContainsPoint(primitive.coordinates, this.coordinates[0][0])) { + return !arraysIntersectArrays(closedPolygon(this.coordinates), closedPolygon(primitive.coordinates)); + } else { + return false; + } + + // point.within(polygon) + } else if (this.type === "Point") { + return polygonContainsPoint(primitive.coordinates, this.coordinates); + + // linestring/multipoint withing polygon + } else if (this.type === "LineString" || this.type === "MultiPoint") { + if (!this.coordinates || this.coordinates.length === 0) { + return false; + } + + for (i = 0; i < this.coordinates.length; i++) { + if (polygonContainsPoint(primitive.coordinates, this.coordinates[i]) === false) { + return false; + } + } + + return true; + + // multilinestring.within(polygon) + } else if (this.type === "MultiLineString") { + for (i = 0; i < this.coordinates.length; i++) { + var ls = new LineString(this.coordinates[i]); + + if (ls.within(primitive) === false) { + contains++; + return false; + } + } + + return true; + + // multipolygon.within(polygon) + } else if (this.type === "MultiPolygon") { + for (i = 0; i < this.coordinates.length; i++) { + var p1 = new Primitive({ type: "Polygon", coordinates: this.coordinates[i] }); + + if (p1.within(primitive) === false) { + return false; + } + } + + return true; + } + + } + + if (primitive.type === "MultiPolygon") { + // point.within(multipolygon) + if (this.type === "Point") { + if (primitive.coordinates.length) { + for (i = 0; i < primitive.coordinates.length; i++) { + coordinates = primitive.coordinates[i]; + if (polygonContainsPoint(coordinates, this.coordinates) && arraysIntersectArrays([this.coordinates], primitive.coordinates) === false) { + return true; + } + } + } + + return false; + // polygon.within(multipolygon) + } else if (this.type === "Polygon") { + for (i = 0; i < this.coordinates.length; i++) { + if (primitive.coordinates[i].length === this.coordinates.length) { + for (j = 0; j < this.coordinates.length; j++) { + if (coordinatesEqual(this.coordinates[j], primitive.coordinates[i][j])) { + return true; + } + } + } + } + + if (arraysIntersectArrays(this.coordinates, primitive.coordinates) === false) { + if (primitive.coordinates.length) { + for (i = 0; i < primitive.coordinates.length; i++) { + coordinates = primitive.coordinates[i]; + if (polygonContainsPoint(coordinates, this.coordinates[0][0]) === false) { + contains = false; + } else { + contains = true; + } + } + + return contains; + } + } + + // linestring.within(multipolygon), multipoint.within(multipolygon) + } else if (this.type === "LineString" || this.type === "MultiPoint") { + for (i = 0; i < primitive.coordinates.length; i++) { + var p = { type: "Polygon", coordinates: primitive.coordinates[i] }; + + if (this.within(p)) { + return true; + } + + return false; + } + + // multilinestring.within(multipolygon) + } else if (this.type === "MultiLineString") { + for (i = 0; i < this.coordinates.length; i++) { + var lines = new LineString(this.coordinates[i]); + + if (lines.within(primitive) === false) { + return false; + } + } + + return true; + + // multipolygon.within(multipolygon) + } else if (this.type === "MultiPolygon") { + for (i = 0; i < primitive.coordinates.length; i++) { + var mpoly = { type: "Polygon", coordinates: primitive.coordinates[i] }; + + if (this.within(mpoly) === false) { + return false; + } + } + + return true; + } + } - /** - * Iterates over own enumerable properties of an object, executing the callback - * for each property. The callback is bound to `thisArg` and invoked with three - * arguments; (value, key, object). Callbacks may exit iteration early by - * explicitly returning `false`. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - * console.log(key); - * }); - * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) - */ - var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); + // default to false + return false; + }; - /** - * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a - * length of `0` and objects with no own enumerable properties are considered - * "empty". - * - * @static - * @memberOf _ - * @category Objects - * @param {Array|Object|string} value The value to inspect. - * @returns {boolean} Returns `true` if the `value` is empty, else `false`. - * @example - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({}); - * // => true - * - * _.isEmpty(''); - * // => true - */ - function isEmpty(value) { - var result = true; - if (!value) { - return result; + Primitive.prototype.intersects = function(primitive) { + // if we are passed a feature, use the polygon inside instead + if (primitive.type === 'Feature') { + primitive = primitive.geometry; } - var className = toString.call(value), - length = value.length; - if ((className == arrayClass || className == stringClass || - (support.argsClass ? className == argsClass : isArguments(value))) || - (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { - return !length; + var p = new Primitive(primitive); + if (this.within(primitive) || p.within(this)) { + return true; } - forOwn(value, function() { - return (result = false); + + + if (this.type !== 'Point' && this.type !== 'MultiPoint' && + primitive.type !== 'Point' && primitive.type !== 'MultiPoint') { + return arraysIntersectArrays(this.coordinates, primitive.coordinates); + } else if (this.type === 'Feature') { + // in the case of a Feature, use the internal primitive for intersection + var inner = new Primitive(this.geometry); + return inner.intersects(primitive); + } + + warn("Type " + this.type + " to " + primitive.type + " intersection is not supported by intersects"); + return false; + }; + + + /* + GeoJSON Point Class + new Point(); + new Point(x,y,z,wtf); + new Point([x,y,z,wtf]); + new Point([x,y]); + new Point({ + type: "Point", + coordinates: [x,y] }); - return result; - } + */ + function Point(input){ + var args = Array.prototype.slice.call(arguments); + + if(input && input.type === "Point" && input.coordinates){ + extend(this, input); + } else if(input && isArray(input)) { + this.coordinates = input; + } else if(args.length >= 2) { + this.coordinates = args; + } else { + throw "Terraformer: invalid input for Terraformer.Point"; + } - /** - * Checks if `value` is a function. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - */ - function isFunction(value) { - return typeof value == 'function'; - } - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value == 'function' && toString.call(value) == funcClass; - }; + this.type = "Point"; } - /** - * Checks if `value` is the language type of Object. - * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(1); - * // => false - */ - function isObject(value) { - // check if the value is the ECMAScript language type of Object - // http://es5.github.io/#x8 - // and avoid a V8 bug - // http://code.google.com/p/v8/issues/detail?id=2291 - return !!(value && objectTypes[typeof value]); - } + Point.prototype = new Primitive(); + Point.prototype.constructor = Point; - /** - * Checks if `value` is an object created by the `Object` constructor. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * _.isPlainObject(new Shape); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - */ - var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { - if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { - return false; + /* + GeoJSON MultiPoint Class + new MultiPoint(); + new MultiPoint([[x,y], [x1,y1]]); + new MultiPoint({ + type: "MultiPoint", + coordinates: [x,y] + }); + */ + function MultiPoint(input){ + if(input && input.type === "MultiPoint" && input.coordinates){ + extend(this, input); + } else if(isArray(input)) { + this.coordinates = input; + } else { + throw "Terraformer: invalid input for Terraformer.MultiPoint"; } - var valueOf = value.valueOf, - objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); - return objProto - ? (value == objProto || getPrototypeOf(value) == objProto) - : shimIsPlainObject(value); + this.type = "MultiPoint"; + } + + MultiPoint.prototype = new Primitive(); + MultiPoint.prototype.constructor = MultiPoint; + MultiPoint.prototype.forEach = function(func){ + for (var i = 0; i < this.coordinates.length; i++) { + func.apply(this, [this.coordinates[i], i, this.coordinates]); + } + return this; + }; + MultiPoint.prototype.addPoint = function(point){ + this.coordinates.push(point); + return this; + }; + MultiPoint.prototype.insertPoint = function(point, index){ + this.coordinates.splice(index, 0, point); + return this; + }; + MultiPoint.prototype.removePoint = function(remove){ + if(typeof remove === "number"){ + this.coordinates.splice(remove, 1); + } else { + this.coordinates.splice(this.coordinates.indexOf(remove), 1); + } + return this; + }; + MultiPoint.prototype.get = function(i){ + return new Point(this.coordinates[i]); }; - /** - * Checks if `value` is a string. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a string, else `false`. - * @example - * - * _.isString('fred'); - * // => true - */ - function isString(value) { - return typeof value == 'string' || - value && typeof value == 'object' && toString.call(value) == stringClass || false; + /* + GeoJSON LineString Class + new LineString(); + new LineString([[x,y], [x1,y1]]); + new LineString({ + type: "LineString", + coordinates: [x,y] + }); + */ + function LineString(input){ + if(input && input.type === "LineString" && input.coordinates){ + extend(this, input); + } else if(isArray(input)) { + this.coordinates = input; + } else { + throw "Terraformer: invalid input for Terraformer.LineString"; + } + + this.type = "LineString"; } - /** - * Recursively merges own enumerable properties of the source object(s), that - * don't resolve to `undefined` into the destination object. Subsequent sources - * will overwrite property assignments of previous sources. If a callback is - * provided it will be executed to produce the merged values of the destination - * and source properties. If the callback returns `undefined` merging will - * be handled by the method instead. The callback is bound to `thisArg` and - * invoked with two arguments; (objectValue, sourceValue). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param {Function} [callback] The function to customize merging properties. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the destination object. - * @example - * - * var names = { - * 'characters': [ - * { 'name': 'barney' }, - * { 'name': 'fred' } - * ] - * }; - * - * var ages = { - * 'characters': [ - * { 'age': 36 }, - * { 'age': 40 } - * ] - * }; - * - * _.merge(names, ages); - * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } - * - * var food = { - * 'fruits': ['apple'], - * 'vegetables': ['beet'] - * }; - * - * var otherFood = { - * 'fruits': ['banana'], - * 'vegetables': ['carrot'] - * }; - * - * _.merge(food, otherFood, function(a, b) { - * return _.isArray(a) ? a.concat(b) : undefined; - * }); - * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } - */ - function merge(object) { - var args = arguments, - length = 2; + LineString.prototype = new Primitive(); + LineString.prototype.constructor = LineString; + LineString.prototype.addVertex = function(point){ + this.coordinates.push(point); + return this; + }; + LineString.prototype.insertVertex = function(point, index){ + this.coordinates.splice(index, 0, point); + return this; + }; + LineString.prototype.removeVertex = function(remove){ + this.coordinates.splice(remove, 1); + return this; + }; - if (!isObject(object)) { - return object; - } - // allows working with `_.reduce` and `_.reduceRight` without using - // their `index` and `collection` arguments - if (typeof args[2] != 'number') { - length = args.length; + /* + GeoJSON MultiLineString Class + new MultiLineString(); + new MultiLineString([ [[x,y], [x1,y1]], [[x2,y2], [x3,y3]] ]); + new MultiLineString({ + type: "MultiLineString", + coordinates: [ [[x,y], [x1,y1]], [[x2,y2], [x3,y3]] ] + }); + */ + function MultiLineString(input){ + if(input && input.type === "MultiLineString" && input.coordinates){ + extend(this, input); + } else if(isArray(input)) { + this.coordinates = input; + } else { + throw "Terraformer: invalid input for Terraformer.MultiLineString"; } - if (length > 3 && typeof args[length - 2] == 'function') { - var callback = baseCreateCallback(args[--length - 1], args[length--], 2); - } else if (length > 2 && typeof args[length - 1] == 'function') { - callback = args[--length]; + + this.type = "MultiLineString"; + } + + MultiLineString.prototype = new Primitive(); + MultiLineString.prototype.constructor = MultiLineString; + MultiLineString.prototype.forEach = function(func){ + for (var i = 0; i < this.coordinates.length; i++) { + func.apply(this, [this.coordinates[i], i, this.coordinates ]); } - var sources = slice(arguments, 1, length), - index = -1, - stackA = getArray(), - stackB = getArray(); + }; + MultiLineString.prototype.get = function(i){ + return new LineString(this.coordinates[i]); + }; - while (++index < length) { - baseMerge(object, sources[index], callback, stackA, stackB); + /* + GeoJSON Polygon Class + new Polygon(); + new Polygon([ [[x,y], [x1,y1], [x2,y2]] ]); + new Polygon({ + type: "Polygon", + coordinates: [ [[x,y], [x1,y1], [x2,y2]] ] + }); + */ + function Polygon(input){ + if(input && input.type === "Polygon" && input.coordinates){ + extend(this, input); + } else if(isArray(input)) { + this.coordinates = input; + } else { + throw "Terraformer: invalid input for Terraformer.Polygon"; } - releaseArray(stackA); - releaseArray(stackB); - return object; + + this.type = "Polygon"; } - /*--------------------------------------------------------------------------*/ + Polygon.prototype = new Primitive(); + Polygon.prototype.constructor = Polygon; + Polygon.prototype.addVertex = function(point){ + this.insertVertex(point, this.coordinates[0].length - 1); + return this; + }; + Polygon.prototype.insertVertex = function(point, index){ + this.coordinates[0].splice(index, 0, point); + return this; + }; + Polygon.prototype.removeVertex = function(remove){ + this.coordinates[0].splice(remove, 1); + return this; + }; + Polygon.prototype.close = function() { + this.coordinates = closedPolygon(this.coordinates); + }; + Polygon.prototype.hasHoles = function() { + return this.coordinates.length > 1; + }; + Polygon.prototype.holes = function() { + holes = []; + if (this.hasHoles()) { + for (var i = 1; i < this.coordinates.length; i++) { + holes.push(new Polygon([this.coordinates[i]])); + } + } + return holes; + }; - /** - * Iterates over elements of a collection, executing the callback for each - * element. The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). Callbacks 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 `_.forIn` or `_.forOwn` - * may be used for object iteration. - * - * @static - * @memberOf _ - * @alias each - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); - * // => logs each number and returns '1,2,3' - * - * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - * // => logs each number and returns the object (property order is not guaranteed across environments) - */ - function forEach(collection, callback, thisArg) { - if (callback && typeof thisArg == 'undefined' && isArray(collection)) { - var index = -1, - length = collection.length; + /* + GeoJSON MultiPolygon Class + new MultiPolygon(); + new MultiPolygon([ [ [[x,y], [x1,y1]], [[x2,y2], [x3,y3]] ] ]); + new MultiPolygon({ + type: "MultiPolygon", + coordinates: [ [ [[x,y], [x1,y1]], [[x2,y2], [x3,y3]] ] ] + }); + */ + function MultiPolygon(input){ + if(input && input.type === "MultiPolygon" && input.coordinates){ + extend(this, input); + } else if(isArray(input)) { + this.coordinates = input; + } else { + throw "Terraformer: invalid input for Terraformer.MultiPolygon"; + } - while (++index < length) { - if (callback(collection[index], index, collection) === false) { - break; + this.type = "MultiPolygon"; + } + + MultiPolygon.prototype = new Primitive(); + MultiPolygon.prototype.constructor = MultiPolygon; + MultiPolygon.prototype.forEach = function(func){ + for (var i = 0; i < this.coordinates.length; i++) { + func.apply(this, [this.coordinates[i], i, this.coordinates ]); + } + }; + MultiPolygon.prototype.get = function(i){ + return new Polygon(this.coordinates[i]); + }; + MultiPolygon.prototype.close = function(){ + var outer = []; + this.forEach(function(polygon){ + outer.push(closedPolygon(polygon)); + }); + this.coordinates = outer; + return this; + }; + + /* + GeoJSON Feature Class + new Feature(); + new Feature({ + type: "Feature", + geometry: { + type: "Polygon", + coordinates: [ [ [[x,y], [x1,y1]], [[x2,y2], [x3,y3]] ] ] } - } + }); + new Feature({ + type: "Polygon", + coordinates: [ [ [[x,y], [x1,y1]], [[x2,y2], [x3,y3]] ] ] + }); + */ + function Feature(input){ + if(input && input.type === "Feature"){ + extend(this, input); + } else if(input && input.type && input.coordinates) { + this.geometry = input; } else { - baseEach(collection, callback, thisArg); + throw "Terraformer: invalid input for Terraformer.Feature"; } - return collection; + + this.type = "Feature"; } - /*--------------------------------------------------------------------------*/ + Feature.prototype = new Primitive(); + Feature.prototype.constructor = Feature; - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are all falsey. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to compact. - * @returns {Array} Returns a 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, - result = []; + /* + GeoJSON FeatureCollection Class + new FeatureCollection(); + new FeatureCollection([feature, feature1]); + new FeatureCollection({ + type: "FeatureCollection", + coordinates: [feature, feature1] + }); + */ + function FeatureCollection(input){ + if(input && input.type === "FeatureCollection" && input.features){ + extend(this, input); + } else if(isArray(input)) { + this.features = input; + } else { + throw "Terraformer: invalid input for Terraformer.FeatureCollection"; + } - while (++index < length) { - var value = array[index]; - if (value) { - result.push(value); + this.type = "FeatureCollection"; + } + + FeatureCollection.prototype = new Primitive(); + FeatureCollection.prototype.constructor = FeatureCollection; + FeatureCollection.prototype.forEach = function(func){ + for (var i = 0; i < this.features.length; i++) { + func.apply(this, [this.features[i], i, this.features]); + } + }; + FeatureCollection.prototype.get = function(id){ + var found; + this.forEach(function(feature){ + if(feature.id === id){ + found = feature; } + }); + return new Feature(found); + }; + + /* + GeoJSON GeometryCollection Class + new GeometryCollection(); + new GeometryCollection([geometry, geometry1]); + new GeometryCollection({ + type: "GeometryCollection", + coordinates: [geometry, geometry1] + }); + */ + function GeometryCollection(input){ + if(input && input.type === "GeometryCollection" && input.geometries){ + extend(this, input); + } else if(isArray(input)) { + this.geometries = input; + } else if(input.coordinates && input.type){ + this.type = "GeometryCollection"; + this.geometries = [input]; + } else { + throw "Terraformer: invalid input for Terraformer.GeometryCollection"; } - return result; + + this.type = "GeometryCollection"; } - /*--------------------------------------------------------------------------*/ + GeometryCollection.prototype = new Primitive(); + GeometryCollection.prototype.constructor = GeometryCollection; + GeometryCollection.prototype.forEach = function(func){ + for (var i = 0; i < this.geometries.length; i++) { + func.apply(this, [this.geometries[i], i, this.geometries]); + } + }; + GeometryCollection.prototype.get = function(i){ + return new Primitive(this.geometries[i]); + }; - /** - * Creates a function that, when called, invokes `func` with the `this` - * binding of `thisArg` and prepends any additional `bind` arguments to those - * provided to the bound function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to bind. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var func = function(greeting) { - * return greeting + ' ' + this.name; - * }; - * - * func = _.bind(func, { 'name': 'fred' }, 'hi'); - * func(); - * // => 'hi fred' - */ - function bind(func, thisArg) { - return arguments.length > 2 - ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) - : createWrapper(func, 1, null, null, thisArg); + function createCircle(center, radius, interpolate){ + var mercatorPosition = positionToMercator(center); + var steps = interpolate || 64; + var polygon = { + type: "Polygon", + coordinates: [[]] + }; + for(var i=1; i<=steps; i++) { + var radians = i * (360/steps) * Math.PI / 180; + polygon.coordinates[0].push([mercatorPosition[0] + radius * Math.cos(radians), mercatorPosition[1] + radius * Math.sin(radians)]); + } + polygon.coordinates = closedPolygon(polygon.coordinates); + + return toGeographic(polygon); } - /*--------------------------------------------------------------------------*/ + function Circle (center, radius, interpolate) { + var steps = interpolate || 64; + var rad = radius || 250; - /** - * This method returns the first argument provided to it. - * - * @static - * @memberOf _ - * @category Utilities - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'name': 'fred' }; - * _.identity(object) === object; - * // => true - */ - function identity(value) { - return value; - } + if(!center || center.length < 2 || !rad || !steps) { + throw new Error("Terraformer: missing parameter for Terraformer.Circle"); + } - /** - * A no-operation function. - * - * @static - * @memberOf _ - * @category Utilities - * @example - * - * var object = { 'name': 'fred' }; - * _.noop(object) === undefined; - * // => true - */ - function noop() { - // no operation performed + extend(this, new Feature({ + type: "Feature", + geometry: createCircle(center, rad, steps), + properties: { + radius: rad, + center: center, + steps: steps + } + })); } - /*--------------------------------------------------------------------------*/ + Circle.prototype = new Primitive(); + Circle.prototype.constructor = Circle; + Circle.prototype.recalculate = function(){ + this.geometry = createCircle(this.properties.center, this.properties.radius, this.properties.steps); + return this; + }; + Circle.prototype.center = function(coordinates){ + if(coordinates){ + this.properties.center = coordinates; + this.recalculate(); + } + return this.properties.center; + }; + Circle.prototype.radius = function(radius){ + if(radius){ + this.properties.radius = radius; + this.recalculate(); + } + return this.properties.radius; + }; + Circle.prototype.steps = function(steps){ + if(steps){ + this.properties.steps = steps; + this.recalculate(); + } + return this.properties.steps; + }; - lodash.assign = assign; - lodash.bind = bind; - lodash.compact = compact; - lodash.forEach = forEach; - lodash.forIn = forIn; - lodash.forOwn = forOwn; - lodash.keys = keys; - lodash.merge = merge; + Circle.prototype.toJSON = function() { + var output = Primitive.prototype.toJSON.call(this); + return output; + }; - lodash.each = forEach; - lodash.extend = assign; + exports.Primitive = Primitive; + exports.Point = Point; + exports.MultiPoint = MultiPoint; + exports.LineString = LineString; + exports.MultiLineString = MultiLineString; + exports.Polygon = Polygon; + exports.MultiPolygon = MultiPolygon; + exports.Feature = Feature; + exports.FeatureCollection = FeatureCollection; + exports.GeometryCollection = GeometryCollection; + exports.Circle = Circle; + + exports.toMercator = toMercator; + exports.toGeographic = toGeographic; + + exports.Tools = {}; + exports.Tools.positionToMercator = positionToMercator; + exports.Tools.positionToGeographic = positionToGeographic; + exports.Tools.applyConverter = applyConverter; + exports.Tools.toMercator = toMercator; + exports.Tools.toGeographic = toGeographic; + exports.Tools.createCircle = createCircle; + + exports.Tools.calculateBounds = calculateBounds; + exports.Tools.calculateEnvelope = calculateEnvelope; + + exports.Tools.coordinatesContainPoint = coordinatesContainPoint; + exports.Tools.polygonContainsPoint = polygonContainsPoint; + exports.Tools.arraysIntersectArrays = arraysIntersectArrays; + exports.Tools.coordinatesContainPoint = coordinatesContainPoint; + exports.Tools.coordinatesEqual = coordinatesEqual; + exports.Tools.convexHull = convexHull; + exports.Tools.isConvex = isConvex; + + exports.MercatorCRS = MercatorCRS; + exports.GeographicCRS = GeographicCRS; + + return exports; +})); + +},{}],47:[function(require,module,exports){ +(function (process){ +var Stream = require('stream') + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) - /*--------------------------------------------------------------------------*/ +exports = module.exports = through +through.through = through - // add functions that return unwrapped values when chaining - lodash.clone = clone; - lodash.identity = identity; - lodash.isArguments = isArguments; - lodash.isArray = isArray; - lodash.isEmpty = isEmpty; - lodash.isFunction = isFunction; - lodash.isObject = isObject; - lodash.isPlainObject = isPlainObject; - lodash.isString = isString; - lodash.noop = noop; +//create a readable writable stream. - /*--------------------------------------------------------------------------*/ +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } - /** - * The semantic version number. - * - * @static - * @memberOf _ - * @type string - */ - lodash.VERSION = '2.4.1'; + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false - /*--------------------------------------------------------------------------*/ +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) - if (freeExports && freeModule) { - // in Node.js or RingoJS - if (moduleExports) { - (freeModule.exports = lodash)._ = lodash; + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) } + } + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream } -}.call(this)); + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],13:[function(require,module,exports){ + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream + } + + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream + } + return stream +} + + +}).call(this,require('_process')) +},{"_process":12,"stream":27}],48:[function(require,module,exports){ module.exports.RADIUS = 6378137; module.exports.FLATTENING = 1/298.257223563; module.exports.POLAR_RADIUS = 6356752.3142; -},{}]},{},[5]); +},{}]},{},[33]); diff --git a/js/app.js b/js/app.js index 6bd810e..3b91391 100644 --- a/js/app.js +++ b/js/app.js @@ -1,6 +1,8 @@ const osmtogeojson = require('osmtogeojson') const util = require('util') const moment = require('moment') +const geojsonMerge = require('@mapbox/geojson-merge') +const terraformer = require('terraformer') // Initialising map @@ -34,6 +36,7 @@ $('#todate').val(moment().format('YYYY-MM-DD[T]HH:mm:ss')) // Set initial values +let prevGeojson = '' let formData = {} let overpassDataSource = { 'type': 'FeatureCollection', @@ -57,7 +60,8 @@ map.on('load', function () { function getQuery (bbox) { if (bbox) { - bbox = 'poly:"' + bbox + '"' + //bbox = 'poly:"' + bbox + '"' + bbox = bbox[1] + ',' + bbox[0] + ',' + bbox[3] + ',' + bbox[2] } else { let bounds = map.getBounds() let north = bounds['_ne'].lat @@ -215,15 +219,30 @@ function getProjDetails () { multiPolygon.coordinates.forEach(function (coords) { count++ let polygon = {'type': 'Polygon', 'coordinates': coords} - let bbox = '' - coords.forEach(function (item) { - item.forEach(function (subItem) { - bbox += subItem[1] + ' ' + subItem[0] - }) - }) + // let bbox = '' + // coords.forEach(function (item) { + // item.forEach(function (subItem) { + // bbox += subItem[1] + ' ' + subItem[0] + // }) + // }) console.log(JSON.stringify(polygon)) console.log(count) - getData(getQuery(bbox)) + let polygonTerraform = new terraformer.Primitive(polygon) + let polygonBbox = polygonTerraform.bbox() + console.log('bbox of a polygon ', polygonBbox) + let polygonUrl = getQuery(polygonBbox) + console.log(polygonUrl) + $.ajax(polygonUrl) + .done(function (data) { + let geojson = osmtogeojson(data) + var mergedStream = geojsonMerge.merge([ prevGeojson, geojson.features ]) + mergedStream.pipe(process.stdout) + console.log(mergedStream) + + }) + .fail(function () { + errorNotice('Too much data to fetch, zoom in further') + }) } ) }) @@ -243,8 +262,8 @@ $('#submit').on('click', function () { 'toDate': moment($('#todate').val()).utc().toISOString() } getProjDetails() - - //getData() + + // getData() } else { errorNotice('Zoom in further to fetch results') } From 6bd9d888973175b4ec384481ea52c6727eb987e2 Mon Sep 17 00:00:00 2001 From: Ramya Date: Mon, 8 Apr 2019 22:09:09 +0700 Subject: [PATCH 11/11] Added Website drawing --- Website | 1 + 1 file changed, 1 insertion(+) create mode 100644 Website diff --git a/Website b/Website new file mode 100644 index 0000000..a609739 --- /dev/null +++ b/Website @@ -0,0 +1 @@ +7Z1tc+MoEoB/TapuP3hKr7b8cZPMzG7VXG12cvv65YpYxGYiCRfCiT2//hoJLAnkRLElK7kllUpJbQSIfmi6AZML/yrdfmZovfo3jXFy4Tnx9sK/vvC82SyCv0KwKwV+NCsFS0biUuRWglvyHUuhI6UbEuO8kZBTmnCybgoXNMvwgjdkiDH61Ex2T5NmqWu0xIbgdoESU/oHiflKSl3HqT74CZPlShYdhfKDO7R4WDK6yWR5F55/X/yUH6dI5SXT5ysU06eayP944V8xSnl5lW6vcCKaVjVb+dynA5/u681wxrs8MIvmU9cN5/fOFM8jHE1cqahHlGxkY/xEUwySG9FmZaX5TjVU/kTSBGVwd7niaQJCFy7vacZvZSJxjxKyzOB6AbXCDASPmHECzf2j/IDTNUgXK5LEX9CObkTdcw5tqe4uV5SR75AtUmXAx4xLcrxpI8WteBLEDkgZziHNjWoQdy/6gnIu0yxokqB1Tu72FU4RW5LsknJOU5lIveknkiRXNKGsaAClXchVKB3HKrXSa5l/ShbyOkF3OLncU6JyymjRhjln9AHXsneKn/0nCsaikWsVkY+Ldv+EUpKIbvc7ZjHKkFJH2VKuJ+/byjDhkTwJdeFtTSRh+owBDc52kGSrOnpYPiI7vud9kIKnWj+aSvpXtS7kBpI8JPvucp/5vryv0NdRtkxwVeDcaZQX+WZpTktpQEyjMJQAmBni+FJoJa/3GbiovWklKnpSx17lhUavAn55/uFbbnQpaGne7E5NKpSuTfWrbpbge36wk+VrtCDZ8kuR5jqoJF9l6wjR04pwfAtyUacnMPEgo5DffVJAvSJxjLMCengLVPYbQdCakowXTRpewi80/JUDAITwXldw71b38CuSMwAxg/dDpEAOQ6d8wqJjtsB42Fa9jOeuqfaXYNTxqLPY4OJVEEwNCFJ4b8vAeRkIvTEZCExDQNJ1YdG+4Ydd8XSOEVusLBRnhEI5rKNA4c4NKAzlJ0R3sjp5BC9oPgV9JbhS9X8ECdcT18DBN3HwW9RceDc3NCecUJE/K9Nq6h9Fw64TdFNxNES3dwwNo+WS4SV4HPGt9ASgxWyXPyMQ7pgDgW8S8cuGidpQ9mDDLBtmPRtmuX4z7PGCjo6tOwuGgNkzYKYbNhEoT1K0th7uKZZtbyneR5TjR9aZGVzDXWOYIXwZ3/RWF2BjOSNYeTHOv+JdBgYSlJOIWi9xhplwdX6wduCMlCgiXqIkcAbAJDAdnBKT3UT4J4yS2Dq9Z0diPxn6EhP+IEyYfgJYiBtGv+GFDYFGoMEflQbfoOGqtBA2/rHxz7Pxj77MFPgd5+/cmTcEyeas7t4lsgHQqXZtbyfeRwAUmGt9FQx21W8EHEZd8QldAwcbD/et4a7LN0PEw6Hpxti5/ZF7fHTGAeDvefzbd+J8nlzd/jr/+sdvPwfpfyemQ3B3R7cWhBdBMHTciY0eFnkGMQ3mjg8Z7F6U++lMP8BGOjbSaUQ6ah7t1Ss90yFi9tDcHrouibZxzqnD3N5avI84Z2qOcdax7VvDYy70TM1A9sKbJuJdY/IIl8vytUsRtHOmZLVJ3UlKMnJPcDx59KT7U6aH6tQfqYkbmVtrcjbWui4XDWNNTFepI2wLlK4RKBEGIL5YWcbeNGPnDMxMxtq2JnRibEU5zdNy9m4ivFswbaB4z7mF8MO52yweMLfQvVXoOgeBwSDDqLlf4mewWEUMuLbfqbIh4EshYBgeGQIOEgHOzH0dpMB5Au+I7HLXyfZtby/eRxg4M2cEbBjYt4bHDAMjz1DwDWZtE9l24LIDV33gmh07cEWDcGyu06U4vcPMDlmnGrS9iXgfQ9bcdGHskNW3hsccsubmngu7/DoGBOecUmxdh2/5zr0BAM7iH8WZMcInSVCei+G59ChMcY0SsYl996dQxAfHmSrBX4XAdUIluN5KXZV3u/od+FEE3lN4QdfVmItj43AaYxCG2i3xIT0dWhOvaSFsUYKSMZwgTh6bdXjmVI4bAWE16nvaimXgaWFoTjdsgeVTlX6NjPxIyyjUTggpG8HICLSGdrVkspN0r7As52C93GfTw0VZg4ra150e0g5yhzDrVJAnQHLhE9ZI9sYEuTwt4a2A7Kl9SK8F2VO6UvOR+qA3EMiucw4wOxxe0ApmncAt4X8qnuC6RC+UdxV44qbBnaLWsL8zf1hsS9Ufsr9BF7anY7Ktf4E4cnsy0pGWT09ou7rNnT1vo/X0UeMYtGF6QstX+vsy0V3BHM1Uasdw7e9fjZNuc/WMeuLJd9rLGRYQcwbinwJIqLd3ND8OEGMxRM+oJ0BCJ2otZ1hAOmyp+j8FZObqeg3VyYGvRcSYdoy06LInRGaujoiq8rCQmCFttTcBrYnacHDH9C0IdYmdBDl6D/rrvpoYqhNXzrEDvR2YDidynD4H4k/nDR98xLAxHNW1DrShzp0d6QvpGRnnNBywY70ZmmMju1dx474VasadNdOVHThRP9QE+nf3B6Ym6PB9x9OpCaf+W+GmnBUfzbEOmk6IHn93xSYyJruGCbz0cs4RmLccOzIEkmGdSPcDQHIMlWouTM2LdZkL607y6fNW83HjyLCJ+7HzDJEeI4TDxAiR36yvNm81EO//4HkGzRwG4ZHD6FSbIPX1CdKeANHLURUeFhBznuEXtjQZSRKyzvGB0KxGBcrX5X/huCdbseupjzhqOtMapmUt2W8BqY+jitobzYy7316jaWZt6o3cZjOzfcB2qO2AEImv6JJmKPlYSbXNc1WaL7TYLSPa7hvmfCd3saENpweWk/bD5l+1T/ocQp/tXfVh9JmEpjI728CTdNPlYJL3NS3wVgYd99jFNH0wgNFAnwQdaNhRVT5y2IHb6n8Wlcmr/wvlf/wf \ No newline at end of file