diff --git a/Docs/Misc/TreesWithWikidata.gif b/Docs/Misc/TreesWithWikidata.gif new file mode 100644 index 000000000..32973b0f3 Binary files /dev/null and b/Docs/Misc/TreesWithWikidata.gif differ diff --git a/Logic/DetermineLayout.ts b/Logic/DetermineLayout.ts index b935481e8..90ee115f2 100644 --- a/Logic/DetermineLayout.ts +++ b/Logic/DetermineLayout.ts @@ -167,6 +167,7 @@ export default class DetermineLayout { const raw = json; json = new FixImages(DetermineLayout._knownImages).convertStrict(json, "While fixing the images") + json.enableNoteImports = json.enableNoteImports ?? false; json = new PrepareTheme(converState).convertStrict(json, "While preparing a dynamic theme") console.log("The layoutconfig is ", json) diff --git a/Logic/ImageProviders/AllImageProviders.ts b/Logic/ImageProviders/AllImageProviders.ts index 3abdc49d0..13881a177 100644 --- a/Logic/ImageProviders/AllImageProviders.ts +++ b/Logic/ImageProviders/AllImageProviders.ts @@ -19,9 +19,19 @@ export default class AllImageProviders { new GenericImageProvider( [].concat(...Imgur.defaultValuePrefix, ...WikimediaImageProvider.commonsPrefixes, ...Mapillary.valuePrefixes) ) - ] + private static providersByName= { + "imgur": Imgur.singleton, +"mapillary": Mapillary.singleton, + "wikidata": WikidataImageProvider.singleton, + "wikimedia": WikimediaImageProvider.singleton + } + + public static byName(name: string){ + return AllImageProviders.providersByName[name.toLowerCase()] + } + public static defaultKeys = [].concat(AllImageProviders.ImageAttributionSource.map(provider => provider.defaultKeyPrefixes)) diff --git a/Logic/ImageProviders/Mapillary.ts b/Logic/ImageProviders/Mapillary.ts index 1486c73a2..9d062f786 100644 --- a/Logic/ImageProviders/Mapillary.ts +++ b/Logic/ImageProviders/Mapillary.ts @@ -4,6 +4,7 @@ import Svg from "../../Svg"; import {Utils} from "../../Utils"; import {LicenseInfo} from "./LicenseInfo"; import Constants from "../../Models/Constants"; +import * as Console from "console"; export class Mapillary extends ImageProvider { @@ -12,11 +13,49 @@ export class Mapillary extends ImageProvider { public static readonly valuePrefixes = [Mapillary.valuePrefix, "http://mapillary.com", "https://mapillary.com", "http://www.mapillary.com", "https://www.mapillary.com"] defaultKeyPrefixes = ["mapillary", "image"] + /** + * Indicates that this is the same URL + * Ignores 'stp' parameter + * + * const a = "https://scontent-bru2-1.xx.fbcdn.net/m1/v/t6/An8xm5SGLt20ETziNqzhhBd8b8S5GHLiIu8N6BbyqHFohFAQoaJJPG8i5yQiSwjYmEqXSfVeoCmpiyBJICEkQK98JOB21kkJoBS8VdhYa-Ty93lBnznQyesJBtKcb32foGut2Hgt10hEMWJbE3dDgA?stp=s1024x768&ccb=10-5&oh=00_AT-ZGTXHzihoaQYBILmEiAEKR64z_IWiTlcAYq_D7Ka0-Q&oe=6278C456&_nc_sid=122ab1" + * const b = "https://scontent-bru2-1.xx.fbcdn.net/m1/v/t6/An8xm5SGLt20ETziNqzhhBd8b8S5GHLiIu8N6BbyqHFohFAQoaJJPG8i5yQiSwjYmEqXSfVeoCmpiyBJICEkQK98JOB21kkJoBS8VdhYa-Ty93lBnznQyesJBtKcb32foGut2Hgt10hEMWJbE3dDgA?stp=s256x192&ccb=10-5&oh=00_AT9BZ1Rpc9zbY_uNu92A_4gj1joiy1b6VtgtLIu_7wh9Bg&oe=6278C456&_nc_sid=122ab1" + * Mapillary.sameUrl(a, b) => true + */ + static sameUrl(a: string, b: string): boolean { + if (a === b) { + return true + } + try { +console.log("COmparing",a,b) + const aUrl = new URL(a) + const bUrl = new URL(b) + if (aUrl.host !== bUrl.host || aUrl.pathname !== bUrl.pathname) { + return false; + } + let allSame = true; + aUrl.searchParams.forEach((value, key) => { + if (key === "stp") { + // This is the key indicating the image size on mapillary; we ignore it + return + } + if (value !== bUrl.searchParams.get(key)) { + allSame = false + return + } + }) + return allSame; + + } catch (e) { + Console.debug("Could not compare ", a, "and", b, "due to", e) + } + return false; + + } + /** * Returns the correct key for API v4.0 */ private static ExtractKeyFromURL(value: string): number { - let key: string; const newApiFormat = value.match(/https?:\/\/www.mapillary.com\/app\/\?pKey=([0-9]*)/) @@ -24,6 +63,8 @@ export class Mapillary extends ImageProvider { key = newApiFormat[1] } else if (value.startsWith(Mapillary.valuePrefix)) { key = value.substring(0, value.lastIndexOf("?")).substring(value.lastIndexOf("/") + 1) + } else if (value.match("[0-9]*")) { + key = value; } const keyAsNumber = Number(key) diff --git a/Logic/Osm/Actions/ChangeTagAction.ts b/Logic/Osm/Actions/ChangeTagAction.ts index 963e8e946..c4a08f34f 100644 --- a/Logic/Osm/Actions/ChangeTagAction.ts +++ b/Logic/Osm/Actions/ChangeTagAction.ts @@ -9,7 +9,8 @@ export default class ChangeTagAction extends OsmChangeAction { private readonly _currentTags: any; private readonly _meta: { theme: string, changeType: string }; - constructor(elementId: string, tagsFilter: TagsFilter, currentTags: any, meta: { + constructor(elementId: string, + tagsFilter: TagsFilter, currentTags: any, meta: { theme: string, changeType: "answer" | "soft-delete" | "add-image" | string }) { diff --git a/Logic/State/UserRelatedState.ts b/Logic/State/UserRelatedState.ts index d18f53618..959c32f6b 100644 --- a/Logic/State/UserRelatedState.ts +++ b/Logic/State/UserRelatedState.ts @@ -53,6 +53,10 @@ export default class UserRelatedState extends ElementsState { osmConfiguration: <'osm' | 'osm-test'>this.featureSwitchApiURL.data, attemptLogin: options?.attemptLogin }) + const translationMode = this.osmConnection.GetPreference("translation-mode").map(str => str === undefined ? undefined : str === "true", [], b => b === undefined ? undefined : b+"") + + translationMode.syncWith(Locale.showLinkToWeblate) + this.isTranslator = this.osmConnection.userDetails.map(ud => { if(!ud.loggedIn){ return false; @@ -60,6 +64,7 @@ export default class UserRelatedState extends ElementsState { const name= ud.name.toLowerCase().replace(/\s+/g, '') return translators.contributors.some(c => c.contributor.toLowerCase().replace(/\s+/g, '') === name) }) + this.isTranslator.addCallbackAndRunD(ud => { if(ud){ Locale.showLinkToWeblate.setData(true) diff --git a/Models/ThemeConfig/Conversion/CreateNoteImportLayer.ts b/Models/ThemeConfig/Conversion/CreateNoteImportLayer.ts index 93dfd02ea..05c0c220c 100644 --- a/Models/ThemeConfig/Conversion/CreateNoteImportLayer.ts +++ b/Models/ThemeConfig/Conversion/CreateNoteImportLayer.ts @@ -163,6 +163,11 @@ export default class CreateNoteImportLayer extends Conversion { private readonly _state: DesugaringContext; @@ -302,11 +303,6 @@ export class ExpandRewrite extends Conversion, T[ /** * Converts a 'special' translation into a regular translation which uses parameters - * E.g. - * - * const tr = { - * "special": - * } */ export class RewriteSpecial extends DesugaringStep { constructor() { @@ -330,6 +326,11 @@ export class RewriteSpecial extends DesugaringStep { * const r = RewriteSpecial.convertIfNeeded(spec, [], "test") * r // => {"en": "{image_upload(,Add a picture to this object)}", "nl": "{image_upload(,Voeg een afbeelding toe)}" } * + * // should handle special case with a prefix and postfix + * const spec = {"special": {"type":"image_upload" }, before: {"en": "PREFIX "}, after: {"en": " POSTFIX", nl: " Achtervoegsel"} } + * const r = RewriteSpecial.convertIfNeeded(spec, [], "test") + * r // => {"en": "PREFIX {image_upload(,)} POSTFIX", "nl": "PREFIX {image_upload(,)} Achtervoegsel" } + * * // should warn for unexpected keys * const errors = [] * RewriteSpecial.convertIfNeeded({"special": {type: "image_carousel"}, "en": "xyz"}, errors, "test") // => {'*': "{image_carousel()}"} @@ -352,7 +353,7 @@ export class RewriteSpecial extends DesugaringStep { return input } - for (const wrongKey of Object.keys(input).filter(k => k !== "special")) { + for (const wrongKey of Object.keys(input).filter(k => k !== "special" && k !== "before" && k !== "after")) { errors.push(`At ${context}: Unexpected key in a special block: ${wrongKey}`) } @@ -400,6 +401,16 @@ export class RewriteSpecial extends DesugaringStep { } } + const before = Translations.T(input.before) + const after = Translations.T(input.after) + + for (const ln of Object.keys(before?.translations??{})) { + foundLanguages.add(ln) + } + for (const ln of Object.keys(after?.translations??{})) { + foundLanguages.add(ln) + } + if(foundLanguages.size === 0){ const args= argNamesList.map(nm => special[nm] ?? "").join(",") return {'*': `{${type}(${args})}` @@ -419,7 +430,9 @@ export class RewriteSpecial extends DesugaringStep { args.push(v) } } - result[ln] = `{${type}(${args.join(",")})}` + const beforeText = before?.textFor(ln) ?? "" + const afterText = after?.textFor(ln) ?? "" + result[ln] = `${beforeText}{${type}(${args.join(",")})}${afterText}` } return result } @@ -437,6 +450,13 @@ export class RewriteSpecial extends DesugaringStep { * const result = new RewriteSpecial().convert(tr,"test").result * const expected = {render: {'*': "{image_carousel(image)}"}, mappings: [{if: "other_image_key", then: {'*': "{image_carousel(other_image_key)}"}} ]} * result // => expected + * + * const tr = { + * render: {special: {type: "image_carousel", image_key: "image"}, before: {en: "Some introduction"} }, + * } + * const result = new RewriteSpecial().convert(tr,"test").result + * const expected = {render: {'en': "Some introduction{image_carousel(image)}"}} + * result // => expected */ convert(json: TagRenderingConfigJson, context: string): { result: TagRenderingConfigJson; errors?: string[]; warnings?: string[]; information?: string[] } { const errors = [] diff --git a/Models/ThemeConfig/Conversion/PrepareTheme.ts b/Models/ThemeConfig/Conversion/PrepareTheme.ts index 1d61f2a3b..f580007bf 100644 --- a/Models/ThemeConfig/Conversion/PrepareTheme.ts +++ b/Models/ThemeConfig/Conversion/PrepareTheme.ts @@ -170,7 +170,13 @@ class AddImportLayers extends DesugaringStep { super("For every layer in the 'layers'-list, create a new layer which'll import notes. (Note that priviliged layers and layers which have a geojson-source set are ignored)", ["layers"], "AddImportLayers"); } - convert(json: LayoutConfigJson, context: string): { result: LayoutConfigJson; errors: string[] } { + convert(json: LayoutConfigJson, context: string): { result: LayoutConfigJson; errors?: string[], warnings?: string[] } { + if (!(json.enableNoteImports ?? true)) { + return { + warnings: ["Not creating a note import layers for theme "+json.id+" as they are disabled"], + result: json + }; + } const errors = [] json = {...json} @@ -178,39 +184,37 @@ class AddImportLayers extends DesugaringStep { json.layers = [...json.layers] - if (json.enableNoteImports ?? true) { - const creator = new CreateNoteImportLayer() - for (let i1 = 0; i1 < allLayers.length; i1++) { - const layer = allLayers[i1]; - if (Constants.priviliged_layers.indexOf(layer.id) >= 0) { - // Priviliged layers are skipped - continue - } + const creator = new CreateNoteImportLayer() + for (let i1 = 0; i1 < allLayers.length; i1++) { + const layer = allLayers[i1]; + if (Constants.priviliged_layers.indexOf(layer.id) >= 0) { + // Priviliged layers are skipped + continue + } - if (layer.source["geoJson"] !== undefined) { - // Layer which don't get their data from OSM are skipped - continue - } + if (layer.source["geoJson"] !== undefined) { + // Layer which don't get their data from OSM are skipped + continue + } - if (layer.title === undefined || layer.name === undefined) { - // Anonymous layers and layers without popup are skipped - continue - } + if (layer.title === undefined || layer.name === undefined) { + // Anonymous layers and layers without popup are skipped + continue + } - if (layer.presets === undefined || layer.presets.length == 0) { - // A preset is needed to be able to generate a new point - continue; - } + if (layer.presets === undefined || layer.presets.length == 0) { + // A preset is needed to be able to generate a new point + continue; + } - try { + try { - const importLayerResult = creator.convert(layer, context + ".(noteimportlayer)[" + i1 + "]") - if (importLayerResult.result !== undefined) { - json.layers.push(importLayerResult.result) - } - } catch (e) { - errors.push("Could not generate an import-layer for " + layer.id + " due to " + e) + const importLayerResult = creator.convert(layer, context + ".(noteimportlayer)[" + i1 + "]") + if (importLayerResult.result !== undefined) { + json.layers.push(importLayerResult.result) } + } catch (e) { + errors.push("Could not generate an import-layer for " + layer.id + " due to " + e) } } @@ -255,6 +259,7 @@ export class AddMiniMap extends DesugaringStep { if (!translation.hasOwnProperty(key)) { continue } + const template = translation[key] const parts = SubstitutedTranslation.ExtractSpecialComponents(template) const hasMiniMap = parts.filter(part => part.special !== undefined).some(special => special.special.func.funcName === "minimap") diff --git a/Models/ThemeConfig/Json/LayoutConfigJson.ts b/Models/ThemeConfig/Json/LayoutConfigJson.ts index 2128499db..252651a4c 100644 --- a/Models/ThemeConfig/Json/LayoutConfigJson.ts +++ b/Models/ThemeConfig/Json/LayoutConfigJson.ts @@ -308,6 +308,8 @@ export interface LayoutConfigJson { /** * If true, notes will be loaded and parsed. If a note is an import (as created by the import_helper.html-tool from mapcomplete), * these notes will be shown if a relevant layer is present. + * + * Default is true for official layers and false for unofficial (sideloaded) layers */ enableNoteImports?: true | boolean; diff --git a/UI/BigComponents/CopyrightPanel.ts b/UI/BigComponents/CopyrightPanel.ts index 1b196f02b..01c2d3dd3 100644 --- a/UI/BigComponents/CopyrightPanel.ts +++ b/UI/BigComponents/CopyrightPanel.ts @@ -24,6 +24,7 @@ import ContributorCount from "../../Logic/ContributorCount"; import Img from "../Base/Img"; import {TypedTranslation} from "../i18n/Translation"; import TranslatorsPanel from "./TranslatorsPanel"; +import {MapillaryLink} from "./MapillaryLink"; export class OpenIdEditor extends VariableUiElement { constructor(state: { locationControl: UIEventSource }, iconStyle?: string, objectId?: string) { @@ -44,19 +45,6 @@ export class OpenIdEditor extends VariableUiElement { } -export class OpenMapillary extends VariableUiElement { - constructor(state: { locationControl: UIEventSource }, iconStyle?: string) { - const t = Translations.t.general.attribution - super(state.locationControl.map(location => { - const mapillaryLink = `https://www.mapillary.com/app/?focus=map&lat=${location?.lat ?? 0}&lng=${location?.lon ?? 0}&z=${Math.max((location?.zoom ?? 2) - 1, 1)}` - return new SubtleButton(Svg.mapillary_black_ui().SetStyle(iconStyle), t.openMapillary, { - url: mapillaryLink, - newTab: true - }) - })) - } -} - export class OpenJosm extends Combine { constructor(state: { osmConnection: OsmConnection, currentBounds: UIEventSource, }, iconStyle?: string) { @@ -132,7 +120,7 @@ export default class CopyrightPanel extends Combine { newTab: true }), new OpenIdEditor(state, iconStyle), - new OpenMapillary(state, iconStyle), + new MapillaryLink(state, iconStyle), new OpenJosm(state, iconStyle), new TranslatorsPanel(state, iconStyle) diff --git a/UI/BigComponents/MapillaryLink.ts b/UI/BigComponents/MapillaryLink.ts new file mode 100644 index 000000000..756e3808c --- /dev/null +++ b/UI/BigComponents/MapillaryLink.ts @@ -0,0 +1,24 @@ +import {VariableUiElement} from "../Base/VariableUIElement"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import Loc from "../../Models/Loc"; +import Translations from "../i18n/Translations"; +import {SubtleButton} from "../Base/SubtleButton"; +import Svg from "../../Svg"; +import Combine from "../Base/Combine"; +import Title from "../Base/Title"; + +export class MapillaryLink extends VariableUiElement { + constructor(state: { locationControl: UIEventSource }, iconStyle?: string) { + const t = Translations.t.general.attribution + super(state.locationControl.map(location => { + const mapillaryLink = `https://www.mapillary.com/app/?focus=map&lat=${location?.lat ?? 0}&lng=${location?.lon ?? 0}&z=${Math.max((location?.zoom ?? 2) - 1, 1)}` + return new SubtleButton(Svg.mapillary_black_ui().SetStyle(iconStyle), + new Combine([ + new Title(t.openMapillary,3), + t.mapillaryHelp]), { + url: mapillaryLink, + newTab: true + }).SetClass("flex flex-col link-no-underline") + })) + } +} \ No newline at end of file diff --git a/UI/Image/AttributedImage.ts b/UI/Image/AttributedImage.ts index 031f81ced..b4485cc26 100644 --- a/UI/Image/AttributedImage.ts +++ b/UI/Image/AttributedImage.ts @@ -1,22 +1,31 @@ import Combine from "../Base/Combine"; import Attribution from "./Attribution"; import Img from "../Base/Img"; -import {ProvidedImage} from "../../Logic/ImageProviders/ImageProvider"; +import ImageProvider, {ProvidedImage} from "../../Logic/ImageProviders/ImageProvider"; import BaseUIElement from "../BaseUIElement"; import {Mapillary} from "../../Logic/ImageProviders/Mapillary"; export class AttributedImage extends Combine { - constructor(imageInfo: ProvidedImage) { + constructor(imageInfo: { + url: string, + provider?: ImageProvider, + date?: Date + } + ) { let img: BaseUIElement; - let attr: BaseUIElement img = new Img(imageInfo.url, false, { fallbackImage: imageInfo.provider === Mapillary.singleton ? "./assets/svg/blocked.svg" : undefined }); - attr = new Attribution(imageInfo.provider.GetAttributionFor(imageInfo.url), - imageInfo.provider.SourceIcon(), - ) + + let attr: BaseUIElement = undefined + if(imageInfo.provider !== undefined){ + attr = new Attribution(imageInfo.provider?.GetAttributionFor(imageInfo.url), + imageInfo.provider?.SourceIcon(), + imageInfo.date + ) + } super([img, attr]); diff --git a/UI/Image/Attribution.ts b/UI/Image/Attribution.ts index 3db016da0..98f72950f 100644 --- a/UI/Image/Attribution.ts +++ b/UI/Image/Attribution.ts @@ -4,10 +4,11 @@ import BaseUIElement from "../BaseUIElement"; import {VariableUiElement} from "../Base/VariableUIElement"; import {UIEventSource} from "../../Logic/UIEventSource"; import {LicenseInfo} from "../../Logic/ImageProviders/LicenseInfo"; +import {FixedUiElement} from "../Base/FixedUiElement"; export default class Attribution extends VariableUiElement { - constructor(license: UIEventSource, icon: BaseUIElement) { + constructor(license: UIEventSource, icon: BaseUIElement, date?: Date) { if (license === undefined) { throw "No license source given in the attribution element" } @@ -23,7 +24,8 @@ export default class Attribution extends VariableUiElement { new Combine([ Translations.W(license?.title).SetClass("block"), Translations.W(license?.artist ?? "").SetClass("block font-bold"), - Translations.W((license?.license ?? "") === "" ? "CC0" : (license?.license ?? "")) + Translations.W((license?.license ?? "") === "" ? "CC0" : (license?.license ?? "")), + date === undefined ? undefined : new FixedUiElement(date.toLocaleDateString()) ]).SetClass("flex flex-col") ]).SetClass("flex flex-row bg-black text-white text-sm absolute bottom-0 left-0 p-0.5 pl-5 pr-3 rounded-lg no-images") diff --git a/UI/Popup/NearbyImages.ts b/UI/Popup/NearbyImages.ts new file mode 100644 index 000000000..a05fec2e3 --- /dev/null +++ b/UI/Popup/NearbyImages.ts @@ -0,0 +1,133 @@ +import Combine from "../Base/Combine"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import {SlideShow} from "../Image/SlideShow"; +import Toggle from "../Input/Toggle"; +import Loading from "../Base/Loading"; +import {AttributedImage} from "../Image/AttributedImage"; +import AllImageProviders from "../../Logic/ImageProviders/AllImageProviders"; +import Svg from "../../Svg"; +import BaseUIElement from "../BaseUIElement"; +import {InputElement} from "../Input/InputElement"; +import {VariableUiElement} from "../Base/VariableUIElement"; +import Translations from "../i18n/Translations"; +import {Mapillary} from "../../Logic/ImageProviders/Mapillary"; + +export interface P4CPicture { + pictureUrl: string, + date: number, + coordinates: { lat: number, lng: number }, + provider: "Mapillary" | string, + author, + license, + detailsUrl: string, + direction, + osmTags: object /*To copy straight into OSM!*/ + , + thumbUrl: string, + details: { + isSpherical: boolean, + } +} + + +interface NearbyImageOptions { + lon: number, + lat: number, + radius: number, + maxDaysOld?: 1095, + blacklist: UIEventSource<{url: string}[]> +} + +export default class NearbyImages extends VariableUiElement { + + constructor(options: NearbyImageOptions) { + const t = Translations.t.image.nearbyPictures + const P4C = require("../../vendor/P4C.min") + const picManager = new P4C.PicturesManager({}); + + const loadedPictures = UIEventSource.FromPromise( + picManager.startPicsRetrievalAround(new P4C.LatLng(options.lat, options.lon), options.radius, { + mindate: new Date().getTime() - (options.maxDaysOld ?? 1095) * 24 * 60 * 60 * 1000 + }) + ).map(images => { + console.log("Images are" ,images, "blacklisted is", options.blacklist.data) + images?.sort((a, b) => b.date - a.date) + return images ?.filter(i => !(options.blacklist?.data?.some(blacklisted => + Mapillary.sameUrl(i.pictureUrl, blacklisted.url))) + && i.details.isSpherical === false); + }, [options.blacklist]) + + super(loadedPictures.map(images => { + if(images === undefined){ + return new Loading(t.loading); + } + if(images.length === 0){ + return t.nothingFound.SetClass("alert block") + } + return new SlideShow(loadedPictures.map(imgs => (imgs ?? []).slice(0, 25).map(i => this.prepareElement(i)))) + })); + + } + + protected prepareElement(info: P4CPicture): BaseUIElement { + const provider = AllImageProviders.byName(info.provider); + return new AttributedImage({url: info.pictureUrl, provider}) + } + + private asAttributedImage(info: P4CPicture): AttributedImage { + const provider = AllImageProviders.byName(info.provider); + return new AttributedImage({url: info.thumbUrl, provider, date: new Date(info.date)}) + } + + protected asToggle(info:P4CPicture): Toggle { + const imgNonSelected = this.asAttributedImage(info); + const imageSelected = this.asAttributedImage(info); + + const nonSelected = new Combine([imgNonSelected]).SetClass("relative block") + const hoveringCheckmark = + new Combine([Svg.confirm_svg().SetClass("block w-24 h-24 -ml-12 -mt-12")]).SetClass("absolute left-1/2 top-1/2 w-0") + const selected = new Combine([ + imageSelected, + hoveringCheckmark, + ]).SetClass("relative block") + + return new Toggle(selected, nonSelected).SetClass("").ToggleOnClick(); + + } + +} + +export class SelectOneNearbyImage extends NearbyImages implements InputElement { + private readonly value: UIEventSource; + + constructor(options: NearbyImageOptions & {value?: UIEventSource}) { + super(options) + this.value = options.value ?? new UIEventSource(undefined); + } + + GetValue(): UIEventSource { + return this.value; + } + + IsValid(t: P4CPicture): boolean { + return false; + } + + protected prepareElement(info: P4CPicture): BaseUIElement { + const toggle = super.asToggle(info) + toggle.isEnabled.addCallback(enabled => { + if (enabled) { + this.value.setData(info) + } + }) + + this.value.addCallback(inf => { + if(inf !== info){ + toggle.isEnabled.setData(false) + } + }) + + return toggle + } + +} diff --git a/UI/Popup/SaveButton.ts b/UI/Popup/SaveButton.ts index c9b5df65c..91c03e189 100644 --- a/UI/Popup/SaveButton.ts +++ b/UI/Popup/SaveButton.ts @@ -2,10 +2,11 @@ import {UIEventSource} from "../../Logic/UIEventSource"; import Translations from "../i18n/Translations"; import {OsmConnection} from "../../Logic/Osm/OsmConnection"; import Toggle from "../Input/Toggle"; +import BaseUIElement from "../BaseUIElement"; export class SaveButton extends Toggle { - constructor(value: UIEventSource, osmConnection: OsmConnection) { + constructor(value: UIEventSource, osmConnection: OsmConnection, textEnabled ?: BaseUIElement, textDisabled ?: BaseUIElement) { if (value === undefined) { throw "No event source for savebutton, something is wrong" } @@ -17,9 +18,9 @@ export class SaveButton extends Toggle { const isSaveable = value.map(v => v !== false && (v ?? "") !== "") - const text = Translations.t.general.save - const saveEnabled = text.Clone().SetClass(`btn`); - const saveDisabled = text.Clone().SetClass(`btn btn-disabled`); + const saveEnabled = (textEnabled ?? Translations.t.general.save.Clone()).SetClass(`btn`); + const saveDisabled = (textDisabled ?? Translations.t.general.save.Clone()).SetClass(`btn btn-disabled`); + const save = new Toggle( saveEnabled, saveDisabled, diff --git a/UI/SpecialVisualizations.ts b/UI/SpecialVisualizations.ts index cf93598e9..2227934d3 100644 --- a/UI/SpecialVisualizations.ts +++ b/UI/SpecialVisualizations.ts @@ -48,6 +48,13 @@ import {TextField} from "./Input/TextField"; import Wikidata, {WikidataResponse} from "../Logic/Web/Wikidata"; import {Translation} from "./i18n/Translation"; import {AllTagsPanel} from "./AllTagsPanel"; +import NearbyImages, {P4CPicture, SelectOneNearbyImage} from "./Popup/NearbyImages"; +import Lazy from "./Base/Lazy"; +import ChangeTagAction from "../Logic/Osm/Actions/ChangeTagAction"; +import {Tag} from "../Logic/Tags/Tag"; +import {And} from "../Logic/Tags/And"; +import {SaveButton} from "./Popup/SaveButton"; +import {MapillaryLink} from "./BigComponents/MapillaryLink"; export interface SpecialVisualization { funcName: string, @@ -141,6 +148,116 @@ class CloseNoteButton implements SpecialVisualization { } +class NearbyImageVis implements SpecialVisualization { + args: { name: string; defaultValue?: string; doc: string; required?: boolean }[] = [ + + { + name: "mode", + defaultValue: "expandable", + doc: "Indicates how this component is initialized. Options are: \n\n- `open`: always show and load the pictures\n- `collapsable`: show the pictures, but a user can collapse them\n- `expandable`: shown by default; but a user can collapse them." + }, + { + name: "mapillary", + defaultValue: "true", + doc: "If 'true', includes a link to mapillary on this location." + } + ] + docs = "A component showing nearby images loaded from various online services such as Mapillary. In edit mode and when used on a feature, the user can select an image to add to the feature"; + funcName = "nearby_images"; + + constr(state: FeaturePipelineState, tagSource: UIEventSource, args: string[], guistate: DefaultGuiState): BaseUIElement { + const t = Translations.t.image.nearbyPictures + const mode: "open" | "expandable" | "collapsable" = args[0] + const feature = state.allElements.ContainingFeatures.get(tagSource.data.id) + const [lon, lat] = GeoOperations.centerpointCoordinates(feature) + const id: string = tagSource.data["id"] + const canBeEdited: boolean = !!(id?.match("(node|way|relation)/-?[0-9]+")) + const selectedImage = new UIEventSource(undefined); + + const nearby = new Lazy(() => { + const alreadyInTheImage = AllImageProviders.LoadImagesFor(tagSource) + const options = { + lon, lat, radius: 50, + value: selectedImage, + blacklist: alreadyInTheImage + }; + const slideshow = canBeEdited ? new SelectOneNearbyImage(options) : new NearbyImages(options); + return new Combine([slideshow, new MapillaryLinkVis().constr(state, tagSource, [])]) + }); + + let withEdit: BaseUIElement = nearby; + + if (canBeEdited) { + const confirmText: BaseUIElement = new SubstitutedTranslation(t.confirm, tagSource, state) + + const onSave = async () => { + console.log("Selected a picture...", selectedImage.data) + const osmTags = selectedImage.data.osmTags + const tags: Tag[] = [] + for (const key in osmTags) { + tags.push(new Tag(key, osmTags[key])) + } + await state?.changes?.applyAction( + new ChangeTagAction( + id, + new And(tags), + tagSource, + { + theme: state?.layoutToUse.id, + changeType: "link-image" + } + ) + ) + }; + + const saveButton = new SaveButton(selectedImage, state.osmConnection, confirmText, t.noImageSelected) + .onClick(onSave) + + withEdit = new Combine([ + t.hasMatchingPicture, + nearby, + saveButton + .SetClass("flex justify-end") + ]).SetClass("flex flex-col") + } + + if (mode === 'open') { + return withEdit + } + const toggleState = new UIEventSource(mode === 'collapsable') + return new Toggle( + new Combine([new Title(t.title), withEdit]), + new Title(t.browseNearby).onClick(() => toggleState.setData(true)), + toggleState + ) + } + +} + +export class MapillaryLinkVis implements SpecialVisualization { + funcName = "mapillary_link" + docs = "Adds a button to open mapillary on the specified location" + args = [{ + name: "zoom", + doc: "The startzoom of mapillary", + defaultValue: "18" + }]; + + public constr(state, tagsSource, args) { + const feat = state.allElements.ContainingFeatures.get(tagsSource.data.id); + const [lon, lat] = GeoOperations.centerpointCoordinates(feat); + let zoom = Number(args[0]) + if (isNaN(zoom)) { + zoom = 18 + } + return new MapillaryLink({ + locationControl: new UIEventSource({ + lat, lon, zoom + }) + }) + } +} + export default class SpecialVisualizations { public static specialVisualizations: SpecialVisualization[] = SpecialVisualizations.init() @@ -309,7 +426,7 @@ export default class SpecialVisualizations { example: "`{minimap()}`, `{minimap(17, id, _list_of_embedded_feature_ids_calculated_by_calculated_tag):height:10rem; border: 2px solid black}`", constr: (state, tagSource, args, _) => { - if(state === undefined){ + if (state === undefined) { return undefined } const keys = [...args] @@ -940,7 +1057,9 @@ export default class SpecialVisualizations { } return new SubstitutedTranslation(title, tagsSource, state) })) - } + }, + new NearbyImageVis(), + new MapillaryLinkVis() ] specialVisualizations.push(new AutoApplyButton(specialVisualizations)) diff --git a/UI/SubstitutedTranslation.ts b/UI/SubstitutedTranslation.ts index 8747a54c7..1391241dd 100644 --- a/UI/SubstitutedTranslation.ts +++ b/UI/SubstitutedTranslation.ts @@ -81,7 +81,7 @@ export class SubstitutedTranslation extends VariableUiElement { }[] { for (const knownSpecial of extraMappings.concat(SpecialVisualizations.specialVisualizations)) { - + // Note: the '.*?' in the regex reads as 'any character, but in a non-greedy way' const matched = template.match(`(.*){${knownSpecial.funcName}\\((.*?)\\)(:.*)?}(.*)`); if (matched != null) { diff --git a/assets/layers/etymology/etymology.json b/assets/layers/etymology/etymology.json index d14512a96..ef6181a8a 100644 --- a/assets/layers/etymology/etymology.json +++ b/assets/layers/etymology/etymology.json @@ -273,4 +273,4 @@ } } ] -} +} \ No newline at end of file diff --git a/assets/layers/note/note.json b/assets/layers/note/note.json index b757c2472..ad908d604 100644 --- a/assets/layers/note/note.json +++ b/assets/layers/note/note.json @@ -59,6 +59,18 @@ "id": "comment", "render": "{add_note_comment()}" }, + { + "id": "nearby-images", + "render": { + "before": { + "en": "

Nearby images

The pictures below are nearby geotagged images and might be helpful to handle this note." + }, + "special": { + "type": "nearby_images", + "mode": "open" + } + } + }, { "id": "report-contributor", "render": { diff --git a/assets/layers/note_import/note_import.json b/assets/layers/note_import/note_import.json deleted file mode 100644 index 72584bed5..000000000 --- a/assets/layers/note_import/note_import.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "id": "note_import", - "name": { - "en": "Possible bookcases", - "nl": "Mogelijke publieke boekenkastjes", - "de": "Mögliche Bücherschränke" - }, - "description": "Template for note note imports.", - "source": { - "osmTags": { - "and": [ - "id~*" - ] - }, - "geoJson": "https://api.openstreetmap.org/api/0.6/notes.json?closed=0&bbox={x_min},{y_min},{x_max},{y_max}", - "geoJsonZoomLevel": 12, - "maxCacheAge": 0 - }, - "minzoom": 10, - "title": { - "render": { - "en": "Possible feature", - "nl": "Mogelijk object", - "de": "Mögliches Objekt" - } - }, - "calculatedTags": [ - "_first_comment:=feat.get('comments')[0].text.toLowerCase()", - "_trigger_index:=(() => {const lines = feat.properties['_first_comment'].split('\\n'); const matchesMapCompleteURL = lines.map(l => l.match(\".*https://mapcomplete.osm.be/\\([a-zA-Z_-]+\\)\\(.html\\).*#import\")); const matchedIndexes = matchesMapCompleteURL.map((doesMatch, i) => [doesMatch !== null, i]).filter(v => v[0]).map(v => v[1]); return matchedIndexes[0] })()", - "_intro:=(() => {const lines = feat.properties['_first_comment'].split('\\n'); lines.splice(feat.get('_trigger_index')-1, lines.length); return lines.map(l => l == '' ? '
' : l).join('');})()", - "_tags:=(() => {let lines = feat.properties['_first_comment'].split('\\n').map(l => l.trim()); lines.splice(0, feat.get('_trigger_index') + 1); lines = lines.filter(l => l != ''); return lines.join(';');})()" - ], - "isShown": { - "render": "yes", - "mappings": [ - { - "if": "_trigger_index=", - "then": "no" - } - ] - }, - "titleIcons": [ - { - "render": "" - } - ], - "tagRenderings": [ - { - "id": "conversation", - "render": "{visualize_note_comments(comments,1)}" - }, - { - "id": "Intro", - "render": "{_intro}" - }, - { - "id": "import", - "render": "{import_button(public_bookcase, _tags, There might be a public bookcase here,./assets/svg/addSmall.svg,,,id)}" - }, - { - "id": "close_note_", - "render": "{close_note(Does not exist
, ./assets/svg/close.svg, id, This feature does not exist)}" - }, - { - "id": "close_note_mapped", - "render": "{close_note(Already mapped, ./assets/svg/checkmark.svg, id, Already mapped)}" - }, - { - "id": "comment", - "render": "{add_note_comment()}" - }, - { - "id": "add_image", - "render": "{add_image_to_note()}" - } - ], - "mapRendering": [ - { - "location": [ - "point", - "centroid" - ], - "icon": { - "render": "teardrop:#3333cc" - }, - "iconSize": "40,40,bottom" - } - ] -} \ No newline at end of file diff --git a/assets/svg/confirm.svg b/assets/svg/confirm.svg new file mode 100644 index 000000000..0f47a199c --- /dev/null +++ b/assets/svg/confirm.svg @@ -0,0 +1,37 @@ + + + + + + + diff --git a/assets/svg/license_info.json b/assets/svg/license_info.json index a8b9bc84e..a6c6a01c2 100644 --- a/assets/svg/license_info.json +++ b/assets/svg/license_info.json @@ -239,6 +239,14 @@ "authors": [], "sources": [] }, + { + "path": "confirm.svg", + "license": "CC0", + "authors": [ + "Pieter Vander Vennet" + ], + "sources": [] + }, { "path": "copyright.svg", "license": "CC0", @@ -1115,11 +1123,15 @@ }, { "path": "search_disable.svg", - "license": "CC0", + "license": "MIT", "authors": [ + "OOjs UI Team and other contributors", "Pieter Vander Vennet" ], - "sources": [] + "sources": [ + "https://commons.wikimedia.org/wiki/File:OOjs_UI_indicator_search-rtl.svg", + "https://phabricator.wikimedia.org/diffusion/GOJU/browse/master/AUTHORS.txt" + ] }, { "path": "send_email.svg", diff --git a/assets/tagRenderings/questions.json b/assets/tagRenderings/questions.json index 19e272e0c..81459d3b3 100644 --- a/assets/tagRenderings/questions.json +++ b/assets/tagRenderings/questions.json @@ -4,7 +4,10 @@ "id": "questions" }, "images": { - "render": "{image_carousel()}{image_upload()}" + "render": "{image_carousel()}{image_upload()}{nearby_images(expandable)}" + }, + "mapillary": { + "render": "{mapillary()}" }, "export_as_gpx": { "render": "{export_as_gpx()}" @@ -36,7 +39,25 @@ { "if": "wikipedia~*", "then": { - "*": "{wikipedia():max-height:25rem}" + "*": "{wikipedia():max-height:25rem}", + "ca": "No hi ha cap enllaça a Viquipèdia encara", + "da": "Der er endnu ikke linket til nogen Wikipedia-side", + "de": "Es wurde noch keine Wikipedia-Seite verlinkt", + "en": "No Wikipedia page has been linked yet", + "es": "Todavía no se ha enlazado una página de wikipedia", + "fil": "Wala pang kawing ng Wikipedia page", + "fr": "Pas encore de lien vers une page Wikipedia", + "hu": "Még nincs Wikipédia-oldal belinkelve", + "it": "Nessuna pagina Wikipedia è ancora stata collegata", + "ja": "ウィキペディアのページはまだリンクされていません", + "nb_NO": "Ingen Wikipedia-side lenket enda", + "nl": "Er werd nog geen Wikipedia-pagina gekoppeld", + "pl": "Link do strony Wikipedii nie został jeszcze określony", + "pt": "Ainda não foi vinculada nenhuma página da Wikipédia", + "ru": "Никакой страницы на Википедии не было прикреплено", + "sv": "Ingen Wikipedia-sida har länkats än", + "zh_Hans": "尚未有连接到的维基百科页面", + "zh_Hant": "還沒有連結到維基百科頁面" }, "hideInAnswer": true }, diff --git a/assets/themes/mapcomplete-changes/mapcomplete-changes.json b/assets/themes/mapcomplete-changes/mapcomplete-changes.json index 0a04dea61..65cc2eba6 100644 --- a/assets/themes/mapcomplete-changes/mapcomplete-changes.json +++ b/assets/themes/mapcomplete-changes/mapcomplete-changes.json @@ -1,13 +1,19 @@ { "id": "mapcomplete-changes", "title": { - "en": "Changes made with MapComplete" + "en": "Changes made with MapComplete", + "de": "Änderungen mit MapComplete", + "es": "Cambios hechos con MapComplete" }, "shortDescription": { - "en": "Shows changes made by MapComplete" + "en": "Shows changes made by MapComplete", + "de": "Zeigt Änderungen von MapComplete", + "es": "Muestra los cambios hechos por MapComplete" }, "description": { - "en": "This maps shows all the changes made with MapComplete" + "en": "This maps shows all the changes made with MapComplete", + "de": "Diese Karte zeigt alle Änderungen die mit MapComplete gemacht wurden", + "es": "Este mapa muestra todos los cambios hechos con MapComplete" }, "maintainer": "", "icon": "./assets/svg/logo.svg", @@ -22,7 +28,9 @@ { "id": "mapcomplete-changes", "name": { - "en": "Changeset centers" + "en": "Changeset centers", + "de": "Schwerpunkte von Änderungssätzen", + "es": "Centros de conjuntos de cambios" }, "minzoom": 0, "source": { @@ -36,35 +44,45 @@ ], "title": { "render": { - "en": "Changeset for {theme}" + "en": "Changeset for {theme}", + "de": "Änderungen für {theme}", + "es": "Conjunto de cambios para {theme}" } }, "description": { - "en": "Shows all MapComplete changes" + "en": "Shows all MapComplete changes", + "de": "Zeigt alle MapComplete Änderungen", + "es": "Muestra todos los cambios de MapComplete" }, "tagRenderings": [ { "id": "render_id", "render": { - "en": "Changeset {id}" + "en": "Changeset {id}", + "de": "Änderung {id}", + "es": "Conjunto de cambios {id}" } }, { "id": "contributor", "render": { - "en": "Change made by {_last_edit:contributor}" + "en": "Change made by {_last_edit:contributor}", + "de": "Änderung wurde von {_last_edit:contributor} gemacht", + "es": "Cambio hecho por {_last_edit:contributor}" } }, { "id": "theme", "render": { - "en": "Change with theme {theme}" + "en": "Change with theme {theme}", + "de": "Änderung mit Thema {theme}" }, "mappings": [ { "if": "theme~http.*", "then": { - "en": "Change with unofficial theme {theme}" + "en": "Change with unofficial theme {theme}", + "de": "Änderung mit inoffiziellem Thema {theme}" } } ] @@ -332,7 +350,8 @@ } ], "question": { - "en": "Themename contains {search}" + "en": "Themename contains {search}", + "de": "Themenname enthält {search}" } } ] @@ -348,7 +367,9 @@ } ], "question": { - "en": "Made by contributor {search}" + "en": "Made by contributor {search}", + "de": "Erstellt von {search}", + "es": "Hecho por contributor/a {search}" } } ] @@ -364,7 +385,9 @@ } ], "question": { - "en": "Not made by contributor {search}" + "en": "Not made by contributor {search}", + "de": "Nicht erstellt von {search}", + "es": "No hecho por contributor/a {search}" } } ] @@ -379,7 +402,9 @@ { "id": "link_to_more", "render": { - "en": "More statistics can be found here" + "en": "More statistics can be found here", + "de": "Weitere Statistiken finden Sie hier", + "es": "Se pueden encontrar más estadísticas aquí" } }, { diff --git a/css/index-tailwind-output.css b/css/index-tailwind-output.css index 1674145c6..a4617ee1e 100644 --- a/css/index-tailwind-output.css +++ b/css/index-tailwind-output.css @@ -773,6 +773,14 @@ video { left: 0px; } +.left-1\/2 { + left: 50%; +} + +.top-1\/2 { + top: 50%; +} + .isolate { isolation: isolate; } @@ -932,6 +940,14 @@ video { margin-right: 0.75rem; } +.-ml-12 { + margin-left: -3rem; +} + +.-mt-12 { + margin-top: -3rem; +} + .mb-0 { margin-bottom: 0px; } @@ -1436,6 +1452,11 @@ video { border-color: rgba(229, 231, 235, var(--tw-border-opacity)); } +.border-green-500 { + --tw-border-opacity: 1; + border-color: rgba(16, 185, 129, var(--tw-border-opacity)); +} + .border-opacity-50 { --tw-border-opacity: 0.5; } diff --git a/langs/en.json b/langs/en.json index 7de41d8eb..ea7b69579 100644 --- a/langs/en.json +++ b/langs/en.json @@ -89,6 +89,7 @@ "josmOpened": "JOSM is opened", "mapContributionsBy": "The current visible data has edits made by {contributors}", "mapContributionsByAndHidden": "The current visible data has edits made by {contributors} and {hiddenCount} more contributors", + "mapillaryHelp": "Mapillary is an online service which gathers street-level pictures and offers them under a free license. Contributors are allowed to use these pictures to improve OpenStreetMap", "openIssueTracker": "File a bug", "openMapillary": "Open Mapillary here", "openOsmcha": "See latest edits made with {theme}", @@ -275,6 +276,15 @@ "doDelete": "Remove image", "dontDelete": "Cancel", "isDeleted": "Deleted", + "nearbyPictures": { + "browseNearby": "Browse nearby images...", + "confirm": "The selected image shows {title()}", + "hasMatchingPicture": "Does a picture match the object? Select it below", + "loading": "Loading nearby images...", + "noImageSelected": "Select an image to link it to the object", + "nothingFound": "No nearby images found...", + "title": "Nearby pictures" + }, "pleaseLogin": "Please log in to add a picture", "respectPrivacy": "Do not photograph people nor license plates. Do not upload Google Maps, Google Streetview or other copyrighted sources.", "toBig": "Your image is too large as it is {actual_size}. Please use images of at most {max_size}", @@ -417,6 +427,7 @@ "importButton": "import_button({layerId}, _tags, I have found a {title} here - add it to the map,./assets/svg/addSmall.svg,,,id)", "importHandled": "
This feature has been handled! Thanks for your effort
", "layerName": "Possible {title}", + "nearbyImagesIntro": "

Nearby pictures

The following pictures are nearby geotagged pictures from various online services. They might help you to resolve this note.{nearby_images(open)}", "notFound": "I could not find {title} - remove it", "popupTitle": "There might be {title} here" }, diff --git a/langs/layers/de.json b/langs/layers/de.json index 27f02fe5f..60a8edba8 100644 --- a/langs/layers/de.json +++ b/langs/layers/de.json @@ -3353,12 +3353,6 @@ "render": "Notiz" } }, - "note_import": { - "name": "Mögliche Bücherschränke", - "title": { - "render": "Mögliches Objekt" - } - }, "observation_tower": { "description": "Türme zur Aussicht auf die umgebende Landschaft", "name": "Aussichtstürme", diff --git a/langs/layers/en.json b/langs/layers/en.json index 2514267e7..76b5f0e48 100644 --- a/langs/layers/en.json +++ b/langs/layers/en.json @@ -4252,6 +4252,11 @@ }, "name": "OpenStreetMap notes", "tagRenderings": { + "nearby-images": { + "render": { + "before": "

Nearby images

The pictures below are nearby geotagged images and might be helpful to handle this note." + } + }, "report-contributor": { "render": "Report {_first_user} as spam" }, @@ -4268,12 +4273,6 @@ "render": "Note" } }, - "note_import": { - "name": "Possible bookcases", - "title": { - "render": "Possible feature" - } - }, "observation_tower": { "description": "Towers with a panoramic view", "name": "Observation towers", diff --git a/langs/layers/nl.json b/langs/layers/nl.json index 47dd7a3cb..8b7be7768 100644 --- a/langs/layers/nl.json +++ b/langs/layers/nl.json @@ -4122,12 +4122,6 @@ "render": "Note" } }, - "note_import": { - "name": "Mogelijke publieke boekenkastjes", - "title": { - "render": "Mogelijk object" - } - }, "observation_tower": { "description": "Torens om van het uitzicht te genieten", "name": "Uitkijktorens", diff --git a/langs/nl.json b/langs/nl.json index 1bfdbdb3a..a9d086da8 100644 --- a/langs/nl.json +++ b/langs/nl.json @@ -333,6 +333,7 @@ "importButton": "import_button({layerId}, _tags, Ik heb hier een {title} gevonden - voeg deze toe aan de kaart...,./assets/svg/addSmall.svg,,,id)", "importHandled": "
Dit punt is afgehandeld. Bedankt om mee te helpen!
", "layerName": "Hier is misschien een {title}", + "nearbyImagesIntro": "

Afbeeldingen in de buurt

De volgende afbeeldingen zijn in de buurt gemaakt en kunnen mogelijks helpen. {nearby_images(open)}", "notFound": "Ik kon hier g{title} vinden - verwijder deze van de kaart", "popupTitle": "Is hier {title}?" }, diff --git a/langs/shared-questions/ca.json b/langs/shared-questions/ca.json index b69f0decf..52a0da4c8 100644 --- a/langs/shared-questions/ca.json +++ b/langs/shared-questions/ca.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "No hi ha cap enllaça a Viquipèdia encara" + }, "1": { "then": "No hi ha cap enllaça a Viquipèdia encara" } diff --git a/langs/shared-questions/da.json b/langs/shared-questions/da.json index 390bc0d81..f484a5fd2 100644 --- a/langs/shared-questions/da.json +++ b/langs/shared-questions/da.json @@ -94,6 +94,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Der er endnu ikke linket til nogen Wikipedia-side" + }, "1": { "then": "Der er endnu ikke linket til nogen Wikipedia-side" } diff --git a/langs/shared-questions/de.json b/langs/shared-questions/de.json index b752664b9..68cc69606 100644 --- a/langs/shared-questions/de.json +++ b/langs/shared-questions/de.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Es wurde noch keine Wikipedia-Seite verlinkt" + }, "1": { "then": "Es wurde noch keine Wikipedia-Seite verlinkt" } diff --git a/langs/shared-questions/en.json b/langs/shared-questions/en.json index 42858b62a..bfd09d4b8 100644 --- a/langs/shared-questions/en.json +++ b/langs/shared-questions/en.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "No Wikipedia page has been linked yet" + }, "1": { "then": "No Wikipedia page has been linked yet" } diff --git a/langs/shared-questions/es.json b/langs/shared-questions/es.json index 438ee688a..433eb9dc2 100644 --- a/langs/shared-questions/es.json +++ b/langs/shared-questions/es.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Todavía no se ha enlazado una página de wikipedia" + }, "1": { "then": "Todavía no se ha enlazado una página de wikipedia" } diff --git a/langs/shared-questions/fil.json b/langs/shared-questions/fil.json index 9b505b25d..2ca97e6dd 100644 --- a/langs/shared-questions/fil.json +++ b/langs/shared-questions/fil.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Wala pang kawing ng Wikipedia page" + }, "1": { "then": "Wala pang kawing ng Wikipedia page" } diff --git a/langs/shared-questions/fr.json b/langs/shared-questions/fr.json index b14771839..934599e6d 100644 --- a/langs/shared-questions/fr.json +++ b/langs/shared-questions/fr.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Pas encore de lien vers une page Wikipedia" + }, "1": { "then": "Pas encore de lien vers une page Wikipedia" } diff --git a/langs/shared-questions/hu.json b/langs/shared-questions/hu.json index 5e2572c13..ada0e744c 100644 --- a/langs/shared-questions/hu.json +++ b/langs/shared-questions/hu.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Még nincs Wikipédia-oldal belinkelve" + }, "1": { "then": "Még nincs Wikipédia-oldal belinkelve" } diff --git a/langs/shared-questions/it.json b/langs/shared-questions/it.json index af3118fb3..67e42c2ef 100644 --- a/langs/shared-questions/it.json +++ b/langs/shared-questions/it.json @@ -81,6 +81,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Nessuna pagina Wikipedia è ancora stata collegata" + }, "1": { "then": "Nessuna pagina Wikipedia è ancora stata collegata" } diff --git a/langs/shared-questions/ja.json b/langs/shared-questions/ja.json index b8f22df6a..159ab212e 100644 --- a/langs/shared-questions/ja.json +++ b/langs/shared-questions/ja.json @@ -98,6 +98,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "ウィキペディアのページはまだリンクされていません" + }, "1": { "then": "ウィキペディアのページはまだリンクされていません" } diff --git a/langs/shared-questions/nb_NO.json b/langs/shared-questions/nb_NO.json index d1491cb83..ad989dbb2 100644 --- a/langs/shared-questions/nb_NO.json +++ b/langs/shared-questions/nb_NO.json @@ -96,6 +96,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Ingen Wikipedia-side lenket enda" + }, "1": { "then": "Ingen Wikipedia-side lenket enda" } diff --git a/langs/shared-questions/nl.json b/langs/shared-questions/nl.json index 4370fb3a2..e999c1730 100644 --- a/langs/shared-questions/nl.json +++ b/langs/shared-questions/nl.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Er werd nog geen Wikipedia-pagina gekoppeld" + }, "1": { "then": "Er werd nog geen Wikipedia-pagina gekoppeld" } diff --git a/langs/shared-questions/pl.json b/langs/shared-questions/pl.json index da5e6d2fc..1c9064f37 100644 --- a/langs/shared-questions/pl.json +++ b/langs/shared-questions/pl.json @@ -98,6 +98,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Link do strony Wikipedii nie został jeszcze określony" + }, "1": { "then": "Link do strony Wikipedii nie został jeszcze określony" } diff --git a/langs/shared-questions/pt.json b/langs/shared-questions/pt.json index e942b6886..970520415 100644 --- a/langs/shared-questions/pt.json +++ b/langs/shared-questions/pt.json @@ -110,6 +110,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Ainda não foi vinculada nenhuma página da Wikipédia" + }, "1": { "then": "Ainda não foi vinculada nenhuma página da Wikipédia" } diff --git a/langs/shared-questions/ru.json b/langs/shared-questions/ru.json index 7dbe2be7c..772121ac1 100644 --- a/langs/shared-questions/ru.json +++ b/langs/shared-questions/ru.json @@ -77,6 +77,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Никакой страницы на Википедии не было прикреплено" + }, "1": { "then": "Никакой страницы на Википедии не было прикреплено" } diff --git a/langs/shared-questions/sv.json b/langs/shared-questions/sv.json index 54dd3fbe5..8b74209dc 100644 --- a/langs/shared-questions/sv.json +++ b/langs/shared-questions/sv.json @@ -98,6 +98,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "Ingen Wikipedia-sida har länkats än" + }, "1": { "then": "Ingen Wikipedia-sida har länkats än" } diff --git a/langs/shared-questions/zh_Hans.json b/langs/shared-questions/zh_Hans.json index 083e7bc4b..aef3fdbb0 100644 --- a/langs/shared-questions/zh_Hans.json +++ b/langs/shared-questions/zh_Hans.json @@ -55,6 +55,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "尚未有连接到的维基百科页面" + }, "1": { "then": "尚未有连接到的维基百科页面" } diff --git a/langs/shared-questions/zh_Hant.json b/langs/shared-questions/zh_Hant.json index 7e6fa861c..9c3bb737f 100644 --- a/langs/shared-questions/zh_Hant.json +++ b/langs/shared-questions/zh_Hant.json @@ -113,6 +113,9 @@ }, "wikipedia": { "mappings": { + "1": { + "then": "還沒有連結到維基百科頁面" + }, "1": { "then": "還沒有連結到維基百科頁面" } diff --git a/test.ts b/test.ts index 4640df0ca..815c72ddb 100644 --- a/test.ts +++ b/test.ts @@ -1,17 +1,19 @@ +import {SelectOneNearbyImage} from "./UI/Popup/NearbyImages"; +import Minimap from "./UI/Base/Minimap"; +import MinimapImplementation from "./UI/Base/MinimapImplementation"; import {VariableUiElement} from "./UI/Base/VariableUIElement"; +import Loc from "./Models/Loc"; import {UIEventSource} from "./Logic/UIEventSource"; -import Wikidata from "./Logic/Web/Wikidata"; -import Combine from "./UI/Base/Combine"; -import {FixedUiElement} from "./UI/Base/FixedUiElement"; -const result = UIEventSource.FromPromise( - Wikidata.searchAdvanced("WOlf", { - lang: "nl", - maxCount: 100, - instanceOf: 5 +MinimapImplementation.initialize() +const map = Minimap.createMiniMap({ + location: new UIEventSource({ + lon: 3.22457, + lat: 51.20876, + zoom: 18 }) -) -result.addCallbackAndRunD(r => console.log(r)) -new VariableUiElement(result.map(items =>new Combine( (items??[])?.map(i => - new FixedUiElement(JSON.stringify(i, null, " ")).SetClass("p-4 block") -)) )).SetClass("flex flex-col").AttachTo("maindiv") \ No newline at end of file +}) +map.AttachTo("extradiv") +map.SetStyle("height: 500px") + +new VariableUiElement(map.location.map( loc => new SelectOneNearbyImage( {...loc, radius: 50}))).AttachTo("maindiv") \ No newline at end of file diff --git a/test/CodeQuality.spec.ts b/test/CodeQuality.spec.ts index 33fffcb54..65b28cb99 100644 --- a/test/CodeQuality.spec.ts +++ b/test/CodeQuality.spec.ts @@ -9,7 +9,7 @@ import {exec} from "child_process"; */ function detectInCode(forbidden: string, reason: string) { - const excludedDirs = [".git", "node_modules", "dist", ".cache", ".parcel-cache", "assets"] + const excludedDirs = [".git", "node_modules", "dist", ".cache", ".parcel-cache", "assets", "vendor"] exec("grep -n \"" + forbidden + "\" -r . " + excludedDirs.map(d => "--exclude-dir=" + d).join(" "), ((error, stdout, stderr) => { if (error?.message?.startsWith("Command failed: grep")) { diff --git a/vendor/P4C.min.js b/vendor/P4C.min.js new file mode 100644 index 000000000..cf162d4a1 --- /dev/null +++ b/vendor/P4C.min.js @@ -0,0 +1,7 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.P4C=f()}}(function(){return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;iac&&(x=ac),y>ac&&(y=ac),[x,y]}var d=this.zc[zoom],f=Math.min(Math.max(Math.sin(D2R*ll[1]),-.9999),.9999),x=Math.round(d+ll[0]*this.Bc[zoom]),y=Math.round(d+.5*Math.log((1+f)/(1-f))*-this.Cc[zoom]);return x>this.Ac[zoom]&&(x=this.Ac[zoom]),y>this.Ac[zoom]&&(y=this.Ac[zoom]),[x,y]},SphericalMercator.prototype.ll=function(px,zoom){if(isFloat(zoom)){var size=this.size*Math.pow(2,zoom),bc=size/360,cc=size/(2*Math.PI),zc=size/2,g=(px[1]-zc)/-cc,lon=(px[0]-zc)/bc,lat=R2D*(2*Math.atan(Math.exp(g))-.5*Math.PI);return[lon,lat]}var g=(px[1]-this.zc[zoom])/-this.Cc[zoom],lon=(px[0]-this.zc[zoom])/this.Bc[zoom],lat=R2D*(2*Math.atan(Math.exp(g))-.5*Math.PI);return[lon,lat]},SphericalMercator.prototype.bbox=function(x,y,zoom,tms_style,srs){tms_style&&(y=Math.pow(2,zoom)-1-y);var ll=[x*this.size,(+y+1)*this.size],ur=[(+x+1)*this.size,y*this.size],bbox=this.ll(ll,zoom).concat(this.ll(ur,zoom));return"900913"===srs?this.convert(bbox,"900913"):bbox},SphericalMercator.prototype.xyz=function(bbox,zoom,tms_style,srs){"900913"===srs&&(bbox=this.convert(bbox,"WGS84"));var ll=[bbox[0],bbox[1]],ur=[bbox[2],bbox[3]],px_ll=this.px(ll,zoom),px_ur=this.px(ur,zoom),x=[Math.floor(px_ll[0]/this.size),Math.floor((px_ur[0]-1)/this.size)],y=[Math.floor(px_ur[1]/this.size),Math.floor((px_ll[1]-1)/this.size)],bounds={minX:Math.min.apply(Math,x)<0?0:Math.min.apply(Math,x),minY:Math.min.apply(Math,y)<0?0:Math.min.apply(Math,y),maxX:Math.max.apply(Math,x),maxY:Math.max.apply(Math,y)};if(tms_style){var tms={minY:Math.pow(2,zoom)-1-bounds.maxY,maxY:Math.pow(2,zoom)-1-bounds.minY};bounds.minY=tms.minY,bounds.maxY=tms.maxY}return bounds},SphericalMercator.prototype.convert=function(bbox,to){return"900913"===to?this.forward(bbox.slice(0,2)).concat(this.forward(bbox.slice(2,4))):this.inverse(bbox.slice(0,2)).concat(this.inverse(bbox.slice(2,4)))},SphericalMercator.prototype.forward=function(ll){var xy=[A*ll[0]*D2R,A*Math.log(Math.tan(.25*Math.PI+.5*ll[1]*D2R))];return xy[0]>MAXEXTENT&&(xy[0]=MAXEXTENT),xy[0]<-MAXEXTENT&&(xy[0]=-MAXEXTENT),xy[1]>MAXEXTENT&&(xy[1]=MAXEXTENT),xy[1]<-MAXEXTENT&&(xy[1]=-MAXEXTENT),xy},SphericalMercator.prototype.inverse=function(xy){return[xy[0]*R2D/A,(.5*Math.PI-2*Math.atan(Math.exp(-xy[1]/A)))*R2D]},SphericalMercator}();"undefined"!=typeof module&&"undefined"!=typeof exports&&(module.exports=exports=SphericalMercator)},{}],2:[function(_dereq_,module,exports){"use strict";function getLens(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");validLen===-1&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){for(var tmp,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen,i=0;i>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)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=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=String(encoding).toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}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||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}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){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=_dereq_("base64-js"),ieee754=_dereq_("ieee754"),isArray=_dereq_("isarray");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),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;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len,start<0&&(start=0)):start>len&&(start=len),end<0?(end+=len,end<0&&(end=0)):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?(255-this[offset]+1)*-1:this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24, +this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i=0},this._={decoder:new StringDecoder,quoting:!1,commenting:!1,field:null,nextChar:null,closingQuote:0,line:[],chunks:[],rawBuf:"",buf:"",rowDelimiterLength:this.options.rowDelimiter?Math.max.apply(Math,this.options.rowDelimiter.map(function(v){return v.length})):void 0},this},util.inherits(Parser,stream.Transform),module.exports.Parser=Parser,Parser.prototype._transform=function(chunk,encoding,callback){var err;return chunk instanceof Buffer&&(chunk=this._.decoder.write(chunk)),err=this.__write(chunk,!1),err?this.emit("error",err):callback()},Parser.prototype._flush=function(callback){var err;return err=this.__write(this._.decoder.end(),!0),err?this.emit("error",err):this._.quoting?void this.emit("error",new Error("Quoted field not terminated at line "+(this.lines+1))):this._.line.length>0&&(err=this.__push(this._.line))?callback(err):callback()},Parser.prototype.__push=function(line){var call_column_udf,columns,err,field,i,j,len,lineAsColumns,rawBuf,ref,row;if(!this.options.skip_lines_with_empty_values||""!==line.join("").trim()){if(row=null,this.options.columns===!0)return this.options.columns=line,void(rawBuf="");if("function"==typeof this.options.columns)return call_column_udf=function(fn,line){var columns,err;try{return columns=fn.call(null,line),[null,columns]}catch(error){return err=error,[err]}},ref=call_column_udf(this.options.columns,line),err=ref[0],columns=ref[1],err?err:(this.options.columns=columns,void(rawBuf=""));if(!this._.line_length&&line.length>0&&(this._.line_length=this.options.columns?this.options.columns.length:line.length),1===line.length&&""===line[0])this.empty_line_count++;else if(line.length!==this._.line_length){if(!this.options.relax_column_count)return null!=this.options.columns?Error("Number of columns on line "+this.lines+" does not match header"):Error("Number of columns is inconsistent on line "+this.lines);this.count++,this.skipped_line_count++}else this.count++;if(null!=this.options.columns){for(lineAsColumns={},i=j=0,len=line.length;jthis.options.to))return this.options.raw?(this.push({raw:this._.rawBuf,row:row}),this._.rawBuf=""):this.push(row),null}},Parser.prototype.__write=function(chars,end){var areNextCharsDelimiter,areNextCharsRowDelimiters,auto_parse,char,err,escapeIsQuote,i,isDelimiter,isEscape,isNextCharAComment,isQuote,isRowDelimiter,isRowDelimiterLength,is_float,is_int,l,ltrim,nextCharPos,ref,ref1,ref2,ref3,ref4,ref5,remainingBuffer,rowDelimiter,rtrim,wasCommenting;for(is_int=function(_this){return function(value){return"function"==typeof _this.is_int?_this.is_int(value):_this.is_int.test(value)}}(this),is_float=function(_this){return function(value){return"function"==typeof _this.is_float?_this.is_float(value):_this.is_float.test(value)}}(this),auto_parse=function(_this){return function(value){return _this.options.auto_parse?"function"==typeof _this.options.auto_parse?_this.options.auto_parse(value):(is_int(value)?value=parseInt(value):is_float(value)?value=parseFloat(value):_this.options.auto_parse_date&&(value=_this.options.auto_parse_date(value)),value):value}}(this),ltrim=this.options.trim||this.options.ltrim,rtrim=this.options.trim||this.options.rtrim,chars=this._.buf+chars,l=chars.length,i=0,0===this.lines&&65279===chars.charCodeAt(0)&&i++;il||!this._.commenting&&l-ii+1?chars.charAt(i+1):"",this.options.raw&&(this._.rawBuf+=char),null==this.options.rowDelimiter&&(nextCharPos=i,rowDelimiter=null,this._.quoting||"\n"!==char&&"\r"!==char?!this._.quoting||char!==this.options.quote||"\n"!==(ref=this._.nextChar)&&"\r"!==ref||(rowDelimiter=this._.nextChar,nextCharPos+=2,this.raw&&(rawBuf+=this._.nextChar)):(rowDelimiter=char,nextCharPos+=1),rowDelimiter&&("\r"===rowDelimiter&&"\n"===chars.charAt(nextCharPos)&&(rowDelimiter+="\n"),this.options.rowDelimiter=[rowDelimiter],this._.rowDelimiterLength=rowDelimiter.length)),this._.commenting||char!==this.options.escape||(escapeIsQuote=this.options.escape===this.options.quote,isEscape=this._.nextChar===this.options.escape,isQuote=this._.nextChar===this.options.quote,escapeIsQuote&&null==this._.field&&!this._.quoting||!isEscape&&!isQuote)){if(!this._.commenting&&char===this.options.quote)if(this._.quoting){if(areNextCharsRowDelimiters=this.options.rowDelimiter&&this.options.rowDelimiter.some(function(rd){return chars.substr(i+1,rd.length)===rd}),areNextCharsDelimiter=chars.substr(i+1,this.options.delimiter.length)===this.options.delimiter,isNextCharAComment=this._.nextChar===this.options.comment,!this._.nextChar||areNextCharsRowDelimiters||areNextCharsDelimiter||isNextCharAComment){this._.quoting=!1,this._.closingQuote=this.options.quote.length,i++,end&&i===l&&(this._.line.push(auto_parse(this._.field||"")),this._.field=null);continue}if(!this.options.relax)return Error("Invalid closing quote at line "+(this.lines+1)+"; found "+JSON.stringify(this._.nextChar)+" instead of delimiter "+JSON.stringify(this.options.delimiter));this._.quoting=!1,this._.field&&(this._.field=""+this.options.quote+this._.field)}else{if(!this._.field){this._.quoting=!0,i++;continue}if(null!=this._.field&&!this.options.relax)return Error("Invalid opening quote at line "+(this.lines+1))}if(isRowDelimiter=this.options.rowDelimiter&&this.options.rowDelimiter.some(function(rd){return chars.substr(i,rd.length)===rd}),(isRowDelimiter||end&&i===l-1)&&this.lines++,wasCommenting=!1,this._.commenting||this._.quoting||!this.options.comment||chars.substr(i,this.options.comment.length)!==this.options.comment?this._.commenting&&isRowDelimiter&&(wasCommenting=!0,this._.commenting=!1):this._.commenting=!0,isDelimiter=chars.substr(i,this.options.delimiter.length)===this.options.delimiter,this._.commenting||this._.quoting||!isDelimiter&&!isRowDelimiter)this._.commenting||this._.quoting||" "!==char&&"\t"!==char?this._.commenting?i++:(null==this._.field&&(this._.field=""),this._.field+=char,i++):(null==this._.field&&(this._.field=""),ltrim&&!this._.field||(this._.field+=char),i++);else{if(isRowDelimiter&&(isRowDelimiterLength=this.options.rowDelimiter.filter(function(rd){return chars.substr(i,rd.length)===rd})[0].length),isRowDelimiter&&0===this._.line.length&&null==this._.field&&(wasCommenting||this.options.skip_empty_lines)){i+=isRowDelimiterLength,this._.nextChar=chars.charAt(i);continue}if(rtrim&&(this._.closingQuote||(this._.field=null!=(ref1=this._.field)?ref1.trimRight():void 0)),this._.line.push(auto_parse(this._.field||"")),this._.closingQuote=0,this._.field=null,isDelimiter&&(i+=this.options.delimiter.length,this._.nextChar=chars.charAt(i),end&&!this._.nextChar&&(isRowDelimiter=!0,this._.line.push(""))),isRowDelimiter){if(err=this.__push(this._.line))return err;this._.line=[],i+=isRowDelimiterLength,this._.nextChar=chars.charAt(i);continue}}if(!this._.commenting&&(null!=(ref2=this._.field)?ref2.length:void 0)>this.options.max_limit_on_data_read)return Error("Field exceeds max_limit_on_data_read setting ("+this.options.max_limit_on_data_read+") "+JSON.stringify(this.options.delimiter));if(!this._.commenting&&(null!=(ref3=this._.line)?ref3.length:void 0)>this.options.max_limit_on_data_read)return Error("Row delimiter not found in the file "+JSON.stringify(this.options.rowDelimiter))}else i++,char=this._.nextChar,this._.nextChar=chars.charAt(i+1),null==this._.field&&(this._.field=""),this._.field+=char,this.options.raw&&(this._.rawBuf+=char),i++;if(end){if(null!=this._.field&&(rtrim&&(this._.closingQuote||(this._.field=null!=(ref4=this._.field)?ref4.trimRight():void 0)),this._.line.push(auto_parse(this._.field||"")),this._.field=null),(null!=(ref5=this._.field)?ref5.length:void 0)>this.options.max_limit_on_data_read)return Error("Delimiter not found in the file "+JSON.stringify(this.options.delimiter));if(0===l&&this.lines++,this._.line.length>this.options.max_limit_on_data_read)return Error("Row delimiter not found in the file "+JSON.stringify(this.options.rowDelimiter))}return this._.buf=chars.substr(i),null},isObjLiteral=function(_obj){var _test;return _test=_obj,"object"==typeof _obj&&null!==_obj&&!Array.isArray(_obj)&&function(){for(;;)if(null===Object.getPrototypeOf(_test=Object.getPrototypeOf(_test)))break;return Object.getPrototypeOf(_obj===_test)}()}}).call(this,_dereq_("_process"),_dereq_("buffer").Buffer)},{_process:18,buffer:4,stream:34,string_decoder:35,util:39}],7:[function(_dereq_,module,exports){(function(Buffer){var StringDecoder,parse;StringDecoder=_dereq_("string_decoder").StringDecoder,parse=_dereq_("./index"),module.exports=function(data,options){var decoder,err,parser,records;if(null==options&&(options={}),records=options.objname?{}:[],data instanceof Buffer&&(decoder=new StringDecoder,data=decoder.write(data)),parser=new parse.Parser(options),parser.push=function(record){return options.objname?records[record[0]]=record[1]:records.push(record)},err=parser.__write(data,!1))throw err;if(data instanceof Buffer&&(err=parser.__write(data.end(),!0)))throw err;return parser._flush(function(){}),records}}).call(this,_dereq_("buffer").Buffer)},{"./index":6,buffer:4,string_decoder:35}],8:[function(_dereq_,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],9:[function(_dereq_,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],10:[function(_dereq_,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],11:[function(_dereq_,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],12:[function(_dereq_,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],13:[function(_dereq_,module,exports){"use strict";function kdbush(points,getX,getY,nodeSize,ArrayType){return new KDBush(points,getX,getY,nodeSize,ArrayType)}function KDBush(points,getX,getY,nodeSize,ArrayType){getX=getX||defaultGetX,getY=getY||defaultGetY,ArrayType=ArrayType||Array,this.nodeSize=nodeSize||64,this.points=points,this.ids=new ArrayType(points.length),this.coords=new ArrayType(2*points.length);for(var i=0;i=minX&&x<=maxX&&y>=minY&&y<=maxY&&result.push(ids[i]);else{var m=Math.floor((left+right)/2);x=coords[2*m],y=coords[2*m+1],x>=minX&&x<=maxX&&y>=minY&&y<=maxY&&result.push(ids[m]);var nextAxis=(axis+1)%2;(0===axis?minX<=x:minY<=y)&&(stack.push(left),stack.push(m-1),stack.push(nextAxis)),(0===axis?maxX>=x:maxY>=y)&&(stack.push(m+1),stack.push(right),stack.push(nextAxis))}}return result}module.exports=range},{}],15:[function(_dereq_,module,exports){"use strict";function sortKD(ids,coords,nodeSize,left,right,depth){if(!(right-left<=nodeSize)){var m=Math.floor((left+right)/2);select(ids,coords,m,left,right,depth%2),sortKD(ids,coords,nodeSize,left,m-1,depth+1),sortKD(ids,coords,nodeSize,m+1,right,depth+1)}}function select(ids,coords,k,left,right,inc){for(;right>left;){if(right-left>600){var n=right-left+1,m=k-left+1,z=Math.log(n),s=.5*Math.exp(2*z/3),sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1),newLeft=Math.max(left,Math.floor(k-m*s/n+sd)),newRight=Math.min(right,Math.floor(k+(n-m)*s/n+sd));select(ids,coords,k,newLeft,newRight,inc)}var t=coords[2*k+inc],i=left,j=right;for(swapItem(ids,coords,left,k),coords[2*right+inc]>t&&swapItem(ids,coords,left,right);it;)j--}coords[2*left+inc]===t?swapItem(ids,coords,left,j):(j++,swapItem(ids,coords,j,right)),j<=k&&(left=j+1),k<=j&&(right=j-1)}}function swapItem(ids,coords,i,j){swap(ids,i,j),swap(coords,2*i,2*j),swap(coords,2*i+1,2*j+1)}function swap(arr,i,j){var tmp=arr[i];arr[i]=arr[j],arr[j]=tmp}module.exports=sortKD},{}],16:[function(_dereq_,module,exports){"use strict";function within(ids,coords,qx,qy,r,nodeSize){for(var stack=[0,ids.length-1,0],result=[],r2=r*r;stack.length;){var axis=stack.pop(),right=stack.pop(),left=stack.pop();if(right-left<=nodeSize)for(var i=left;i<=right;i++)sqDist(coords[2*i],coords[2*i+1],qx,qy)<=r2&&result.push(ids[i]);else{var m=Math.floor((left+right)/2),x=coords[2*m],y=coords[2*m+1];sqDist(x,y,qx,qy)<=r2&&result.push(ids[m]);var nextAxis=(axis+1)%2;(0===axis?qx-r<=x:qy-r<=y)&&(stack.push(left),stack.push(m-1),stack.push(nextAxis)),(0===axis?qx+r>=x:qy+r>=y)&&(stack.push(m+1),stack.push(right),stack.push(nextAxis))}}return result}function sqDist(ax,ay,bx,by){var dx=ax-bx,dy=ay-by;return dx*dx+dy*dy}module.exports=within},{}],17:[function(_dereq_,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0?("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?pna.nextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,pna.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,pna.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&unpipeInfo.hasUnpiped===!1&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?pna.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:pna.nextTick;Writable.WritableState=WritableState;var util=_dereq_("core-util-is");util.inherits=_dereq_("inherits");var internalUtil={deprecate:_dereq_("util-deprecate")},Stream=_dereq_("./internal/streams/stream"),Buffer=_dereq_("safe-buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=_dereq_("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||this===Writable&&(object&&object._writableState instanceof WritableState)}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding, +this},Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,_dereq_("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},_dereq_("timers").setImmediate)},{"./_stream_duplex":20,"./internal/streams/destroy":26,"./internal/streams/stream":27,_process:18,"core-util-is":5,inherits:10,"process-nextick-args":17,"safe-buffer":33,timers:36,"util-deprecate":37}],25:[function(_dereq_,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=_dereq_("safe-buffer").Buffer,util=_dereq_("util");module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}(),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":33,util:3}],26:[function(_dereq_,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||pna.nextTick(emitErrorNT,this,err),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(pna.nextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)}),this)}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var pna=_dereq_("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":17}],27:[function(_dereq_,module,exports){module.exports=_dereq_("events").EventEmitter},{events:8}],28:[function(_dereq_,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)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;enc=(""+enc).toLowerCase(),retried=!0}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}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:return this.write=simpleWrite,void(this.end=simpleEnd)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){return byte<=127?0:byte>>5===6?2:byte>>4===14?3:byte>>3===30?4:byte>>6===2?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0))}function utf8CheckExtraBytes(self,buf,p){if(128!==(192&buf[0]))return self.lastNeed=0,"�";if(self.lastNeed>1&&buf.length>1){if(128!==(192&buf[1]))return self.lastNeed=1,"�";if(self.lastNeed>2&&buf.length>2&&128!==(192&buf[2]))return self.lastNeed=2,"�"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}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);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�":r}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>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}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 base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=_dereq_("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,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!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:4}],36:[function(_dereq_,module,exports){(function(setImmediate,clearImmediate){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var nextTick=_dereq_("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)},{"process/browser.js":18,timers:36}],37:[function(_dereq_,module,exports){(function(global){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],38:[function(_dereq_,module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],39:[function(_dereq_,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){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)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}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")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;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}}),x=args[i];i=0?k=n:(k=len+n,k<0&&(k=0));for(var currentElement;k=0;)this.eventListeners[event].splice(this.eventListeners[event].indexOf(handler),1);return this}},{key:"fire",value:function(event,data){if(void 0!==this.eventListeners[event]){var _iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_loop=function(){var f=_step.value;setTimeout(function(){f(data)},0)},_iterator=this.eventListeners[event][Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0)_loop()}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}}return this}}]),EventLauncher}();module.exports=EventLauncher},{}],43:[function(_dereq_,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=0)&&(null==options.ignorefetchers||options.ignorefetchers.indexOf(fId)<0)&&promises.push(_this2.fetchers[fId].requestPictures(boundingBox,options).then(function(p){return _this2.fire("fetcherdone",fId),p},function(e){_this2.fire("fetcherfailed",fId),console.log(e)}))};for(var fId in this.fetchers)_loop(fId);if(0==promises.length)throw new Error("ctrl.picturesmanager.picsretrieval.nofetchersused");return Promise.all(promises).then(function(values){var prev=null,result=values.filter(function(a){return null!==a&&void 0!==a});return result.length>0&&(result=result.reduce(function(a,b){return a.concat(b)}).sort(function(a,b){return b.date-a.date}).filter(function(a){if(void 0==a)return!1;if(boundingBox.contains(a.coordinates)){if(null!=prev){var looklike=a.lookAlike(prev);return looklike||(prev=a),!looklike}return prev=a,!0}return!1})),result})}},{key:"startPicsRetrievalAround",value:function(center,radius,options){var _this3=this,deg2rad=function(deg){return deg*Math.PI/180},rad2deg=function(rad){return 180*rad/Math.PI},latRad=deg2rad(center.lat),radiusOnLat=Math.cos(latRad)*EARTH_RADIUS,deltaLat=rad2deg(radius/EARTH_RADIUS),deltaLon=rad2deg(radius/radiusOnLat),bbox=new LatLngBounds(new LatLng(center.lat-deltaLat,center.lng-deltaLon),new LatLng(center.lat+deltaLat,center.lng+deltaLon)),angle=options.cameraAngle&&!isNaN(options.cameraAngle)?parseInt(options.cameraAngle):DEFAULT_CAMERA_ANGLE;return options.towardscenter?this.startPicsRetrieval(bbox,options).then(function(pictures){return pictures.filter(function(p){return p.details.isSpherical||!isNaN(p.direction)&&_this3._canBeSeen(p.coordinates,center,p.direction,angle)})}):this.startPicsRetrieval(bbox,options)}},{key:"startSummaryRetrieval",value:function(boundingBox,options){var _this4=this;options=Object.assign({mindate:null,maxdate:null,usefetchers:null,ignorefetchers:null},this.options,options),options.usefetchers&&options.ignorefetchers&&(options.ignorefetchers=null);var promises=[],_loop2=function(fId){(null==options.usefetchers||options.usefetchers.indexOf(fId)>=0)&&(null==options.ignorefetchers||options.ignorefetchers.indexOf(fId)<0)&&promises.push(_this4.fetchers[fId].requestSummary(boundingBox,options).then(function(s){return _this4.fire("fetcherdone",fId),s},function(e){_this4.fire("fetcherfailed",fId),console.log(e)}))};for(var fId in this.fetchers)_loop2(fId);return Promise.all(promises).then(function(values){values=values.filter(function(v){return null!=v});var result={last:0,amount:0,approxAmount:!1};for(var s in values)values[s].last>result.last&&(result.last=values[s].last),result.approxAmount=result.approxAmount||">"==values[s].amount.charAt(0),result.amount+=parseInt(values[s].amount.substring(1));return result})}},{key:"startDetectionsRetrieval",value:function(boundingBox,options){var _this5=this;options=Object.assign({types:[],usefetchers:null,ignorefetchers:null},this.options,options),options.usefetchers&&options.ignorefetchers&&(options.ignorefetchers=null),null===options.usefetchers&&null===options.ignorefetchers&&(options.usefetchers=["mapillary"]);var promises=[],_loop3=function(fId){(null==options.usefetchers||options.usefetchers.indexOf(fId)>=0)&&(null==options.ignorefetchers||options.ignorefetchers.indexOf(fId)<0)&&promises.push(_this5.fetchers[fId].requestDetections(boundingBox,options).then(function(p){return _this5.fire("fetcherdone",fId),p},function(e){_this5.fire("fetcherfailed",fId),console.log(e)}))};for(var fId in this.fetchers)_loop3(fId);if(0==promises.length)throw new Error("ctrl.picturesmanager.detectionsretrieval.nofetchersused");return Promise.all(promises).then(function(values){var result=values.filter(function(a){return null!==a&&void 0!==a});return result.length>0&&(result=result.reduce(function(a,b){return a.concat(b)}).sort(function(a,b){return b.date-a.date}).filter(function(a){return void 0!=a&&!!boundingBox.contains(a.coordinates)})),options.asgeojson?{type:"FeatureCollection",features:result.map(function(f){return{type:"Feature",geometry:{type:"Point",coordinates:[f.coordinates.lng,f.coordinates.lat]},properties:Object.assign({},Detection.TYPE_DETAILS[f.type].osmTags,{"source:geometry":(_this5.fetchers[f.provider].name||f.provider)+" "+new Date(f.date).toISOString().split("T")[0]})}})}:result})}},{key:"getPicturesFromTags",value:function(tags){var _ref,_this6=this;return(_ref=[]).concat.apply(_ref,_toConsumableArray(Object.keys(this.fetchers).filter(function(k){return"flickr"!=k}).map(function(k){return _this6.fetchers[k].tagsToPictures(tags)})))}},{key:"_canBeSeen",value:function(start,end,startDirection,startOpening){var minDir=startDirection-startOpening/2;minDir<0&&(minDir+=360);var maxDir=startDirection+startOpening/2;maxDir<0&&(maxDir+=360);var dist=Math.sqrt(Math.pow(end.lat-start.lat,2)+Math.pow(end.lng-start.lng,2)),minCoord=new LatLng(dist*Math.cos(deg2rad(minDir))+start.lat,dist*Math.sin(deg2rad(minDir))+start.lng),maxCoord=new LatLng(dist*Math.cos(deg2rad(maxDir))+start.lat,dist*Math.sin(deg2rad(maxDir))+start.lng),bounds=new LatLngBounds(minCoord,maxCoord);return start.lat===end.lat?Math.abs(end.lng-minCoord.lng)<=dist&&bounds.getSouth()end.lat:start.lng===end.lng?Math.abs(end.lat-minCoord.lat)<=dist&&bounds.getWest()end.lng:bounds.contains(end)}}]),PicturesManager}(EventLauncher);module.exports=PicturesManager},{"../model/Detection":50,"../model/LatLng":51,"../model/LatLngBounds":52,"./EventLauncher":42,"./fetchers/CSV":45,"./fetchers/Flickr":46,"./fetchers/Mapillary":47,"./fetchers/OpenStreetCam":48,"./fetchers/WikiCommons":49}],45:[function(_dereq_,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var _createClass=function(){function defineProperties(target,props){for(var i=0;i0))throw new Error("ctrl.fetchers.csv.invalidcsvurl");return _this.csvURL=csv,_this.options=Object.assign({bbox:null,license:"Unknown license",user:"Unknown user"},options),_this.csv=null,_this.tree=null,_this.isDownloading=!1,_this}return _inherits(CSV,_Fetcher),_createClass(CSV,[{key:"requestPictures",value:function(boundingBox,options){var _this2=this;return new Promise(function(resolve,reject){options=options||{};var bbox=new LatLngBounds(boundingBox.getSouthWest().wrap(),boundingBox.getNorthEast().wrap());null===_this2.options.bbox||_this2.options.bbox.intersects(bbox)?_this2.getCSV().then(function(){var result=_this2.tree.range(bbox.getWest(),bbox.getSouth(),bbox.getEast(),bbox.getNorth()).map(function(id){return _this2.csv[id]}).filter(function(p){return(null==options.mindate||options.mindate<=1e3*p.timestamp)&&(null==options.maxdate||options.maxdate>=1e3*p.timestamp)}).map(function(p){return new Picture(p.picture_url,1e3*p.timestamp,new LatLng(p.latitude,p.longitude),_this2.name,p.user||_this2.options.user,p.license||_this2.options.license,p.details_url||p.picture_url,isNaN(p.direction)?null:parseInt(p.direction),{image:p.picture_url})});resolve(result)}).catch(reject):resolve([])})}},{key:"requestSummary",value:function(boundingBox,options){var _this3=this;return new Promise(function(resolve,reject){options=options||{};var bbox=new LatLngBounds(boundingBox.getSouthWest().wrap(),boundingBox.getNorthEast().wrap());null===_this3.options.bbox||_this3.options.bbox.intersects(bbox)?_this3.getCSV().then(function(){var last=null,count=0;_this3.tree.range(bbox.getWest(),bbox.getSouth(),bbox.getEast(),bbox.getNorth()).map(function(id){return _this3.csv[id]}).filter(function(p){return(null==options.mindate||options.mindate<=1e3*p.timestamp)&&(null==options.maxdate||options.maxdate>=1e3*p.timestamp)}).forEach(function(p){count++,(null===last||last<1e3*p.timestamp)&&(last=1e3*p.timestamp)}),resolve({last:last,amount:"e"+count,bbox:bbox.toBBoxString()})}).catch(reject):resolve({amount:"e0",bbox:bbox.toBBoxString()})})}},{key:"getCSV",value:function(){var _this4=this;return new Promise(function(resolve,reject){null!==_this4.tree?resolve():_this4.isDownloading?setTimeout(function(){_this4.getCSV().then(resolve)},100):(_this4.isDownloading=!0,_this4.ajax(_this4.csvURL,"csv").then(function(d){_this4.csv=CSVParser(d,{columns:!0,delimiter:";"}),_this4.tree=kdbush(_this4.csv,function(p){return parseFloat(p.longitude)},function(p){return parseFloat(p.latitude)}),resolve()}).catch(reject))})}},{key:"name",get:function(){return this.options&&this.options.name||"CSV Source"}},{key:"logoUrl",get:function(){return this.options&&this.options.logo||""}},{key:"homepageUrl",get:function(){return this.options&&this.options.homepage||""}}]),CSV}(Fetcher);module.exports=CSV},{"../../model/LatLng":51,"../../model/LatLngBounds":52,"../../model/Picture":53,"../Fetcher":43,"csv-parse/lib/sync":7,kdbush:13}],46:[function(_dereq_,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var _createClass=function(){function defineProperties(target,props){for(var i=0;i0))throw new Error("ctrl.fetchers.flickr.invalidapikey");return _this.apiKey=apiKey,_this}return _inherits(Flickr,_Fetcher),_createClass(Flickr,[{key:"requestPictures",value:function(boundingBox,options){var data=Object.assign({picsPerRequest:100,page:1,pictures:[],bbox:new LatLngBounds(boundingBox.getSouthWest().wrap(),boundingBox.getNorthEast().wrap())},this.options,options);return this.licenses?this.download(data):this.downloadLicenses(data)}},{key:"requestSummary",value:function(boundingBox,options){var _this2=this;options=Object.assign({},this.options,options);var url="https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key="+this.apiKey+(null!=options.mindate?"&min_taken_date="+new Date(options.mindate).toISOString().split("T")[0]:"")+(null!=options.maxdate?"&max_taken_date="+new Date(options.maxdate).toISOString().split("T")[0]:"")+"&bbox="+boundingBox.getWest()+"%2C"+boundingBox.getSouth()+"%2C"+boundingBox.getEast()+"%2C"+boundingBox.getNorth()+"&has_geo=1&per_page=1&license=4,5,7,8,9,10&format=json&nojsoncallback=1&extras=date_taken";return this.ajax(url,"json").then(function(data){return null!==data&&void 0!==data.photos&&void 0!==data.photos.total&&void 0!==data.photos.photo||_this2.fail(null,null,new Error("ctrl.fetcher.flickr.getsummaryfailed")),parseInt(data.photos.total)>0?{last:new Date(data.photos.photo[0].datetaken.replace(" ","T")).getTime(),amount:"e"+data.photos.total,bbox:boundingBox.toBBoxString()}:{amount:"e0",bbox:boundingBox.toBBoxString()}})}},{key:"downloadLicenses",value:function(info){var _this3=this;return this.ajax("https://api.flickr.com/services/rest/?method=flickr.photos.licenses.getInfo&api_key="+this.apiKey+"&format=json&nojsoncallback=1","json").then(function(d){if(_this3.licenses={},d.stat&&"ok"==d.stat&&d.licenses&&d.licenses.license){for(var i=0;i=4&&6!=v}),url="https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key="+this.apiKey+(null!=info.mindate?"&min_taken_date="+new Date(info.mindate).toISOString().split("T")[0]:"")+(null!=info.maxdate?"&max_taken_date="+new Date(info.maxdate).toISOString().split("T")[0]:"")+"&bbox="+info.bbox.getWest()+"%2C"+info.bbox.getSouth()+"%2C"+info.bbox.getEast()+"%2C"+info.bbox.getNorth()+"&has_geo=1&per_page="+info.picsPerRequest+"&page="+info.page+"&license="+licenseList.join(",")+"&format=json&nojsoncallback=1&extras=license%2Cdate_taken%2Cowner_name%2Cgeo%2Curl_l%2Curl_z";return this.ajax(url,"json").then(function(result){if(null===result||void 0===result.photos||void 0===result.photos.photo)throw new Error("ctrl.fetcher.flickr.getpicturesfailed");if(result.stat&&"ok"===result.stat&&result.photos.photo&&result.photos.photo.length>0){for(var i=0;i0&&info.pictures.push(new Picture(pic.url_l,new Date(pic.datetaken.replace(" ","T")).getTime(),new LatLng(pic.latitude,pic.longitude),_this4.name,pic.ownername,_this4.licenses[pic.license],"https://www.flickr.com/photos/"+pic.owner+"/"+pic.id,null,{flickr:"https://www.flickr.com/photos/"+pic.owner+"/"+pic.id},pic.url_z))}info.page=result.photos.photo.length==info.picsPerRequest?info.page+1:-1}else info.page=-1;return info.page>0?_this4.download(info):info.pictures})}},{key:"name",get:function(){return"Flickr"}},{key:"logoUrl",get:function(){return"https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Flickr_wordmark.svg/640px-Flickr_wordmark.svg.png"}},{key:"homepageUrl",get:function(){return"https://www.flickr.com/"}}]),Flickr}(Fetcher);module.exports=Flickr},{"../../model/LatLng":51,"../../model/LatLngBounds":52,"../../model/Picture":53,"../Fetcher":43}],47:[function(_dereq_,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var _DTC_TO_MPL,_createClass=function(){function defineProperties(target,props){for(var i=0;i0))throw new Error("ctrl.fetchers.mapillary.invalidclientid");return _this.clientId=clientId,_this}return _inherits(Mapillary,_Fetcher),_createClass(Mapillary,[{key:"requestPictures",value:function(boundingBox){var _this2=this,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},url="https://graph.mapillary.com/images?fields=id,camera_type,captured_at,computed_compass_angle,computed_geometry&bbox="+[boundingBox.getWest(),boundingBox.getSouth(),boundingBox.getEast(),boundingBox.getNorth()].join(",")+"&access_token="+this.clientId;return this.ajax(url,"json").then(function(res){if(!res||!res.data)return Promise.reject(new Error("ctrl.fetcher.mapillary.getpicturesfailed"));var images={};if(res.data.filter(function(pic){return(!options.mindate||new Date(pic.captured_at).getTime()>=options.mindate)&&(!options.maxdate||new Date(pic.captured_at).getTime()<=options.maxdate)}).forEach(function(pic){images[pic.id]=pic}),0===Object.keys(images).length)return[];var url2="https://graph.mapillary.com/images?image_ids="+Object.keys(images).join(",")+"&fields=fields=id,thumb_256_url,thumb_2048_url&access_token="+_this2.clientId;return _this2.ajax(url2,"json").then(function(res2){return res2&&res2.data?(res2.data.forEach(function(pic){images[pic.id].url=pic.thumb_2048_url,images[pic.id].thumb=pic.thumb_256_url}),Object.values(images).filter(function(pic){return pic.url&&pic.captured_at&&pic.computed_geometry}).map(function(pic){return new Picture(pic.url,new Date(pic.captured_at).getTime(),new LatLng(pic.computed_geometry.coordinates[1],pic.computed_geometry.coordinates[0]),_this2.name,"Mapillary contributor","CC By-SA 4.0","https://www.mapillary.com/app/?pKey="+pic.id+"&lat="+pic.computed_geometry.coordinates[1]+"&lng="+pic.computed_geometry.coordinates[0]+"&focus=photo",pic.computed_compass_angle,{mapillary:pic.id.toString()},pic.thumb,{isSpherical:"spherical"===pic.camera_type})})):Promise.reject(new Error("ctrl.fetcher.mapillary.getpicturesfailed"))})})}},{key:"requestSummary",value:function(boundingBox){var _this3=this,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.requestPictures(boundingBox,options).then(function(pics){return pics.length>0?(pics.sort(function(a,b){return b.date-a.date}),{last:pics[0].date,amount:"e"+pics.length,bbox:boundingBox.toBBoxString()}):{amount:"e0",bbox:boundingBox.toBBoxString()}}).catch(function(e){console.error(e),_this3.fail(null,null,new Error("ctrl.fetcher.mapillary.getsummaryfailed"))})}},{key:"requestDetections",value:function(boundingBox){var options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},url="https://graph.mapillary.com/map_features?fields=id,object_value,last_seen_at,geometry&bbox="+[boundingBox.getWest(),boundingBox.getSouth(),boundingBox.getEast(),boundingBox.getNorth()].join(",")+(options.types?"&object_values="+options.types.map(function(ot){return"string"==typeof DTC_TO_MPL[ot]?DTC_TO_MPL[ot]:DTC_TO_MPL[ot].join(",")}).join(","):"")+"&access_token="+this.clientId;return this.ajax(url,"json").then(function(res){return res&&res.data?res.data.map(function(dtc){return new Detection(MPL_TO_DTC[dtc.object_value],new LatLng(dtc.geometry.coordinates[1],dtc.geometry.coordinates[0]),new Date(dtc.last_seen_at).getTime(),"mapillary"); +}):Promise.reject(new Error("ctrl.fetcher.mapillary.getdetectionsfailed"))})}},{key:"tagsToPictures",value:function(tags){var result=[];return Object.keys(tags).filter(function(k){return k.startsWith("mapillary")}).forEach(function(k){tags[k].split(";").forEach(function(mid){/^[0-9A-Za-z_\-]{22}$/.test(mid.trim())&&result.push("https://images.mapillary.com/"+mid.trim()+"/thumb-2048.jpg")})}),result}},{key:"name",get:function(){return"Mapillary"}},{key:"logoUrl",get:function(){return"https://upload.wikimedia.org/wikipedia/commons/5/51/Mapillary_dotcompass_2019.png"}},{key:"homepageUrl",get:function(){return"https://www.mapillary.com/"}}]),Mapillary}(Fetcher);module.exports=Mapillary},{"../../model/Detection":50,"../../model/LatLng":51,"../../model/LatLngBounds":52,"../../model/Picture":53,"../Fetcher":43,"@mapbox/sphericalmercator":1}],48:[function(_dereq_,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var _createClass=function(){function defineProperties(target,props){for(var i=0;i0){data.currentPageItems.sort(function(a,b){return b.timestamp-a.timestamp});var amount=data.currentPageItems.length,last=1e3*data.currentPageItems[0].timestamp;if(options.maxdate&&last>options.maxdate)for(var i=0;ioptions.maxdate;)i++,amount--,last=i1000",bbox:options.bbox.toBBoxString()}}return{amount:"e0",bbox:options.bbox.toBBoxString()}})}},{key:"tagsToPictures",value:function(tags){var result=[];return tags.image&&tags.image.split(";").forEach(function(img){(img.startsWith("http://")||img.startsWith("https://"))&&result.push(img)}),result}},{key:"download",value:function(data){var _this3=this,url=API_URL+"list/nearby-photos/",params={coordinate:data.bbox.getCenter().lat+","+data.bbox.getCenter().lng,radius:data.bbox.getNorthEast().distanceTo(data.bbox.getSouthWest())/2};return data.mindate&&(params.date=new Date(data.mindate).toISOString().split("T")[0]),this.ajaxPost(url,params,"json").then(function(result){if(null!==result&&void 0!==result.status&&"600"===result.status.apiCode||_this3.fail(null,null,new Error("ctrl.fetcher.openstreetcam.getpicturesfailed")),result.currentPageItems&&result.currentPageItems.length>0){result.currentPageItems.sort(function(a,b){return parseInt(a.timestamp)-parseInt(b.timestamp)});for(var i=0;i0){var lastDate=null,picAmount=0;for(var picId in data.query.pages){var pic=data.query.pages[picId];if(pic.imageinfo&&pic.imageinfo.length>0&&pic.coordinates&&pic.coordinates.length>0&&pic.imageinfo[0].url&&pic.imageinfo[0].timestamp&&pic.coordinates[0].lat&&pic.coordinates[0].lon&&pic.imageinfo[0].user&&pic.imageinfo[0].extmetadata.LicenseShortName){var date=null;if(pic.imageinfo[0].metadata&&pic.imageinfo[0].metadata.length>0)for(var mdId=0;mdId=options.mindate)&&(null==options.maxdate||date<=options.maxdate)&&(picAmount++,(null==lastDate||lastDate<=date)&&(lastDate=date))}}return picAmount>0?{last:lastDate,amount:">"+picAmount,bbox:options.bbox.toBBoxString()}:{amount:"e0",bbox:options.bbox.toBBoxString()}}return{amount:"e0",bbox:options.bbox.toBBoxString()}}if(""===data.batchcomplete)return{amount:"e0",bbox:options.bbox.toBBoxString()};throw new Error("ctrl.fetcher.wikicommons.getlightfailed")})}},{key:"tagsToPictures",value:function(tags){var _this2=this,result=[];return tags.wikimedia_commons&&tags.wikimedia_commons.split(";").forEach(function(pic){if(pic.startsWith("File:")){var wmid=pic.substring(5).replace(/ /g,"_"),digest=_this2._md5(wmid),url="https://upload.wikimedia.org/wikipedia/commons/"+digest[0]+"/"+digest[0]+digest[1]+"/"+encodeURIComponent(wmid);result.push(_this2.toThumbURL(url))}}),result}},{key:"download",value:function(info){var _this3=this,url="https://commons.wikimedia.org/w/api.php?action=query&format=json&origin=*&prop=coordinates|imageinfo&continue="+(info.continue&&info.continue.continue?info.continue.continue:"")+(info.continue&&info.continue.cocontinue?"&cocontinue="+info.continue.cocontinue:"")+"&generator=geosearch&iiprop=timestamp|user|url|extmetadata|metadata|size&iiextmetadatafilter=LicenseShortName&ggsbbox="+info.bbox.getNorth()+"|"+info.bbox.getWest()+"|"+info.bbox.getSouth()+"|"+info.bbox.getEast()+"&ggslimit="+info.picsPerRequest+"&iilimit="+(info.picsPerRequest-1)+"&colimit="+(info.picsPerRequest-1)+"&ggsnamespace=6&&iimetadataversion=latest";return this.ajax(url,"json").then(function(result){if(result.query&&result.query.pages&&Object.keys(result.query.pages).length>0){for(var picId in result.query.pages){var pic=result.query.pages[picId];if(pic.imageinfo&&pic.imageinfo.length>0&&pic.coordinates&&pic.coordinates.length>0&&pic.imageinfo[0].url&&pic.imageinfo[0].timestamp&&pic.coordinates[0].lat&&pic.coordinates[0].lon&&pic.imageinfo[0].user&&pic.imageinfo[0].extmetadata.LicenseShortName){var date=null;if(pic.imageinfo[0].metadata&&pic.imageinfo[0].metadata.length>0)for(var mdId=0;mdId=info.mindate)&&(null==info.maxdate||date<=info.maxdate)&&info.pictures.push(new Picture(pic.imageinfo[0].width&&pic.imageinfo[0].width>1024?_this3.toThumbURL(pic.imageinfo[0].url):pic.imageinfo[0].url,date,new LatLng(pic.coordinates[0].lat,pic.coordinates[0].lon),_this3.name,pic.imageinfo[0].user,pic.imageinfo[0].extmetadata.LicenseShortName.value,pic.imageinfo[0].descriptionurl,null,{wikimedia_commons:pic.title},_this3.toThumbURL(pic.imageinfo[0].url,640)))}}info.continue=result.continue&&(result.continue.cocontinue||result.continue.continue)?result.continue:null}else info.continue=null;return null!==info.continue?_this3.download(info):info.pictures})}},{key:"toThumbURL",value:function(url,size){size=size||1024;var rgx=/^(.+wikipedia\/commons)\/([a-zA-Z0-9]\/[a-zA-Z0-9]{2})\/(.+)$/,rgxRes=rgx.exec(url);return rgxRes[1]+"/thumb/"+rgxRes[2]+"/"+rgxRes[3]+"/"+size+"px-"+rgxRes[3]}},{key:"_md5",value:function(str){var xl=void 0,rotateLeft=function(lValue,iShiftBits){return lValue<>>32-iShiftBits},addUnsigned=function(lX,lY){var lX4=void 0,lY4=void 0,lX8=void 0,lY8=void 0,lResult=void 0;return lX8=2147483648&lX,lY8=2147483648&lY,lX4=1073741824&lX,lY4=1073741824&lY,lResult=(1073741823&lX)+(1073741823&lY),lX4&lY4?2147483648^lResult^lX8^lY8:lX4|lY4?1073741824&lResult?3221225472^lResult^lX8^lY8:1073741824^lResult^lX8^lY8:lResult^lX8^lY8},_F=function(x,y,z){return x&y|~x&z},_G=function(x,y,z){return x&z|y&~z},_H=function(x,y,z){return x^y^z},_I=function(x,y,z){return y^(x|~z)},_FF=function(a,b,c,d,x,s,ac){return a=addUnsigned(a,addUnsigned(addUnsigned(_F(b,c,d),x),ac)),addUnsigned(rotateLeft(a,s),b)},_GG=function(a,b,c,d,x,s,ac){return a=addUnsigned(a,addUnsigned(addUnsigned(_G(b,c,d),x),ac)),addUnsigned(rotateLeft(a,s),b)},_HH=function(a,b,c,d,x,s,ac){return a=addUnsigned(a,addUnsigned(addUnsigned(_H(b,c,d),x),ac)),addUnsigned(rotateLeft(a,s),b)},_II=function(a,b,c,d,x,s,ac){return a=addUnsigned(a,addUnsigned(addUnsigned(_I(b,c,d),x),ac)),addUnsigned(rotateLeft(a,s),b)},convertToWordArray=function(str){for(var lWordCount=void 0,lMessageLength=str.length,lNumberOfWords_temp1=lMessageLength+8,lNumberOfWords_temp2=(lNumberOfWords_temp1-lNumberOfWords_temp1%64)/64,lNumberOfWords=16*(lNumberOfWords_temp2+1),lWordArray=new Array(lNumberOfWords-1),lBytePosition=0,lByteCount=0;lByteCount>>29,lWordArray},wordToHex=function(lValue){var wordToHexValue="",wordToHexValue_temp="",lByte=void 0,lCount=void 0;for(lCount=0;lCount<=3;lCount++)lByte=lValue>>>8*lCount&255,wordToHexValue_temp="0"+lByte.toString(16),wordToHexValue+=wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);return wordToHexValue},x=[],k=void 0,AA=void 0,BB=void 0,CC=void 0,DD=void 0,a=void 0,b=void 0,c=void 0,d=void 0,S11=7,S12=12,S13=17,S14=22,S21=5,S22=9,S23=14,S24=20,S31=4,S32=11,S33=16,S34=23,S41=6,S42=10,S43=15,S44=21;for(str=this._utf8_encode(str),x=convertToWordArray(str),a=1732584193,b=4023233417,c=2562383102,d=271733878,xl=x.length,k=0;k127&&c1<2048)enc=String.fromCharCode(c1>>6|192,63&c1|128);else if(55296!=(63488&c1))enc=String.fromCharCode(c1>>12|224,c1>>6&63|128,63&c1|128);else{if(55296!=(64512&c1))throw new RangeError("Unmatched trail surrogate at "+n);var c2=string.charCodeAt(++n);if(56320!=(64512&c2))throw new RangeError("Unmatched lead surrogate at "+(n-1));c1=((1023&c1)<<10)+(1023&c2)+65536,enc=String.fromCharCode(c1>>18|240,c1>>12&63|128,c1>>6&63|128,63&c1|128)}null!==enc&&(end>start&&(utftext+=string.slice(start,end)),utftext+=enc,start=end=n+1)}return end>start&&(utftext+=string.slice(start,stringl)),utftext}},{key:"name",get:function(){return"Wikimedia Commons"}},{key:"logoUrl",get:function(){return"https://commons.wikimedia.org/static/images/project-logos/commonswiki.png"}},{key:"homepageUrl",get:function(){return"https://commons.wikimedia.org"}}]),WikiCommons}(Fetcher);module.exports=WikiCommons},{"../../model/LatLng":51,"../../model/LatLngBounds":52,"../../model/Picture":53,"../Fetcher":43}],50:[function(_dereq_,module,exports){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _Detection$TYPE_DETAI,Detection=function Detection(type,coordinates,date,provider){if(_classCallCheck(this,Detection),"number"!=typeof type||type<0)throw new Error("model.detection.invalid.type");if(null===coordinates||void 0===coordinates||"number"!=typeof coordinates.lat||"number"!=typeof coordinates.lng)throw new Error("model.detection.invalid.coordinates");if("number"!=typeof date||isNaN(date))throw new Error("model.detection.invalid.date");try{new Date(date)}catch(e){throw new Error("model.detection.invalid.date")}if("string"!=typeof provider||0===provider.length)throw new Error("model.detection.invalid.provider");this.type=type,this.coordinates=coordinates,this.date=date,this.provider=provider};Detection.OBJECT_BENCH=1,Detection.SIGN_STOP=2,Detection.MARK_CROSSING=3,Detection.OBJECT_BICYCLE_PARKING=4,Detection.OBJECT_CCTV=5,Detection.OBJECT_HYDRANT=6,Detection.OBJECT_POSTBOX=7,Detection.OBJECT_MANHOLE=8,Detection.OBJECT_PARKING_METER=9,Detection.OBJECT_PHONE=10,Detection.SIGN_ADVERT=11,Detection.SIGN_INFO=12,Detection.SIGN_STORE=13,Detection.OBJECT_STREET_LIGHT=14,Detection.OBJECT_POLE=15,Detection.OBJECT_UTILITY_POLE=19,Detection.SIGN_RESERVED_PARKING=16,Detection.SIGN_ANIMAL_CROSSING=17,Detection.SIGN_RAILWAY_CROSSING=18,Detection.TYPE_DETAILS=(_Detection$TYPE_DETAI={},_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_BENCH,{name:"Bench",osmTags:{amenity:"bench"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Garden_bench_001.jpg/320px-Garden_bench_001.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_STOP,{name:"Stop sign",osmTags:{traffic_sign:"stop"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Vienna_Convention_road_sign_B2a.svg/320px-Vienna_Convention_road_sign_B2a.svg.png"}),_defineProperty(_Detection$TYPE_DETAI,Detection.MARK_CROSSING,{name:"Pedestrian crossing",osmTags:{highway:"crossing"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/A_closeup_of_Pedastrian_cross.JPG/320px-A_closeup_of_Pedastrian_cross.JPG"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_BICYCLE_PARKING,{name:"Bicycle parking",osmTags:{amenity:"bicycle_parking"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/AlewifeBikeParking.agr.2001.JPG/320px-AlewifeBikeParking.agr.2001.JPG"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_CCTV,{name:"CCTV camera",osmTags:{man_made:"surveillance"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/AxisCCTV.jpg/320px-AxisCCTV.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_HYDRANT,{name:"Fire hydrant",osmTags:{emergency:"fire_hydrant","fire_hydrant:type":"pillar"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Brandkraan.jpg/320px-Brandkraan.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_POSTBOX,{name:"Post box",osmTags:{amenity:"post_box"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Mt_Abu_mailbox.jpg/320px-Mt_Abu_mailbox.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_MANHOLE,{name:"Manhole",osmTags:{manhole:"unknown"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/French_Quater_New_Orleans_Curious_Lid_NIOPSI.jpg/320px-French_Quater_New_Orleans_Curious_Lid_NIOPSI.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_PARKING_METER,{name:"Parking meter",osmTags:{amenity:"vending_machine",vending:"parking_tickets"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Riga_%2813.08.2011%29_405.JPG/320px-Riga_%2813.08.2011%29_405.JPG"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_PHONE,{name:"Telephone (public/emergency)",osmTags:{amenity:"telephone"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Telefono_publico_venezolano_2012_000.jpg/320px-Telefono_publico_venezolano_2012_000.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_ADVERT,{name:"Advert sign",osmTags:{advertising:"sign"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1d/The_Chevron_sign_of_excellence%2C_Chevron_Motoroils%2C_enamel_advertising_sign.JPG/320px-The_Chevron_sign_of_excellence%2C_Chevron_Motoroils%2C_enamel_advertising_sign.JPG"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_INFO,{name:"Information sign",osmTags:{advertising:"board"},symbol:"https://wiki.openstreetmap.org/w/images/thumb/f/fc/IMG_6076.JPG/320px-IMG_6076.JPG"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_STORE,{name:"Store sign",osmTags:{advertising:"sign"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Kruidvat_store_sign%2C_Winschoten_%282019%29_01.jpg/320px-Kruidvat_store_sign%2C_Winschoten_%282019%29_01.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_STREET_LIGHT,{name:"Street light",osmTags:{highway:"street_lamp"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Rome_(Italy)%2C_street_light_--_2013_--_3484.jpg/320px-Rome_(Italy)%2C_street_light_--_2013_--_3484.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_POLE,{name:"Pole",osmTags:{power:"pole"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Rusty_can_on_a_public_pole%2C_Winschoten_%282019%29_01.jpg/270px-Rusty_can_on_a_public_pole%2C_Winschoten_%282019%29_01.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.OBJECT_UTILITY_POLE,{name:"Utility pole",osmTags:{man_made:"utility_pole"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Top_of_power_line_pole_-_east_side.jpg/320px-Top_of_power_line_pole_-_east_side.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_RESERVED_PARKING,{name:"Reserved parking",osmTags:{amenity:"parking_space","capacity:disabled":1},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/f/fe/Reserved_Parking_disabled_persons.jpg/320px-Reserved_Parking_disabled_persons.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_ANIMAL_CROSSING,{name:"Animal crossing sign",osmTags:{hazard:"animal_crossing"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Animal_crossing_sign.jpg/320px-Animal_crossing_sign.jpg"}),_defineProperty(_Detection$TYPE_DETAI,Detection.SIGN_RAILWAY_CROSSING,{name:"Railway crossing sign",osmTags:{railway:"level_crossing"},symbol:"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/France_road_sign_A8.svg/320px-France_road_sign_A8.svg.png"}),_Detection$TYPE_DETAI),module.exports=Detection},{}],51:[function(_dereq_,module,exports){"use strict";var LatLng=function LatLng(lat,lng,alt){if((!(lat instanceof LatLng||lat&&lat.length&&2==lat.length||lat.lat&&lat.lng)||void 0!==lng)&&(isNaN(lat)||isNaN(lng)))throw new Error("Invalid LatLng object: ("+lat+", "+lng+")");lat instanceof LatLng||lat.lat&&lat.lng?(this.lat=lat.lat,this.lng=lat.lng,this.alt=lat.alt):2==lat.length?(this.lat=lat[0],this.lng=lat[1]):(this.lat=+lat,this.lng=+lng,void 0!==alt&&(this.alt=+alt))};LatLng.prototype={equals:function(obj,maxMargin){if(!obj)return!1;obj=new LatLng(obj);var margin=Math.max(Math.abs(this.lat-obj.lat),Math.abs(this.lng-obj.lng));return margin<=(void 0===maxMargin?1e-9:maxMargin)},toString:function(precision){return"LatLng("+this.lat+", "+this.lng+")"},wrap:function(){for(var lng=this.lng;lng<-180;)lng+=360;for(;lng>180;)lng-=360;for(var lat=this.lat;lat<-90;)lat+=180;for(;lat>90;)lat-=180;return new LatLng(lat,lng,this.alt)},toBounds:function(sizeInMeters){var latAccuracy=180*sizeInMeters/40075017,lngAccuracy=latAccuracy/Math.cos(Math.PI/180*this.lat);return L.latLngBounds([this.lat-latAccuracy,this.lng-lngAccuracy],[this.lat+latAccuracy,this.lng+lngAccuracy])},clone:function(){return new LatLng(this.lat,this.lng,this.alt)},distanceTo:function(other){var rad=Math.PI/180,lat1=this.lat*rad,lat2=other.lat*rad,a=Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos((other.lng-this.lng)*rad);return 6371e3*Math.acos(Math.min(a,1))}},module.exports=LatLng},{}],52:[function(_dereq_,module,exports){"use strict";var LatLng=_dereq_("./LatLng"),LatLngBounds=function LatLngBounds(corner1,corner2){if(corner1){var latlngs=corner2?[corner1,corner2]:corner1;if(corner1 instanceof LatLngBounds)this._southWest=corner1._southWest,this._northEast=corner1._northEast;else for(var i=0,len=latlngs.length;i=sw.lat&&ne2.lat<=ne.lat&&sw2.lng>=sw.lng&&ne2.lng<=ne.lng},intersects:function(bounds){bounds=new LatLngBounds(bounds);var sw=this._southWest,ne=this._northEast,sw2=bounds.getSouthWest(),ne2=bounds.getNorthEast(),latIntersects=ne2.lat>=sw.lat&&sw2.lat<=ne.lat,lngIntersects=ne2.lng>=sw.lng&&sw2.lng<=ne.lng;return latIntersects&&lngIntersects},overlaps:function(bounds){bounds=new LatLngBounds(bounds);var sw=this._southWest,ne=this._northEast,sw2=bounds.getSouthWest(),ne2=bounds.getNorthEast(),latOverlaps=ne2.lat>sw.lat&&sw2.latsw.lng&&sw2.lng0))throw new Error("model.picture.invalid.pictureUrl");if(this.pictureUrl=pictureUrl,"number"!=typeof date||isNaN(date))throw new Error("model.picture.invalid.date");try{new Date(date),this.date=date}catch(e){ +throw new Error("model.picture.invalid.date")}if(null===coords||void 0===coords||"number"!=typeof coords.lat||"number"!=typeof coords.lng)throw new Error("model.picture.invalid.coords");if(this.coordinates=coords,!("string"==typeof provider&&provider.length>0))throw new Error("model.picture.invalid.provider");this.provider=provider,this.author=author||null,this.license=license||null,this.detailsUrl=detailsUrl||null,this.direction="number"==typeof direction&&direction>=0&&direction<360?direction:null,this.osmTags=osmTags||null,this.thumbUrl=thumbUrl||null,this.details=details||{}}return _createClass(Picture,[{key:"lookAlike",value:function(other){return this.coordinates.equals(other.coordinates)&&this.date===other.date&&this.direction===other.direction}}]),Picture}();module.exports=Picture},{}]},{},[40])(40)});